blob: 6d4d499d823b97fd829d7a536a0fbeac0dfafbc4 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
6 *
7 * Do ":help uganda" in Vim to read copying and usage conditions.
8 * Do ":help credits" in Vim to see a list of people who contributed.
9 * See README.txt for an overview of the Vim source code.
10 */
11
12/*
13 * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
14 * Also for OS/2, using the excellent EMX package!!!
15 * Also for BeOS and Atari MiNT.
16 *
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
19 */
20
21/*
22 * Some systems have a prototype for select() that has (int *) instead of
23 * (fd_set *), which is wrong. This define removes that prototype. We define
24 * our own prototype below.
25 * Don't use it for the Mac, it causes a warning for precompiled headers.
26 * TODO: use a configure check for precompiled headers?
27 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000028#if !defined(__APPLE__) && !defined(__TANDEM)
Bram Moolenaar071d4272004-06-13 20:20:40 +000029# define select select_declared_wrong
30#endif
31
32#include "vim.h"
33
Bram Moolenaar325b7a22004-07-05 15:58:32 +000034#ifdef FEAT_MZSCHEME
35# include "if_mzsch.h"
36#endif
37
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#include "os_unixx.h" /* unix includes for os_unix.c only */
39
40#ifdef USE_XSMP
41# include <X11/SM/SMlib.h>
42#endif
43
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000044#ifdef HAVE_SELINUX
45# include <selinux/selinux.h>
46static int selinux_enabled = -1;
47#endif
48
Bram Moolenaar071d4272004-06-13 20:20:40 +000049/*
50 * Use this prototype for select, some include files have a wrong prototype
51 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000052#ifndef __TANDEM
53# undef select
54# ifdef __BEOS__
55# define select beos_select
56# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
Bram Moolenaara2442432007-04-26 14:26:37 +000059#ifdef __CYGWIN__
60# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000061# include <cygwin/version.h>
62# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
63 * for cygwin_conv_path() */
Bram Moolenaara2442432007-04-26 14:26:37 +000064# endif
65#endif
66
Bram Moolenaar071d4272004-06-13 20:20:40 +000067#if defined(HAVE_SELECT)
68extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
69#endif
70
71#ifdef FEAT_MOUSE_GPM
72# include <gpm.h>
73/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
74 * I just copied relevant defines here. A cleaner solution would be to put gpm
75 * code into separate file and include there linux/keyboard.h
76 */
77/* #include <linux/keyboard.h> */
78# define KG_SHIFT 0
79# define KG_CTRL 2
80# define KG_ALT 3
81# define KG_ALTGR 1
82# define KG_SHIFTL 4
83# define KG_SHIFTR 5
84# define KG_CTRLL 6
85# define KG_CTRLR 7
86# define KG_CAPSSHIFT 8
87
88static void gpm_close __ARGS((void));
89static int gpm_open __ARGS((void));
90static int mch_gpm_process __ARGS((void));
91#endif
92
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000093#ifdef FEAT_SYSMOUSE
94# include <sys/consio.h>
95# include <sys/fbio.h>
96
97static int sysmouse_open __ARGS((void));
98static void sysmouse_close __ARGS((void));
99static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG);
100#endif
101
Bram Moolenaar071d4272004-06-13 20:20:40 +0000102/*
103 * end of autoconf section. To be extended...
104 */
105
106/* Are the following #ifdefs still required? And why? Is that for X11? */
107
108#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
109# ifdef SIGWINCH
110# undef SIGWINCH
111# endif
112# ifdef TIOCGWINSZ
113# undef TIOCGWINSZ
114# endif
115#endif
116
117#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
118# define SIGWINCH SIGWINDOW
119#endif
120
121#ifdef FEAT_X11
122# include <X11/Xlib.h>
123# include <X11/Xutil.h>
124# include <X11/Xatom.h>
125# ifdef FEAT_XCLIPBOARD
126# include <X11/Intrinsic.h>
127# include <X11/Shell.h>
128# include <X11/StringDefs.h>
129static Widget xterm_Shell = (Widget)0;
130static void xterm_update __ARGS((void));
131# endif
132
133# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
134Window x11_window = 0;
135# endif
136Display *x11_display = NULL;
137
138# ifdef FEAT_TITLE
139static int get_x11_windis __ARGS((void));
140static void set_x11_title __ARGS((char_u *));
141static void set_x11_icon __ARGS((char_u *));
142# endif
143#endif
144
145#ifdef FEAT_TITLE
146static int get_x11_title __ARGS((int));
147static int get_x11_icon __ARGS((int));
148
149static char_u *oldtitle = NULL;
150static int did_set_title = FALSE;
151static char_u *oldicon = NULL;
152static int did_set_icon = FALSE;
153#endif
154
155static void may_core_dump __ARGS((void));
156
157static int WaitForChar __ARGS((long));
158#if defined(__BEOS__)
159int RealWaitForChar __ARGS((int, long, int *));
160#else
161static int RealWaitForChar __ARGS((int, long, int *));
162#endif
163
164#ifdef FEAT_XCLIPBOARD
165static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000166# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167#endif
168
169static void handle_resize __ARGS((void));
170
171#if defined(SIGWINCH)
172static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
173#endif
174#if defined(SIGINT)
175static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
176#endif
177#if defined(SIGPWR)
178static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
179#endif
180#if defined(SIGALRM) && defined(FEAT_X11) \
181 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
182# define SET_SIG_ALARM
183static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000184/* volatile because it is used in signal handler sig_alarm(). */
185static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000186#endif
187static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
188
Bram Moolenaardf177f62005-02-22 08:39:57 +0000189static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190static void set_signals __ARGS((void));
191static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
192#ifndef __EMX__
193static int have_wildcard __ARGS((int, char_u **));
194static int have_dollars __ARGS((int, char_u **));
195#endif
196
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197#ifndef __EMX__
198static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
199#endif
200
201#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000202# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203#endif
204
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000205/* volatile because it is used in signal handler sig_winch(). */
206static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207#ifndef __EMX__
208static char_u *extra_shell_arg = NULL;
209static int show_shell_mess = TRUE;
210#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000211/* volatile because it is used in signal handler deathtrap(). */
212static volatile int deadly_signal = 0; /* The signal we caught */
213/* volatile because it is used in signal handler deathtrap(). */
214static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215
216static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
217
218#ifdef USE_XSMP
219typedef struct
220{
221 SmcConn smcconn; /* The SM connection ID */
222 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200223 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224 Bool save_yourself; /* If we're in the middle of a save_yourself */
225 Bool shutdown; /* If we're in shutdown mode */
226} xsmp_config_T;
227
228static xsmp_config_T xsmp;
229#endif
230
231#ifdef SYS_SIGLIST_DECLARED
232/*
233 * I have seen
234 * extern char *_sys_siglist[NSIG];
235 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
236 * that describe the signals. That is nearly what we want here. But
237 * autoconf does only check for sys_siglist (without the underscore), I
238 * do not want to change everything today.... jw.
239 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
240 */
241#endif
242
243static struct signalinfo
244{
245 int sig; /* Signal number, eg. SIGSEGV etc */
246 char *name; /* Signal name (not char_u!). */
247 char deadly; /* Catch as a deadly signal? */
248} signal_info[] =
249{
250#ifdef SIGHUP
251 {SIGHUP, "HUP", TRUE},
252#endif
253#ifdef SIGQUIT
254 {SIGQUIT, "QUIT", TRUE},
255#endif
256#ifdef SIGILL
257 {SIGILL, "ILL", TRUE},
258#endif
259#ifdef SIGTRAP
260 {SIGTRAP, "TRAP", TRUE},
261#endif
262#ifdef SIGABRT
263 {SIGABRT, "ABRT", TRUE},
264#endif
265#ifdef SIGEMT
266 {SIGEMT, "EMT", TRUE},
267#endif
268#ifdef SIGFPE
269 {SIGFPE, "FPE", TRUE},
270#endif
271#ifdef SIGBUS
272 {SIGBUS, "BUS", TRUE},
273#endif
274#ifdef SIGSEGV
275 {SIGSEGV, "SEGV", TRUE},
276#endif
277#ifdef SIGSYS
278 {SIGSYS, "SYS", TRUE},
279#endif
280#ifdef SIGALRM
281 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
282#endif
283#ifdef SIGTERM
284 {SIGTERM, "TERM", TRUE},
285#endif
286#ifdef SIGVTALRM
287 {SIGVTALRM, "VTALRM", TRUE},
288#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000289#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
290 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
291 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 {SIGPROF, "PROF", TRUE},
293#endif
294#ifdef SIGXCPU
295 {SIGXCPU, "XCPU", TRUE},
296#endif
297#ifdef SIGXFSZ
298 {SIGXFSZ, "XFSZ", TRUE},
299#endif
300#ifdef SIGUSR1
301 {SIGUSR1, "USR1", TRUE},
302#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000303#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
304 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305 {SIGUSR2, "USR2", TRUE},
306#endif
307#ifdef SIGINT
308 {SIGINT, "INT", FALSE},
309#endif
310#ifdef SIGWINCH
311 {SIGWINCH, "WINCH", FALSE},
312#endif
313#ifdef SIGTSTP
314 {SIGTSTP, "TSTP", FALSE},
315#endif
316#ifdef SIGPIPE
317 {SIGPIPE, "PIPE", FALSE},
318#endif
319 {-1, "Unknown!", FALSE}
320};
321
Bram Moolenaar25724922009-07-14 15:38:41 +0000322 int
323mch_chdir(path)
324 char *path;
325{
326 if (p_verbose >= 5)
327 {
328 verbose_enter();
329 smsg((char_u *)"chdir(%s)", path);
330 verbose_leave();
331 }
332# ifdef VMS
333 return chdir(vms_fixfilename(path));
334# else
335 return chdir(path);
336# endif
337}
338
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000339/*
340 * Write s[len] to the screen.
341 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000342 void
343mch_write(s, len)
344 char_u *s;
345 int len;
346{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000347 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348 if (p_wd) /* Unix is too fast, slow down a bit more */
349 RealWaitForChar(read_cmd_fd, p_wd, NULL);
350}
351
352/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000353 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000354 * Get a characters from the keyboard.
355 * Return the number of characters that are available.
356 * If wtime == 0 do not wait for characters.
357 * If wtime == n wait a short time for characters.
358 * If wtime == -1 wait forever for characters.
359 */
360 int
361mch_inchar(buf, maxlen, wtime, tb_change_cnt)
362 char_u *buf;
363 int maxlen;
364 long wtime; /* don't use "time", MIPS cannot handle it */
365 int tb_change_cnt;
366{
367 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368
Bram Moolenaar67c53842010-05-22 18:28:27 +0200369#ifdef FEAT_NETBEANS_INTG
370 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200371 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200372#endif
373
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 /* Check if window changed size while we were busy, perhaps the ":set
375 * columns=99" command was used. */
376 while (do_resize)
377 handle_resize();
378
379 if (wtime >= 0)
380 {
381 while (WaitForChar(wtime) == 0) /* no character available */
382 {
383 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000384 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200386#ifdef FEAT_NETBEANS_INTG
387 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200388 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200389#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390 }
391 }
392 else /* wtime == -1 */
393 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 /*
395 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000396 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 * Also done when interrupted by SIGWINCH.
398 */
399 if (WaitForChar(p_ut) == 0)
400 {
401#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000402 if (trigger_cursorhold() && maxlen >= 3
403 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000405 buf[0] = K_SPECIAL;
406 buf[1] = KS_EXTRA;
407 buf[2] = (int)KE_CURSORHOLD;
408 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000411 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 }
413 }
414
415 for (;;) /* repeat until we got a character */
416 {
417 while (do_resize) /* window changed size */
418 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200419
420#ifdef FEAT_NETBEANS_INTG
421 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200422 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200423#endif
Bram Moolenaar48bae372010-07-29 23:12:15 +0200424#ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200426 * We want to be interrupted by the winch signal
427 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200429 if (WaitForChar(-1L) == 0)
430 {
431 if (do_resize) /* interrupted by SIGWINCH signal */
432 handle_resize();
433 return 0;
434 }
Bram Moolenaar48bae372010-07-29 23:12:15 +0200435#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436
437 /* If input was put directly in typeahead buffer bail out here. */
438 if (typebuf_changed(tb_change_cnt))
439 return 0;
440
441 /*
442 * For some terminals we only get one character at a time.
443 * We want the get all available characters, so we could keep on
444 * trying until none is available
445 * For some other terminals this is quite slow, that's why we don't do
446 * it.
447 */
448 len = read_from_input_buf(buf, (long)maxlen);
449 if (len > 0)
450 {
451#ifdef OS2
452 int i;
453
454 for (i = 0; i < len; i++)
455 if (buf[i] == 0)
456 buf[i] = K_NUL;
457#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 return len;
459 }
460 }
461}
462
463 static void
464handle_resize()
465{
466 do_resize = FALSE;
467 shell_resized();
468}
469
470/*
471 * return non-zero if a character is available
472 */
473 int
474mch_char_avail()
475{
476 return WaitForChar(0L);
477}
478
479#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
480# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000481# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482# endif
483# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
484# include <sys/sysctl.h>
485# endif
486# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
487# include <sys/sysinfo.h>
488# endif
489
490/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000491 * Return total amount of memory available in Kbyte.
492 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494 long_u
495mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000496 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497{
498# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000499 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500# else
501 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000502 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503
504# ifdef HAVE_SYSCTL
505 int mib[2], physmem;
506 size_t len;
507
508 /* BSD way of getting the amount of RAM available. */
509 mib[0] = CTL_HW;
510 mib[1] = HW_USERMEM;
511 len = sizeof(physmem);
512 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
513 mem = (long_u)physmem;
514# endif
515
516# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
517 if (mem == 0)
518 {
519 struct sysinfo sinfo;
520
521 /* Linux way of getting amount of RAM available */
522 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000523 {
524# ifdef HAVE_SYSINFO_MEM_UNIT
525 /* avoid overflow as much as possible */
526 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
527 {
528 sinfo.mem_unit = sinfo.mem_unit >> 1;
529 --shiftright;
530 }
531 mem = sinfo.totalram * sinfo.mem_unit;
532# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000534# endif
535 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 }
537# endif
538
539# ifdef HAVE_SYSCONF
540 if (mem == 0)
541 {
542 long pagesize, pagecount;
543
544 /* Solaris way of getting amount of RAM available */
545 pagesize = sysconf(_SC_PAGESIZE);
546 pagecount = sysconf(_SC_PHYS_PAGES);
547 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000548 {
549 /* avoid overflow as much as possible */
550 while (shiftright > 0 && (pagesize & 1) == 0)
551 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000552 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000553 --shiftright;
554 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557 }
558# endif
559
560 /* Return the minimum of the physical memory and the user limit, because
561 * using more than the user limit may cause Vim to be terminated. */
562# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
563 {
564 struct rlimit rlp;
565
566 if (getrlimit(RLIMIT_DATA, &rlp) == 0
567 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
568# ifdef RLIM_INFINITY
569 && rlp.rlim_cur != RLIM_INFINITY
570# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000571 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000573 {
574 mem = (long_u)rlp.rlim_cur;
575 shiftright = 10;
576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 }
578# endif
579
580 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000581 return mem >> shiftright;
582 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583# endif
584}
585#endif
586
587 void
588mch_delay(msec, ignoreinput)
589 long msec;
590 int ignoreinput;
591{
592 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000593#ifdef FEAT_MZSCHEME
594 long total = msec; /* remember original value */
595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596
597 if (ignoreinput)
598 {
599 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000600 * here. But we don't want QUIT to kill us (CTRL-\ used in a
601 * shell may produce SIGQUIT). */
602 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 old_tmode = curr_tmode;
604 if (curr_tmode == TMODE_RAW)
605 settmode(TMODE_SLEEP);
606
607 /*
608 * Everybody sleeps in a different way...
609 * Prefer nanosleep(), some versions of usleep() can only sleep up to
610 * one second.
611 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000612#ifdef FEAT_MZSCHEME
613 do
614 {
615 /* if total is large enough, wait by portions in p_mzq */
616 if (total > p_mzq)
617 msec = p_mzq;
618 else
619 msec = total;
620 total -= msec;
621#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622#ifdef HAVE_NANOSLEEP
623 {
624 struct timespec ts;
625
626 ts.tv_sec = msec / 1000;
627 ts.tv_nsec = (msec % 1000) * 1000000;
628 (void)nanosleep(&ts, NULL);
629 }
630#else
631# ifdef HAVE_USLEEP
632 while (msec >= 1000)
633 {
634 usleep((unsigned int)(999 * 1000));
635 msec -= 999;
636 }
637 usleep((unsigned int)(msec * 1000));
638# else
639# ifndef HAVE_SELECT
640 poll(NULL, 0, (int)msec);
641# else
642# ifdef __EMX__
643 _sleep2(msec);
644# else
645 {
646 struct timeval tv;
647
648 tv.tv_sec = msec / 1000;
649 tv.tv_usec = (msec % 1000) * 1000;
650 /*
651 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
652 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
653 */
654 select(0, NULL, NULL, NULL, &tv);
655 }
656# endif /* __EMX__ */
657# endif /* HAVE_SELECT */
658# endif /* HAVE_NANOSLEEP */
659#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000660#ifdef FEAT_MZSCHEME
661 }
662 while (total > 0);
663#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664
665 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000666 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 }
668 else
669 WaitForChar(msec);
670}
671
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000672#if 0 /* disabled, no longer needed now that regmatch() is not recursive */
673# if defined(HAVE_GETRLIMIT)
674# define HAVE_STACK_LIMIT
675# endif
676#endif
677
678#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
680# define HAVE_CHECK_STACK_GROWTH
681/*
682 * Support for checking for an almost-out-of-stack-space situation.
683 */
684
685/*
686 * Return a pointer to an item on the stack. Used to find out if the stack
687 * grows up or down.
688 */
689static void check_stack_growth __ARGS((char *p));
690static int stack_grows_downwards;
691
692/*
693 * Find out if the stack grows upwards or downwards.
694 * "p" points to a variable on the stack of the caller.
695 */
696 static void
697check_stack_growth(p)
698 char *p;
699{
700 int i;
701
702 stack_grows_downwards = (p > (char *)&i);
703}
704#endif
705
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000706#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707static char *stack_limit = NULL;
708
709#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
710# include <pthread.h>
711# include <pthread_np.h>
712#endif
713
714/*
715 * Find out until how var the stack can grow without getting into trouble.
716 * Called when starting up and when switching to the signal stack in
717 * deathtrap().
718 */
719 static void
720get_stack_limit()
721{
722 struct rlimit rlp;
723 int i;
724 long lim;
725
726 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
727 * limit doesn't fit in a long (rlim_cur might be "long long"). */
728 if (getrlimit(RLIMIT_STACK, &rlp) == 0
729 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
730# ifdef RLIM_INFINITY
731 && rlp.rlim_cur != RLIM_INFINITY
732# endif
733 )
734 {
735 lim = (long)rlp.rlim_cur;
736#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
737 {
738 pthread_attr_t attr;
739 size_t size;
740
741 /* On FreeBSD the initial thread always has a fixed stack size, no
742 * matter what the limits are set to. Normally it's 1 Mbyte. */
743 pthread_attr_init(&attr);
744 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
745 {
746 pthread_attr_getstacksize(&attr, &size);
747 if (lim > (long)size)
748 lim = (long)size;
749 }
750 pthread_attr_destroy(&attr);
751 }
752#endif
753 if (stack_grows_downwards)
754 {
755 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
756 if (stack_limit >= (char *)&i)
757 /* overflow, set to 1/16 of current stack position */
758 stack_limit = (char *)((long)&i / 16L);
759 }
760 else
761 {
762 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
763 if (stack_limit <= (char *)&i)
764 stack_limit = NULL; /* overflow */
765 }
766 }
767}
768
769/*
770 * Return FAIL when running out of stack space.
771 * "p" must point to any variable local to the caller that's on the stack.
772 */
773 int
774mch_stackcheck(p)
775 char *p;
776{
777 if (stack_limit != NULL)
778 {
779 if (stack_grows_downwards)
780 {
781 if (p < stack_limit)
782 return FAIL;
783 }
784 else if (p > stack_limit)
785 return FAIL;
786 }
787 return OK;
788}
789#endif
790
791#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
792/*
793 * Support for using the signal stack.
794 * This helps when we run out of stack space, which causes a SIGSEGV. The
795 * signal handler then must run on another stack, since the normal stack is
796 * completely full.
797 */
798
799#ifndef SIGSTKSZ
800# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
801#endif
802
803# ifdef HAVE_SIGALTSTACK
804static stack_t sigstk; /* for sigaltstack() */
805# else
806static struct sigstack sigstk; /* for sigstack() */
807# endif
808
809static void init_signal_stack __ARGS((void));
810static char *signal_stack;
811
812 static void
813init_signal_stack()
814{
815 if (signal_stack != NULL)
816 {
817# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000818# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
819 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
821 * "struct sigaltstack" needs to be declared. */
822 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
823# endif
824
825# ifdef HAVE_SS_BASE
826 sigstk.ss_base = signal_stack;
827# else
828 sigstk.ss_sp = signal_stack;
829# endif
830 sigstk.ss_size = SIGSTKSZ;
831 sigstk.ss_flags = 0;
832 (void)sigaltstack(&sigstk, NULL);
833# else
834 sigstk.ss_sp = signal_stack;
835 if (stack_grows_downwards)
836 sigstk.ss_sp += SIGSTKSZ - 1;
837 sigstk.ss_onstack = 0;
838 (void)sigstack(&sigstk, NULL);
839# endif
840 }
841}
842#endif
843
844/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000845 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846 * will barf when the second argument to signal() is ``wrong''.
847 * Let me try it with a few tricky defines from my own osdef.h (jw).
848 */
849#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 static RETSIGTYPE
851sig_winch SIGDEFARG(sigarg)
852{
853 /* this is not required on all systems, but it doesn't hurt anybody */
854 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
855 do_resize = TRUE;
856 SIGRETURN;
857}
858#endif
859
860#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000861 static RETSIGTYPE
862catch_sigint SIGDEFARG(sigarg)
863{
864 /* this is not required on all systems, but it doesn't hurt anybody */
865 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
866 got_int = TRUE;
867 SIGRETURN;
868}
869#endif
870
871#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872 static RETSIGTYPE
873catch_sigpwr SIGDEFARG(sigarg)
874{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000875 /* this is not required on all systems, but it doesn't hurt anybody */
876 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877 /*
878 * I'm not sure we get the SIGPWR signal when the system is really going
879 * down or when the batteries are almost empty. Just preserve the swap
880 * files and don't exit, that can't do any harm.
881 */
882 ml_sync_all(FALSE, FALSE);
883 SIGRETURN;
884}
885#endif
886
887#ifdef SET_SIG_ALARM
888/*
889 * signal function for alarm().
890 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000891 static RETSIGTYPE
892sig_alarm SIGDEFARG(sigarg)
893{
894 /* doesn't do anything, just to break a system call */
895 sig_alarm_called = TRUE;
896 SIGRETURN;
897}
898#endif
899
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000900#if (defined(HAVE_SETJMP_H) \
901 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
902 || defined(FEAT_LIBCALL))) \
903 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904/*
905 * A simplistic version of setjmp() that only allows one level of using.
906 * Don't call twice before calling mch_endjmp()!.
907 * Usage:
908 * mch_startjmp();
909 * if (SETJMP(lc_jump_env) != 0)
910 * {
911 * mch_didjmp();
912 * EMSG("crash!");
913 * }
914 * else
915 * {
916 * do_the_work;
917 * mch_endjmp();
918 * }
919 * Note: Can't move SETJMP() here, because a function calling setjmp() must
920 * not return before the saved environment is used.
921 * Returns OK for normal return, FAIL when the protected code caused a
922 * problem and LONGJMP() was used.
923 */
924 void
925mch_startjmp()
926{
927#ifdef SIGHASARG
928 lc_signal = 0;
929#endif
930 lc_active = TRUE;
931}
932
933 void
934mch_endjmp()
935{
936 lc_active = FALSE;
937}
938
939 void
940mch_didjmp()
941{
942# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
943 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
944 * otherwise catching the signal only works once. */
945 init_signal_stack();
946# endif
947}
948#endif
949
950/*
951 * This function handles deadly signals.
952 * It tries to preserve any swap file and exit properly.
953 * (partly from Elvis).
954 */
955 static RETSIGTYPE
956deathtrap SIGDEFARG(sigarg)
957{
958 static int entered = 0; /* count the number of times we got here.
959 Note: when memory has been corrupted
960 this may get an arbitrary value! */
961#ifdef SIGHASARG
962 int i;
963#endif
964
965#if defined(HAVE_SETJMP_H)
966 /*
967 * Catch a crash in protected code.
968 * Restores the environment saved in lc_jump_env, which looks like
969 * SETJMP() returns 1.
970 */
971 if (lc_active)
972 {
973# if defined(SIGHASARG)
974 lc_signal = sigarg;
975# endif
976 lc_active = FALSE; /* don't jump again */
977 LONGJMP(lc_jump_env, 1);
978 /* NOTREACHED */
979 }
980#endif
981
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000982#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000983# ifdef SIGQUIT
984 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
985 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
986 * pressing CTRL-\, but we don't want Vim to exit then. */
987 if (in_mch_delay && sigarg == SIGQUIT)
988 SIGRETURN;
989# endif
990
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000991 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
992 * here. This avoids that a non-reentrant function is interrupted, e.g.,
993 * free(). Calling free() again may then cause a crash. */
994 if (entered == 0
995 && (0
996# ifdef SIGHUP
997 || sigarg == SIGHUP
998# endif
999# ifdef SIGQUIT
1000 || sigarg == SIGQUIT
1001# endif
1002# ifdef SIGTERM
1003 || sigarg == SIGTERM
1004# endif
1005# ifdef SIGPWR
1006 || sigarg == SIGPWR
1007# endif
1008# ifdef SIGUSR1
1009 || sigarg == SIGUSR1
1010# endif
1011# ifdef SIGUSR2
1012 || sigarg == SIGUSR2
1013# endif
1014 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001015 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001016 SIGRETURN;
1017#endif
1018
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 /* Remember how often we have been called. */
1020 ++entered;
1021
1022#ifdef FEAT_EVAL
1023 /* Set the v:dying variable. */
1024 set_vim_var_nr(VV_DYING, (long)entered);
1025#endif
1026
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001027#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 /* Since we are now using the signal stack, need to reset the stack
1029 * limit. Otherwise using a regexp will fail. */
1030 get_stack_limit();
1031#endif
1032
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001033#if 0
1034 /* This is for opening gdb the moment Vim crashes.
1035 * You need to manually adjust the file name and Vim executable name.
1036 * Suggested by SungHyun Nam. */
1037 {
1038# define VI_GDB_FILE "/tmp/vimgdb"
1039# define VIM_NAME "/usr/bin/vim"
1040 FILE *fp = fopen(VI_GDB_FILE, "w");
1041 if (fp)
1042 {
1043 fprintf(fp,
1044 "file %s\n"
1045 "attach %d\n"
1046 "set height 1000\n"
1047 "bt full\n"
1048 , VIM_NAME, getpid());
1049 fclose(fp);
1050 system("xterm -e gdb -x "VI_GDB_FILE);
1051 unlink(VI_GDB_FILE);
1052 }
1053 }
1054#endif
1055
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056#ifdef SIGHASARG
1057 /* try to find the name of this signal */
1058 for (i = 0; signal_info[i].sig != -1; i++)
1059 if (sigarg == signal_info[i].sig)
1060 break;
1061 deadly_signal = sigarg;
1062#endif
1063
1064 full_screen = FALSE; /* don't write message to the GUI, it might be
1065 * part of the problem... */
1066 /*
1067 * If something goes wrong after entering here, we may get here again.
1068 * When this happens, give a message and try to exit nicely (resetting the
1069 * terminal mode, etc.)
1070 * When this happens twice, just exit, don't even try to give a message,
1071 * stack may be corrupt or something weird.
1072 * When this still happens again (or memory was corrupted in such a way
1073 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1074 */
1075 if (entered >= 3)
1076 {
1077 reset_signals(); /* don't catch any signals anymore */
1078 may_core_dump();
1079 if (entered >= 4)
1080 _exit(8);
1081 exit(7);
1082 }
1083 if (entered == 2)
1084 {
1085 OUT_STR(_("Vim: Double signal, exiting\n"));
1086 out_flush();
1087 getout(1);
1088 }
1089
1090#ifdef SIGHASARG
1091 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
1092 signal_info[i].name);
1093#else
1094 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
1095#endif
1096 preserve_exit(); /* preserve files and exit */
1097
Bram Moolenaar009b2592004-10-24 19:18:58 +00001098#ifdef NBDEBUG
1099 reset_signals();
1100 may_core_dump();
1101 abort();
1102#endif
1103
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104 SIGRETURN;
1105}
1106
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001107#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108/*
1109 * On Solaris with multi-threading, suspending might not work immediately.
1110 * Catch the SIGCONT signal, which will be used as an indication whether the
1111 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001112 *
1113 * On Linux, signal is not always handled immediately either.
1114 * See https://bugs.launchpad.net/bugs/291373
1115 *
1116 * volatile because it is used in in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001118static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1120
1121/*
1122 * signal handler for SIGCONT
1123 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 static RETSIGTYPE
1125sigcont_handler SIGDEFARG(sigarg)
1126{
1127 sigcont_received = TRUE;
1128 SIGRETURN;
1129}
1130#endif
1131
1132/*
1133 * If the machine has job control, use it to suspend the program,
1134 * otherwise fake it by starting a new shell.
1135 */
1136 void
1137mch_suspend()
1138{
1139 /* BeOS does have SIGTSTP, but it doesn't work. */
1140#if defined(SIGTSTP) && !defined(__BEOS__)
1141 out_flush(); /* needed to make cursor visible on some systems */
1142 settmode(TMODE_COOK);
1143 out_flush(); /* needed to disable mouse on some systems */
1144
1145# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1146 /* Since we are going to sleep, we can't respond to requests for the X
1147 * selections. Lose them, otherwise other applications will hang. But
1148 * first copy the text to cut buffer 0. */
1149 if (clip_star.owned || clip_plus.owned)
1150 {
1151 x11_export_final_selection();
1152 if (clip_star.owned)
1153 clip_lose_selection(&clip_star);
1154 if (clip_plus.owned)
1155 clip_lose_selection(&clip_plus);
1156 if (x11_display != NULL)
1157 XFlush(x11_display);
1158 }
1159# endif
1160
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001161# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 sigcont_received = FALSE;
1163# endif
1164 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001165# if defined(_REENTRANT) && defined(SIGCONT)
1166 /*
1167 * Wait for the SIGCONT signal to be handled. It generally happens
1168 * immediately, but somehow not all the time. Do not call pause()
1169 * because there would be race condition which would hang Vim if
1170 * signal happened in between the test of sigcont_received and the
1171 * call to pause(). If signal is not yet received, call sleep(0)
1172 * to just yield CPU. Signal should then be received. If somehow
1173 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1174 * further if signal is not received after 1+2+3+4 ms (not expected
1175 * to happen).
1176 */
1177 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001178 long wait_time;
1179 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001180 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001181 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001182 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183# endif
1184
1185# ifdef FEAT_TITLE
1186 /*
1187 * Set oldtitle to NULL, so the current title is obtained again.
1188 */
1189 vim_free(oldtitle);
1190 oldtitle = NULL;
1191# endif
1192 settmode(TMODE_RAW);
1193 need_check_timestamps = TRUE;
1194 did_check_timestamps = FALSE;
1195#else
1196 suspend_shell();
1197#endif
1198}
1199
1200 void
1201mch_init()
1202{
1203 Columns = 80;
1204 Rows = 24;
1205
1206 out_flush();
1207 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001208
Bram Moolenaar56718732006-03-15 22:53:57 +00001209#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001210 mac_conv_init();
1211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212}
1213
1214 static void
1215set_signals()
1216{
1217#if defined(SIGWINCH)
1218 /*
1219 * WINDOW CHANGE signal is handled with sig_winch().
1220 */
1221 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1222#endif
1223
1224 /*
1225 * We want the STOP signal to work, to make mch_suspend() work.
1226 * For "rvim" the STOP signal is ignored.
1227 */
1228#ifdef SIGTSTP
1229 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1230#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001231#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 signal(SIGCONT, sigcont_handler);
1233#endif
1234
1235 /*
1236 * We want to ignore breaking of PIPEs.
1237 */
1238#ifdef SIGPIPE
1239 signal(SIGPIPE, SIG_IGN);
1240#endif
1241
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001243 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244#endif
1245
1246 /*
1247 * Ignore alarm signals (Perl's alarm() generates it).
1248 */
1249#ifdef SIGALRM
1250 signal(SIGALRM, SIG_IGN);
1251#endif
1252
1253 /*
1254 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1255 * work will be lost.
1256 */
1257#ifdef SIGPWR
1258 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1259#endif
1260
1261 /*
1262 * Arrange for other signals to gracefully shutdown Vim.
1263 */
1264 catch_signals(deathtrap, SIG_ERR);
1265
1266#if defined(FEAT_GUI) && defined(SIGHUP)
1267 /*
1268 * When the GUI is running, ignore the hangup signal.
1269 */
1270 if (gui.in_use)
1271 signal(SIGHUP, SIG_IGN);
1272#endif
1273}
1274
Bram Moolenaardf177f62005-02-22 08:39:57 +00001275#if defined(SIGINT) || defined(PROTO)
1276/*
1277 * Catch CTRL-C (only works while in Cooked mode).
1278 */
1279 static void
1280catch_int_signal()
1281{
1282 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1283}
1284#endif
1285
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 void
1287reset_signals()
1288{
1289 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001290#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291 /* SIGCONT isn't in the list, because its default action is ignore */
1292 signal(SIGCONT, SIG_DFL);
1293#endif
1294}
1295
1296 static void
1297catch_signals(func_deadly, func_other)
1298 RETSIGTYPE (*func_deadly)();
1299 RETSIGTYPE (*func_other)();
1300{
1301 int i;
1302
1303 for (i = 0; signal_info[i].sig != -1; i++)
1304 if (signal_info[i].deadly)
1305 {
1306#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1307 struct sigaction sa;
1308
1309 /* Setup to use the alternate stack for the signal function. */
1310 sa.sa_handler = func_deadly;
1311 sigemptyset(&sa.sa_mask);
1312# if defined(__linux__) && defined(_REENTRANT)
1313 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1314 * thread handling in combination with using the alternate stack:
1315 * pthread library functions try to use the stack pointer to
1316 * identify the current thread, causing a SEGV signal, which
1317 * recursively calls deathtrap() and hangs. */
1318 sa.sa_flags = 0;
1319# else
1320 sa.sa_flags = SA_ONSTACK;
1321# endif
1322 sigaction(signal_info[i].sig, &sa, NULL);
1323#else
1324# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1325 struct sigvec sv;
1326
1327 /* Setup to use the alternate stack for the signal function. */
1328 sv.sv_handler = func_deadly;
1329 sv.sv_mask = 0;
1330 sv.sv_flags = SV_ONSTACK;
1331 sigvec(signal_info[i].sig, &sv, NULL);
1332# else
1333 signal(signal_info[i].sig, func_deadly);
1334# endif
1335#endif
1336 }
1337 else if (func_other != SIG_ERR)
1338 signal(signal_info[i].sig, func_other);
1339}
1340
1341/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001342 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001343 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1344 * return TRUE
1345 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1346 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001347 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001348 * Returns TRUE when Vim should exit.
1349 */
1350 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001351vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001352 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001353{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001354 static int got_signal = 0;
1355 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001356
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001357 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001358 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001359 case SIGNAL_BLOCK: blocked = TRUE;
1360 break;
1361
1362 case SIGNAL_UNBLOCK: blocked = FALSE;
1363 if (got_signal != 0)
1364 {
1365 kill(getpid(), got_signal);
1366 got_signal = 0;
1367 }
1368 break;
1369
1370 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001371 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001372 got_signal = sig;
1373#ifdef SIGPWR
1374 if (sig != SIGPWR)
1375#endif
1376 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001377 break;
1378 }
1379 return FALSE;
1380}
1381
1382/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383 * Check_win checks whether we have an interactive stdout.
1384 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385 int
1386mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001387 int argc UNUSED;
1388 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389{
1390#ifdef OS2
1391 /*
1392 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1393 * name, mostly it's just "vim" and found in the path, which is unusable.
1394 */
1395 if (mch_isFullName(argv[0]))
1396 exe_name = vim_strsave((char_u *)argv[0]);
1397#endif
1398 if (isatty(1))
1399 return OK;
1400 return FAIL;
1401}
1402
1403/*
1404 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1405 */
1406 int
1407mch_input_isatty()
1408{
1409 if (isatty(read_cmd_fd))
1410 return TRUE;
1411 return FALSE;
1412}
1413
1414#ifdef FEAT_X11
1415
1416# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1417 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1418
1419static void xopen_message __ARGS((struct timeval *tvp));
1420
1421/*
1422 * Give a message about the elapsed time for opening the X window.
1423 */
1424 static void
1425xopen_message(tvp)
1426 struct timeval *tvp; /* must contain start time */
1427{
1428 struct timeval end_tv;
1429
1430 /* Compute elapsed time. */
1431 gettimeofday(&end_tv, NULL);
1432 smsg((char_u *)_("Opening the X display took %ld msec"),
1433 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001434 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435}
1436# endif
1437#endif
1438
1439#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1440/*
1441 * A few functions shared by X11 title and clipboard code.
1442 */
1443static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1444static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1445static int x_connect_to_server __ARGS((void));
1446static int test_x11_window __ARGS((Display *dpy));
1447
1448static int got_x_error = FALSE;
1449
1450/*
1451 * X Error handler, otherwise X just exits! (very rude) -- webb
1452 */
1453 static int
1454x_error_handler(dpy, error_event)
1455 Display *dpy;
1456 XErrorEvent *error_event;
1457{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001458 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 STRCAT(IObuff, _("\nVim: Got X error\n"));
1460
1461 /* We cannot print a message and continue, because no X calls are allowed
1462 * here (causes my system to hang). Silently continuing might be an
1463 * alternative... */
1464 preserve_exit(); /* preserve files and exit */
1465
1466 return 0; /* NOTREACHED */
1467}
1468
1469/*
1470 * Another X Error handler, just used to check for errors.
1471 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 static int
1473x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001474 Display *dpy UNUSED;
1475 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476{
1477 got_x_error = TRUE;
1478 return 0;
1479}
1480
1481#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1482# if defined(HAVE_SETJMP_H)
1483/*
1484 * An X IO Error handler, used to catch error while opening the display.
1485 */
1486static int x_IOerror_check __ARGS((Display *dpy));
1487
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 static int
1489x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001490 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491{
1492 /* This function should not return, it causes exit(). Longjump instead. */
1493 LONGJMP(lc_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001494# ifdef VMS
1495 return 0; /* avoid the compiler complains about missing return value */
1496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497}
1498# endif
1499
1500/*
1501 * An X IO Error handler, used to catch terminal errors.
1502 */
1503static int x_IOerror_handler __ARGS((Display *dpy));
1504
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505 static int
1506x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001507 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508{
1509 xterm_dpy = NULL;
1510 x11_window = 0;
1511 x11_display = NULL;
1512 xterm_Shell = (Widget)0;
1513
1514 /* This function should not return, it causes exit(). Longjump instead. */
1515 LONGJMP(x_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001516# ifdef VMS
1517 return 0; /* avoid the compiler complains about missing return value */
1518# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519}
1520#endif
1521
1522/*
1523 * Return TRUE when connection to the X server is desired.
1524 */
1525 static int
1526x_connect_to_server()
1527{
1528 regmatch_T regmatch;
1529
1530#if defined(FEAT_CLIENTSERVER)
1531 if (x_force_connect)
1532 return TRUE;
1533#endif
1534 if (x_no_connect)
1535 return FALSE;
1536
1537 /* Check for a match with "exclude:" from 'clipboard'. */
1538 if (clip_exclude_prog != NULL)
1539 {
1540 regmatch.rm_ic = FALSE; /* Don't ignore case */
1541 regmatch.regprog = clip_exclude_prog;
1542 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1543 return FALSE;
1544 }
1545 return TRUE;
1546}
1547
1548/*
1549 * Test if "dpy" and x11_window are valid by getting the window title.
1550 * I don't actually want it yet, so there may be a simpler call to use, but
1551 * this will cause the error handler x_error_check() to be called if anything
1552 * is wrong, such as the window pointer being invalid (as can happen when the
1553 * user changes his DISPLAY, but not his WINDOWID) -- webb
1554 */
1555 static int
1556test_x11_window(dpy)
1557 Display *dpy;
1558{
1559 int (*old_handler)();
1560 XTextProperty text_prop;
1561
1562 old_handler = XSetErrorHandler(x_error_check);
1563 got_x_error = FALSE;
1564 if (XGetWMName(dpy, x11_window, &text_prop))
1565 XFree((void *)text_prop.value);
1566 XSync(dpy, False);
1567 (void)XSetErrorHandler(old_handler);
1568
1569 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001570 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571
1572 return (got_x_error ? FAIL : OK);
1573}
1574#endif
1575
1576#ifdef FEAT_TITLE
1577
1578#ifdef FEAT_X11
1579
1580static int get_x11_thing __ARGS((int get_title, int test_only));
1581
1582/*
1583 * try to get x11 window and display
1584 *
1585 * return FAIL for failure, OK otherwise
1586 */
1587 static int
1588get_x11_windis()
1589{
1590 char *winid;
1591 static int result = -1;
1592#define XD_NONE 0 /* x11_display not set here */
1593#define XD_HERE 1 /* x11_display opened here */
1594#define XD_GUI 2 /* x11_display used from gui.dpy */
1595#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1596 static int x11_display_from = XD_NONE;
1597 static int did_set_error_handler = FALSE;
1598
1599 if (!did_set_error_handler)
1600 {
1601 /* X just exits if it finds an error otherwise! */
1602 (void)XSetErrorHandler(x_error_handler);
1603 did_set_error_handler = TRUE;
1604 }
1605
Bram Moolenaar9372a112005-12-06 19:59:18 +00001606#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if (gui.in_use)
1608 {
1609 /*
1610 * If the X11 display was opened here before, for the window where Vim
1611 * was started, close that one now to avoid a memory leak.
1612 */
1613 if (x11_display_from == XD_HERE && x11_display != NULL)
1614 {
1615 XCloseDisplay(x11_display);
1616 x11_display_from = XD_NONE;
1617 }
1618 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1619 {
1620 x11_display_from = XD_GUI;
1621 return OK;
1622 }
1623 x11_display = NULL;
1624 return FAIL;
1625 }
1626 else if (x11_display_from == XD_GUI)
1627 {
1628 /* GUI must have stopped somehow, clear x11_display */
1629 x11_window = 0;
1630 x11_display = NULL;
1631 x11_display_from = XD_NONE;
1632 }
1633#endif
1634
1635 /* When started with the "-X" argument, don't try connecting. */
1636 if (!x_connect_to_server())
1637 return FAIL;
1638
1639 /*
1640 * If WINDOWID not set, should try another method to find out
1641 * what the current window number is. The only code I know for
1642 * this is very complicated.
1643 * We assume that zero is invalid for WINDOWID.
1644 */
1645 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1646 x11_window = (Window)atol(winid);
1647
1648#ifdef FEAT_XCLIPBOARD
1649 if (xterm_dpy != NULL && x11_window != 0)
1650 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001651 /* We may have checked it already, but Gnome terminal can move us to
1652 * another window, so we need to check every time. */
1653 if (x11_display_from != XD_XTERM)
1654 {
1655 /*
1656 * If the X11 display was opened here before, for the window where
1657 * Vim was started, close that one now to avoid a memory leak.
1658 */
1659 if (x11_display_from == XD_HERE && x11_display != NULL)
1660 XCloseDisplay(x11_display);
1661 x11_display = xterm_dpy;
1662 x11_display_from = XD_XTERM;
1663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 if (test_x11_window(x11_display) == FAIL)
1665 {
1666 /* probably bad $WINDOWID */
1667 x11_window = 0;
1668 x11_display = NULL;
1669 x11_display_from = XD_NONE;
1670 return FAIL;
1671 }
1672 return OK;
1673 }
1674#endif
1675
1676 if (x11_window == 0 || x11_display == NULL)
1677 result = -1;
1678
1679 if (result != -1) /* Have already been here and set this */
1680 return result; /* Don't do all these X calls again */
1681
1682 if (x11_window != 0 && x11_display == NULL)
1683 {
1684#ifdef SET_SIG_ALARM
1685 RETSIGTYPE (*sig_save)();
1686#endif
1687#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1688 struct timeval start_tv;
1689
1690 if (p_verbose > 0)
1691 gettimeofday(&start_tv, NULL);
1692#endif
1693
1694#ifdef SET_SIG_ALARM
1695 /*
1696 * Opening the Display may hang if the DISPLAY setting is wrong, or
1697 * the network connection is bad. Set an alarm timer to get out.
1698 */
1699 sig_alarm_called = FALSE;
1700 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1701 (RETSIGTYPE (*)())sig_alarm);
1702 alarm(2);
1703#endif
1704 x11_display = XOpenDisplay(NULL);
1705
1706#ifdef SET_SIG_ALARM
1707 alarm(0);
1708 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1709 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001710 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711#endif
1712 if (x11_display != NULL)
1713 {
1714# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1715 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001716 {
1717 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001719 verbose_leave();
1720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721# endif
1722 if (test_x11_window(x11_display) == FAIL)
1723 {
1724 /* Maybe window id is bad */
1725 x11_window = 0;
1726 XCloseDisplay(x11_display);
1727 x11_display = NULL;
1728 }
1729 else
1730 x11_display_from = XD_HERE;
1731 }
1732 }
1733 if (x11_window == 0 || x11_display == NULL)
1734 return (result = FAIL);
1735 return (result = OK);
1736}
1737
1738/*
1739 * Determine original x11 Window Title
1740 */
1741 static int
1742get_x11_title(test_only)
1743 int test_only;
1744{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001745 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746}
1747
1748/*
1749 * Determine original x11 Window icon
1750 */
1751 static int
1752get_x11_icon(test_only)
1753 int test_only;
1754{
1755 int retval = FALSE;
1756
1757 retval = get_x11_thing(FALSE, test_only);
1758
1759 /* could not get old icon, use terminal name */
1760 if (oldicon == NULL && !test_only)
1761 {
1762 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001763 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001765 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766 }
1767
1768 return retval;
1769}
1770
1771 static int
1772get_x11_thing(get_title, test_only)
1773 int get_title; /* get title string */
1774 int test_only;
1775{
1776 XTextProperty text_prop;
1777 int retval = FALSE;
1778 Status status;
1779
1780 if (get_x11_windis() == OK)
1781 {
1782 /* Get window/icon name if any */
1783 if (get_title)
1784 status = XGetWMName(x11_display, x11_window, &text_prop);
1785 else
1786 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1787
1788 /*
1789 * If terminal is xterm, then x11_window may be a child window of the
1790 * outer xterm window that actually contains the window/icon name, so
1791 * keep traversing up the tree until a window with a title/icon is
1792 * found.
1793 */
1794 /* Previously this was only done for xterm and alikes. I don't see a
1795 * reason why it would fail for other terminal emulators.
1796 * if (term_is_xterm) */
1797 {
1798 Window root;
1799 Window parent;
1800 Window win = x11_window;
1801 Window *children;
1802 unsigned int num_children;
1803
1804 while (!status || text_prop.value == NULL)
1805 {
1806 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1807 &num_children))
1808 break;
1809 if (children)
1810 XFree((void *)children);
1811 if (parent == root || parent == 0)
1812 break;
1813
1814 win = parent;
1815 if (get_title)
1816 status = XGetWMName(x11_display, win, &text_prop);
1817 else
1818 status = XGetWMIconName(x11_display, win, &text_prop);
1819 }
1820 }
1821 if (status && text_prop.value != NULL)
1822 {
1823 retval = TRUE;
1824 if (!test_only)
1825 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001826#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1827 if (text_prop.encoding == XA_STRING
1828# ifdef FEAT_MBYTE
1829 && !has_mbyte
1830# endif
1831 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 {
1833#endif
1834 if (get_title)
1835 oldtitle = vim_strsave((char_u *)text_prop.value);
1836 else
1837 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001838#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 }
1840 else
1841 {
1842 char **cl;
1843 Status transform_status;
1844 int n = 0;
1845
1846 transform_status = XmbTextPropertyToTextList(x11_display,
1847 &text_prop,
1848 &cl, &n);
1849 if (transform_status >= Success && n > 0 && cl[0])
1850 {
1851 if (get_title)
1852 oldtitle = vim_strsave((char_u *) cl[0]);
1853 else
1854 oldicon = vim_strsave((char_u *) cl[0]);
1855 XFreeStringList(cl);
1856 }
1857 else
1858 {
1859 if (get_title)
1860 oldtitle = vim_strsave((char_u *)text_prop.value);
1861 else
1862 oldicon = vim_strsave((char_u *)text_prop.value);
1863 }
1864 }
1865#endif
1866 }
1867 XFree((void *)text_prop.value);
1868 }
1869 }
1870 return retval;
1871}
1872
1873/* Are Xutf8 functions available? Avoid error from old compilers. */
1874#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1875# if X_HAVE_UTF8_STRING
1876# define USE_UTF8_STRING
1877# endif
1878#endif
1879
1880/*
1881 * Set x11 Window Title
1882 *
1883 * get_x11_windis() must be called before this and have returned OK
1884 */
1885 static void
1886set_x11_title(title)
1887 char_u *title;
1888{
1889 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1890 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1891 * supported everywhere and STRING doesn't work for multi-byte titles.
1892 */
1893#ifdef USE_UTF8_STRING
1894 if (enc_utf8)
1895 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1896 NULL, NULL, 0, NULL, NULL, NULL);
1897 else
1898#endif
1899 {
1900#if XtSpecificationRelease >= 4
1901# ifdef FEAT_XFONTSET
1902 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1903 NULL, NULL, 0, NULL, NULL, NULL);
1904# else
1905 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001906 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907
1908 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001909 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 XSetWMProperties(x11_display, x11_window, &text_prop,
1911 NULL, NULL, 0, NULL, NULL, NULL);
1912# endif
1913#else
1914 XStoreName(x11_display, x11_window, (char *)title);
1915#endif
1916 }
1917 XFlush(x11_display);
1918}
1919
1920/*
1921 * Set x11 Window icon
1922 *
1923 * get_x11_windis() must be called before this and have returned OK
1924 */
1925 static void
1926set_x11_icon(icon)
1927 char_u *icon;
1928{
1929 /* See above for comments about using X*SetWMProperties(). */
1930#ifdef USE_UTF8_STRING
1931 if (enc_utf8)
1932 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1933 NULL, 0, NULL, NULL, NULL);
1934 else
1935#endif
1936 {
1937#if XtSpecificationRelease >= 4
1938# ifdef FEAT_XFONTSET
1939 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1940 NULL, 0, NULL, NULL, NULL);
1941# else
1942 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001943 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001945 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1947 NULL, 0, NULL, NULL, NULL);
1948# endif
1949#else
1950 XSetIconName(x11_display, x11_window, (char *)icon);
1951#endif
1952 }
1953 XFlush(x11_display);
1954}
1955
1956#else /* FEAT_X11 */
1957
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 static int
1959get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001960 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961{
1962 return FALSE;
1963}
1964
1965 static int
1966get_x11_icon(test_only)
1967 int test_only;
1968{
1969 if (!test_only)
1970 {
1971 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001972 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001974 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
1976 return FALSE;
1977}
1978
1979#endif /* FEAT_X11 */
1980
1981 int
1982mch_can_restore_title()
1983{
1984 return get_x11_title(TRUE);
1985}
1986
1987 int
1988mch_can_restore_icon()
1989{
1990 return get_x11_icon(TRUE);
1991}
1992
1993/*
1994 * Set the window title and icon.
1995 */
1996 void
1997mch_settitle(title, icon)
1998 char_u *title;
1999 char_u *icon;
2000{
2001 int type = 0;
2002 static int recursive = 0;
2003
2004 if (T_NAME == NULL) /* no terminal name (yet) */
2005 return;
2006 if (title == NULL && icon == NULL) /* nothing to do */
2007 return;
2008
2009 /* When one of the X11 functions causes a deadly signal, we get here again
2010 * recursively. Avoid hanging then (something is probably locked). */
2011 if (recursive)
2012 return;
2013 ++recursive;
2014
2015 /*
2016 * if the window ID and the display is known, we may use X11 calls
2017 */
2018#ifdef FEAT_X11
2019 if (get_x11_windis() == OK)
2020 type = 1;
2021#else
2022# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2023 if (gui.in_use)
2024 type = 1;
2025# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026#endif
2027
2028 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002029 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 * than x11 calls, because the x11 calls don't always work
2031 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 if ((type || *T_TS != NUL) && title != NULL)
2033 {
2034 if (oldtitle == NULL
2035#ifdef FEAT_GUI
2036 && !gui.in_use
2037#endif
2038 ) /* first call but not in GUI, save title */
2039 (void)get_x11_title(FALSE);
2040
2041 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2042 term_settitle(title);
2043#ifdef FEAT_X11
2044 else
2045# ifdef FEAT_GUI_GTK
2046 if (!gui.in_use) /* don't do this if GTK+ is running */
2047# endif
2048 set_x11_title(title); /* x11 */
2049#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002050#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2052 else
2053 gui_mch_settitle(title, icon);
2054#endif
2055 did_set_title = TRUE;
2056 }
2057
2058 if ((type || *T_CIS != NUL) && icon != NULL)
2059 {
2060 if (oldicon == NULL
2061#ifdef FEAT_GUI
2062 && !gui.in_use
2063#endif
2064 ) /* first call, save icon */
2065 get_x11_icon(FALSE);
2066
2067 if (*T_CIS != NUL)
2068 {
2069 out_str(T_CIS); /* set icon start */
2070 out_str_nf(icon);
2071 out_str(T_CIE); /* set icon end */
2072 out_flush();
2073 }
2074#ifdef FEAT_X11
2075 else
2076# ifdef FEAT_GUI_GTK
2077 if (!gui.in_use) /* don't do this if GTK+ is running */
2078# endif
2079 set_x11_icon(icon); /* x11 */
2080#endif
2081 did_set_icon = TRUE;
2082 }
2083 --recursive;
2084}
2085
2086/*
2087 * Restore the window/icon title.
2088 * "which" is one of:
2089 * 1 only restore title
2090 * 2 only restore icon
2091 * 3 restore title and icon
2092 */
2093 void
2094mch_restore_title(which)
2095 int which;
2096{
2097 /* only restore the title or icon when it has been set */
2098 mch_settitle(((which & 1) && did_set_title) ?
2099 (oldtitle ? oldtitle : p_titleold) : NULL,
2100 ((which & 2) && did_set_icon) ? oldicon : NULL);
2101}
2102
2103#endif /* FEAT_TITLE */
2104
2105/*
2106 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002107 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 */
2109 int
2110vim_is_xterm(name)
2111 char_u *name;
2112{
2113 if (name == NULL)
2114 return FALSE;
2115 return (STRNICMP(name, "xterm", 5) == 0
2116 || STRNICMP(name, "nxterm", 6) == 0
2117 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002118 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 || STRNICMP(name, "rxvt", 4) == 0
2120 || STRCMP(name, "builtin_xterm") == 0);
2121}
2122
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002123#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2124/*
2125 * Return TRUE if "name" appears to be that of a terminal
2126 * known to support the xterm-style mouse protocol.
2127 * Relies on term_is_xterm having been set to its correct value.
2128 */
2129 int
2130use_xterm_like_mouse(name)
2131 char_u *name;
2132{
2133 return (name != NULL
2134 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2135}
2136#endif
2137
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2139/*
2140 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2141 * Return 1 for "xterm".
2142 * Return 2 for "xterm2".
2143 */
2144 int
2145use_xterm_mouse()
2146{
2147 if (ttym_flags == TTYM_XTERM2)
2148 return 2;
2149 if (ttym_flags == TTYM_XTERM)
2150 return 1;
2151 return 0;
2152}
2153#endif
2154
2155 int
2156vim_is_iris(name)
2157 char_u *name;
2158{
2159 if (name == NULL)
2160 return FALSE;
2161 return (STRNICMP(name, "iris-ansi", 9) == 0
2162 || STRCMP(name, "builtin_iris-ansi") == 0);
2163}
2164
2165 int
2166vim_is_vt300(name)
2167 char_u *name;
2168{
2169 if (name == NULL)
2170 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002171 /* catch VT100 - VT5xx */
2172 return ((STRNICMP(name, "vt", 2) == 0
2173 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 || STRCMP(name, "builtin_vt320") == 0);
2175}
2176
2177/*
2178 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2179 * This should include all windowed terminal emulators.
2180 */
2181 int
2182vim_is_fastterm(name)
2183 char_u *name;
2184{
2185 if (name == NULL)
2186 return FALSE;
2187 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2188 return TRUE;
2189 return ( STRNICMP(name, "hpterm", 6) == 0
2190 || STRNICMP(name, "sun-cmd", 7) == 0
2191 || STRNICMP(name, "screen", 6) == 0
2192 || STRNICMP(name, "dtterm", 6) == 0);
2193}
2194
2195/*
2196 * Insert user name in s[len].
2197 * Return OK if a name found.
2198 */
2199 int
2200mch_get_user_name(s, len)
2201 char_u *s;
2202 int len;
2203{
2204#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002205 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 return OK;
2207#else
2208 return mch_get_uname(getuid(), s, len);
2209#endif
2210}
2211
2212/*
2213 * Insert user name for "uid" in s[len].
2214 * Return OK if a name found.
2215 */
2216 int
2217mch_get_uname(uid, s, len)
2218 uid_t uid;
2219 char_u *s;
2220 int len;
2221{
2222#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2223 struct passwd *pw;
2224
2225 if ((pw = getpwuid(uid)) != NULL
2226 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2227 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002228 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 return OK;
2230 }
2231#endif
2232 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2233 return FAIL; /* a number is not a name */
2234}
2235
2236/*
2237 * Insert host name is s[len].
2238 */
2239
2240#ifdef HAVE_SYS_UTSNAME_H
2241 void
2242mch_get_host_name(s, len)
2243 char_u *s;
2244 int len;
2245{
2246 struct utsname vutsname;
2247
2248 if (uname(&vutsname) < 0)
2249 *s = NUL;
2250 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002251 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252}
2253#else /* HAVE_SYS_UTSNAME_H */
2254
2255# ifdef HAVE_SYS_SYSTEMINFO_H
2256# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2257# endif
2258
2259 void
2260mch_get_host_name(s, len)
2261 char_u *s;
2262 int len;
2263{
2264# ifdef VAXC
2265 vaxc$gethostname((char *)s, len);
2266# else
2267 gethostname((char *)s, len);
2268# endif
2269 s[len - 1] = NUL; /* make sure it's terminated */
2270}
2271#endif /* HAVE_SYS_UTSNAME_H */
2272
2273/*
2274 * return process ID
2275 */
2276 long
2277mch_get_pid()
2278{
2279 return (long)getpid();
2280}
2281
2282#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2283static char *strerror __ARGS((int));
2284
2285 static char *
2286strerror(err)
2287 int err;
2288{
2289 extern int sys_nerr;
2290 extern char *sys_errlist[];
2291 static char er[20];
2292
2293 if (err > 0 && err < sys_nerr)
2294 return (sys_errlist[err]);
2295 sprintf(er, "Error %d", err);
2296 return er;
2297}
2298#endif
2299
2300/*
2301 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2302 * Return OK for success, FAIL for failure.
2303 */
2304 int
2305mch_dirname(buf, len)
2306 char_u *buf;
2307 int len;
2308{
2309#if defined(USE_GETCWD)
2310 if (getcwd((char *)buf, len) == NULL)
2311 {
2312 STRCPY(buf, strerror(errno));
2313 return FAIL;
2314 }
2315 return OK;
2316#else
2317 return (getwd((char *)buf) != NULL ? OK : FAIL);
2318#endif
2319}
2320
2321#if defined(OS2) || defined(PROTO)
2322/*
2323 * Replace all slashes by backslashes.
2324 * When 'shellslash' set do it the other way around.
2325 */
2326 void
2327slash_adjust(p)
2328 char_u *p;
2329{
2330 while (*p)
2331 {
2332 if (*p == psepcN)
2333 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002334 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 }
2336}
2337#endif
2338
2339/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002340 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 *
2342 * return FAIL for failure, OK for success
2343 */
2344 int
2345mch_FullName(fname, buf, len, force)
2346 char_u *fname, *buf;
2347 int len;
2348 int force; /* also expand when already absolute path */
2349{
2350 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002351#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002353#endif
2354#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 int fd = -1;
2356 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002357#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 char_u olddir[MAXPATHL];
2359 char_u *p;
2360 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002361#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002362 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2363 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002364#endif
2365
Bram Moolenaar38323e42007-03-06 19:22:53 +00002366#ifdef VMS
2367 fname = vms_fixfilename(fname);
2368#endif
2369
Bram Moolenaara2442432007-04-26 14:26:37 +00002370#ifdef __CYGWIN__
2371 /*
2372 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2373 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002374# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2375 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2376# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002377 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002378# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002379 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002380#endif
2381
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 /* expand it if forced or not an absolute path */
2383 if (force || !mch_isFullName(fname))
2384 {
2385 /*
2386 * If the file name has a path, change to that directory for a moment,
2387 * and then do the getwd() (and get back to where we were).
2388 * This will get the correct path name with "../" things.
2389 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002390#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 only_drive = 0;
2392 if (((p = vim_strrchr(fname, '/')) != NULL)
2393 || ((p = vim_strrchr(fname, '\\')) != NULL)
2394 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002395#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002397#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002399#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 /*
2401 * Use fchdir() if possible, it's said to be faster and more
2402 * reliable. But on SunOS 4 it might not work. Check this by
2403 * doing a fchdir() right now.
2404 */
2405 if (!dont_fchdir)
2406 {
2407 fd = open(".", O_RDONLY | O_EXTRA, 0);
2408 if (fd >= 0 && fchdir(fd) < 0)
2409 {
2410 close(fd);
2411 fd = -1;
2412 dont_fchdir = TRUE; /* don't try again */
2413 }
2414 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416
2417 /* Only change directory when we are sure we can return to where
2418 * we are now. After doing "su" chdir(".") might not work. */
2419 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002420#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002422#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 (mch_dirname(olddir, MAXPATHL) == FAIL
2424 || mch_chdir((char *)olddir) != 0))
2425 {
2426 p = NULL; /* can't get current dir: don't chdir */
2427 retval = FAIL;
2428 }
2429 else
2430 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002431#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 /*
2433 * compensate for case where ':' from "D:" was the only
2434 * path separator detected in the file name; the _next_
2435 * character has to be removed, and then restored later.
2436 */
2437 if (only_drive)
2438 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002439#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 /* The directory is copied into buf[], to be able to remove
2441 * the file name without changing it (could be a string in
2442 * read-only memory) */
2443 if (p - fname >= len)
2444 retval = FAIL;
2445 else
2446 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002447 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 if (mch_chdir((char *)buf))
2449 retval = FAIL;
2450 else
2451 fname = p + 1;
2452 *buf = NUL;
2453 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002454#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (only_drive)
2456 {
2457 p--;
2458 if (retval != FAIL)
2459 fname--;
2460 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002461#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 }
2463 }
2464 if (mch_dirname(buf, len) == FAIL)
2465 {
2466 retval = FAIL;
2467 *buf = NUL;
2468 }
2469 if (p != NULL)
2470 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002471#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 if (fd >= 0)
2473 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002474 if (p_verbose >= 5)
2475 {
2476 verbose_enter();
2477 MSG("fchdir() to previous dir");
2478 verbose_leave();
2479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 l = fchdir(fd);
2481 close(fd);
2482 }
2483 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 l = mch_chdir((char *)olddir);
2486 if (l != 0)
2487 EMSG(_(e_prev_dir));
2488 }
2489
2490 l = STRLEN(buf);
2491 if (l >= len)
2492 retval = FAIL;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002493#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 else
2495 {
2496 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2497 && STRCMP(fname, ".") != 0)
2498 STRCAT(buf, "/");
2499 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002500#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002502
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002504 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505 return FAIL;
2506
2507 /* Do not append ".", "/dir/." is equal to "/dir". */
2508 if (STRCMP(fname, ".") != 0)
2509 STRCAT(buf, fname);
2510
2511 return OK;
2512}
2513
2514/*
2515 * Return TRUE if "fname" does not depend on the current directory.
2516 */
2517 int
2518mch_isFullName(fname)
2519 char_u *fname;
2520{
2521#ifdef __EMX__
2522 return _fnisabs(fname);
2523#else
2524# ifdef VMS
2525 return ( fname[0] == '/' || fname[0] == '.' ||
2526 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2527 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2528 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2529# else
2530 return (*fname == '/' || *fname == '~');
2531# endif
2532#endif
2533}
2534
Bram Moolenaar24552be2005-12-10 20:17:30 +00002535#if defined(USE_FNAME_CASE) || defined(PROTO)
2536/*
2537 * Set the case of the file name, if it already exists. This will cause the
2538 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002539 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002540 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002541 void
2542fname_case(name, len)
2543 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002544 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002545{
2546 struct stat st;
2547 char_u *slash, *tail;
2548 DIR *dirp;
2549 struct dirent *dp;
2550
2551 if (lstat((char *)name, &st) >= 0)
2552 {
2553 /* Open the directory where the file is located. */
2554 slash = vim_strrchr(name, '/');
2555 if (slash == NULL)
2556 {
2557 dirp = opendir(".");
2558 tail = name;
2559 }
2560 else
2561 {
2562 *slash = NUL;
2563 dirp = opendir((char *)name);
2564 *slash = '/';
2565 tail = slash + 1;
2566 }
2567
2568 if (dirp != NULL)
2569 {
2570 while ((dp = readdir(dirp)) != NULL)
2571 {
2572 /* Only accept names that differ in case and are the same byte
2573 * length. TODO: accept different length name. */
2574 if (STRICMP(tail, dp->d_name) == 0
2575 && STRLEN(tail) == STRLEN(dp->d_name))
2576 {
2577 char_u newname[MAXPATHL + 1];
2578 struct stat st2;
2579
2580 /* Verify the inode is equal. */
2581 vim_strncpy(newname, name, MAXPATHL);
2582 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2583 MAXPATHL - (tail - name));
2584 if (lstat((char *)newname, &st2) >= 0
2585 && st.st_ino == st2.st_ino
2586 && st.st_dev == st2.st_dev)
2587 {
2588 STRCPY(tail, dp->d_name);
2589 break;
2590 }
2591 }
2592 }
2593
2594 closedir(dirp);
2595 }
2596 }
2597}
2598#endif
2599
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600/*
2601 * Get file permissions for 'name'.
2602 * Returns -1 when it doesn't exist.
2603 */
2604 long
2605mch_getperm(name)
2606 char_u *name;
2607{
2608 struct stat statb;
2609
2610 /* Keep the #ifdef outside of stat(), it may be a macro. */
2611#ifdef VMS
2612 if (stat((char *)vms_fixfilename(name), &statb))
2613#else
2614 if (stat((char *)name, &statb))
2615#endif
2616 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002617#ifdef __INTERIX
2618 /* The top bit makes the value negative, which means the file doesn't
2619 * exist. Remove the bit, we don't use it. */
2620 return statb.st_mode & ~S_ADDACE;
2621#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002623#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624}
2625
2626/*
2627 * set file permission for 'name' to 'perm'
2628 *
2629 * return FAIL for failure, OK otherwise
2630 */
2631 int
2632mch_setperm(name, perm)
2633 char_u *name;
2634 long perm;
2635{
2636 return (chmod((char *)
2637#ifdef VMS
2638 vms_fixfilename(name),
2639#else
2640 name,
2641#endif
2642 (mode_t)perm) == 0 ? OK : FAIL);
2643}
2644
2645#if defined(HAVE_ACL) || defined(PROTO)
2646# ifdef HAVE_SYS_ACL_H
2647# include <sys/acl.h>
2648# endif
2649# ifdef HAVE_SYS_ACCESS_H
2650# include <sys/access.h>
2651# endif
2652
2653# ifdef HAVE_SOLARIS_ACL
2654typedef struct vim_acl_solaris_T {
2655 int acl_cnt;
2656 aclent_t *acl_entry;
2657} vim_acl_solaris_T;
2658# endif
2659
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002660#if defined(HAVE_SELINUX) || defined(PROTO)
2661/*
2662 * Copy security info from "from_file" to "to_file".
2663 */
2664 void
2665mch_copy_sec(from_file, to_file)
2666 char_u *from_file;
2667 char_u *to_file;
2668{
2669 if (from_file == NULL)
2670 return;
2671
2672 if (selinux_enabled == -1)
2673 selinux_enabled = is_selinux_enabled();
2674
2675 if (selinux_enabled > 0)
2676 {
2677 security_context_t from_context = NULL;
2678 security_context_t to_context = NULL;
2679
2680 if (getfilecon((char *)from_file, &from_context) < 0)
2681 {
2682 /* If the filesystem doesn't support extended attributes,
2683 the original had no special security context and the
2684 target cannot have one either. */
2685 if (errno == EOPNOTSUPP)
2686 return;
2687
2688 MSG_PUTS(_("\nCould not get security context for "));
2689 msg_outtrans(from_file);
2690 msg_putchar('\n');
2691 return;
2692 }
2693 if (getfilecon((char *)to_file, &to_context) < 0)
2694 {
2695 MSG_PUTS(_("\nCould not get security context for "));
2696 msg_outtrans(to_file);
2697 msg_putchar('\n');
2698 freecon (from_context);
2699 return ;
2700 }
2701 if (strcmp(from_context, to_context) != 0)
2702 {
2703 if (setfilecon((char *)to_file, from_context) < 0)
2704 {
2705 MSG_PUTS(_("\nCould not set security context for "));
2706 msg_outtrans(to_file);
2707 msg_putchar('\n');
2708 }
2709 }
2710 freecon(to_context);
2711 freecon(from_context);
2712 }
2713}
2714#endif /* HAVE_SELINUX */
2715
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716/*
2717 * Return a pointer to the ACL of file "fname" in allocated memory.
2718 * Return NULL if the ACL is not available for whatever reason.
2719 */
2720 vim_acl_T
2721mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002722 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723{
2724 vim_acl_T ret = NULL;
2725#ifdef HAVE_POSIX_ACL
2726 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2727#else
2728#ifdef HAVE_SOLARIS_ACL
2729 vim_acl_solaris_T *aclent;
2730
2731 aclent = malloc(sizeof(vim_acl_solaris_T));
2732 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2733 {
2734 free(aclent);
2735 return NULL;
2736 }
2737 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2738 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2739 {
2740 free(aclent->acl_entry);
2741 free(aclent);
2742 return NULL;
2743 }
2744 ret = (vim_acl_T)aclent;
2745#else
2746#if defined(HAVE_AIX_ACL)
2747 int aclsize;
2748 struct acl *aclent;
2749
2750 aclsize = sizeof(struct acl);
2751 aclent = malloc(aclsize);
2752 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2753 {
2754 if (errno == ENOSPC)
2755 {
2756 aclsize = aclent->acl_len;
2757 aclent = realloc(aclent, aclsize);
2758 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2759 {
2760 free(aclent);
2761 return NULL;
2762 }
2763 }
2764 else
2765 {
2766 free(aclent);
2767 return NULL;
2768 }
2769 }
2770 ret = (vim_acl_T)aclent;
2771#endif /* HAVE_AIX_ACL */
2772#endif /* HAVE_SOLARIS_ACL */
2773#endif /* HAVE_POSIX_ACL */
2774 return ret;
2775}
2776
2777/*
2778 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2779 */
2780 void
2781mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002782 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 vim_acl_T aclent;
2784{
2785 if (aclent == NULL)
2786 return;
2787#ifdef HAVE_POSIX_ACL
2788 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2789#else
2790#ifdef HAVE_SOLARIS_ACL
2791 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2792 ((vim_acl_solaris_T *)aclent)->acl_entry);
2793#else
2794#ifdef HAVE_AIX_ACL
2795 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2796#endif /* HAVE_AIX_ACL */
2797#endif /* HAVE_SOLARIS_ACL */
2798#endif /* HAVE_POSIX_ACL */
2799}
2800
2801 void
2802mch_free_acl(aclent)
2803 vim_acl_T aclent;
2804{
2805 if (aclent == NULL)
2806 return;
2807#ifdef HAVE_POSIX_ACL
2808 acl_free((acl_t)aclent);
2809#else
2810#ifdef HAVE_SOLARIS_ACL
2811 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2812 free(aclent);
2813#else
2814#ifdef HAVE_AIX_ACL
2815 free(aclent);
2816#endif /* HAVE_AIX_ACL */
2817#endif /* HAVE_SOLARIS_ACL */
2818#endif /* HAVE_POSIX_ACL */
2819}
2820#endif
2821
2822/*
2823 * Set hidden flag for "name".
2824 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825 void
2826mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002827 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828{
2829 /* can't hide a file */
2830}
2831
2832/*
2833 * return TRUE if "name" is a directory
2834 * return FALSE if "name" is not a directory
2835 * return FALSE for error
2836 */
2837 int
2838mch_isdir(name)
2839 char_u *name;
2840{
2841 struct stat statb;
2842
2843 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2844 return FALSE;
2845 if (stat((char *)name, &statb))
2846 return FALSE;
2847#ifdef _POSIX_SOURCE
2848 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2849#else
2850 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2851#endif
2852}
2853
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854static int executable_file __ARGS((char_u *name));
2855
2856/*
2857 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2858 */
2859 static int
2860executable_file(name)
2861 char_u *name;
2862{
2863 struct stat st;
2864
2865 if (stat((char *)name, &st))
2866 return 0;
2867 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2868}
2869
2870/*
2871 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2872 * Return -1 if unknown.
2873 */
2874 int
2875mch_can_exe(name)
2876 char_u *name;
2877{
2878 char_u *buf;
2879 char_u *p, *e;
2880 int retval;
2881
2882 /* If it's an absolute or relative path don't need to use $PATH. */
2883 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2884 || (name[1] == '.' && name[2] == '/'))))
2885 return executable_file(name);
2886
2887 p = (char_u *)getenv("PATH");
2888 if (p == NULL || *p == NUL)
2889 return -1;
2890 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2891 if (buf == NULL)
2892 return -1;
2893
2894 /*
2895 * Walk through all entries in $PATH to check if "name" exists there and
2896 * is an executable file.
2897 */
2898 for (;;)
2899 {
2900 e = (char_u *)strchr((char *)p, ':');
2901 if (e == NULL)
2902 e = p + STRLEN(p);
2903 if (e - p <= 1) /* empty entry means current dir */
2904 STRCPY(buf, "./");
2905 else
2906 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002907 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 add_pathsep(buf);
2909 }
2910 STRCAT(buf, name);
2911 retval = executable_file(buf);
2912 if (retval == 1)
2913 break;
2914
2915 if (*e != ':')
2916 break;
2917 p = e + 1;
2918 }
2919
2920 vim_free(buf);
2921 return retval;
2922}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924/*
2925 * Check what "name" is:
2926 * NODE_NORMAL: file or directory (or doesn't exist)
2927 * NODE_WRITABLE: writable device, socket, fifo, etc.
2928 * NODE_OTHER: non-writable things
2929 */
2930 int
2931mch_nodetype(name)
2932 char_u *name;
2933{
2934 struct stat st;
2935
2936 if (stat((char *)name, &st))
2937 return NODE_NORMAL;
2938 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2939 return NODE_NORMAL;
2940#ifndef OS2
2941 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2942 return NODE_OTHER;
2943#endif
2944 /* Everything else is writable? */
2945 return NODE_WRITABLE;
2946}
2947
2948 void
2949mch_early_init()
2950{
2951#ifdef HAVE_CHECK_STACK_GROWTH
2952 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 check_stack_growth((char *)&i);
2955
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002956# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 get_stack_limit();
2958# endif
2959
2960#endif
2961
2962 /*
2963 * Setup an alternative stack for signals. Helps to catch signals when
2964 * running out of stack space.
2965 * Use of sigaltstack() is preferred, it's more portable.
2966 * Ignore any errors.
2967 */
2968#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00002969 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 init_signal_stack();
2971#endif
2972}
2973
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002974#if defined(EXITFREE) || defined(PROTO)
2975 void
2976mch_free_mem()
2977{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00002978# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2979 if (clip_star.owned)
2980 clip_lose_selection(&clip_star);
2981 if (clip_plus.owned)
2982 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002983# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00002984# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002985 if (xterm_Shell != (Widget)0)
2986 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00002987# ifndef LESSTIF_VERSION
2988 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002989 if (xterm_dpy != NULL)
2990 XtCloseDisplay(xterm_dpy);
2991 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00002992 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002993 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00002994# ifdef FEAT_X11
2995 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
2996# endif
2997 }
2998# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002999# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003000# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003001 if (x11_display != NULL
3002# ifdef FEAT_XCLIPBOARD
3003 && x11_display != xterm_dpy
3004# endif
3005 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003006 XCloseDisplay(x11_display);
3007# endif
3008# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3009 vim_free(signal_stack);
3010 signal_stack = NULL;
3011# endif
3012# ifdef FEAT_TITLE
3013 vim_free(oldtitle);
3014 vim_free(oldicon);
3015# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003016}
3017#endif
3018
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019static void exit_scroll __ARGS((void));
3020
3021/*
3022 * Output a newline when exiting.
3023 * Make sure the newline goes to the same stream as the text.
3024 */
3025 static void
3026exit_scroll()
3027{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003028 if (silent_mode)
3029 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 if (newline_on_exit || msg_didout)
3031 {
3032 if (msg_use_printf())
3033 {
3034 if (info_message)
3035 mch_msg("\n");
3036 else
3037 mch_errmsg("\r\n");
3038 }
3039 else
3040 out_char('\n');
3041 }
3042 else
3043 {
3044 restore_cterm_colors(); /* get original colors back */
3045 msg_clr_eos_force(); /* clear the rest of the display */
3046 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3047 }
3048}
3049
3050 void
3051mch_exit(r)
3052 int r;
3053{
3054 exiting = TRUE;
3055
3056#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3057 x11_export_final_selection();
3058#endif
3059
3060#ifdef FEAT_GUI
3061 if (!gui.in_use)
3062#endif
3063 {
3064 settmode(TMODE_COOK);
3065#ifdef FEAT_TITLE
3066 mch_restore_title(3); /* restore xterm title and icon name */
3067#endif
3068 /*
3069 * When t_ti is not empty but it doesn't cause swapping terminal
3070 * pages, need to output a newline when msg_didout is set. But when
3071 * t_ti does swap pages it should not go to the shell page. Do this
3072 * before stoptermcap().
3073 */
3074 if (swapping_screen() && !newline_on_exit)
3075 exit_scroll();
3076
3077 /* Stop termcap: May need to check for T_CRV response, which
3078 * requires RAW mode. */
3079 stoptermcap();
3080
3081 /*
3082 * A newline is only required after a message in the alternate screen.
3083 * This is set to TRUE by wait_return().
3084 */
3085 if (!swapping_screen() || newline_on_exit)
3086 exit_scroll();
3087
3088 /* Cursor may have been switched off without calling starttermcap()
3089 * when doing "vim -u vimrc" and vimrc contains ":q". */
3090 if (full_screen)
3091 cursor_on();
3092 }
3093 out_flush();
3094 ml_close_all(TRUE); /* remove all memfiles */
3095 may_core_dump();
3096#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 gui_exit(r);
3099#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003100
Bram Moolenaar56718732006-03-15 22:53:57 +00003101#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003102 mac_conv_cleanup();
3103#endif
3104
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105#ifdef __QNX__
3106 /* A core dump won't be created if the signal handler
3107 * doesn't return, so we can't call exit() */
3108 if (deadly_signal != 0)
3109 return;
3110#endif
3111
Bram Moolenaar009b2592004-10-24 19:18:58 +00003112#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003113 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003114#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003115
3116#ifdef EXITFREE
3117 free_all_mem();
3118#endif
3119
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 exit(r);
3121}
3122
3123 static void
3124may_core_dump()
3125{
3126 if (deadly_signal != 0)
3127 {
3128 signal(deadly_signal, SIG_DFL);
3129 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3130 }
3131}
3132
3133#ifndef VMS
3134
3135 void
3136mch_settmode(tmode)
3137 int tmode;
3138{
3139 static int first = TRUE;
3140
3141 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3142#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3143 /*
3144 * for "new" tty systems
3145 */
3146# ifdef HAVE_TERMIOS_H
3147 static struct termios told;
3148 struct termios tnew;
3149# else
3150 static struct termio told;
3151 struct termio tnew;
3152# endif
3153
3154 if (first)
3155 {
3156 first = FALSE;
3157# if defined(HAVE_TERMIOS_H)
3158 tcgetattr(read_cmd_fd, &told);
3159# else
3160 ioctl(read_cmd_fd, TCGETA, &told);
3161# endif
3162 }
3163
3164 tnew = told;
3165 if (tmode == TMODE_RAW)
3166 {
3167 /*
3168 * ~ICRNL enables typing ^V^M
3169 */
3170 tnew.c_iflag &= ~ICRNL;
3171 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3172# if defined(IEXTEN) && !defined(__MINT__)
3173 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3174 /* but it breaks function keys on MINT */
3175# endif
3176 );
3177# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3178 tnew.c_oflag &= ~ONLCR;
3179# endif
3180 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3181 tnew.c_cc[VTIME] = 0; /* don't wait */
3182 }
3183 else if (tmode == TMODE_SLEEP)
3184 tnew.c_lflag &= ~(ECHO);
3185
3186# if defined(HAVE_TERMIOS_H)
3187 {
3188 int n = 10;
3189
3190 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3191 * few times. */
3192 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3193 && errno == EINTR && n > 0)
3194 --n;
3195 }
3196# else
3197 ioctl(read_cmd_fd, TCSETA, &tnew);
3198# endif
3199
3200#else
3201
3202 /*
3203 * for "old" tty systems
3204 */
3205# ifndef TIOCSETN
3206# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3207# endif
3208 static struct sgttyb ttybold;
3209 struct sgttyb ttybnew;
3210
3211 if (first)
3212 {
3213 first = FALSE;
3214 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3215 }
3216
3217 ttybnew = ttybold;
3218 if (tmode == TMODE_RAW)
3219 {
3220 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3221 ttybnew.sg_flags |= RAW;
3222 }
3223 else if (tmode == TMODE_SLEEP)
3224 ttybnew.sg_flags &= ~(ECHO);
3225 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3226#endif
3227 curr_tmode = tmode;
3228}
3229
3230/*
3231 * Try to get the code for "t_kb" from the stty setting
3232 *
3233 * Even if termcap claims a backspace key, the user's setting *should*
3234 * prevail. stty knows more about reality than termcap does, and if
3235 * somebody's usual erase key is DEL (which, for most BSD users, it will
3236 * be), they're going to get really annoyed if their erase key starts
3237 * doing forward deletes for no reason. (Eric Fischer)
3238 */
3239 void
3240get_stty()
3241{
3242 char_u buf[2];
3243 char_u *p;
3244
3245 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3246#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3247 /* for "new" tty systems */
3248# ifdef HAVE_TERMIOS_H
3249 struct termios keys;
3250# else
3251 struct termio keys;
3252# endif
3253
3254# if defined(HAVE_TERMIOS_H)
3255 if (tcgetattr(read_cmd_fd, &keys) != -1)
3256# else
3257 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3258# endif
3259 {
3260 buf[0] = keys.c_cc[VERASE];
3261 intr_char = keys.c_cc[VINTR];
3262#else
3263 /* for "old" tty systems */
3264 struct sgttyb keys;
3265
3266 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3267 {
3268 buf[0] = keys.sg_erase;
3269 intr_char = keys.sg_kill;
3270#endif
3271 buf[1] = NUL;
3272 add_termcode((char_u *)"kb", buf, FALSE);
3273
3274 /*
3275 * If <BS> and <DEL> are now the same, redefine <DEL>.
3276 */
3277 p = find_termcode((char_u *)"kD");
3278 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3279 do_fixdel(NULL);
3280 }
3281#if 0
3282 } /* to keep cindent happy */
3283#endif
3284}
3285
3286#endif /* VMS */
3287
3288#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3289/*
3290 * Set mouse clicks on or off.
3291 */
3292 void
3293mch_setmouse(on)
3294 int on;
3295{
3296 static int ison = FALSE;
3297 int xterm_mouse_vers;
3298
3299 if (on == ison) /* return quickly if nothing to do */
3300 return;
3301
3302 xterm_mouse_vers = use_xterm_mouse();
3303 if (xterm_mouse_vers > 0)
3304 {
3305 if (on) /* enable mouse events, use mouse tracking if available */
3306 out_str_nf((char_u *)
3307 (xterm_mouse_vers > 1
3308 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3309 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3310 else /* disable mouse events, could probably always send the same */
3311 out_str_nf((char_u *)
3312 (xterm_mouse_vers > 1
3313 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3314 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3315 ison = on;
3316 }
3317
3318# ifdef FEAT_MOUSE_DEC
3319 else if (ttym_flags == TTYM_DEC)
3320 {
3321 if (on) /* enable mouse events */
3322 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3323 else /* disable mouse events */
3324 out_str_nf((char_u *)"\033['z");
3325 ison = on;
3326 }
3327# endif
3328
3329# ifdef FEAT_MOUSE_GPM
3330 else
3331 {
3332 if (on)
3333 {
3334 if (gpm_open())
3335 ison = TRUE;
3336 }
3337 else
3338 {
3339 gpm_close();
3340 ison = FALSE;
3341 }
3342 }
3343# endif
3344
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003345# ifdef FEAT_SYSMOUSE
3346 else
3347 {
3348 if (on)
3349 {
3350 if (sysmouse_open() == OK)
3351 ison = TRUE;
3352 }
3353 else
3354 {
3355 sysmouse_close();
3356 ison = FALSE;
3357 }
3358 }
3359# endif
3360
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361# ifdef FEAT_MOUSE_JSB
3362 else
3363 {
3364 if (on)
3365 {
3366 /* D - Enable Mouse up/down messages
3367 * L - Enable Left Button Reporting
3368 * M - Enable Middle Button Reporting
3369 * R - Enable Right Button Reporting
3370 * K - Enable SHIFT and CTRL key Reporting
3371 * + - Enable Advanced messaging of mouse moves and up/down messages
3372 * Q - Quiet No Ack
3373 * # - Numeric value of mouse pointer required
3374 * 0 = Multiview 2000 cursor, used as standard
3375 * 1 = Windows Arrow
3376 * 2 = Windows I Beam
3377 * 3 = Windows Hour Glass
3378 * 4 = Windows Cross Hair
3379 * 5 = Windows UP Arrow
3380 */
3381#ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3382 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3383 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3384#else
3385 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3386 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3387#endif
3388 ison = TRUE;
3389 }
3390 else
3391 {
3392 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3393 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3394 ison = FALSE;
3395 }
3396 }
3397# endif
3398# ifdef FEAT_MOUSE_PTERM
3399 else
3400 {
3401 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3402 if (on)
3403 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3404 else
3405 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3406 ison = on;
3407 }
3408# endif
3409}
3410
3411/*
3412 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3413 */
3414 void
3415check_mouse_termcode()
3416{
3417# ifdef FEAT_MOUSE_XTERM
3418 if (use_xterm_mouse()
3419# ifdef FEAT_GUI
3420 && !gui.in_use
3421# endif
3422 )
3423 {
3424 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003425 ? IF_EB("\233M", CSI_STR "M")
3426 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 if (*p_mouse != NUL)
3428 {
3429 /* force mouse off and maybe on to send possibly new mouse
3430 * activation sequence to the xterm, with(out) drag tracing. */
3431 mch_setmouse(FALSE);
3432 setmouse();
3433 }
3434 }
3435 else
3436 del_mouse_termcode(KS_MOUSE);
3437# endif
3438
3439# ifdef FEAT_MOUSE_GPM
3440 if (!use_xterm_mouse()
3441# ifdef FEAT_GUI
3442 && !gui.in_use
3443# endif
3444 )
3445 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3446# endif
3447
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003448# ifdef FEAT_SYSMOUSE
3449 if (!use_xterm_mouse()
3450# ifdef FEAT_GUI
3451 && !gui.in_use
3452# endif
3453 )
3454 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3455# endif
3456
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457# ifdef FEAT_MOUSE_JSB
3458 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3459 if (!use_xterm_mouse()
3460# ifdef FEAT_GUI
3461 && !gui.in_use
3462# endif
3463 )
3464 set_mouse_termcode(KS_JSBTERM_MOUSE,
3465 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3466 else
3467 del_mouse_termcode(KS_JSBTERM_MOUSE);
3468# endif
3469
3470# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003471 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 * define it in the GUI or when using an xterm. */
3473 if (!use_xterm_mouse()
3474# ifdef FEAT_GUI
3475 && !gui.in_use
3476# endif
3477 )
3478 set_mouse_termcode(KS_NETTERM_MOUSE,
3479 (char_u *)IF_EB("\033}", ESC_STR "}"));
3480 else
3481 del_mouse_termcode(KS_NETTERM_MOUSE);
3482# endif
3483
3484# ifdef FEAT_MOUSE_DEC
3485 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3486 if (!use_xterm_mouse()
3487# ifdef FEAT_GUI
3488 && !gui.in_use
3489# endif
3490 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003491 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3492 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 else
3494 del_mouse_termcode(KS_DEC_MOUSE);
3495# endif
3496# ifdef FEAT_MOUSE_PTERM
3497 /* same as the dec mouse */
3498 if (!use_xterm_mouse()
3499# ifdef FEAT_GUI
3500 && !gui.in_use
3501# endif
3502 )
3503 set_mouse_termcode(KS_PTERM_MOUSE,
3504 (char_u *) IF_EB("\033[", ESC_STR "["));
3505 else
3506 del_mouse_termcode(KS_PTERM_MOUSE);
3507# endif
3508}
3509#endif
3510
3511/*
3512 * set screen mode, always fails.
3513 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 int
3515mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003516 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517{
3518 EMSG(_(e_screenmode));
3519 return FAIL;
3520}
3521
3522#ifndef VMS
3523
3524/*
3525 * Try to get the current window size:
3526 * 1. with an ioctl(), most accurate method
3527 * 2. from the environment variables LINES and COLUMNS
3528 * 3. from the termcap
3529 * 4. keep using the old values
3530 * Return OK when size could be determined, FAIL otherwise.
3531 */
3532 int
3533mch_get_shellsize()
3534{
3535 long rows = 0;
3536 long columns = 0;
3537 char_u *p;
3538
3539 /*
3540 * For OS/2 use _scrsize().
3541 */
3542# ifdef __EMX__
3543 {
3544 int s[2];
3545
3546 _scrsize(s);
3547 columns = s[0];
3548 rows = s[1];
3549 }
3550# endif
3551
3552 /*
3553 * 1. try using an ioctl. It is the most accurate method.
3554 *
3555 * Try using TIOCGWINSZ first, some systems that have it also define
3556 * TIOCGSIZE but don't have a struct ttysize.
3557 */
3558# ifdef TIOCGWINSZ
3559 {
3560 struct winsize ws;
3561 int fd = 1;
3562
3563 /* When stdout is not a tty, use stdin for the ioctl(). */
3564 if (!isatty(fd) && isatty(read_cmd_fd))
3565 fd = read_cmd_fd;
3566 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3567 {
3568 columns = ws.ws_col;
3569 rows = ws.ws_row;
3570 }
3571 }
3572# else /* TIOCGWINSZ */
3573# ifdef TIOCGSIZE
3574 {
3575 struct ttysize ts;
3576 int fd = 1;
3577
3578 /* When stdout is not a tty, use stdin for the ioctl(). */
3579 if (!isatty(fd) && isatty(read_cmd_fd))
3580 fd = read_cmd_fd;
3581 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3582 {
3583 columns = ts.ts_cols;
3584 rows = ts.ts_lines;
3585 }
3586 }
3587# endif /* TIOCGSIZE */
3588# endif /* TIOCGWINSZ */
3589
3590 /*
3591 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003592 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3593 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003594 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003595 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 {
3597 if ((p = (char_u *)getenv("LINES")))
3598 rows = atoi((char *)p);
3599 if ((p = (char_u *)getenv("COLUMNS")))
3600 columns = atoi((char *)p);
3601 }
3602
3603#ifdef HAVE_TGETENT
3604 /*
3605 * 3. try reading "co" and "li" entries from termcap
3606 */
3607 if (columns == 0 || rows == 0)
3608 getlinecol(&columns, &rows);
3609#endif
3610
3611 /*
3612 * 4. If everything fails, use the old values
3613 */
3614 if (columns <= 0 || rows <= 0)
3615 return FAIL;
3616
3617 Rows = rows;
3618 Columns = columns;
3619 return OK;
3620}
3621
3622/*
3623 * Try to set the window size to Rows and Columns.
3624 */
3625 void
3626mch_set_shellsize()
3627{
3628 if (*T_CWS)
3629 {
3630 /*
3631 * NOTE: if you get an error here that term_set_winsize() is
3632 * undefined, check the output of configure. It could probably not
3633 * find a ncurses, termcap or termlib library.
3634 */
3635 term_set_winsize((int)Rows, (int)Columns);
3636 out_flush();
3637 screen_start(); /* don't know where cursor is now */
3638 }
3639}
3640
3641#endif /* VMS */
3642
3643/*
3644 * Rows and/or Columns has changed.
3645 */
3646 void
3647mch_new_shellsize()
3648{
3649 /* Nothing to do. */
3650}
3651
Bram Moolenaardf177f62005-02-22 08:39:57 +00003652#ifndef USE_SYSTEM
3653static void append_ga_line __ARGS((garray_T *gap));
3654
3655/*
3656 * Append the text in "gap" below the cursor line and clear "gap".
3657 */
3658 static void
3659append_ga_line(gap)
3660 garray_T *gap;
3661{
3662 /* Remove trailing CR. */
3663 if (gap->ga_len > 0
3664 && !curbuf->b_p_bin
3665 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
3666 --gap->ga_len;
3667 ga_append(gap, NUL);
3668 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
3669 gap->ga_len = 0;
3670}
3671#endif
3672
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673 int
3674mch_call_shell(cmd, options)
3675 char_u *cmd;
3676 int options; /* SHELL_*, see vim.h */
3677{
3678#ifdef VMS
3679 char *ifn = NULL;
3680 char *ofn = NULL;
3681#endif
3682 int tmode = cur_tmode;
3683#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3684 int x;
3685# ifndef __EMX__
3686 char_u *newcmd; /* only needed for unix */
3687# else
3688 /*
3689 * Set the preferred shell in the EMXSHELL environment variable (but
3690 * only if it is different from what is already in the environment).
3691 * Emx then takes care of whether to use "/c" or "-c" in an
3692 * intelligent way. Simply pass the whole thing to emx's system() call.
3693 * Emx also starts an interactive shell if system() is passed an empty
3694 * string.
3695 */
3696 char_u *p, *old;
3697
3698 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3699 {
3700 /* should check HAVE_SETENV, but I know we don't have it. */
3701 p = alloc(10 + strlen(p_sh));
3702 if (p)
3703 {
3704 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3705 putenv((char *)p); /* don't free the pointer! */
3706 }
3707 }
3708# endif
3709
3710 out_flush();
3711
3712 if (options & SHELL_COOKED)
3713 settmode(TMODE_COOK); /* set to normal mode */
3714
3715# ifdef __EMX__
3716 if (cmd == NULL)
3717 x = system(""); /* this starts an interactive shell in emx */
3718 else
3719 x = system((char *)cmd);
3720 /* system() returns -1 when error occurs in starting shell */
3721 if (x == -1 && !emsg_silent)
3722 {
3723 MSG_PUTS(_("\nCannot execute shell "));
3724 msg_outtrans(p_sh);
3725 msg_putchar('\n');
3726 }
3727# else /* not __EMX__ */
3728 if (cmd == NULL)
3729 x = system((char *)p_sh);
3730 else
3731 {
3732# ifdef VMS
3733 if (ofn = strchr((char *)cmd, '>'))
3734 *ofn++ = '\0';
3735 if (ifn = strchr((char *)cmd, '<'))
3736 {
3737 char *p;
3738
3739 *ifn++ = '\0';
3740 p = strchr(ifn,' '); /* chop off any trailing spaces */
3741 if (p)
3742 *p = '\0';
3743 }
3744 if (ofn)
3745 x = vms_sys((char *)cmd, ofn, ifn);
3746 else
3747 x = system((char *)cmd);
3748# else
3749 newcmd = lalloc(STRLEN(p_sh)
3750 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3751 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3752 if (newcmd == NULL)
3753 x = 0;
3754 else
3755 {
3756 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3757 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3758 (char *)p_shcf,
3759 (char *)cmd);
3760 x = system((char *)newcmd);
3761 vim_free(newcmd);
3762 }
3763# endif
3764 }
3765# ifdef VMS
3766 x = vms_sys_status(x);
3767# endif
3768 if (emsg_silent)
3769 ;
3770 else if (x == 127)
3771 MSG_PUTS(_("\nCannot execute shell sh\n"));
3772# endif /* __EMX__ */
3773 else if (x && !(options & SHELL_SILENT))
3774 {
3775 MSG_PUTS(_("\nshell returned "));
3776 msg_outnum((long)x);
3777 msg_putchar('\n');
3778 }
3779
3780 if (tmode == TMODE_RAW)
3781 settmode(TMODE_RAW); /* set to raw mode */
3782# ifdef FEAT_TITLE
3783 resettitle();
3784# endif
3785 return x;
3786
3787#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3788
Bram Moolenaardf177f62005-02-22 08:39:57 +00003789# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3790 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791
3792 char_u *newcmd = NULL;
3793 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003794 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 pid_t wait_pid = 0;
3796# ifdef HAVE_UNION_WAIT
3797 union wait status;
3798# else
3799 int status = -1;
3800# endif
3801 int retval = -1;
3802 char **argv = NULL;
3803 int argc;
3804 int i;
3805 char_u *p;
3806 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003808# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 int pty_slave_fd = -1;
3810 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003811# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003812 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813 int fd_fromshell[2];
3814 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003815# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003817# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 static char envbuf_Rows[20];
3819 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003821 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822
3823 out_flush();
3824 if (options & SHELL_COOKED)
3825 settmode(TMODE_COOK); /* set to normal mode */
3826
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 newcmd = vim_strsave(p_sh);
3828 if (newcmd == NULL) /* out of memory */
3829 goto error;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003830
3831 /*
3832 * Do this loop twice:
3833 * 1: find number of arguments
3834 * 2: separate them and build argv[]
3835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836 for (i = 0; i < 2; ++i)
3837 {
3838 p = newcmd;
3839 inquote = FALSE;
3840 argc = 0;
3841 for (;;)
3842 {
3843 if (i == 1)
3844 argv[argc] = (char *)p;
3845 ++argc;
3846 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3847 {
3848 if (*p == '"')
3849 inquote = !inquote;
3850 ++p;
3851 }
3852 if (*p == NUL)
3853 break;
3854 if (i == 1)
3855 *p++ = NUL;
3856 p = skipwhite(p);
3857 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003858 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 {
3860 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3861 if (argv == NULL) /* out of memory */
3862 goto error;
3863 }
3864 }
3865 if (cmd != NULL)
3866 {
3867 if (extra_shell_arg != NULL)
3868 argv[argc++] = (char *)extra_shell_arg;
3869 argv[argc++] = (char *)p_shcf;
3870 argv[argc++] = (char *)cmd;
3871 }
3872 argv[argc] = NULL;
3873
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003875 * For the GUI, when writing the output into the buffer and when reading
3876 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3877 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003879 if ((options & (SHELL_READ|SHELL_WRITE))
3880# ifdef FEAT_GUI
3881 || (gui.in_use && show_shell_mess)
3882# endif
3883 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003885# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 /*
3887 * Try to open a master pty.
3888 * If this works, open the slave pty.
3889 * If the slave can't be opened, close the master pty.
3890 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003891 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 {
3893 pty_master_fd = OpenPTY(&tty_name); /* open pty */
3894 if (pty_master_fd >= 0 && ((pty_slave_fd =
3895 open(tty_name, O_RDWR | O_EXTRA, 0)) < 0))
3896 {
3897 close(pty_master_fd);
3898 pty_master_fd = -1;
3899 }
3900 }
3901 /*
3902 * If not opening a pty or it didn't work, try using pipes.
3903 */
3904 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003905# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 {
3907 pipe_error = (pipe(fd_toshell) < 0);
3908 if (!pipe_error) /* pipe create OK */
3909 {
3910 pipe_error = (pipe(fd_fromshell) < 0);
3911 if (pipe_error) /* pipe create failed */
3912 {
3913 close(fd_toshell[0]);
3914 close(fd_toshell[1]);
3915 }
3916 }
3917 if (pipe_error)
3918 {
3919 MSG_PUTS(_("\nCannot create pipes\n"));
3920 out_flush();
3921 }
3922 }
3923 }
3924
3925 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 {
3927# ifdef __BEOS__
3928 beos_cleanup_read_thread();
3929# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003930
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3932 {
3933 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003934 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003936 || (gui.in_use && show_shell_mess)
3937# endif
3938 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003940# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941 if (pty_master_fd >= 0) /* close the pseudo tty */
3942 {
3943 close(pty_master_fd);
3944 close(pty_slave_fd);
3945 }
3946 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003947# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 {
3949 close(fd_toshell[0]);
3950 close(fd_toshell[1]);
3951 close(fd_fromshell[0]);
3952 close(fd_fromshell[1]);
3953 }
3954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 }
3956 else if (pid == 0) /* child */
3957 {
3958 reset_signals(); /* handle signals normally */
3959
3960 if (!show_shell_mess || (options & SHELL_EXPAND))
3961 {
3962 int fd;
3963
3964 /*
3965 * Don't want to show any message from the shell. Can't just
3966 * close stdout and stderr though, because some systems will
3967 * break if you try to write to them after that, so we must
3968 * use dup() to replace them with something else -- webb
3969 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3970 * waiting for input.
3971 */
3972 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3973 fclose(stdin);
3974 fclose(stdout);
3975 fclose(stderr);
3976
3977 /*
3978 * If any of these open()'s and dup()'s fail, we just continue
3979 * anyway. It's not fatal, and on most systems it will make
3980 * no difference at all. On a few it will cause the execvp()
3981 * to exit with a non-zero status even when the completion
3982 * could be done, which is nothing too serious. If the open()
3983 * or dup() failed we'd just do the same thing ourselves
3984 * anyway -- webb
3985 */
3986 if (fd >= 0)
3987 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003988 ignored = dup(fd); /* To replace stdin (fd 0) */
3989 ignored = dup(fd); /* To replace stdout (fd 1) */
3990 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991
3992 /* Don't need this now that we've duplicated it */
3993 close(fd);
3994 }
3995 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00003996 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003998 || gui.in_use
3999# endif
4000 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 {
4002
Bram Moolenaardf177f62005-02-22 08:39:57 +00004003# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004004 /* Create our own process group, so that the child and all its
4005 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004006 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004007 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004008 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004009 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004010# if defined(SIGHUP)
4011 /* When doing "!xterm&" and 'shell' is bash: the shell
4012 * will exit and send SIGHUP to all processes in its
4013 * group, killing the just started process. Ignore SIGHUP
4014 * to avoid that. (suggested by Simon Schubert)
4015 */
4016 signal(SIGHUP, SIG_IGN);
4017# endif
4018 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004019# endif
4020# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004021 if (pty_slave_fd >= 0)
4022 {
4023 /* push stream discipline modules */
4024 if (options & SHELL_COOKED)
4025 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004027 /* Try to become controlling tty (probably doesn't work,
4028 * unless run by root) */
4029 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004031 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004032# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004034# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 setenv("TERM", "dumb", 1);
4036 sprintf((char *)envbuf, "%ld", Rows);
4037 setenv("ROWS", (char *)envbuf, 1);
4038 sprintf((char *)envbuf, "%ld", Rows);
4039 setenv("LINES", (char *)envbuf, 1);
4040 sprintf((char *)envbuf, "%ld", Columns);
4041 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004042# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 /*
4044 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004045 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 */
4047 putenv("TERM=dumb");
4048 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4049 putenv(envbuf_Rows);
4050 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4051 putenv(envbuf_Rows);
4052 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4053 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004054# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055
Bram Moolenaara5792f52005-11-23 21:25:05 +00004056 /*
4057 * stderr is only redirected when using the GUI, so that a
4058 * program like gpg can still access the terminal to get a
4059 * passphrase using stderr.
4060 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004061# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 if (pty_master_fd >= 0)
4063 {
4064 close(pty_master_fd); /* close master side of pty */
4065
4066 /* set up stdin/stdout/stderr for the child */
4067 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004068 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004070 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004071 if (gui.in_use)
4072 {
4073 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004074 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004075 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004076
4077 close(pty_slave_fd); /* has been dupped, close it now */
4078 }
4079 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004080# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 {
4082 /* set up stdin for the child */
4083 close(fd_toshell[1]);
4084 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004085 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 close(fd_toshell[0]);
4087
4088 /* set up stdout for the child */
4089 close(fd_fromshell[0]);
4090 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004091 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 close(fd_fromshell[1]);
4093
Bram Moolenaara5792f52005-11-23 21:25:05 +00004094# ifdef FEAT_GUI
4095 if (gui.in_use)
4096 {
4097 /* set up stderr for the child */
4098 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004099 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004100 }
4101# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 }
4103 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004104
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 /*
4106 * There is no type cast for the argv, because the type may be
4107 * different on different machines. This may cause a warning
4108 * message with strict compilers, don't worry about it.
4109 * Call _exit() instead of exit() to avoid closing the connection
4110 * to the X server (esp. with GTK, which uses atexit()).
4111 */
4112 execvp(argv[0], argv);
4113 _exit(EXEC_FAILED); /* exec failed, return failure code */
4114 }
4115 else /* parent */
4116 {
4117 /*
4118 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004119 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 */
4121 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004122 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123
4124 /*
4125 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004126 * This is also used to pipe stdin/stdout to/from the external
4127 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004129 if ((options & (SHELL_READ|SHELL_WRITE))
4130# ifdef FEAT_GUI
4131 || (gui.in_use && show_shell_mess)
4132# endif
4133 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004135# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004137# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004139# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4141 int ta_len = 0; /* valid bytes in ta_buf[] */
4142 int len;
4143 int p_more_save;
4144 int old_State;
4145 int c;
4146 int toshell_fd;
4147 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004148 garray_T ga;
4149 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004150# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4151 struct timeval start_tv;
4152# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153
Bram Moolenaardf177f62005-02-22 08:39:57 +00004154# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 if (pty_master_fd >= 0)
4156 {
4157 close(pty_slave_fd); /* close slave side of pty */
4158 fromshell_fd = pty_master_fd;
4159 toshell_fd = dup(pty_master_fd);
4160 }
4161 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004162# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 {
4164 close(fd_toshell[0]);
4165 close(fd_fromshell[1]);
4166 toshell_fd = fd_toshell[1];
4167 fromshell_fd = fd_fromshell[0];
4168 }
4169
4170 /*
4171 * Write to the child if there are typed characters.
4172 * Read from the child if there are characters available.
4173 * Repeat the reading a few times if more characters are
4174 * available. Need to check for typed keys now and then, but
4175 * not too often (delays when no chars are available).
4176 * This loop is quit if no characters can be read from the pty
4177 * (WaitForChar detected special condition), or there are no
4178 * characters available and the child has exited.
4179 * Only check if the child has exited when there is no more
4180 * output. The child may exit before all the output has
4181 * been printed.
4182 *
4183 * Currently this busy loops!
4184 * This can probably dead-lock when the write blocks!
4185 */
4186 p_more_save = p_more;
4187 p_more = FALSE;
4188 old_State = State;
4189 State = EXTERNCMD; /* don't redraw at window resize */
4190
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004191 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004192 {
4193 /* Fork a process that will write the lines to the
4194 * external program. */
4195 if ((wpid = fork()) == -1)
4196 {
4197 MSG_PUTS(_("\nCannot fork\n"));
4198 }
4199 else if (wpid == 0)
4200 {
4201 linenr_T lnum = curbuf->b_op_start.lnum;
4202 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004203 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004204 char_u *s;
4205 size_t l;
4206
4207 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004208 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004209 for (;;)
4210 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004211 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004212 if (l == 0)
4213 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004214 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004215 /* NL -> NUL translation */
4216 len = write(toshell_fd, "", (size_t)1);
4217 else
4218 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004219 s = vim_strchr(lp + written, NL);
4220 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004221 s == NULL ? l
4222 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004223 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004224 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004225 {
4226 /* Finished a line, add a NL, unless this line
4227 * should not have one. */
4228 if (lnum != curbuf->b_op_end.lnum
4229 || !curbuf->b_p_bin
4230 || (lnum != write_no_eol_lnum
4231 && (lnum !=
4232 curbuf->b_ml.ml_line_count
4233 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004234 ignored = write(toshell_fd, "\n",
4235 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004236 ++lnum;
4237 if (lnum > curbuf->b_op_end.lnum)
4238 {
4239 /* finished all the lines, close pipe */
4240 close(toshell_fd);
4241 toshell_fd = -1;
4242 break;
4243 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004244 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004245 written = 0;
4246 }
4247 else if (len > 0)
4248 written += len;
4249 }
4250 _exit(0);
4251 }
4252 else
4253 {
4254 close(toshell_fd);
4255 toshell_fd = -1;
4256 }
4257 }
4258
4259 if (options & SHELL_READ)
4260 ga_init2(&ga, 1, BUFLEN);
4261
4262 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004263# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4264 gettimeofday(&start_tv, NULL);
4265# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266 for (;;)
4267 {
4268 /*
4269 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004270 * if there are any.
4271 * Don't do this if we are expanding wild cards (would eat
4272 * typeahead).
4273 * Don't do this when filtering and terminal is in cooked
4274 * mode, the shell command will handle the I/O. Avoids
4275 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004276 * Don't get characters when the child has already
4277 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004278 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004279 * while (noread_cnt > 4), avoids that ":r !ls" eats
4280 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 */
4282 len = 0;
4283 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004284 && ((options &
4285 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4286 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004287# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004288 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004289# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004290 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004291 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004292 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004294 if (ta_len == 0)
4295 {
4296 /* Get extra characters when we don't have any.
4297 * Reset the counter and timer. */
4298 noread_cnt = 0;
4299# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4300 gettimeofday(&start_tv, NULL);
4301# endif
4302 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4303 }
4304 if (ta_len > 0 || len > 0)
4305 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 /*
4307 * For pipes:
4308 * Check for CTRL-C: send interrupt signal to child.
4309 * Check for CTRL-D: EOF, close pipe to child.
4310 */
4311 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4312 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004313# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 /*
4315 * Send SIGINT to the child's group or all
4316 * processes in our group.
4317 */
4318 if (ta_buf[ta_len] == Ctrl_C
4319 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004320 {
4321# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004323# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004326 if (wpid > 0)
4327 kill(wpid, SIGINT);
4328 }
4329# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004330 if (pty_master_fd < 0 && toshell_fd >= 0
4331 && ta_buf[ta_len] == Ctrl_D)
4332 {
4333 close(toshell_fd);
4334 toshell_fd = -1;
4335 }
4336 }
4337
4338 /* replace K_BS by <BS> and K_DEL by <DEL> */
4339 for (i = ta_len; i < ta_len + len; ++i)
4340 {
4341 if (ta_buf[i] == CSI && len - i > 2)
4342 {
4343 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4344 if (c == K_DEL || c == K_KDEL || c == K_BS)
4345 {
4346 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4347 (size_t)(len - i - 2));
4348 if (c == K_DEL || c == K_KDEL)
4349 ta_buf[i] = DEL;
4350 else
4351 ta_buf[i] = Ctrl_H;
4352 len -= 2;
4353 }
4354 }
4355 else if (ta_buf[i] == '\r')
4356 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004357# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004359 i += (*mb_ptr2len_len)(ta_buf + i,
4360 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362 }
4363
4364 /*
4365 * For pipes: echo the typed characters.
4366 * For a pty this does not seem to work.
4367 */
4368 if (pty_master_fd < 0)
4369 {
4370 for (i = ta_len; i < ta_len + len; ++i)
4371 {
4372 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4373 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004374# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375 else if (has_mbyte)
4376 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004377 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378
4379 msg_outtrans_len(ta_buf + i, l);
4380 i += l - 1;
4381 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004382# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 else
4384 msg_outtrans_len(ta_buf + i, 1);
4385 }
4386 windgoto(msg_row, msg_col);
4387 out_flush();
4388 }
4389
4390 ta_len += len;
4391
4392 /*
4393 * Write the characters to the child, unless EOF has
4394 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004395 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004396 * When writing buffer lines, drop the typed
4397 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004399 if (options & SHELL_WRITE)
4400 ta_len = 0;
4401 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402 {
4403 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4404 if (len > 0)
4405 {
4406 ta_len -= len;
4407 mch_memmove(ta_buf, ta_buf + len, ta_len);
4408 }
4409 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 }
4412
Bram Moolenaardf177f62005-02-22 08:39:57 +00004413 if (got_int)
4414 {
4415 /* CTRL-C sends a signal to the child, we ignore it
4416 * ourselves */
4417# ifdef HAVE_SETSID
4418 kill(-pid, SIGINT);
4419# else
4420 kill(0, SIGINT);
4421# endif
4422 if (wpid > 0)
4423 kill(wpid, SIGINT);
4424 got_int = FALSE;
4425 }
4426
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427 /*
4428 * Check if the child has any characters to be printed.
4429 * Read them and write them to our window. Repeat this as
4430 * long as there is something to do, avoid the 10ms wait
4431 * for mch_inchar(), or sending typeahead characters to
4432 * the external process.
4433 * TODO: This should handle escape sequences, compatible
4434 * to some terminal (vt52?).
4435 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004436 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4438 {
4439 len = read(fromshell_fd, (char *)buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004440# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004442# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004444# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 );
4446 if (len <= 0) /* end of file or error */
4447 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004448
4449 noread_cnt = 0;
4450 if (options & SHELL_READ)
4451 {
4452 /* Do NUL -> NL translation, append NL separated
4453 * lines to the current buffer. */
4454 for (i = 0; i < len; ++i)
4455 {
4456 if (buffer[i] == NL)
4457 append_ga_line(&ga);
4458 else if (buffer[i] == NUL)
4459 ga_append(&ga, NL);
4460 else
4461 ga_append(&ga, buffer[i]);
4462 }
4463 }
4464# ifdef FEAT_MBYTE
4465 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466 {
4467 int l;
4468
Bram Moolenaardf177f62005-02-22 08:39:57 +00004469 len += buffer_off;
4470 buffer[len] = NUL;
4471
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472 /* Check if the last character in buffer[] is
4473 * incomplete, keep these bytes for the next
4474 * round. */
4475 for (p = buffer; p < buffer + len; p += l)
4476 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004477 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 if (l == 0)
4479 l = 1; /* NUL byte? */
4480 else if (MB_BYTE2LEN(*p) != l)
4481 break;
4482 }
4483 if (p == buffer) /* no complete character */
4484 {
4485 /* avoid getting stuck at an illegal byte */
4486 if (len >= 12)
4487 ++p;
4488 else
4489 {
4490 buffer_off = len;
4491 continue;
4492 }
4493 }
4494 c = *p;
4495 *p = NUL;
4496 msg_puts(buffer);
4497 if (p < buffer + len)
4498 {
4499 *p = c;
4500 buffer_off = (buffer + len) - p;
4501 mch_memmove(buffer, p, buffer_off);
4502 continue;
4503 }
4504 buffer_off = 0;
4505 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004506# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 {
4509 buffer[len] = NUL;
4510 msg_puts(buffer);
4511 }
4512
4513 windgoto(msg_row, msg_col);
4514 cursor_on();
4515 out_flush();
4516 if (got_int)
4517 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004518
4519# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4520 {
4521 struct timeval now_tv;
4522 long msec;
4523
4524 /* Avoid that we keep looping here without
4525 * checking for a CTRL-C for a long time. Don't
4526 * break out too often to avoid losing typeahead. */
4527 gettimeofday(&now_tv, NULL);
4528 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4529 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4530 if (msec > 2000)
4531 {
4532 noread_cnt = 5;
4533 break;
4534 }
4535 }
4536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 }
4538
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004539 /* If we already detected the child has finished break the
4540 * loop now. */
4541 if (wait_pid == pid)
4542 break;
4543
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 /*
4545 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004546 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004548# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004550# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004552# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4554 || (wait_pid == pid && WIFEXITED(status)))
4555 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004556 /* Don't break the loop yet, try reading more
4557 * characters from "fromshell_fd" first. When using
4558 * pipes there might still be something to read and
4559 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004562 else
4563 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 }
4565finished:
4566 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004567 if (options & SHELL_READ)
4568 {
4569 if (ga.ga_len > 0)
4570 {
4571 append_ga_line(&ga);
4572 /* remember that the NL was missing */
4573 write_no_eol_lnum = curwin->w_cursor.lnum;
4574 }
4575 else
4576 write_no_eol_lnum = 0;
4577 ga_clear(&ga);
4578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580 /*
4581 * Give all typeahead that wasn't used back to ui_inchar().
4582 */
4583 if (ta_len)
4584 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 State = old_State;
4586 if (toshell_fd >= 0)
4587 close(toshell_fd);
4588 close(fromshell_fd);
4589 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590
4591 /*
4592 * Wait until our child has exited.
4593 * Ignore wait() returning pids of other children and returning
4594 * because of some signal like SIGWINCH.
4595 * Don't wait if wait_pid was already set above, indicating the
4596 * child already exited.
4597 */
4598 while (wait_pid != pid)
4599 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004600# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004601 /* Ugly hack: when compiled with Python threads are probably
4602 * used, in which case wait() sometimes hangs for no obvious
4603 * reason. Use waitpid() instead and loop (like the GUI). */
4604# ifdef __NeXT__
4605 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4606# else
4607 wait_pid = waitpid(pid, &status, WNOHANG);
4608# endif
4609 if (wait_pid == 0)
4610 {
4611 /* Wait for 1/100 sec before trying again. */
4612 mch_delay(10L, TRUE);
4613 continue;
4614 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004615# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 if (wait_pid <= 0
4619# ifdef ECHILD
4620 && errno == ECHILD
4621# endif
4622 )
4623 break;
4624 }
4625
Bram Moolenaardf177f62005-02-22 08:39:57 +00004626 /* Make sure the child that writes to the external program is
4627 * dead. */
4628 if (wpid > 0)
4629 kill(wpid, SIGKILL);
4630
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 /*
4632 * Set to raw mode right now, otherwise a CTRL-C after
4633 * catch_signals() will kill Vim.
4634 */
4635 if (tmode == TMODE_RAW)
4636 settmode(TMODE_RAW);
4637 did_settmode = TRUE;
4638 set_signals();
4639
4640 if (WIFEXITED(status))
4641 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004642 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 retval = WEXITSTATUS(status);
4644 if (retval && !emsg_silent)
4645 {
4646 if (retval == EXEC_FAILED)
4647 {
4648 MSG_PUTS(_("\nCannot execute shell "));
4649 msg_outtrans(p_sh);
4650 msg_putchar('\n');
4651 }
4652 else if (!(options & SHELL_SILENT))
4653 {
4654 MSG_PUTS(_("\nshell returned "));
4655 msg_outnum((long)retval);
4656 msg_putchar('\n');
4657 }
4658 }
4659 }
4660 else
4661 MSG_PUTS(_("\nCommand terminated\n"));
4662 }
4663 }
4664 vim_free(argv);
4665
4666error:
4667 if (!did_settmode)
4668 if (tmode == TMODE_RAW)
4669 settmode(TMODE_RAW); /* set to raw mode */
4670# ifdef FEAT_TITLE
4671 resettitle();
4672# endif
4673 vim_free(newcmd);
4674
4675 return retval;
4676
4677#endif /* USE_SYSTEM */
4678}
4679
4680/*
4681 * Check for CTRL-C typed by reading all available characters.
4682 * In cooked mode we should get SIGINT, no need to check.
4683 */
4684 void
4685mch_breakcheck()
4686{
4687 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4688 fill_input_buf(FALSE);
4689}
4690
4691/*
4692 * Wait "msec" msec until a character is available from the keyboard or from
4693 * inbuf[]. msec == -1 will block forever.
4694 * When a GUI is being used, this will never get called -- webb
4695 */
4696 static int
4697WaitForChar(msec)
4698 long msec;
4699{
4700#ifdef FEAT_MOUSE_GPM
4701 int gpm_process_wanted;
4702#endif
4703#ifdef FEAT_XCLIPBOARD
4704 int rest;
4705#endif
4706 int avail;
4707
4708 if (input_available()) /* something in inbuf[] */
4709 return 1;
4710
4711#if defined(FEAT_MOUSE_DEC)
4712 /* May need to query the mouse position. */
4713 if (WantQueryMouse)
4714 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004715 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4717 }
4718#endif
4719
4720 /*
4721 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4722 * events. This is a bit complicated, because they might both be defined.
4723 */
4724#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4725# ifdef FEAT_XCLIPBOARD
4726 rest = 0;
4727 if (do_xterm_trace())
4728 rest = msec;
4729# endif
4730 do
4731 {
4732# ifdef FEAT_XCLIPBOARD
4733 if (rest != 0)
4734 {
4735 msec = XT_TRACE_DELAY;
4736 if (rest >= 0 && rest < XT_TRACE_DELAY)
4737 msec = rest;
4738 if (rest >= 0)
4739 rest -= msec;
4740 }
4741# endif
4742# ifdef FEAT_MOUSE_GPM
4743 gpm_process_wanted = 0;
4744 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4745# else
4746 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4747# endif
4748 if (!avail)
4749 {
4750 if (input_available())
4751 return 1;
4752# ifdef FEAT_XCLIPBOARD
4753 if (rest == 0 || !do_xterm_trace())
4754# endif
4755 break;
4756 }
4757 }
4758 while (FALSE
4759# ifdef FEAT_MOUSE_GPM
4760 || (gpm_process_wanted && mch_gpm_process() == 0)
4761# endif
4762# ifdef FEAT_XCLIPBOARD
4763 || (!avail && rest != 0)
4764# endif
4765 );
4766
4767#else
4768 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4769#endif
4770 return avail;
4771}
4772
4773/*
4774 * Wait "msec" msec until a character is available from file descriptor "fd".
4775 * Time == -1 will block forever.
4776 * When a GUI is being used, this will not be used for input -- webb
4777 * Returns also, when a request from Sniff is waiting -- toni.
4778 * Or when a Linux GPM mouse event is waiting.
4779 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780#if defined(__BEOS__)
4781 int
4782#else
4783 static int
4784#endif
4785RealWaitForChar(fd, msec, check_for_gpm)
4786 int fd;
4787 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004788 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004789{
4790 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004791#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004792 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004793#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004794#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795 static int busy = FALSE;
4796
4797 /* May retry getting characters after an event was handled. */
4798# define MAY_LOOP
4799
4800# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4801 /* Remember at what time we started, so that we know how much longer we
4802 * should wait after being interrupted. */
4803# define USE_START_TV
4804 struct timeval start_tv;
4805
4806 if (msec > 0 && (
4807# ifdef FEAT_XCLIPBOARD
4808 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004809# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 ||
4811# endif
4812# endif
4813# ifdef USE_XSMP
4814 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004815# ifdef FEAT_MZSCHEME
4816 ||
4817# endif
4818# endif
4819# ifdef FEAT_MZSCHEME
4820 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821# endif
4822 ))
4823 gettimeofday(&start_tv, NULL);
4824# endif
4825
4826 /* Handle being called recursively. This may happen for the session
4827 * manager stuff, it may save the file, which does a breakcheck. */
4828 if (busy)
4829 return 0;
4830#endif
4831
4832#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004833 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834#endif
4835 {
4836#ifdef MAY_LOOP
4837 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004838# ifdef FEAT_MZSCHEME
4839 int mzquantum_used = FALSE;
4840# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841#endif
4842#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004843 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004844 int nfd;
4845# ifdef FEAT_XCLIPBOARD
4846 int xterm_idx = -1;
4847# endif
4848# ifdef FEAT_MOUSE_GPM
4849 int gpm_idx = -1;
4850# endif
4851# ifdef USE_XSMP
4852 int xsmp_idx = -1;
4853# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004854# ifdef FEAT_NETBEANS_INTG
4855 int nb_idx = -1;
4856# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004857 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004859# ifdef FEAT_MZSCHEME
4860 mzvim_check_threads();
4861 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4862 {
4863 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4864 mzquantum_used = TRUE;
4865 }
4866# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 fds[0].fd = fd;
4868 fds[0].events = POLLIN;
4869 nfd = 1;
4870
4871# ifdef FEAT_SNIFF
4872# define SNIFF_IDX 1
4873 if (want_sniff_request)
4874 {
4875 fds[SNIFF_IDX].fd = fd_from_sniff;
4876 fds[SNIFF_IDX].events = POLLIN;
4877 nfd++;
4878 }
4879# endif
4880# ifdef FEAT_XCLIPBOARD
4881 if (xterm_Shell != (Widget)0)
4882 {
4883 xterm_idx = nfd;
4884 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4885 fds[nfd].events = POLLIN;
4886 nfd++;
4887 }
4888# endif
4889# ifdef FEAT_MOUSE_GPM
4890 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4891 {
4892 gpm_idx = nfd;
4893 fds[nfd].fd = gpm_fd;
4894 fds[nfd].events = POLLIN;
4895 nfd++;
4896 }
4897# endif
4898# ifdef USE_XSMP
4899 if (xsmp_icefd != -1)
4900 {
4901 xsmp_idx = nfd;
4902 fds[nfd].fd = xsmp_icefd;
4903 fds[nfd].events = POLLIN;
4904 nfd++;
4905 }
4906# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004907#ifdef FEAT_NETBEANS_INTG
4908 if (nb_fd != -1)
4909 {
4910 nb_idx = nfd;
4911 fds[nfd].fd = nb_fd;
4912 fds[nfd].events = POLLIN;
4913 nfd++;
4914 }
4915#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004917 ret = poll(fds, nfd, towait);
4918# ifdef FEAT_MZSCHEME
4919 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004920 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004921 finished = FALSE;
4922# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923
4924# ifdef FEAT_SNIFF
4925 if (ret < 0)
4926 sniff_disconnect(1);
4927 else if (want_sniff_request)
4928 {
4929 if (fds[SNIFF_IDX].revents & POLLHUP)
4930 sniff_disconnect(1);
4931 if (fds[SNIFF_IDX].revents & POLLIN)
4932 sniff_request_waiting = 1;
4933 }
4934# endif
4935# ifdef FEAT_XCLIPBOARD
4936 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4937 {
4938 xterm_update(); /* Maybe we should hand out clipboard */
4939 if (--ret == 0 && !input_available())
4940 /* Try again */
4941 finished = FALSE;
4942 }
4943# endif
4944# ifdef FEAT_MOUSE_GPM
4945 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4946 {
4947 *check_for_gpm = 1;
4948 }
4949# endif
4950# ifdef USE_XSMP
4951 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4952 {
4953 if (fds[xsmp_idx].revents & POLLIN)
4954 {
4955 busy = TRUE;
4956 xsmp_handle_requests();
4957 busy = FALSE;
4958 }
4959 else if (fds[xsmp_idx].revents & POLLHUP)
4960 {
4961 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004962 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 xsmp_close();
4964 }
4965 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004966 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967 }
4968# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004969#ifdef FEAT_NETBEANS_INTG
4970 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
4971 {
4972 netbeans_read();
4973 --ret;
4974 }
4975#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976
4977
4978#else /* HAVE_SELECT */
4979
4980 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004981 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 fd_set rfds, efds;
4983 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004984 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004986# ifdef FEAT_MZSCHEME
4987 mzvim_check_threads();
4988 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4989 {
4990 towait = p_mzq; /* don't wait longer than 'mzquantum' */
4991 mzquantum_used = TRUE;
4992 }
4993# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994# ifdef __EMX__
4995 /* don't check for incoming chars if not in raw mode, because select()
4996 * always returns TRUE then (in some version of emx.dll) */
4997 if (curr_tmode != TMODE_RAW)
4998 return 0;
4999# endif
5000
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005001 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005003 tv.tv_sec = towait / 1000;
5004 tv.tv_usec = (towait % 1000) * (1000000/1000);
5005 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005007 else
5008 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009
5010 /*
5011 * Select on ready for reading and exceptional condition (end of file).
5012 */
5013 FD_ZERO(&rfds); /* calls bzero() on a sun */
5014 FD_ZERO(&efds);
5015 FD_SET(fd, &rfds);
5016# if !defined(__QNX__) && !defined(__CYGWIN32__)
5017 /* For QNX select() always returns 1 if this is set. Why? */
5018 FD_SET(fd, &efds);
5019# endif
5020 maxfd = fd;
5021
5022# ifdef FEAT_SNIFF
5023 if (want_sniff_request)
5024 {
5025 FD_SET(fd_from_sniff, &rfds);
5026 FD_SET(fd_from_sniff, &efds);
5027 if (maxfd < fd_from_sniff)
5028 maxfd = fd_from_sniff;
5029 }
5030# endif
5031# ifdef FEAT_XCLIPBOARD
5032 if (xterm_Shell != (Widget)0)
5033 {
5034 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5035 if (maxfd < ConnectionNumber(xterm_dpy))
5036 maxfd = ConnectionNumber(xterm_dpy);
5037 }
5038# endif
5039# ifdef FEAT_MOUSE_GPM
5040 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5041 {
5042 FD_SET(gpm_fd, &rfds);
5043 FD_SET(gpm_fd, &efds);
5044 if (maxfd < gpm_fd)
5045 maxfd = gpm_fd;
5046 }
5047# endif
5048# ifdef USE_XSMP
5049 if (xsmp_icefd != -1)
5050 {
5051 FD_SET(xsmp_icefd, &rfds);
5052 FD_SET(xsmp_icefd, &efds);
5053 if (maxfd < xsmp_icefd)
5054 maxfd = xsmp_icefd;
5055 }
5056# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005057#ifdef FEAT_NETBEANS_INTG
5058 if (nb_fd != -1)
5059 {
5060 FD_SET(nb_fd, &rfds);
5061 if (maxfd < nb_fd)
5062 maxfd = nb_fd;
5063 }
5064#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065
5066# ifdef OLD_VMS
5067 /* Old VMS as v6.2 and older have broken select(). It waits more than
5068 * required. Should not be used */
5069 ret = 0;
5070# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005071 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5072# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005073# ifdef __TANDEM
5074 if (ret == -1 && errno == ENOTSUP)
5075 {
5076 FD_ZERO(&rfds);
5077 FD_ZERO(&efds);
5078 ret = 0;
5079 }
5080#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005081# ifdef FEAT_MZSCHEME
5082 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005083 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005084 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085# endif
5086
5087# ifdef FEAT_SNIFF
5088 if (ret < 0 )
5089 sniff_disconnect(1);
5090 else if (ret > 0 && want_sniff_request)
5091 {
5092 if (FD_ISSET(fd_from_sniff, &efds))
5093 sniff_disconnect(1);
5094 if (FD_ISSET(fd_from_sniff, &rfds))
5095 sniff_request_waiting = 1;
5096 }
5097# endif
5098# ifdef FEAT_XCLIPBOARD
5099 if (ret > 0 && xterm_Shell != (Widget)0
5100 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5101 {
5102 xterm_update(); /* Maybe we should hand out clipboard */
5103 /* continue looping when we only got the X event and the input
5104 * buffer is empty */
5105 if (--ret == 0 && !input_available())
5106 {
5107 /* Try again */
5108 finished = FALSE;
5109 }
5110 }
5111# endif
5112# ifdef FEAT_MOUSE_GPM
5113 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5114 {
5115 if (FD_ISSET(gpm_fd, &efds))
5116 gpm_close();
5117 else if (FD_ISSET(gpm_fd, &rfds))
5118 *check_for_gpm = 1;
5119 }
5120# endif
5121# ifdef USE_XSMP
5122 if (ret > 0 && xsmp_icefd != -1)
5123 {
5124 if (FD_ISSET(xsmp_icefd, &efds))
5125 {
5126 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005127 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128 xsmp_close();
5129 if (--ret == 0)
5130 finished = FALSE; /* keep going if event was only one */
5131 }
5132 else if (FD_ISSET(xsmp_icefd, &rfds))
5133 {
5134 busy = TRUE;
5135 xsmp_handle_requests();
5136 busy = FALSE;
5137 if (--ret == 0)
5138 finished = FALSE; /* keep going if event was only one */
5139 }
5140 }
5141# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005142#ifdef FEAT_NETBEANS_INTG
5143 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5144 {
5145 netbeans_read();
5146 --ret;
5147 }
5148#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149
5150#endif /* HAVE_SELECT */
5151
5152#ifdef MAY_LOOP
5153 if (finished || msec == 0)
5154 break;
5155
5156 /* We're going to loop around again, find out for how long */
5157 if (msec > 0)
5158 {
5159# ifdef USE_START_TV
5160 struct timeval mtv;
5161
5162 /* Compute remaining wait time. */
5163 gettimeofday(&mtv, NULL);
5164 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5165 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5166# else
5167 /* Guess we got interrupted halfway. */
5168 msec = msec / 2;
5169# endif
5170 if (msec <= 0)
5171 break; /* waited long enough */
5172 }
5173#endif
5174 }
5175
5176 return (ret > 0);
5177}
5178
5179#ifndef VMS
5180
5181#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005183 * Expand a path into all matching files and/or directories. Handles "*",
5184 * "?", "[a-z]", "**", etc.
5185 * "path" has backslashes before chars that are not to be expanded.
5186 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 */
5188 int
5189mch_expandpath(gap, path, flags)
5190 garray_T *gap;
5191 char_u *path;
5192 int flags; /* EW_* flags */
5193{
Bram Moolenaar02743632005-07-25 20:42:36 +00005194 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195}
5196#endif
5197
5198/*
5199 * mch_expand_wildcards() - this code does wild-card pattern matching using
5200 * the shell
5201 *
5202 * return OK for success, FAIL for error (you may lose some memory) and put
5203 * an error message in *file.
5204 *
5205 * num_pat is number of input patterns
5206 * pat is array of pointers to input patterns
5207 * num_file is pointer to number of matched file names
5208 * file is pointer to array of pointers to matched file names
5209 */
5210
5211#ifndef SEEK_SET
5212# define SEEK_SET 0
5213#endif
5214#ifndef SEEK_END
5215# define SEEK_END 2
5216#endif
5217
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005218#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005219
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220 int
5221mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5222 int num_pat;
5223 char_u **pat;
5224 int *num_file;
5225 char_u ***file;
5226 int flags; /* EW_* flags */
5227{
5228 int i;
5229 size_t len;
5230 char_u *p;
5231 int dir;
5232#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005233 /*
5234 * This is the OS/2 implementation.
5235 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236# define EXPL_ALLOC_INC 16
5237 char_u **expl_files;
5238 size_t files_alloced, files_free;
5239 char_u *buf;
5240 int has_wildcard;
5241
5242 *num_file = 0; /* default: no files found */
5243 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5244 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5245 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5246 if (*file == NULL)
5247 return FAIL;
5248
5249 for (; num_pat > 0; num_pat--, pat++)
5250 {
5251 expl_files = NULL;
5252 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5253 /* expand environment var or home dir */
5254 buf = expand_env_save(*pat);
5255 else
5256 buf = vim_strsave(*pat);
5257 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005258 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259 if (has_wildcard) /* yes, so expand them */
5260 expl_files = (char_u **)_fnexplode(buf);
5261
5262 /*
5263 * return value of buf if no wildcards left,
5264 * OR if no match AND EW_NOTFOUND is set.
5265 */
5266 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5267 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5268 { /* simply save the current contents of *buf */
5269 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5270 if (expl_files != NULL)
5271 {
5272 expl_files[0] = vim_strsave(buf);
5273 expl_files[1] = NULL;
5274 }
5275 }
5276 vim_free(buf);
5277
5278 /*
5279 * Count number of names resulting from expansion,
5280 * At the same time add a backslash to the end of names that happen to
5281 * be directories, and replace slashes with backslashes.
5282 */
5283 if (expl_files)
5284 {
5285 for (i = 0; (p = expl_files[i]) != NULL; i++)
5286 {
5287 dir = mch_isdir(p);
5288 /* If we don't want dirs and this is one, skip it */
5289 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5290 continue;
5291
Bram Moolenaara2031822006-03-07 22:29:51 +00005292 /* Skip files that are not executable if we check for that. */
5293 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5294 continue;
5295
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296 if (--files_free == 0)
5297 {
5298 /* need more room in table of pointers */
5299 files_alloced += EXPL_ALLOC_INC;
5300 *file = (char_u **)vim_realloc(*file,
5301 sizeof(char_u **) * files_alloced);
5302 if (*file == NULL)
5303 {
5304 EMSG(_(e_outofmem));
5305 *num_file = 0;
5306 return FAIL;
5307 }
5308 files_free = EXPL_ALLOC_INC;
5309 }
5310 slash_adjust(p);
5311 if (dir)
5312 {
5313 /* For a directory we add a '/', unless it's already
5314 * there. */
5315 len = STRLEN(p);
5316 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5317 {
5318 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005319 if (!after_pathsep((*file)[*num_file],
5320 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005321 {
5322 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005323 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005324 }
5325 }
5326 }
5327 else
5328 {
5329 (*file)[*num_file] = vim_strsave(p);
5330 }
5331
5332 /*
5333 * Error message already given by either alloc or vim_strsave.
5334 * Should return FAIL, but returning OK works also.
5335 */
5336 if ((*file)[*num_file] == NULL)
5337 break;
5338 (*num_file)++;
5339 }
5340 _fnexplodefree((char **)expl_files);
5341 }
5342 }
5343 return OK;
5344
5345#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005346 /*
5347 * This is the non-OS/2 implementation (really Unix).
5348 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349 int j;
5350 char_u *tempname;
5351 char_u *command;
5352 FILE *fd;
5353 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005354#define STYLE_ECHO 0 /* use "echo", the default */
5355#define STYLE_GLOB 1 /* use "glob", for csh */
5356#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5357#define STYLE_PRINT 3 /* use "print -N", for zsh */
5358#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5359 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360 int shell_style = STYLE_ECHO;
5361 int check_spaces;
5362 static int did_find_nul = FALSE;
5363 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005364 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005365 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005366
5367 *num_file = 0; /* default: no files found */
5368 *file = NULL;
5369
5370 /*
5371 * If there are no wildcards, just copy the names to allocated memory.
5372 * Saves a lot of time, because we don't have to start a new shell.
5373 */
5374 if (!have_wildcard(num_pat, pat))
5375 return save_patterns(num_pat, pat, num_file, file);
5376
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005377# ifdef HAVE_SANDBOX
5378 /* Don't allow any shell command in the sandbox. */
5379 if (sandbox != 0 && check_secure())
5380 return FAIL;
5381# endif
5382
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 /*
5384 * Don't allow the use of backticks in secure and restricted mode.
5385 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005386 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 for (i = 0; i < num_pat; ++i)
5388 if (vim_strchr(pat[i], '`') != NULL
5389 && (check_restricted() || check_secure()))
5390 return FAIL;
5391
5392 /*
5393 * get a name for the temp file
5394 */
5395 if ((tempname = vim_tempname('o')) == NULL)
5396 {
5397 EMSG(_(e_notmp));
5398 return FAIL;
5399 }
5400
5401 /*
5402 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005403 * file.
5404 * STYLE_BT: NL separated
5405 * If expanding `cmd` execute it directly.
5406 * STYLE_GLOB: NUL separated
5407 * If we use *csh, "glob" will work better than "echo".
5408 * STYLE_PRINT: NL or NUL separated
5409 * If we use *zsh, "print -N" will work better than "glob".
5410 * STYLE_VIMGLOB: NL separated
5411 * If we use *sh*, we define "vimglob()".
5412 * STYLE_ECHO: space separated.
5413 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 */
5415 if (num_pat == 1 && *pat[0] == '`'
5416 && (len = STRLEN(pat[0])) > 2
5417 && *(pat[0] + len - 1) == '`')
5418 shell_style = STYLE_BT;
5419 else if ((len = STRLEN(p_sh)) >= 3)
5420 {
5421 if (STRCMP(p_sh + len - 3, "csh") == 0)
5422 shell_style = STYLE_GLOB;
5423 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5424 shell_style = STYLE_PRINT;
5425 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005426 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5427 "sh") != NULL)
5428 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005429
Bram Moolenaarc7247912008-01-13 12:54:11 +00005430 /* Compute the length of the command. We need 2 extra bytes: for the
5431 * optional '&' and for the NUL.
5432 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005433 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005434 if (shell_style == STYLE_VIMGLOB)
5435 len += STRLEN(sh_vimglob_func);
5436
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005437 for (i = 0; i < num_pat; ++i)
5438 {
5439 /* Count the length of the patterns in the same way as they are put in
5440 * "command" below. */
5441#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005443#else
5444 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005445 for (j = 0; pat[i][j] != NUL; ++j)
5446 {
5447 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5448 ++len; /* may add a backslash */
5449 ++len;
5450 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005451#endif
5452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005453 command = alloc(len);
5454 if (command == NULL)
5455 {
5456 /* out of memory */
5457 vim_free(tempname);
5458 return FAIL;
5459 }
5460
5461 /*
5462 * Build the shell command:
5463 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5464 * recognizes this).
5465 * - Add the shell command to print the expanded names.
5466 * - Add the temp file name.
5467 * - Add the file name patterns.
5468 */
5469 if (shell_style == STYLE_BT)
5470 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005471 /* change `command; command& ` to (command; command ) */
5472 STRCPY(command, "(");
5473 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005475 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 while (p > command && vim_iswhite(*p))
5477 --p;
5478 if (*p == '&') /* remove trailing '&' */
5479 {
5480 ampersent = TRUE;
5481 *p = ' ';
5482 }
5483 STRCAT(command, ">");
5484 }
5485 else
5486 {
5487 if (flags & EW_NOTFOUND)
5488 STRCPY(command, "set nonomatch; ");
5489 else
5490 STRCPY(command, "unset nonomatch; ");
5491 if (shell_style == STYLE_GLOB)
5492 STRCAT(command, "glob >");
5493 else if (shell_style == STYLE_PRINT)
5494 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005495 else if (shell_style == STYLE_VIMGLOB)
5496 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 else
5498 STRCAT(command, "echo >");
5499 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005500
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005502
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503 if (shell_style != STYLE_BT)
5504 for (i = 0; i < num_pat; ++i)
5505 {
5506 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005507 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005508 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509#ifdef USE_SYSTEM
5510 STRCAT(command, " \"");
5511 STRCAT(command, pat[i]);
5512 STRCAT(command, "\"");
5513#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005514 int intick = FALSE;
5515
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516 p = command + STRLEN(command);
5517 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005518 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005519 {
5520 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005521 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005522 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5523 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005524 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005525 * backslash inside backticks, before a special character
5526 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005527 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005528 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5529 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005530 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005531 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005532 }
5533 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005534 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005535 /* Put a backslash before a special character, but not
5536 * when inside ``. */
5537 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005538
5539 /* Copy one character. */
5540 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005541 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 *p = NUL;
5543#endif
5544 }
5545 if (flags & EW_SILENT)
5546 show_shell_mess = FALSE;
5547 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005548 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549
5550 /*
5551 * Using zsh -G: If a pattern has no matches, it is just deleted from
5552 * the argument list, otherwise zsh gives an error message and doesn't
5553 * expand any other pattern.
5554 */
5555 if (shell_style == STYLE_PRINT)
5556 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5557
5558 /*
5559 * If we use -f then shell variables set in .cshrc won't get expanded.
5560 * vi can do it, so we will too, but it is only necessary if there is a "$"
5561 * in one of the patterns, otherwise we can still use the fast option.
5562 */
5563 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5564 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5565
5566 /*
5567 * execute the shell command
5568 */
5569 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5570
5571 /* When running in the background, give it some time to create the temp
5572 * file, but don't wait for it to finish. */
5573 if (ampersent)
5574 mch_delay(10L, TRUE);
5575
5576 extra_shell_arg = NULL; /* cleanup */
5577 show_shell_mess = TRUE;
5578 vim_free(command);
5579
Bram Moolenaarc7247912008-01-13 12:54:11 +00005580 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005581 {
5582 mch_remove(tempname);
5583 vim_free(tempname);
5584 /*
5585 * With interactive completion, the error message is not printed.
5586 * However with USE_SYSTEM, I don't know how to turn off error messages
5587 * from the shell, so screen may still get messed up -- webb.
5588 */
5589#ifndef USE_SYSTEM
5590 if (!(flags & EW_SILENT))
5591#endif
5592 {
5593 redraw_later_clear(); /* probably messed up screen */
5594 msg_putchar('\n'); /* clear bottom line quickly */
5595 cmdline_row = Rows - 1; /* continue on last line */
5596#ifdef USE_SYSTEM
5597 if (!(flags & EW_SILENT))
5598#endif
5599 {
5600 MSG(_(e_wildexpand));
5601 msg_start(); /* don't overwrite this message */
5602 }
5603 }
5604 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5605 * EW_NOTFOUND is given */
5606 if (shell_style == STYLE_BT)
5607 return FAIL;
5608 goto notfound;
5609 }
5610
5611 /*
5612 * read the names from the file into memory
5613 */
5614 fd = fopen((char *)tempname, READBIN);
5615 if (fd == NULL)
5616 {
5617 /* Something went wrong, perhaps a file name with a special char. */
5618 if (!(flags & EW_SILENT))
5619 {
5620 MSG(_(e_wildexpand));
5621 msg_start(); /* don't overwrite this message */
5622 }
5623 vim_free(tempname);
5624 goto notfound;
5625 }
5626 fseek(fd, 0L, SEEK_END);
5627 len = ftell(fd); /* get size of temp file */
5628 fseek(fd, 0L, SEEK_SET);
5629 buffer = alloc(len + 1);
5630 if (buffer == NULL)
5631 {
5632 /* out of memory */
5633 mch_remove(tempname);
5634 vim_free(tempname);
5635 fclose(fd);
5636 return FAIL;
5637 }
5638 i = fread((char *)buffer, 1, len, fd);
5639 fclose(fd);
5640 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005641 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 {
5643 /* unexpected read error */
5644 EMSG2(_(e_notread), tempname);
5645 vim_free(tempname);
5646 vim_free(buffer);
5647 return FAIL;
5648 }
5649 vim_free(tempname);
5650
Bram Moolenaarc7247912008-01-13 12:54:11 +00005651# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5653 p = buffer;
5654 for (i = 0; i < len; ++i)
5655 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5656 *p++ = buffer[i];
5657 len = p - buffer;
5658# endif
5659
5660
5661 /* file names are separated with Space */
5662 if (shell_style == STYLE_ECHO)
5663 {
5664 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5665 p = buffer;
5666 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5667 {
5668 while (*p != ' ' && *p != '\n')
5669 ++p;
5670 p = skipwhite(p); /* skip to next entry */
5671 }
5672 }
5673 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005674 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 {
5676 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5677 p = buffer;
5678 for (i = 0; *p != NUL; ++i) /* count number of entries */
5679 {
5680 while (*p != '\n' && *p != NUL)
5681 ++p;
5682 if (*p != NUL)
5683 ++p;
5684 p = skipwhite(p); /* skip leading white space */
5685 }
5686 }
5687 /* file names are separated with NUL */
5688 else
5689 {
5690 /*
5691 * Some versions of zsh use spaces instead of NULs to separate
5692 * results. Only do this when there is no NUL before the end of the
5693 * buffer, otherwise we would never be able to use file names with
5694 * embedded spaces when zsh does use NULs.
5695 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5696 * don't check for spaces again.
5697 */
5698 check_spaces = FALSE;
5699 if (shell_style == STYLE_PRINT && !did_find_nul)
5700 {
5701 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaar78a15312009-05-15 19:33:18 +00005702 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 did_find_nul = TRUE;
5704 else
5705 check_spaces = TRUE;
5706 }
5707
5708 /*
5709 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5710 * already is one, for STYLE_GLOB it needs to be added.
5711 */
5712 if (len && buffer[len - 1] == NUL)
5713 --len;
5714 else
5715 buffer[len] = NUL;
5716 i = 0;
5717 for (p = buffer; p < buffer + len; ++p)
5718 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5719 {
5720 ++i;
5721 *p = NUL;
5722 }
5723 if (len)
5724 ++i; /* count last entry */
5725 }
5726 if (i == 0)
5727 {
5728 /*
5729 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5730 * /bin/sh will happily expand it to nothing rather than returning an
5731 * error; and hey, it's good to check anyway -- webb.
5732 */
5733 vim_free(buffer);
5734 goto notfound;
5735 }
5736 *num_file = i;
5737 *file = (char_u **)alloc(sizeof(char_u *) * i);
5738 if (*file == NULL)
5739 {
5740 /* out of memory */
5741 vim_free(buffer);
5742 return FAIL;
5743 }
5744
5745 /*
5746 * Isolate the individual file names.
5747 */
5748 p = buffer;
5749 for (i = 0; i < *num_file; ++i)
5750 {
5751 (*file)[i] = p;
5752 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005753 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5754 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005756 while (!(shell_style == STYLE_ECHO && *p == ' ')
5757 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 ++p;
5759 if (p == buffer + len) /* last entry */
5760 *p = NUL;
5761 else
5762 {
5763 *p++ = NUL;
5764 p = skipwhite(p); /* skip to next entry */
5765 }
5766 }
5767 else /* NUL separates */
5768 {
5769 while (*p && p < buffer + len) /* skip entry */
5770 ++p;
5771 ++p; /* skip NUL */
5772 }
5773 }
5774
5775 /*
5776 * Move the file names to allocated memory.
5777 */
5778 for (j = 0, i = 0; i < *num_file; ++i)
5779 {
5780 /* Require the files to exist. Helps when using /bin/sh */
5781 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5782 continue;
5783
5784 /* check if this entry should be included */
5785 dir = (mch_isdir((*file)[i]));
5786 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5787 continue;
5788
Bram Moolenaara2031822006-03-07 22:29:51 +00005789 /* Skip files that are not executable if we check for that. */
5790 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5791 continue;
5792
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5794 if (p)
5795 {
5796 STRCPY(p, (*file)[i]);
5797 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005798 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 (*file)[j++] = p;
5800 }
5801 }
5802 vim_free(buffer);
5803 *num_file = j;
5804
5805 if (*num_file == 0) /* rejected all entries */
5806 {
5807 vim_free(*file);
5808 *file = NULL;
5809 goto notfound;
5810 }
5811
5812 return OK;
5813
5814notfound:
5815 if (flags & EW_NOTFOUND)
5816 return save_patterns(num_pat, pat, num_file, file);
5817 return FAIL;
5818
5819#endif /* __EMX__ */
5820}
5821
5822#endif /* VMS */
5823
5824#ifndef __EMX__
5825 static int
5826save_patterns(num_pat, pat, num_file, file)
5827 int num_pat;
5828 char_u **pat;
5829 int *num_file;
5830 char_u ***file;
5831{
5832 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005833 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834
5835 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5836 if (*file == NULL)
5837 return FAIL;
5838 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005839 {
5840 s = vim_strsave(pat[i]);
5841 if (s != NULL)
5842 /* Be compatible with expand_filename(): halve the number of
5843 * backslashes. */
5844 backslash_halve(s);
5845 (*file)[i] = s;
5846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 *num_file = num_pat;
5848 return OK;
5849}
5850#endif
5851
5852
5853/*
5854 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5855 * expand.
5856 */
5857 int
5858mch_has_exp_wildcard(p)
5859 char_u *p;
5860{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005861 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 {
5863#ifndef OS2
5864 if (*p == '\\' && p[1] != NUL)
5865 ++p;
5866 else
5867#endif
5868 if (vim_strchr((char_u *)
5869#ifdef VMS
5870 "*?%"
5871#else
5872# ifdef OS2
5873 "*?"
5874# else
5875 "*?[{'"
5876# endif
5877#endif
5878 , *p) != NULL)
5879 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880 }
5881 return FALSE;
5882}
5883
5884/*
5885 * Return TRUE if the string "p" contains a wildcard.
5886 * Don't recognize '~' at the end as a wildcard.
5887 */
5888 int
5889mch_has_wildcard(p)
5890 char_u *p;
5891{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005892 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893 {
5894#ifndef OS2
5895 if (*p == '\\' && p[1] != NUL)
5896 ++p;
5897 else
5898#endif
5899 if (vim_strchr((char_u *)
5900#ifdef VMS
5901 "*?%$"
5902#else
5903# ifdef OS2
5904# ifdef VIM_BACKTICK
5905 "*?$`"
5906# else
5907 "*?$"
5908# endif
5909# else
5910 "*?[{`'$"
5911# endif
5912#endif
5913 , *p) != NULL
5914 || (*p == '~' && p[1] != NUL))
5915 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916 }
5917 return FALSE;
5918}
5919
5920#ifndef __EMX__
5921 static int
5922have_wildcard(num, file)
5923 int num;
5924 char_u **file;
5925{
5926 int i;
5927
5928 for (i = 0; i < num; i++)
5929 if (mch_has_wildcard(file[i]))
5930 return 1;
5931 return 0;
5932}
5933
5934 static int
5935have_dollars(num, file)
5936 int num;
5937 char_u **file;
5938{
5939 int i;
5940
5941 for (i = 0; i < num; i++)
5942 if (vim_strchr(file[i], '$') != NULL)
5943 return TRUE;
5944 return FALSE;
5945}
5946#endif /* ifndef __EMX__ */
5947
5948#ifndef HAVE_RENAME
5949/*
5950 * Scaled-down version of rename(), which is missing in Xenix.
5951 * This version can only move regular files and will fail if the
5952 * destination exists.
5953 */
5954 int
5955mch_rename(src, dest)
5956 const char *src, *dest;
5957{
5958 struct stat st;
5959
5960 if (stat(dest, &st) >= 0) /* fail if destination exists */
5961 return -1;
5962 if (link(src, dest) != 0) /* link file to new name */
5963 return -1;
5964 if (mch_remove(src) == 0) /* delete link to old name */
5965 return 0;
5966 return -1;
5967}
5968#endif /* !HAVE_RENAME */
5969
5970#ifdef FEAT_MOUSE_GPM
5971/*
5972 * Initializes connection with gpm (if it isn't already opened)
5973 * Return 1 if succeeded (or connection already opened), 0 if failed
5974 */
5975 static int
5976gpm_open()
5977{
5978 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
5979
5980 if (!gpm_flag)
5981 {
5982 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
5983 gpm_connect.defaultMask = ~GPM_HARD;
5984 /* Default handling for mouse move*/
5985 gpm_connect.minMod = 0; /* Handle any modifier keys */
5986 gpm_connect.maxMod = 0xffff;
5987 if (Gpm_Open(&gpm_connect, 0) > 0)
5988 {
5989 /* gpm library tries to handling TSTP causes
5990 * problems. Anyways, we close connection to Gpm whenever
5991 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005992 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00005994# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00005996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997 return 1; /* succeed */
5998 }
5999 if (gpm_fd == -2)
6000 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6001 return 0;
6002 }
6003 return 1; /* already open */
6004}
6005
6006/*
6007 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 */
6009 static void
6010gpm_close()
6011{
6012 if (gpm_flag && gpm_fd >= 0) /* if Open */
6013 Gpm_Close();
6014}
6015
6016/* Reads gpm event and adds special keys to input buf. Returns length of
6017 * generated key sequence.
6018 * This function is made after gui_send_mouse_event
6019 */
6020 static int
6021mch_gpm_process()
6022{
6023 int button;
6024 static Gpm_Event gpm_event;
6025 char_u string[6];
6026 int_u vim_modifiers;
6027 int row,col;
6028 unsigned char buttons_mask;
6029 unsigned char gpm_modifiers;
6030 static unsigned char old_buttons = 0;
6031
6032 Gpm_GetEvent(&gpm_event);
6033
6034#ifdef FEAT_GUI
6035 /* Don't put events in the input queue now. */
6036 if (hold_gui_events)
6037 return 0;
6038#endif
6039
6040 row = gpm_event.y - 1;
6041 col = gpm_event.x - 1;
6042
6043 string[0] = ESC; /* Our termcode */
6044 string[1] = 'M';
6045 string[2] = 'G';
6046 switch (GPM_BARE_EVENTS(gpm_event.type))
6047 {
6048 case GPM_DRAG:
6049 string[3] = MOUSE_DRAG;
6050 break;
6051 case GPM_DOWN:
6052 buttons_mask = gpm_event.buttons & ~old_buttons;
6053 old_buttons = gpm_event.buttons;
6054 switch (buttons_mask)
6055 {
6056 case GPM_B_LEFT:
6057 button = MOUSE_LEFT;
6058 break;
6059 case GPM_B_MIDDLE:
6060 button = MOUSE_MIDDLE;
6061 break;
6062 case GPM_B_RIGHT:
6063 button = MOUSE_RIGHT;
6064 break;
6065 default:
6066 return 0;
6067 /*Don't know what to do. Can more than one button be
6068 * reported in one event? */
6069 }
6070 string[3] = (char_u)(button | 0x20);
6071 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6072 break;
6073 case GPM_UP:
6074 string[3] = MOUSE_RELEASE;
6075 old_buttons &= ~gpm_event.buttons;
6076 break;
6077 default:
6078 return 0;
6079 }
6080 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6081 gpm_modifiers = gpm_event.modifiers;
6082 vim_modifiers = 0x0;
6083 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6084 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6085 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6086 */
6087 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6088 vim_modifiers |= MOUSE_SHIFT;
6089
6090 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6091 vim_modifiers |= MOUSE_CTRL;
6092 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6093 vim_modifiers |= MOUSE_ALT;
6094 string[3] |= vim_modifiers;
6095 string[4] = (char_u)(col + ' ' + 1);
6096 string[5] = (char_u)(row + ' ' + 1);
6097 add_to_input_buf(string, 6);
6098 return 6;
6099}
6100#endif /* FEAT_MOUSE_GPM */
6101
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006102#ifdef FEAT_SYSMOUSE
6103/*
6104 * Initialize connection with sysmouse.
6105 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6106 * output, any sysmouse output than will be processed via sig_sysmouse().
6107 * Return OK if succeeded, FAIL if failed.
6108 */
6109 static int
6110sysmouse_open()
6111{
6112 struct mouse_info mouse;
6113
6114 mouse.operation = MOUSE_MODE;
6115 mouse.u.mode.mode = 0;
6116 mouse.u.mode.signal = SIGUSR2;
6117 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6118 {
6119 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6120 mouse.operation = MOUSE_SHOW;
6121 ioctl(1, CONS_MOUSECTL, &mouse);
6122 return OK;
6123 }
6124 return FAIL;
6125}
6126
6127/*
6128 * Stop processing SIGUSR2 signals, and also make sure that
6129 * virtual console do not send us any sysmouse related signal.
6130 */
6131 static void
6132sysmouse_close()
6133{
6134 struct mouse_info mouse;
6135
6136 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6137 mouse.operation = MOUSE_MODE;
6138 mouse.u.mode.mode = 0;
6139 mouse.u.mode.signal = 0;
6140 ioctl(1, CONS_MOUSECTL, &mouse);
6141}
6142
6143/*
6144 * Gets info from sysmouse and adds special keys to input buf.
6145 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006146 static RETSIGTYPE
6147sig_sysmouse SIGDEFARG(sigarg)
6148{
6149 struct mouse_info mouse;
6150 struct video_info video;
6151 char_u string[6];
6152 int row, col;
6153 int button;
6154 int buttons;
6155 static int oldbuttons = 0;
6156
6157#ifdef FEAT_GUI
6158 /* Don't put events in the input queue now. */
6159 if (hold_gui_events)
6160 return;
6161#endif
6162
6163 mouse.operation = MOUSE_GETINFO;
6164 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6165 && ioctl(1, FBIO_MODEINFO, &video) != -1
6166 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6167 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6168 {
6169 row = mouse.u.data.y / video.vi_cheight;
6170 col = mouse.u.data.x / video.vi_cwidth;
6171 buttons = mouse.u.data.buttons;
6172 string[0] = ESC; /* Our termcode */
6173 string[1] = 'M';
6174 string[2] = 'S';
6175 if (oldbuttons == buttons && buttons != 0)
6176 {
6177 button = MOUSE_DRAG;
6178 }
6179 else
6180 {
6181 switch (buttons)
6182 {
6183 case 0:
6184 button = MOUSE_RELEASE;
6185 break;
6186 case 1:
6187 button = MOUSE_LEFT;
6188 break;
6189 case 2:
6190 button = MOUSE_MIDDLE;
6191 break;
6192 case 4:
6193 button = MOUSE_RIGHT;
6194 break;
6195 default:
6196 return;
6197 }
6198 oldbuttons = buttons;
6199 }
6200 string[3] = (char_u)(button);
6201 string[4] = (char_u)(col + ' ' + 1);
6202 string[5] = (char_u)(row + ' ' + 1);
6203 add_to_input_buf(string, 6);
6204 }
6205 return;
6206}
6207#endif /* FEAT_SYSMOUSE */
6208
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209#if defined(FEAT_LIBCALL) || defined(PROTO)
6210typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6211typedef char_u * (*INTPROCSTR)__ARGS((int));
6212typedef int (*STRPROCINT)__ARGS((char_u *));
6213typedef int (*INTPROCINT)__ARGS((int));
6214
6215/*
6216 * Call a DLL routine which takes either a string or int param
6217 * and returns an allocated string.
6218 */
6219 int
6220mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6221 char_u *libname;
6222 char_u *funcname;
6223 char_u *argstring; /* NULL when using a argint */
6224 int argint;
6225 char_u **string_result;/* NULL when using number_result */
6226 int *number_result;
6227{
6228# if defined(USE_DLOPEN)
6229 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006230 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231# else
6232 shl_t hinstLib;
6233# endif
6234 STRPROCSTR ProcAdd;
6235 INTPROCSTR ProcAddI;
6236 char_u *retval_str = NULL;
6237 int retval_int = 0;
6238 int success = FALSE;
6239
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006240 /*
6241 * Get a handle to the DLL module.
6242 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006244 /* First clear any error, it's not cleared by the dlopen() call. */
6245 (void)dlerror();
6246
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 hinstLib = dlopen((char *)libname, RTLD_LAZY
6248# ifdef RTLD_LOCAL
6249 | RTLD_LOCAL
6250# endif
6251 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006252 if (hinstLib == NULL)
6253 {
6254 /* "dlerr" must be used before dlclose() */
6255 dlerr = (char *)dlerror();
6256 if (dlerr != NULL)
6257 EMSG2(_("dlerror = \"%s\""), dlerr);
6258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259# else
6260 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6261# endif
6262
6263 /* If the handle is valid, try to get the function address. */
6264 if (hinstLib != NULL)
6265 {
6266# ifdef HAVE_SETJMP_H
6267 /*
6268 * Catch a crash when calling the library function. For example when
6269 * using a number where a string pointer is expected.
6270 */
6271 mch_startjmp();
6272 if (SETJMP(lc_jump_env) != 0)
6273 {
6274 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006275# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006276 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006277# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 mch_didjmp();
6279 }
6280 else
6281# endif
6282 {
6283 retval_str = NULL;
6284 retval_int = 0;
6285
6286 if (argstring != NULL)
6287 {
6288# if defined(USE_DLOPEN)
6289 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006290 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291# else
6292 if (shl_findsym(&hinstLib, (const char *)funcname,
6293 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6294 ProcAdd = NULL;
6295# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006296 if ((success = (ProcAdd != NULL
6297# if defined(USE_DLOPEN)
6298 && dlerr == NULL
6299# endif
6300 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 {
6302 if (string_result == NULL)
6303 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6304 else
6305 retval_str = (ProcAdd)(argstring);
6306 }
6307 }
6308 else
6309 {
6310# if defined(USE_DLOPEN)
6311 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006312 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313# else
6314 if (shl_findsym(&hinstLib, (const char *)funcname,
6315 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6316 ProcAddI = NULL;
6317# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006318 if ((success = (ProcAddI != NULL
6319# if defined(USE_DLOPEN)
6320 && dlerr == NULL
6321# endif
6322 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 {
6324 if (string_result == NULL)
6325 retval_int = ((INTPROCINT)ProcAddI)(argint);
6326 else
6327 retval_str = (ProcAddI)(argint);
6328 }
6329 }
6330
6331 /* Save the string before we free the library. */
6332 /* Assume that a "1" or "-1" result is an illegal pointer. */
6333 if (string_result == NULL)
6334 *number_result = retval_int;
6335 else if (retval_str != NULL
6336 && retval_str != (char_u *)1
6337 && retval_str != (char_u *)-1)
6338 *string_result = vim_strsave(retval_str);
6339 }
6340
6341# ifdef HAVE_SETJMP_H
6342 mch_endjmp();
6343# ifdef SIGHASARG
6344 if (lc_signal != 0)
6345 {
6346 int i;
6347
6348 /* try to find the name of this signal */
6349 for (i = 0; signal_info[i].sig != -1; i++)
6350 if (lc_signal == signal_info[i].sig)
6351 break;
6352 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6353 }
6354# endif
6355# endif
6356
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006358 /* "dlerr" must be used before dlclose() */
6359 if (dlerr != NULL)
6360 EMSG2(_("dlerror = \"%s\""), dlerr);
6361
6362 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 (void)dlclose(hinstLib);
6364# else
6365 (void)shl_unload(hinstLib);
6366# endif
6367 }
6368
6369 if (!success)
6370 {
6371 EMSG2(_(e_libcall), funcname);
6372 return FAIL;
6373 }
6374
6375 return OK;
6376}
6377#endif
6378
6379#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6380static int xterm_trace = -1; /* default: disabled */
6381static int xterm_button;
6382
6383/*
6384 * Setup a dummy window for X selections in a terminal.
6385 */
6386 void
6387setup_term_clip()
6388{
6389 int z = 0;
6390 char *strp = "";
6391 Widget AppShell;
6392
6393 if (!x_connect_to_server())
6394 return;
6395
6396 open_app_context();
6397 if (app_context != NULL && xterm_Shell == (Widget)0)
6398 {
6399 int (*oldhandler)();
6400#if defined(HAVE_SETJMP_H)
6401 int (*oldIOhandler)();
6402#endif
6403# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6404 struct timeval start_tv;
6405
6406 if (p_verbose > 0)
6407 gettimeofday(&start_tv, NULL);
6408# endif
6409
6410 /* Ignore X errors while opening the display */
6411 oldhandler = XSetErrorHandler(x_error_check);
6412
6413#if defined(HAVE_SETJMP_H)
6414 /* Ignore X IO errors while opening the display */
6415 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6416 mch_startjmp();
6417 if (SETJMP(lc_jump_env) != 0)
6418 {
6419 mch_didjmp();
6420 xterm_dpy = NULL;
6421 }
6422 else
6423#endif
6424 {
6425 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6426 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6427#if defined(HAVE_SETJMP_H)
6428 mch_endjmp();
6429#endif
6430 }
6431
6432#if defined(HAVE_SETJMP_H)
6433 /* Now handle X IO errors normally. */
6434 (void)XSetIOErrorHandler(oldIOhandler);
6435#endif
6436 /* Now handle X errors normally. */
6437 (void)XSetErrorHandler(oldhandler);
6438
6439 if (xterm_dpy == NULL)
6440 {
6441 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006442 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443 return;
6444 }
6445
6446 /* Catch terminating error of the X server connection. */
6447 (void)XSetIOErrorHandler(x_IOerror_handler);
6448
6449# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6450 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006451 {
6452 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006454 verbose_leave();
6455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456# endif
6457
6458 /* Create a Shell to make converters work. */
6459 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6460 applicationShellWidgetClass, xterm_dpy,
6461 NULL);
6462 if (AppShell == (Widget)0)
6463 return;
6464 xterm_Shell = XtVaCreatePopupShell("VIM",
6465 topLevelShellWidgetClass, AppShell,
6466 XtNmappedWhenManaged, 0,
6467 XtNwidth, 1,
6468 XtNheight, 1,
6469 NULL);
6470 if (xterm_Shell == (Widget)0)
6471 return;
6472
6473 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006474 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 if (x11_display == NULL)
6476 x11_display = xterm_dpy;
6477
6478 XtRealizeWidget(xterm_Shell);
6479 XSync(xterm_dpy, False);
6480 xterm_update();
6481 }
6482 if (xterm_Shell != (Widget)0)
6483 {
6484 clip_init(TRUE);
6485 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6486 x11_window = (Window)atol(strp);
6487 /* Check if $WINDOWID is valid. */
6488 if (test_x11_window(xterm_dpy) == FAIL)
6489 x11_window = 0;
6490 if (x11_window != 0)
6491 xterm_trace = 0;
6492 }
6493}
6494
6495 void
6496start_xterm_trace(button)
6497 int button;
6498{
6499 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6500 return;
6501 xterm_trace = 1;
6502 xterm_button = button;
6503 do_xterm_trace();
6504}
6505
6506
6507 void
6508stop_xterm_trace()
6509{
6510 if (xterm_trace < 0)
6511 return;
6512 xterm_trace = 0;
6513}
6514
6515/*
6516 * Query the xterm pointer and generate mouse termcodes if necessary
6517 * return TRUE if dragging is active, else FALSE
6518 */
6519 static int
6520do_xterm_trace()
6521{
6522 Window root, child;
6523 int root_x, root_y;
6524 int win_x, win_y;
6525 int row, col;
6526 int_u mask_return;
6527 char_u buf[50];
6528 char_u *strp;
6529 long got_hints;
6530 static char_u *mouse_code;
6531 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6532 static int prev_row = 0, prev_col = 0;
6533 static XSizeHints xterm_hints;
6534
6535 if (xterm_trace <= 0)
6536 return FALSE;
6537
6538 if (xterm_trace == 1)
6539 {
6540 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006541 * have changed recently. */
6542 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6543 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 || xterm_hints.width_inc <= 1
6545 || xterm_hints.height_inc <= 1)
6546 {
6547 xterm_trace = -1; /* Not enough data -- disable tracing */
6548 return FALSE;
6549 }
6550
6551 /* Rely on the same mouse code for the duration of this */
6552 mouse_code = find_termcode(mouse_name);
6553 prev_row = mouse_row;
6554 prev_row = mouse_col;
6555 xterm_trace = 2;
6556
6557 /* Find the offset of the chars, there might be a scrollbar on the
6558 * left of the window and/or a menu on the top (eterm etc.) */
6559 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6560 &win_x, &win_y, &mask_return);
6561 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6562 - (xterm_hints.height_inc / 2);
6563 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6564 xterm_hints.y = 2;
6565 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6566 - (xterm_hints.width_inc / 2);
6567 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6568 xterm_hints.x = 2;
6569 return TRUE;
6570 }
6571 if (mouse_code == NULL)
6572 {
6573 xterm_trace = 0;
6574 return FALSE;
6575 }
6576
6577 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6578 &win_x, &win_y, &mask_return);
6579
6580 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6581 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6582 if (row == prev_row && col == prev_col)
6583 return TRUE;
6584
6585 STRCPY(buf, mouse_code);
6586 strp = buf + STRLEN(buf);
6587 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6588 *strp++ = (char_u)(col + ' ' + 1);
6589 *strp++ = (char_u)(row + ' ' + 1);
6590 *strp = 0;
6591 add_to_input_buf(buf, STRLEN(buf));
6592
6593 prev_row = row;
6594 prev_col = col;
6595 return TRUE;
6596}
6597
6598# if defined(FEAT_GUI) || defined(PROTO)
6599/*
6600 * Destroy the display, window and app_context. Required for GTK.
6601 */
6602 void
6603clear_xterm_clip()
6604{
6605 if (xterm_Shell != (Widget)0)
6606 {
6607 XtDestroyWidget(xterm_Shell);
6608 xterm_Shell = (Widget)0;
6609 }
6610 if (xterm_dpy != NULL)
6611 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006612# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 /* Lesstif and Solaris crash here, lose some memory */
6614 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006615# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 if (x11_display == xterm_dpy)
6617 x11_display = NULL;
6618 xterm_dpy = NULL;
6619 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006620# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 if (app_context != (XtAppContext)NULL)
6622 {
6623 /* Lesstif and Solaris crash here, lose some memory */
6624 XtDestroyApplicationContext(app_context);
6625 app_context = (XtAppContext)NULL;
6626 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628}
6629# endif
6630
6631/*
6632 * Catch up with any queued X events. This may put keyboard input into the
6633 * input buffer, call resize call-backs, trigger timers etc. If there is
6634 * nothing in the X event queue (& no timers pending), then we return
6635 * immediately.
6636 */
6637 static void
6638xterm_update()
6639{
6640 XEvent event;
6641
6642 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6643 {
6644 XtAppNextEvent(app_context, &event);
6645#ifdef FEAT_CLIENTSERVER
6646 {
6647 XPropertyEvent *e = (XPropertyEvent *)&event;
6648
6649 if (e->type == PropertyNotify && e->window == commWindow
6650 && e->atom == commProperty && e->state == PropertyNewValue)
6651 serverEventProc(xterm_dpy, &event);
6652 }
6653#endif
6654 XtDispatchEvent(&event);
6655 }
6656}
6657
6658 int
6659clip_xterm_own_selection(cbd)
6660 VimClipboard *cbd;
6661{
6662 if (xterm_Shell != (Widget)0)
6663 return clip_x11_own_selection(xterm_Shell, cbd);
6664 return FAIL;
6665}
6666
6667 void
6668clip_xterm_lose_selection(cbd)
6669 VimClipboard *cbd;
6670{
6671 if (xterm_Shell != (Widget)0)
6672 clip_x11_lose_selection(xterm_Shell, cbd);
6673}
6674
6675 void
6676clip_xterm_request_selection(cbd)
6677 VimClipboard *cbd;
6678{
6679 if (xterm_Shell != (Widget)0)
6680 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6681}
6682
6683 void
6684clip_xterm_set_selection(cbd)
6685 VimClipboard *cbd;
6686{
6687 clip_x11_set_selection(cbd);
6688}
6689#endif
6690
6691
6692#if defined(USE_XSMP) || defined(PROTO)
6693/*
6694 * Code for X Session Management Protocol.
6695 */
6696static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6697static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6698static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6699static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6700static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6701
6702
6703# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6704static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6705
6706/*
6707 * This is our chance to ask the user if they want to save,
6708 * or abort the logout
6709 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 static void
6711xsmp_handle_interaction(smc_conn, client_data)
6712 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006713 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714{
6715 cmdmod_T save_cmdmod;
6716 int cancel_shutdown = False;
6717
6718 save_cmdmod = cmdmod;
6719 cmdmod.confirm = TRUE;
6720 if (check_changed_any(FALSE))
6721 /* Mustn't logout */
6722 cancel_shutdown = True;
6723 cmdmod = save_cmdmod;
6724 setcursor(); /* position cursor */
6725 out_flush();
6726
6727 /* Done interaction */
6728 SmcInteractDone(smc_conn, cancel_shutdown);
6729
6730 /* Finish off
6731 * Only end save-yourself here if we're not cancelling shutdown;
6732 * we'll get a cancelled callback later in which we'll end it.
6733 * Hopefully get around glitchy SMs (like GNOME-1)
6734 */
6735 if (!cancel_shutdown)
6736 {
6737 xsmp.save_yourself = False;
6738 SmcSaveYourselfDone(smc_conn, True);
6739 }
6740}
6741# endif
6742
6743/*
6744 * Callback that starts save-yourself.
6745 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 static void
6747xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6748 shutdown, interact_style, fast)
6749 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006750 SmPointer client_data UNUSED;
6751 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006753 int interact_style UNUSED;
6754 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755{
6756 /* Handle already being in saveyourself */
6757 if (xsmp.save_yourself)
6758 SmcSaveYourselfDone(smc_conn, True);
6759 xsmp.save_yourself = True;
6760 xsmp.shutdown = shutdown;
6761
6762 /* First up, preserve all files */
6763 out_flush();
6764 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6765
6766 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006767 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768
6769# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6770 /* Now see if we can ask about unsaved files */
6771 if (shutdown && !fast && gui.in_use)
6772 /* Need to interact with user, but need SM's permission */
6773 SmcInteractRequest(smc_conn, SmDialogError,
6774 xsmp_handle_interaction, client_data);
6775 else
6776# endif
6777 {
6778 /* Can stop the cycle here */
6779 SmcSaveYourselfDone(smc_conn, True);
6780 xsmp.save_yourself = False;
6781 }
6782}
6783
6784
6785/*
6786 * Callback to warn us of imminent death.
6787 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 static void
6789xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006790 SmcConn smc_conn UNUSED;
6791 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792{
6793 xsmp_close();
6794
6795 /* quit quickly leaving swapfiles for modified buffers behind */
6796 getout_preserve_modified(0);
6797}
6798
6799
6800/*
6801 * Callback to tell us that save-yourself has completed.
6802 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 static void
6804xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006805 SmcConn smc_conn UNUSED;
6806 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807{
6808 xsmp.save_yourself = False;
6809}
6810
6811
6812/*
6813 * Callback to tell us that an instigated shutdown was cancelled
6814 * (maybe even by us)
6815 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 static void
6817xsmp_shutdown_cancelled(smc_conn, client_data)
6818 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006819 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820{
6821 if (xsmp.save_yourself)
6822 SmcSaveYourselfDone(smc_conn, True);
6823 xsmp.save_yourself = False;
6824 xsmp.shutdown = False;
6825}
6826
6827
6828/*
6829 * Callback to tell us that a new ICE connection has been established.
6830 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831 static void
6832xsmp_ice_connection(iceConn, clientData, opening, watchData)
6833 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006834 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006836 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837{
6838 /* Intercept creation of ICE connection fd */
6839 if (opening)
6840 {
6841 xsmp_icefd = IceConnectionNumber(iceConn);
6842 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6843 }
6844}
6845
6846
6847/* Handle any ICE processing that's required; return FAIL if SM lost */
6848 int
6849xsmp_handle_requests()
6850{
6851 Bool rep;
6852
6853 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6854 == IceProcessMessagesIOError)
6855 {
6856 /* Lost ICE */
6857 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006858 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006859 xsmp_close();
6860 return FAIL;
6861 }
6862 else
6863 return OK;
6864}
6865
6866static int dummy;
6867
6868/* Set up X Session Management Protocol */
6869 void
6870xsmp_init(void)
6871{
6872 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 SmcCallbacks smcallbacks;
6874#if 0
6875 SmPropValue smname;
6876 SmProp smnameprop;
6877 SmProp *smprops[1];
6878#endif
6879
6880 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006881 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882
6883 xsmp.save_yourself = xsmp.shutdown = False;
6884
6885 /* Set up SM callbacks - must have all, even if they're not used */
6886 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6887 smcallbacks.save_yourself.client_data = NULL;
6888 smcallbacks.die.callback = xsmp_die;
6889 smcallbacks.die.client_data = NULL;
6890 smcallbacks.save_complete.callback = xsmp_save_complete;
6891 smcallbacks.save_complete.client_data = NULL;
6892 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6893 smcallbacks.shutdown_cancelled.client_data = NULL;
6894
6895 /* Set up a watch on ICE connection creations. The "dummy" argument is
6896 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6897 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6898 {
6899 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006900 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901 return;
6902 }
6903
6904 /* Create an SM connection */
6905 xsmp.smcconn = SmcOpenConnection(
6906 NULL,
6907 NULL,
6908 SmProtoMajor,
6909 SmProtoMinor,
6910 SmcSaveYourselfProcMask | SmcDieProcMask
6911 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6912 &smcallbacks,
6913 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00006914 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 sizeof(errorstring),
6916 errorstring);
6917 if (xsmp.smcconn == NULL)
6918 {
6919 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006920
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006922 {
6923 vim_snprintf(errorreport, sizeof(errorreport),
6924 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6925 verb_msg((char_u *)errorreport);
6926 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 return;
6928 }
6929 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6930
6931#if 0
6932 /* ID ourselves */
6933 smname.value = "vim";
6934 smname.length = 3;
6935 smnameprop.name = "SmProgram";
6936 smnameprop.type = "SmARRAY8";
6937 smnameprop.num_vals = 1;
6938 smnameprop.vals = &smname;
6939
6940 smprops[0] = &smnameprop;
6941 SmcSetProperties(xsmp.smcconn, 1, smprops);
6942#endif
6943}
6944
6945
6946/* Shut down XSMP comms. */
6947 void
6948xsmp_close()
6949{
6950 if (xsmp_icefd != -1)
6951 {
6952 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00006953 if (xsmp.clientid != NULL)
6954 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00006955 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 xsmp_icefd = -1;
6957 }
6958}
6959#endif /* USE_XSMP */
6960
6961
6962#ifdef EBCDIC
6963/* Translate character to its CTRL- value */
6964char CtrlTable[] =
6965{
6966/* 00 - 5E */
6967 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6968 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6969 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6970 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6971 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6972 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6973/* ^ */ 0x1E,
6974/* - */ 0x1F,
6975/* 61 - 6C */
6976 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6977/* _ */ 0x1F,
6978/* 6E - 80 */
6979 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6980/* a */ 0x01,
6981/* b */ 0x02,
6982/* c */ 0x03,
6983/* d */ 0x37,
6984/* e */ 0x2D,
6985/* f */ 0x2E,
6986/* g */ 0x2F,
6987/* h */ 0x16,
6988/* i */ 0x05,
6989/* 8A - 90 */
6990 0, 0, 0, 0, 0, 0, 0,
6991/* j */ 0x15,
6992/* k */ 0x0B,
6993/* l */ 0x0C,
6994/* m */ 0x0D,
6995/* n */ 0x0E,
6996/* o */ 0x0F,
6997/* p */ 0x10,
6998/* q */ 0x11,
6999/* r */ 0x12,
7000/* 9A - A1 */
7001 0, 0, 0, 0, 0, 0, 0, 0,
7002/* s */ 0x13,
7003/* t */ 0x3C,
7004/* u */ 0x3D,
7005/* v */ 0x32,
7006/* w */ 0x26,
7007/* x */ 0x18,
7008/* y */ 0x19,
7009/* z */ 0x3F,
7010/* AA - AC */
7011 0, 0, 0,
7012/* [ */ 0x27,
7013/* AE - BC */
7014 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7015/* ] */ 0x1D,
7016/* BE - C0 */ 0, 0, 0,
7017/* A */ 0x01,
7018/* B */ 0x02,
7019/* C */ 0x03,
7020/* D */ 0x37,
7021/* E */ 0x2D,
7022/* F */ 0x2E,
7023/* G */ 0x2F,
7024/* H */ 0x16,
7025/* I */ 0x05,
7026/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7027/* J */ 0x15,
7028/* K */ 0x0B,
7029/* L */ 0x0C,
7030/* M */ 0x0D,
7031/* N */ 0x0E,
7032/* O */ 0x0F,
7033/* P */ 0x10,
7034/* Q */ 0x11,
7035/* R */ 0x12,
7036/* DA - DF */ 0, 0, 0, 0, 0, 0,
7037/* \ */ 0x1C,
7038/* E1 */ 0,
7039/* S */ 0x13,
7040/* T */ 0x3C,
7041/* U */ 0x3D,
7042/* V */ 0x32,
7043/* W */ 0x26,
7044/* X */ 0x18,
7045/* Y */ 0x19,
7046/* Z */ 0x3F,
7047/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7048 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7049};
7050
7051char MetaCharTable[]=
7052{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7053 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7054 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7055 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7056 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7057};
7058
7059
7060/* TODO: Use characters NOT numbers!!! */
7061char CtrlCharTable[]=
7062{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7063 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7064 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7065 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7066 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7067};
7068
7069
7070#endif