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