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