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