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