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