blob: cda5407f83834884f6bad3adcaafc385de3fc991 [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 Moolenaar5bd32f42014-04-02 14:05:38 +020049#ifdef HAVE_SMACK
50# include <attr/xattr.h>
51# include <linux/xattr.h>
52# ifndef SMACK_LABEL_LEN
53# define SMACK_LABEL_LEN 1024
54# endif
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057/*
58 * Use this prototype for select, some include files have a wrong prototype
59 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000060#ifndef __TANDEM
61# undef select
62# ifdef __BEOS__
63# define select beos_select
64# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#endif
66
Bram Moolenaara2442432007-04-26 14:26:37 +000067#ifdef __CYGWIN__
68# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000069# include <cygwin/version.h>
70# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
71 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010072# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
73# define WIN32_LEAN_AND_MEAN
74# include <windows.h>
75# include "winclip.pro"
76# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000077# endif
78#endif
79
Bram Moolenaar071d4272004-06-13 20:20:40 +000080#if defined(HAVE_SELECT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +010081extern int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
Bram Moolenaar071d4272004-06-13 20:20:40 +000082#endif
83
84#ifdef FEAT_MOUSE_GPM
85# include <gpm.h>
86/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
87 * I just copied relevant defines here. A cleaner solution would be to put gpm
88 * code into separate file and include there linux/keyboard.h
89 */
90/* #include <linux/keyboard.h> */
91# define KG_SHIFT 0
92# define KG_CTRL 2
93# define KG_ALT 3
94# define KG_ALTGR 1
95# define KG_SHIFTL 4
96# define KG_SHIFTR 5
97# define KG_CTRLL 6
98# define KG_CTRLR 7
99# define KG_CAPSSHIFT 8
100
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100101static void gpm_close(void);
102static int gpm_open(void);
103static int mch_gpm_process(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104#endif
105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000106#ifdef FEAT_SYSMOUSE
107# include <sys/consio.h>
108# include <sys/fbio.h>
109
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100110static int sysmouse_open(void);
111static void sysmouse_close(void);
Bram Moolenaard99df422016-01-29 23:20:40 +0100112static RETSIGTYPE sig_sysmouse SIGPROTOARG;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000113#endif
114
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115/*
116 * end of autoconf section. To be extended...
117 */
118
119/* Are the following #ifdefs still required? And why? Is that for X11? */
120
121#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
122# ifdef SIGWINCH
123# undef SIGWINCH
124# endif
125# ifdef TIOCGWINSZ
126# undef TIOCGWINSZ
127# endif
128#endif
129
130#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
131# define SIGWINCH SIGWINDOW
132#endif
133
134#ifdef FEAT_X11
135# include <X11/Xlib.h>
136# include <X11/Xutil.h>
137# include <X11/Xatom.h>
138# ifdef FEAT_XCLIPBOARD
139# include <X11/Intrinsic.h>
140# include <X11/Shell.h>
141# include <X11/StringDefs.h>
142static Widget xterm_Shell = (Widget)0;
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100143static void clip_update(void);
144static void xterm_update(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145# endif
146
147# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
148Window x11_window = 0;
149# endif
150Display *x11_display = NULL;
151
152# ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100153static int get_x11_windis(void);
154static void set_x11_title(char_u *);
155static void set_x11_icon(char_u *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156# endif
157#endif
158
159#ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100160static int get_x11_title(int);
161static int get_x11_icon(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162
163static char_u *oldtitle = NULL;
164static int did_set_title = FALSE;
165static char_u *oldicon = NULL;
166static int did_set_icon = FALSE;
167#endif
168
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100169static void may_core_dump(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000170
Bram Moolenaar205b8862011-09-07 15:04:31 +0200171#ifdef HAVE_UNION_WAIT
172typedef union wait waitstatus;
173#else
174typedef int waitstatus;
175#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100176static pid_t wait4pid(pid_t, waitstatus *);
Bram Moolenaar205b8862011-09-07 15:04:31 +0200177
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100178static int WaitForChar(long);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +0100179static int WaitForCharOrMouse(long);
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100180#if defined(__BEOS__) || defined(VMS)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100181int RealWaitForChar(int, long, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182#else
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100183static int RealWaitForChar(int, long, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000184#endif
185
186#ifdef FEAT_XCLIPBOARD
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100187static int do_xterm_trace(void);
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000188# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#endif
190
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100191static void handle_resize(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192
193#if defined(SIGWINCH)
Bram Moolenaard99df422016-01-29 23:20:40 +0100194static RETSIGTYPE sig_winch SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000195#endif
196#if defined(SIGINT)
Bram Moolenaard99df422016-01-29 23:20:40 +0100197static RETSIGTYPE catch_sigint SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198#endif
199#if defined(SIGPWR)
Bram Moolenaard99df422016-01-29 23:20:40 +0100200static RETSIGTYPE catch_sigpwr SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201#endif
202#if defined(SIGALRM) && defined(FEAT_X11) \
203 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
204# define SET_SIG_ALARM
Bram Moolenaard99df422016-01-29 23:20:40 +0100205static RETSIGTYPE sig_alarm SIGPROTOARG;
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000206/* volatile because it is used in signal handler sig_alarm(). */
207static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208#endif
Bram Moolenaard99df422016-01-29 23:20:40 +0100209static RETSIGTYPE deathtrap SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100211static void catch_int_signal(void);
212static void set_signals(void);
213static void catch_signals(RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)());
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100215static int have_wildcard(int, char_u **);
216static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217#endif
218
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100220static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221#endif
222
223#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000224# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225#endif
226
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000227/* volatile because it is used in signal handler sig_winch(). */
228static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229#ifndef __EMX__
230static char_u *extra_shell_arg = NULL;
231static int show_shell_mess = TRUE;
232#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000233/* volatile because it is used in signal handler deathtrap(). */
234static volatile int deadly_signal = 0; /* The signal we caught */
235/* volatile because it is used in signal handler deathtrap(). */
236static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237
238static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
239
240#ifdef USE_XSMP
241typedef struct
242{
243 SmcConn smcconn; /* The SM connection ID */
244 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200245 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 Bool save_yourself; /* If we're in the middle of a save_yourself */
247 Bool shutdown; /* If we're in shutdown mode */
248} xsmp_config_T;
249
250static xsmp_config_T xsmp;
251#endif
252
253#ifdef SYS_SIGLIST_DECLARED
254/*
255 * I have seen
256 * extern char *_sys_siglist[NSIG];
257 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
258 * that describe the signals. That is nearly what we want here. But
259 * autoconf does only check for sys_siglist (without the underscore), I
260 * do not want to change everything today.... jw.
261 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
262 */
263#endif
264
265static struct signalinfo
266{
267 int sig; /* Signal number, eg. SIGSEGV etc */
268 char *name; /* Signal name (not char_u!). */
269 char deadly; /* Catch as a deadly signal? */
270} signal_info[] =
271{
272#ifdef SIGHUP
273 {SIGHUP, "HUP", TRUE},
274#endif
275#ifdef SIGQUIT
276 {SIGQUIT, "QUIT", TRUE},
277#endif
278#ifdef SIGILL
279 {SIGILL, "ILL", TRUE},
280#endif
281#ifdef SIGTRAP
282 {SIGTRAP, "TRAP", TRUE},
283#endif
284#ifdef SIGABRT
285 {SIGABRT, "ABRT", TRUE},
286#endif
287#ifdef SIGEMT
288 {SIGEMT, "EMT", TRUE},
289#endif
290#ifdef SIGFPE
291 {SIGFPE, "FPE", TRUE},
292#endif
293#ifdef SIGBUS
294 {SIGBUS, "BUS", TRUE},
295#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100296#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
297 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 {SIGSEGV, "SEGV", TRUE},
299#endif
300#ifdef SIGSYS
301 {SIGSYS, "SYS", TRUE},
302#endif
303#ifdef SIGALRM
304 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
305#endif
306#ifdef SIGTERM
307 {SIGTERM, "TERM", TRUE},
308#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100309#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000310 {SIGVTALRM, "VTALRM", TRUE},
311#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000312#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
313 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
314 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 {SIGPROF, "PROF", TRUE},
316#endif
317#ifdef SIGXCPU
318 {SIGXCPU, "XCPU", TRUE},
319#endif
320#ifdef SIGXFSZ
321 {SIGXFSZ, "XFSZ", TRUE},
322#endif
323#ifdef SIGUSR1
324 {SIGUSR1, "USR1", TRUE},
325#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000326#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
327 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 {SIGUSR2, "USR2", TRUE},
329#endif
330#ifdef SIGINT
331 {SIGINT, "INT", FALSE},
332#endif
333#ifdef SIGWINCH
334 {SIGWINCH, "WINCH", FALSE},
335#endif
336#ifdef SIGTSTP
337 {SIGTSTP, "TSTP", FALSE},
338#endif
339#ifdef SIGPIPE
340 {SIGPIPE, "PIPE", FALSE},
341#endif
342 {-1, "Unknown!", FALSE}
343};
344
Bram Moolenaar25724922009-07-14 15:38:41 +0000345 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100346mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000347{
348 if (p_verbose >= 5)
349 {
350 verbose_enter();
351 smsg((char_u *)"chdir(%s)", path);
352 verbose_leave();
353 }
354# ifdef VMS
355 return chdir(vms_fixfilename(path));
356# else
357 return chdir(path);
358# endif
359}
360
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000361/*
362 * Write s[len] to the screen.
363 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100365mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000367 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368 if (p_wd) /* Unix is too fast, slow down a bit more */
369 RealWaitForChar(read_cmd_fd, p_wd, NULL);
370}
371
372/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000373 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 * Get a characters from the keyboard.
375 * Return the number of characters that are available.
376 * If wtime == 0 do not wait for characters.
377 * If wtime == n wait a short time for characters.
378 * If wtime == -1 wait forever for characters.
379 */
380 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100381mch_inchar(
382 char_u *buf,
383 int maxlen,
384 long wtime, /* don't use "time", MIPS cannot handle it */
385 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386{
387 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000388
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200389#ifdef MESSAGE_QUEUE
390 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200391#endif
392
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 /* Check if window changed size while we were busy, perhaps the ":set
394 * columns=99" command was used. */
395 while (do_resize)
396 handle_resize();
397
398 if (wtime >= 0)
399 {
400 while (WaitForChar(wtime) == 0) /* no character available */
401 {
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100402 if (do_resize)
403 handle_resize();
404#ifdef FEAT_CLIENTSERVER
405 else if (!server_waiting())
406#else
407 else
408#endif
409 /* return if not interrupted by resize or server */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410 return 0;
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200411#ifdef MESSAGE_QUEUE
412 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 }
415 }
416 else /* wtime == -1 */
417 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 /*
419 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000420 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 * Also done when interrupted by SIGWINCH.
422 */
423 if (WaitForChar(p_ut) == 0)
424 {
425#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000426 if (trigger_cursorhold() && maxlen >= 3
427 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000429 buf[0] = K_SPECIAL;
430 buf[1] = KS_EXTRA;
431 buf[2] = (int)KE_CURSORHOLD;
432 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000435 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 }
437 }
438
439 for (;;) /* repeat until we got a character */
440 {
441 while (do_resize) /* window changed size */
442 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200443
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200444#ifdef MESSAGE_QUEUE
445 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200446#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200448 * We want to be interrupted by the winch signal
449 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200451 if (WaitForChar(-1L) == 0)
452 {
453 if (do_resize) /* interrupted by SIGWINCH signal */
454 handle_resize();
455 return 0;
456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457
458 /* If input was put directly in typeahead buffer bail out here. */
459 if (typebuf_changed(tb_change_cnt))
460 return 0;
461
462 /*
463 * For some terminals we only get one character at a time.
464 * We want the get all available characters, so we could keep on
465 * trying until none is available
466 * For some other terminals this is quite slow, that's why we don't do
467 * it.
468 */
469 len = read_from_input_buf(buf, (long)maxlen);
470 if (len > 0)
471 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472 return len;
473 }
474 }
475}
476
477 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100478handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479{
480 do_resize = FALSE;
481 shell_resized();
482}
483
484/*
485 * return non-zero if a character is available
486 */
487 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100488mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489{
490 return WaitForChar(0L);
491}
492
493#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
494# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000495# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496# endif
497# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
498# include <sys/sysctl.h>
499# endif
500# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
501# include <sys/sysinfo.h>
502# endif
503
504/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000505 * Return total amount of memory available in Kbyte.
506 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100509mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510{
511# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000512 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513# else
514 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000515 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516
517# ifdef HAVE_SYSCTL
518 int mib[2], physmem;
519 size_t len;
520
521 /* BSD way of getting the amount of RAM available. */
522 mib[0] = CTL_HW;
523 mib[1] = HW_USERMEM;
524 len = sizeof(physmem);
525 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
526 mem = (long_u)physmem;
527# endif
528
529# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
530 if (mem == 0)
531 {
532 struct sysinfo sinfo;
533
534 /* Linux way of getting amount of RAM available */
535 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000536 {
537# ifdef HAVE_SYSINFO_MEM_UNIT
538 /* avoid overflow as much as possible */
539 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
540 {
541 sinfo.mem_unit = sinfo.mem_unit >> 1;
542 --shiftright;
543 }
544 mem = sinfo.totalram * sinfo.mem_unit;
545# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000547# endif
548 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 }
550# endif
551
552# ifdef HAVE_SYSCONF
553 if (mem == 0)
554 {
555 long pagesize, pagecount;
556
557 /* Solaris way of getting amount of RAM available */
558 pagesize = sysconf(_SC_PAGESIZE);
559 pagecount = sysconf(_SC_PHYS_PAGES);
560 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000561 {
562 /* avoid overflow as much as possible */
563 while (shiftright > 0 && (pagesize & 1) == 0)
564 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000565 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000566 --shiftright;
567 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 }
571# endif
572
573 /* Return the minimum of the physical memory and the user limit, because
574 * using more than the user limit may cause Vim to be terminated. */
575# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
576 {
577 struct rlimit rlp;
578
579 if (getrlimit(RLIMIT_DATA, &rlp) == 0
580 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
581# ifdef RLIM_INFINITY
582 && rlp.rlim_cur != RLIM_INFINITY
583# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000584 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000586 {
587 mem = (long_u)rlp.rlim_cur;
588 shiftright = 10;
589 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590 }
591# endif
592
593 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000594 return mem >> shiftright;
595 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596# endif
597}
598#endif
599
600 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100601mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602{
603 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000604#ifdef FEAT_MZSCHEME
605 long total = msec; /* remember original value */
606#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607
608 if (ignoreinput)
609 {
610 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000611 * here. But we don't want QUIT to kill us (CTRL-\ used in a
612 * shell may produce SIGQUIT). */
613 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 old_tmode = curr_tmode;
615 if (curr_tmode == TMODE_RAW)
616 settmode(TMODE_SLEEP);
617
618 /*
619 * Everybody sleeps in a different way...
620 * Prefer nanosleep(), some versions of usleep() can only sleep up to
621 * one second.
622 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000623#ifdef FEAT_MZSCHEME
624 do
625 {
626 /* if total is large enough, wait by portions in p_mzq */
627 if (total > p_mzq)
628 msec = p_mzq;
629 else
630 msec = total;
631 total -= msec;
632#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633#ifdef HAVE_NANOSLEEP
634 {
635 struct timespec ts;
636
637 ts.tv_sec = msec / 1000;
638 ts.tv_nsec = (msec % 1000) * 1000000;
639 (void)nanosleep(&ts, NULL);
640 }
641#else
642# ifdef HAVE_USLEEP
643 while (msec >= 1000)
644 {
645 usleep((unsigned int)(999 * 1000));
646 msec -= 999;
647 }
648 usleep((unsigned int)(msec * 1000));
649# else
650# ifndef HAVE_SELECT
651 poll(NULL, 0, (int)msec);
652# else
653# ifdef __EMX__
654 _sleep2(msec);
655# else
656 {
657 struct timeval tv;
658
659 tv.tv_sec = msec / 1000;
660 tv.tv_usec = (msec % 1000) * 1000;
661 /*
662 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
663 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
664 */
665 select(0, NULL, NULL, NULL, &tv);
666 }
667# endif /* __EMX__ */
668# endif /* HAVE_SELECT */
669# endif /* HAVE_NANOSLEEP */
670#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000671#ifdef FEAT_MZSCHEME
672 }
673 while (total > 0);
674#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675
676 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000677 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678 }
679 else
680 WaitForChar(msec);
681}
682
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000683#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
685# define HAVE_CHECK_STACK_GROWTH
686/*
687 * Support for checking for an almost-out-of-stack-space situation.
688 */
689
690/*
691 * Return a pointer to an item on the stack. Used to find out if the stack
692 * grows up or down.
693 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100694static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695static int stack_grows_downwards;
696
697/*
698 * Find out if the stack grows upwards or downwards.
699 * "p" points to a variable on the stack of the caller.
700 */
701 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100702check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703{
704 int i;
705
706 stack_grows_downwards = (p > (char *)&i);
707}
708#endif
709
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000710#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711static char *stack_limit = NULL;
712
713#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
714# include <pthread.h>
715# include <pthread_np.h>
716#endif
717
718/*
719 * Find out until how var the stack can grow without getting into trouble.
720 * Called when starting up and when switching to the signal stack in
721 * deathtrap().
722 */
723 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100724get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725{
726 struct rlimit rlp;
727 int i;
728 long lim;
729
730 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
731 * limit doesn't fit in a long (rlim_cur might be "long long"). */
732 if (getrlimit(RLIMIT_STACK, &rlp) == 0
733 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
734# ifdef RLIM_INFINITY
735 && rlp.rlim_cur != RLIM_INFINITY
736# endif
737 )
738 {
739 lim = (long)rlp.rlim_cur;
740#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
741 {
742 pthread_attr_t attr;
743 size_t size;
744
745 /* On FreeBSD the initial thread always has a fixed stack size, no
746 * matter what the limits are set to. Normally it's 1 Mbyte. */
747 pthread_attr_init(&attr);
748 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
749 {
750 pthread_attr_getstacksize(&attr, &size);
751 if (lim > (long)size)
752 lim = (long)size;
753 }
754 pthread_attr_destroy(&attr);
755 }
756#endif
757 if (stack_grows_downwards)
758 {
759 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
760 if (stack_limit >= (char *)&i)
761 /* overflow, set to 1/16 of current stack position */
762 stack_limit = (char *)((long)&i / 16L);
763 }
764 else
765 {
766 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
767 if (stack_limit <= (char *)&i)
768 stack_limit = NULL; /* overflow */
769 }
770 }
771}
772
773/*
774 * Return FAIL when running out of stack space.
775 * "p" must point to any variable local to the caller that's on the stack.
776 */
777 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100778mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779{
780 if (stack_limit != NULL)
781 {
782 if (stack_grows_downwards)
783 {
784 if (p < stack_limit)
785 return FAIL;
786 }
787 else if (p > stack_limit)
788 return FAIL;
789 }
790 return OK;
791}
792#endif
793
794#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
795/*
796 * Support for using the signal stack.
797 * This helps when we run out of stack space, which causes a SIGSEGV. The
798 * signal handler then must run on another stack, since the normal stack is
799 * completely full.
800 */
801
Bram Moolenaar39766a72013-11-03 00:41:00 +0100802#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100803# include <AvailabilityMacros.h>
804#endif
805
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806#ifndef SIGSTKSZ
807# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
808#endif
809
810# ifdef HAVE_SIGALTSTACK
811static stack_t sigstk; /* for sigaltstack() */
812# else
813static struct sigstack sigstk; /* for sigstack() */
814# endif
815
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100816static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817static char *signal_stack;
818
819 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100820init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821{
822 if (signal_stack != NULL)
823 {
824# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000825# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
826 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000827 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
828 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100829 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830# endif
831
832# ifdef HAVE_SS_BASE
833 sigstk.ss_base = signal_stack;
834# else
835 sigstk.ss_sp = signal_stack;
836# endif
837 sigstk.ss_size = SIGSTKSZ;
838 sigstk.ss_flags = 0;
839 (void)sigaltstack(&sigstk, NULL);
840# else
841 sigstk.ss_sp = signal_stack;
842 if (stack_grows_downwards)
843 sigstk.ss_sp += SIGSTKSZ - 1;
844 sigstk.ss_onstack = 0;
845 (void)sigstack(&sigstk, NULL);
846# endif
847 }
848}
849#endif
850
851/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000852 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 * will barf when the second argument to signal() is ``wrong''.
854 * Let me try it with a few tricky defines from my own osdef.h (jw).
855 */
856#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857 static RETSIGTYPE
858sig_winch SIGDEFARG(sigarg)
859{
860 /* this is not required on all systems, but it doesn't hurt anybody */
861 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
862 do_resize = TRUE;
863 SIGRETURN;
864}
865#endif
866
867#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 static RETSIGTYPE
869catch_sigint SIGDEFARG(sigarg)
870{
871 /* this is not required on all systems, but it doesn't hurt anybody */
872 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
873 got_int = TRUE;
874 SIGRETURN;
875}
876#endif
877
878#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 static RETSIGTYPE
880catch_sigpwr SIGDEFARG(sigarg)
881{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000882 /* this is not required on all systems, but it doesn't hurt anybody */
883 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884 /*
885 * I'm not sure we get the SIGPWR signal when the system is really going
886 * down or when the batteries are almost empty. Just preserve the swap
887 * files and don't exit, that can't do any harm.
888 */
889 ml_sync_all(FALSE, FALSE);
890 SIGRETURN;
891}
892#endif
893
894#ifdef SET_SIG_ALARM
895/*
896 * signal function for alarm().
897 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 static RETSIGTYPE
899sig_alarm SIGDEFARG(sigarg)
900{
901 /* doesn't do anything, just to break a system call */
902 sig_alarm_called = TRUE;
903 SIGRETURN;
904}
905#endif
906
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000907#if (defined(HAVE_SETJMP_H) \
908 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
909 || defined(FEAT_LIBCALL))) \
910 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911/*
912 * A simplistic version of setjmp() that only allows one level of using.
913 * Don't call twice before calling mch_endjmp()!.
914 * Usage:
915 * mch_startjmp();
916 * if (SETJMP(lc_jump_env) != 0)
917 * {
918 * mch_didjmp();
919 * EMSG("crash!");
920 * }
921 * else
922 * {
923 * do_the_work;
924 * mch_endjmp();
925 * }
926 * Note: Can't move SETJMP() here, because a function calling setjmp() must
927 * not return before the saved environment is used.
928 * Returns OK for normal return, FAIL when the protected code caused a
929 * problem and LONGJMP() was used.
930 */
931 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100932mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933{
934#ifdef SIGHASARG
935 lc_signal = 0;
936#endif
937 lc_active = TRUE;
938}
939
940 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100941mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942{
943 lc_active = FALSE;
944}
945
946 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100947mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
950 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
951 * otherwise catching the signal only works once. */
952 init_signal_stack();
953# endif
954}
955#endif
956
957/*
958 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200959 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200961 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
962 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 */
964 static RETSIGTYPE
965deathtrap SIGDEFARG(sigarg)
966{
967 static int entered = 0; /* count the number of times we got here.
968 Note: when memory has been corrupted
969 this may get an arbitrary value! */
970#ifdef SIGHASARG
971 int i;
972#endif
973
974#if defined(HAVE_SETJMP_H)
975 /*
976 * Catch a crash in protected code.
977 * Restores the environment saved in lc_jump_env, which looks like
978 * SETJMP() returns 1.
979 */
980 if (lc_active)
981 {
982# if defined(SIGHASARG)
983 lc_signal = sigarg;
984# endif
985 lc_active = FALSE; /* don't jump again */
986 LONGJMP(lc_jump_env, 1);
987 /* NOTREACHED */
988 }
989#endif
990
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000991#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000992# ifdef SIGQUIT
993 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
994 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
995 * pressing CTRL-\, but we don't want Vim to exit then. */
996 if (in_mch_delay && sigarg == SIGQUIT)
997 SIGRETURN;
998# endif
999
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001000 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1001 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1002 * free(). Calling free() again may then cause a crash. */
1003 if (entered == 0
1004 && (0
1005# ifdef SIGHUP
1006 || sigarg == SIGHUP
1007# endif
1008# ifdef SIGQUIT
1009 || sigarg == SIGQUIT
1010# endif
1011# ifdef SIGTERM
1012 || sigarg == SIGTERM
1013# endif
1014# ifdef SIGPWR
1015 || sigarg == SIGPWR
1016# endif
1017# ifdef SIGUSR1
1018 || sigarg == SIGUSR1
1019# endif
1020# ifdef SIGUSR2
1021 || sigarg == SIGUSR2
1022# endif
1023 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001024 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001025 SIGRETURN;
1026#endif
1027
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 /* Remember how often we have been called. */
1029 ++entered;
1030
1031#ifdef FEAT_EVAL
1032 /* Set the v:dying variable. */
1033 set_vim_var_nr(VV_DYING, (long)entered);
1034#endif
1035
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001036#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 /* Since we are now using the signal stack, need to reset the stack
1038 * limit. Otherwise using a regexp will fail. */
1039 get_stack_limit();
1040#endif
1041
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001042#if 0
1043 /* This is for opening gdb the moment Vim crashes.
1044 * You need to manually adjust the file name and Vim executable name.
1045 * Suggested by SungHyun Nam. */
1046 {
1047# define VI_GDB_FILE "/tmp/vimgdb"
1048# define VIM_NAME "/usr/bin/vim"
1049 FILE *fp = fopen(VI_GDB_FILE, "w");
1050 if (fp)
1051 {
1052 fprintf(fp,
1053 "file %s\n"
1054 "attach %d\n"
1055 "set height 1000\n"
1056 "bt full\n"
1057 , VIM_NAME, getpid());
1058 fclose(fp);
1059 system("xterm -e gdb -x "VI_GDB_FILE);
1060 unlink(VI_GDB_FILE);
1061 }
1062 }
1063#endif
1064
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065#ifdef SIGHASARG
1066 /* try to find the name of this signal */
1067 for (i = 0; signal_info[i].sig != -1; i++)
1068 if (sigarg == signal_info[i].sig)
1069 break;
1070 deadly_signal = sigarg;
1071#endif
1072
1073 full_screen = FALSE; /* don't write message to the GUI, it might be
1074 * part of the problem... */
1075 /*
1076 * If something goes wrong after entering here, we may get here again.
1077 * When this happens, give a message and try to exit nicely (resetting the
1078 * terminal mode, etc.)
1079 * When this happens twice, just exit, don't even try to give a message,
1080 * stack may be corrupt or something weird.
1081 * When this still happens again (or memory was corrupted in such a way
1082 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1083 */
1084 if (entered >= 3)
1085 {
1086 reset_signals(); /* don't catch any signals anymore */
1087 may_core_dump();
1088 if (entered >= 4)
1089 _exit(8);
1090 exit(7);
1091 }
1092 if (entered == 2)
1093 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001094 /* No translation, it may call malloc(). */
1095 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096 out_flush();
1097 getout(1);
1098 }
1099
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001100 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001102 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 signal_info[i].name);
1104#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001105 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001107
1108 /* Preserve files and exit. This sets the really_exiting flag to prevent
1109 * calling free(). */
1110 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111
Bram Moolenaar009b2592004-10-24 19:18:58 +00001112#ifdef NBDEBUG
1113 reset_signals();
1114 may_core_dump();
1115 abort();
1116#endif
1117
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 SIGRETURN;
1119}
1120
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001121#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122/*
1123 * On Solaris with multi-threading, suspending might not work immediately.
1124 * Catch the SIGCONT signal, which will be used as an indication whether the
1125 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001126 *
1127 * On Linux, signal is not always handled immediately either.
1128 * See https://bugs.launchpad.net/bugs/291373
1129 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001130 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001132static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001133static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134
1135/*
1136 * signal handler for SIGCONT
1137 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 static RETSIGTYPE
1139sigcont_handler SIGDEFARG(sigarg)
1140{
1141 sigcont_received = TRUE;
1142 SIGRETURN;
1143}
1144#endif
1145
Bram Moolenaar62b42182010-09-21 22:09:37 +02001146# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001147static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001148# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001149static void save_clipboard(void);
1150static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001151
1152static void *clip_star_save = NULL;
1153static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001154# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001155
1156/*
1157 * Called when Vim is going to sleep or execute a shell command.
1158 * We can't respond to requests for the X selections. Lose them, otherwise
1159 * other applications will hang. But first copy the text to cut buffer 0.
1160 */
1161 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001162loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001163{
1164 if (clip_star.owned || clip_plus.owned)
1165 {
1166 x11_export_final_selection();
1167 if (clip_star.owned)
1168 clip_lose_selection(&clip_star);
1169 if (clip_plus.owned)
1170 clip_lose_selection(&clip_plus);
1171 if (x11_display != NULL)
1172 XFlush(x11_display);
1173 }
1174}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001175
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001176# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001177/*
1178 * Save clipboard text to restore later.
1179 */
1180 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001181save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001182{
1183 if (clip_star.owned)
1184 clip_star_save = get_register('*', TRUE);
1185 if (clip_plus.owned)
1186 clip_plus_save = get_register('+', TRUE);
1187}
1188
1189/*
1190 * Restore clipboard text if no one own the X selection.
1191 */
1192 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001193restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001194{
1195 if (clip_star_save != NULL)
1196 {
1197 if (!clip_gen_owner_exists(&clip_star))
1198 put_register('*', clip_star_save);
1199 else
1200 free_register(clip_star_save);
1201 clip_star_save = NULL;
1202 }
1203 if (clip_plus_save != NULL)
1204 {
1205 if (!clip_gen_owner_exists(&clip_plus))
1206 put_register('+', clip_plus_save);
1207 else
1208 free_register(clip_plus_save);
1209 clip_plus_save = NULL;
1210 }
1211}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001212# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001213#endif
1214
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215/*
1216 * If the machine has job control, use it to suspend the program,
1217 * otherwise fake it by starting a new shell.
1218 */
1219 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001220mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221{
1222 /* BeOS does have SIGTSTP, but it doesn't work. */
1223#if defined(SIGTSTP) && !defined(__BEOS__)
1224 out_flush(); /* needed to make cursor visible on some systems */
1225 settmode(TMODE_COOK);
1226 out_flush(); /* needed to disable mouse on some systems */
1227
1228# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001229 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230# endif
1231
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001232# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 sigcont_received = FALSE;
1234# endif
1235 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001236# if defined(_REENTRANT) && defined(SIGCONT)
1237 /*
1238 * Wait for the SIGCONT signal to be handled. It generally happens
1239 * immediately, but somehow not all the time. Do not call pause()
1240 * because there would be race condition which would hang Vim if
1241 * signal happened in between the test of sigcont_received and the
1242 * call to pause(). If signal is not yet received, call sleep(0)
1243 * to just yield CPU. Signal should then be received. If somehow
1244 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1245 * further if signal is not received after 1+2+3+4 ms (not expected
1246 * to happen).
1247 */
1248 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001249 long wait_time;
1250 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001251 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001252 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001253 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254# endif
1255
1256# ifdef FEAT_TITLE
1257 /*
1258 * Set oldtitle to NULL, so the current title is obtained again.
1259 */
1260 vim_free(oldtitle);
1261 oldtitle = NULL;
1262# endif
1263 settmode(TMODE_RAW);
1264 need_check_timestamps = TRUE;
1265 did_check_timestamps = FALSE;
1266#else
1267 suspend_shell();
1268#endif
1269}
1270
1271 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001272mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273{
1274 Columns = 80;
1275 Rows = 24;
1276
1277 out_flush();
1278 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001279
Bram Moolenaar56718732006-03-15 22:53:57 +00001280#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001281 mac_conv_init();
1282#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001283#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1284 win_clip_init();
1285#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286}
1287
1288 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001289set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290{
1291#if defined(SIGWINCH)
1292 /*
1293 * WINDOW CHANGE signal is handled with sig_winch().
1294 */
1295 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1296#endif
1297
1298 /*
1299 * We want the STOP signal to work, to make mch_suspend() work.
1300 * For "rvim" the STOP signal is ignored.
1301 */
1302#ifdef SIGTSTP
1303 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1304#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001305#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306 signal(SIGCONT, sigcont_handler);
1307#endif
1308
1309 /*
1310 * We want to ignore breaking of PIPEs.
1311 */
1312#ifdef SIGPIPE
1313 signal(SIGPIPE, SIG_IGN);
1314#endif
1315
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001317 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318#endif
1319
1320 /*
1321 * Ignore alarm signals (Perl's alarm() generates it).
1322 */
1323#ifdef SIGALRM
1324 signal(SIGALRM, SIG_IGN);
1325#endif
1326
1327 /*
1328 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1329 * work will be lost.
1330 */
1331#ifdef SIGPWR
1332 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1333#endif
1334
1335 /*
1336 * Arrange for other signals to gracefully shutdown Vim.
1337 */
1338 catch_signals(deathtrap, SIG_ERR);
1339
1340#if defined(FEAT_GUI) && defined(SIGHUP)
1341 /*
1342 * When the GUI is running, ignore the hangup signal.
1343 */
1344 if (gui.in_use)
1345 signal(SIGHUP, SIG_IGN);
1346#endif
1347}
1348
Bram Moolenaardf177f62005-02-22 08:39:57 +00001349#if defined(SIGINT) || defined(PROTO)
1350/*
1351 * Catch CTRL-C (only works while in Cooked mode).
1352 */
1353 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001354catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001355{
1356 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1357}
1358#endif
1359
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001361reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362{
1363 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001364#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365 /* SIGCONT isn't in the list, because its default action is ignore */
1366 signal(SIGCONT, SIG_DFL);
1367#endif
1368}
1369
1370 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001371catch_signals(
1372 RETSIGTYPE (*func_deadly)(),
1373 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374{
1375 int i;
1376
1377 for (i = 0; signal_info[i].sig != -1; i++)
1378 if (signal_info[i].deadly)
1379 {
1380#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1381 struct sigaction sa;
1382
1383 /* Setup to use the alternate stack for the signal function. */
1384 sa.sa_handler = func_deadly;
1385 sigemptyset(&sa.sa_mask);
1386# if defined(__linux__) && defined(_REENTRANT)
1387 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1388 * thread handling in combination with using the alternate stack:
1389 * pthread library functions try to use the stack pointer to
1390 * identify the current thread, causing a SEGV signal, which
1391 * recursively calls deathtrap() and hangs. */
1392 sa.sa_flags = 0;
1393# else
1394 sa.sa_flags = SA_ONSTACK;
1395# endif
1396 sigaction(signal_info[i].sig, &sa, NULL);
1397#else
1398# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1399 struct sigvec sv;
1400
1401 /* Setup to use the alternate stack for the signal function. */
1402 sv.sv_handler = func_deadly;
1403 sv.sv_mask = 0;
1404 sv.sv_flags = SV_ONSTACK;
1405 sigvec(signal_info[i].sig, &sv, NULL);
1406# else
1407 signal(signal_info[i].sig, func_deadly);
1408# endif
1409#endif
1410 }
1411 else if (func_other != SIG_ERR)
1412 signal(signal_info[i].sig, func_other);
1413}
1414
1415/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001416 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001417 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1418 * return TRUE
1419 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1420 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001421 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001422 * Returns TRUE when Vim should exit.
1423 */
1424 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001425vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001426{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001427 static int got_signal = 0;
1428 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001429
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001430 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001431 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001432 case SIGNAL_BLOCK: blocked = TRUE;
1433 break;
1434
1435 case SIGNAL_UNBLOCK: blocked = FALSE;
1436 if (got_signal != 0)
1437 {
1438 kill(getpid(), got_signal);
1439 got_signal = 0;
1440 }
1441 break;
1442
1443 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001444 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001445 got_signal = sig;
1446#ifdef SIGPWR
1447 if (sig != SIGPWR)
1448#endif
1449 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001450 break;
1451 }
1452 return FALSE;
1453}
1454
1455/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456 * Check_win checks whether we have an interactive stdout.
1457 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001459mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461 if (isatty(1))
1462 return OK;
1463 return FAIL;
1464}
1465
1466/*
1467 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1468 */
1469 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001470mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471{
1472 if (isatty(read_cmd_fd))
1473 return TRUE;
1474 return FALSE;
1475}
1476
1477#ifdef FEAT_X11
1478
1479# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1480 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1481
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001482static void xopen_message(struct timeval *tvp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483
1484/*
1485 * Give a message about the elapsed time for opening the X window.
1486 */
1487 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001488xopen_message(
1489 struct timeval *tvp) /* must contain start time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490{
1491 struct timeval end_tv;
1492
1493 /* Compute elapsed time. */
1494 gettimeofday(&end_tv, NULL);
1495 smsg((char_u *)_("Opening the X display took %ld msec"),
1496 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001497 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498}
1499# endif
1500#endif
1501
1502#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1503/*
1504 * A few functions shared by X11 title and clipboard code.
1505 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001506static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1507static int x_error_check(Display *dpy, XErrorEvent *error_event);
1508static int x_connect_to_server(void);
1509static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510
1511static int got_x_error = FALSE;
1512
1513/*
1514 * X Error handler, otherwise X just exits! (very rude) -- webb
1515 */
1516 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001517x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001519 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520 STRCAT(IObuff, _("\nVim: Got X error\n"));
1521
1522 /* We cannot print a message and continue, because no X calls are allowed
1523 * here (causes my system to hang). Silently continuing might be an
1524 * alternative... */
1525 preserve_exit(); /* preserve files and exit */
1526
1527 return 0; /* NOTREACHED */
1528}
1529
1530/*
1531 * Another X Error handler, just used to check for errors.
1532 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001534x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535{
1536 got_x_error = TRUE;
1537 return 0;
1538}
1539
1540#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1541# if defined(HAVE_SETJMP_H)
1542/*
1543 * An X IO Error handler, used to catch error while opening the display.
1544 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001545static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001548x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549{
1550 /* This function should not return, it causes exit(). Longjump instead. */
1551 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001552# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001553 return 0; /* avoid the compiler complains about missing return value */
1554# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555}
1556# endif
1557
1558/*
1559 * An X IO Error handler, used to catch terminal errors.
1560 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001561static int x_IOerror_handler(Display *dpy);
1562static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001563static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001566x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567{
1568 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001569 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 x11_window = 0;
1571 x11_display = NULL;
1572 xterm_Shell = (Widget)0;
1573
1574 /* This function should not return, it causes exit(). Longjump instead. */
1575 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001576# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001577 return 0; /* avoid the compiler complains about missing return value */
1578# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001580
1581/*
1582 * If the X11 connection was lost try to restore it.
1583 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001584 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001585 */
1586 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001587may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001588{
1589 if (xterm_dpy_was_reset)
1590 {
1591 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001592
1593# ifndef LESSTIF_VERSION
1594 /* This has been reported to avoid Vim getting stuck. */
1595 if (app_context != (XtAppContext)NULL)
1596 {
1597 XtDestroyApplicationContext(app_context);
1598 app_context = (XtAppContext)NULL;
1599 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1600 }
1601# endif
1602
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001603 setup_term_clip();
1604 get_x11_title(FALSE);
1605 }
1606}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607#endif
1608
1609/*
1610 * Return TRUE when connection to the X server is desired.
1611 */
1612 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001613x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615#if defined(FEAT_CLIENTSERVER)
1616 if (x_force_connect)
1617 return TRUE;
1618#endif
1619 if (x_no_connect)
1620 return FALSE;
1621
1622 /* Check for a match with "exclude:" from 'clipboard'. */
1623 if (clip_exclude_prog != NULL)
1624 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001625 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 return FALSE;
1627 }
1628 return TRUE;
1629}
1630
1631/*
1632 * Test if "dpy" and x11_window are valid by getting the window title.
1633 * I don't actually want it yet, so there may be a simpler call to use, but
1634 * this will cause the error handler x_error_check() to be called if anything
1635 * is wrong, such as the window pointer being invalid (as can happen when the
1636 * user changes his DISPLAY, but not his WINDOWID) -- webb
1637 */
1638 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001639test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640{
1641 int (*old_handler)();
1642 XTextProperty text_prop;
1643
1644 old_handler = XSetErrorHandler(x_error_check);
1645 got_x_error = FALSE;
1646 if (XGetWMName(dpy, x11_window, &text_prop))
1647 XFree((void *)text_prop.value);
1648 XSync(dpy, False);
1649 (void)XSetErrorHandler(old_handler);
1650
1651 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001652 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653
1654 return (got_x_error ? FAIL : OK);
1655}
1656#endif
1657
1658#ifdef FEAT_TITLE
1659
1660#ifdef FEAT_X11
1661
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001662static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663
1664/*
1665 * try to get x11 window and display
1666 *
1667 * return FAIL for failure, OK otherwise
1668 */
1669 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001670get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671{
1672 char *winid;
1673 static int result = -1;
1674#define XD_NONE 0 /* x11_display not set here */
1675#define XD_HERE 1 /* x11_display opened here */
1676#define XD_GUI 2 /* x11_display used from gui.dpy */
1677#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1678 static int x11_display_from = XD_NONE;
1679 static int did_set_error_handler = FALSE;
1680
1681 if (!did_set_error_handler)
1682 {
1683 /* X just exits if it finds an error otherwise! */
1684 (void)XSetErrorHandler(x_error_handler);
1685 did_set_error_handler = TRUE;
1686 }
1687
Bram Moolenaar9372a112005-12-06 19:59:18 +00001688#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 if (gui.in_use)
1690 {
1691 /*
1692 * If the X11 display was opened here before, for the window where Vim
1693 * was started, close that one now to avoid a memory leak.
1694 */
1695 if (x11_display_from == XD_HERE && x11_display != NULL)
1696 {
1697 XCloseDisplay(x11_display);
1698 x11_display_from = XD_NONE;
1699 }
1700 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1701 {
1702 x11_display_from = XD_GUI;
1703 return OK;
1704 }
1705 x11_display = NULL;
1706 return FAIL;
1707 }
1708 else if (x11_display_from == XD_GUI)
1709 {
1710 /* GUI must have stopped somehow, clear x11_display */
1711 x11_window = 0;
1712 x11_display = NULL;
1713 x11_display_from = XD_NONE;
1714 }
1715#endif
1716
1717 /* When started with the "-X" argument, don't try connecting. */
1718 if (!x_connect_to_server())
1719 return FAIL;
1720
1721 /*
1722 * If WINDOWID not set, should try another method to find out
1723 * what the current window number is. The only code I know for
1724 * this is very complicated.
1725 * We assume that zero is invalid for WINDOWID.
1726 */
1727 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1728 x11_window = (Window)atol(winid);
1729
1730#ifdef FEAT_XCLIPBOARD
1731 if (xterm_dpy != NULL && x11_window != 0)
1732 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001733 /* We may have checked it already, but Gnome terminal can move us to
1734 * another window, so we need to check every time. */
1735 if (x11_display_from != XD_XTERM)
1736 {
1737 /*
1738 * If the X11 display was opened here before, for the window where
1739 * Vim was started, close that one now to avoid a memory leak.
1740 */
1741 if (x11_display_from == XD_HERE && x11_display != NULL)
1742 XCloseDisplay(x11_display);
1743 x11_display = xterm_dpy;
1744 x11_display_from = XD_XTERM;
1745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 if (test_x11_window(x11_display) == FAIL)
1747 {
1748 /* probably bad $WINDOWID */
1749 x11_window = 0;
1750 x11_display = NULL;
1751 x11_display_from = XD_NONE;
1752 return FAIL;
1753 }
1754 return OK;
1755 }
1756#endif
1757
1758 if (x11_window == 0 || x11_display == NULL)
1759 result = -1;
1760
1761 if (result != -1) /* Have already been here and set this */
1762 return result; /* Don't do all these X calls again */
1763
1764 if (x11_window != 0 && x11_display == NULL)
1765 {
1766#ifdef SET_SIG_ALARM
1767 RETSIGTYPE (*sig_save)();
1768#endif
1769#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1770 struct timeval start_tv;
1771
1772 if (p_verbose > 0)
1773 gettimeofday(&start_tv, NULL);
1774#endif
1775
1776#ifdef SET_SIG_ALARM
1777 /*
1778 * Opening the Display may hang if the DISPLAY setting is wrong, or
1779 * the network connection is bad. Set an alarm timer to get out.
1780 */
1781 sig_alarm_called = FALSE;
1782 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1783 (RETSIGTYPE (*)())sig_alarm);
1784 alarm(2);
1785#endif
1786 x11_display = XOpenDisplay(NULL);
1787
1788#ifdef SET_SIG_ALARM
1789 alarm(0);
1790 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1791 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001792 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793#endif
1794 if (x11_display != NULL)
1795 {
1796# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1797 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001798 {
1799 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001801 verbose_leave();
1802 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803# endif
1804 if (test_x11_window(x11_display) == FAIL)
1805 {
1806 /* Maybe window id is bad */
1807 x11_window = 0;
1808 XCloseDisplay(x11_display);
1809 x11_display = NULL;
1810 }
1811 else
1812 x11_display_from = XD_HERE;
1813 }
1814 }
1815 if (x11_window == 0 || x11_display == NULL)
1816 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001817
1818# ifdef FEAT_EVAL
1819 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1820# endif
1821
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 return (result = OK);
1823}
1824
1825/*
1826 * Determine original x11 Window Title
1827 */
1828 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001829get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001831 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832}
1833
1834/*
1835 * Determine original x11 Window icon
1836 */
1837 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001838get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839{
1840 int retval = FALSE;
1841
1842 retval = get_x11_thing(FALSE, test_only);
1843
1844 /* could not get old icon, use terminal name */
1845 if (oldicon == NULL && !test_only)
1846 {
1847 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001848 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001850 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 }
1852
1853 return retval;
1854}
1855
1856 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001857get_x11_thing(
1858 int get_title, /* get title string */
1859 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860{
1861 XTextProperty text_prop;
1862 int retval = FALSE;
1863 Status status;
1864
1865 if (get_x11_windis() == OK)
1866 {
1867 /* Get window/icon name if any */
1868 if (get_title)
1869 status = XGetWMName(x11_display, x11_window, &text_prop);
1870 else
1871 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1872
1873 /*
1874 * If terminal is xterm, then x11_window may be a child window of the
1875 * outer xterm window that actually contains the window/icon name, so
1876 * keep traversing up the tree until a window with a title/icon is
1877 * found.
1878 */
1879 /* Previously this was only done for xterm and alikes. I don't see a
1880 * reason why it would fail for other terminal emulators.
1881 * if (term_is_xterm) */
1882 {
1883 Window root;
1884 Window parent;
1885 Window win = x11_window;
1886 Window *children;
1887 unsigned int num_children;
1888
1889 while (!status || text_prop.value == NULL)
1890 {
1891 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1892 &num_children))
1893 break;
1894 if (children)
1895 XFree((void *)children);
1896 if (parent == root || parent == 0)
1897 break;
1898
1899 win = parent;
1900 if (get_title)
1901 status = XGetWMName(x11_display, win, &text_prop);
1902 else
1903 status = XGetWMIconName(x11_display, win, &text_prop);
1904 }
1905 }
1906 if (status && text_prop.value != NULL)
1907 {
1908 retval = TRUE;
1909 if (!test_only)
1910 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001911#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1912 if (text_prop.encoding == XA_STRING
1913# ifdef FEAT_MBYTE
1914 && !has_mbyte
1915# endif
1916 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 {
1918#endif
1919 if (get_title)
1920 oldtitle = vim_strsave((char_u *)text_prop.value);
1921 else
1922 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001923#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 }
1925 else
1926 {
1927 char **cl;
1928 Status transform_status;
1929 int n = 0;
1930
1931 transform_status = XmbTextPropertyToTextList(x11_display,
1932 &text_prop,
1933 &cl, &n);
1934 if (transform_status >= Success && n > 0 && cl[0])
1935 {
1936 if (get_title)
1937 oldtitle = vim_strsave((char_u *) cl[0]);
1938 else
1939 oldicon = vim_strsave((char_u *) cl[0]);
1940 XFreeStringList(cl);
1941 }
1942 else
1943 {
1944 if (get_title)
1945 oldtitle = vim_strsave((char_u *)text_prop.value);
1946 else
1947 oldicon = vim_strsave((char_u *)text_prop.value);
1948 }
1949 }
1950#endif
1951 }
1952 XFree((void *)text_prop.value);
1953 }
1954 }
1955 return retval;
1956}
1957
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001958/* Xutf8 functions are not avaialble on older systems. Note that on some
1959 * systems X_HAVE_UTF8_STRING may be defined in a header file but
1960 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
1961 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001963# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964# define USE_UTF8_STRING
1965# endif
1966#endif
1967
1968/*
1969 * Set x11 Window Title
1970 *
1971 * get_x11_windis() must be called before this and have returned OK
1972 */
1973 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001974set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975{
1976 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1977 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1978 * supported everywhere and STRING doesn't work for multi-byte titles.
1979 */
1980#ifdef USE_UTF8_STRING
1981 if (enc_utf8)
1982 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1983 NULL, NULL, 0, NULL, NULL, NULL);
1984 else
1985#endif
1986 {
1987#if XtSpecificationRelease >= 4
1988# ifdef FEAT_XFONTSET
1989 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1990 NULL, NULL, 0, NULL, NULL, NULL);
1991# else
1992 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001993 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994
1995 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001996 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 XSetWMProperties(x11_display, x11_window, &text_prop,
1998 NULL, NULL, 0, NULL, NULL, NULL);
1999# endif
2000#else
2001 XStoreName(x11_display, x11_window, (char *)title);
2002#endif
2003 }
2004 XFlush(x11_display);
2005}
2006
2007/*
2008 * Set x11 Window icon
2009 *
2010 * get_x11_windis() must be called before this and have returned OK
2011 */
2012 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002013set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014{
2015 /* See above for comments about using X*SetWMProperties(). */
2016#ifdef USE_UTF8_STRING
2017 if (enc_utf8)
2018 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2019 NULL, 0, NULL, NULL, NULL);
2020 else
2021#endif
2022 {
2023#if XtSpecificationRelease >= 4
2024# ifdef FEAT_XFONTSET
2025 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2026 NULL, 0, NULL, NULL, NULL);
2027# else
2028 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002029 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002031 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2033 NULL, 0, NULL, NULL, NULL);
2034# endif
2035#else
2036 XSetIconName(x11_display, x11_window, (char *)icon);
2037#endif
2038 }
2039 XFlush(x11_display);
2040}
2041
2042#else /* FEAT_X11 */
2043
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002045get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046{
2047 return FALSE;
2048}
2049
2050 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002051get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052{
2053 if (!test_only)
2054 {
2055 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002056 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002058 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 }
2060 return FALSE;
2061}
2062
2063#endif /* FEAT_X11 */
2064
2065 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002066mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067{
2068 return get_x11_title(TRUE);
2069}
2070
2071 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002072mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073{
2074 return get_x11_icon(TRUE);
2075}
2076
2077/*
2078 * Set the window title and icon.
2079 */
2080 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002081mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082{
2083 int type = 0;
2084 static int recursive = 0;
2085
2086 if (T_NAME == NULL) /* no terminal name (yet) */
2087 return;
2088 if (title == NULL && icon == NULL) /* nothing to do */
2089 return;
2090
2091 /* When one of the X11 functions causes a deadly signal, we get here again
2092 * recursively. Avoid hanging then (something is probably locked). */
2093 if (recursive)
2094 return;
2095 ++recursive;
2096
2097 /*
2098 * if the window ID and the display is known, we may use X11 calls
2099 */
2100#ifdef FEAT_X11
2101 if (get_x11_windis() == OK)
2102 type = 1;
2103#else
2104# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2105 if (gui.in_use)
2106 type = 1;
2107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108#endif
2109
2110 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002111 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 * than x11 calls, because the x11 calls don't always work
2113 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 if ((type || *T_TS != NUL) && title != NULL)
2115 {
2116 if (oldtitle == NULL
2117#ifdef FEAT_GUI
2118 && !gui.in_use
2119#endif
2120 ) /* first call but not in GUI, save title */
2121 (void)get_x11_title(FALSE);
2122
2123 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2124 term_settitle(title);
2125#ifdef FEAT_X11
2126 else
2127# ifdef FEAT_GUI_GTK
2128 if (!gui.in_use) /* don't do this if GTK+ is running */
2129# endif
2130 set_x11_title(title); /* x11 */
2131#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002132#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2134 else
2135 gui_mch_settitle(title, icon);
2136#endif
2137 did_set_title = TRUE;
2138 }
2139
2140 if ((type || *T_CIS != NUL) && icon != NULL)
2141 {
2142 if (oldicon == NULL
2143#ifdef FEAT_GUI
2144 && !gui.in_use
2145#endif
2146 ) /* first call, save icon */
2147 get_x11_icon(FALSE);
2148
2149 if (*T_CIS != NUL)
2150 {
2151 out_str(T_CIS); /* set icon start */
2152 out_str_nf(icon);
2153 out_str(T_CIE); /* set icon end */
2154 out_flush();
2155 }
2156#ifdef FEAT_X11
2157 else
2158# ifdef FEAT_GUI_GTK
2159 if (!gui.in_use) /* don't do this if GTK+ is running */
2160# endif
2161 set_x11_icon(icon); /* x11 */
2162#endif
2163 did_set_icon = TRUE;
2164 }
2165 --recursive;
2166}
2167
2168/*
2169 * Restore the window/icon title.
2170 * "which" is one of:
2171 * 1 only restore title
2172 * 2 only restore icon
2173 * 3 restore title and icon
2174 */
2175 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002176mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177{
2178 /* only restore the title or icon when it has been set */
2179 mch_settitle(((which & 1) && did_set_title) ?
2180 (oldtitle ? oldtitle : p_titleold) : NULL,
2181 ((which & 2) && did_set_icon) ? oldicon : NULL);
2182}
2183
2184#endif /* FEAT_TITLE */
2185
2186/*
2187 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002188 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 */
2190 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002191vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192{
2193 if (name == NULL)
2194 return FALSE;
2195 return (STRNICMP(name, "xterm", 5) == 0
2196 || STRNICMP(name, "nxterm", 6) == 0
2197 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002198 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 || STRNICMP(name, "rxvt", 4) == 0
2200 || STRCMP(name, "builtin_xterm") == 0);
2201}
2202
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002203#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2204/*
2205 * Return TRUE if "name" appears to be that of a terminal
2206 * known to support the xterm-style mouse protocol.
2207 * Relies on term_is_xterm having been set to its correct value.
2208 */
2209 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002210use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002211{
2212 return (name != NULL
2213 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2214}
2215#endif
2216
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2218/*
2219 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2220 * Return 1 for "xterm".
2221 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002222 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002223 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 */
2225 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002226use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002228 if (ttym_flags == TTYM_SGR)
2229 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002230 if (ttym_flags == TTYM_URXVT)
2231 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 if (ttym_flags == TTYM_XTERM2)
2233 return 2;
2234 if (ttym_flags == TTYM_XTERM)
2235 return 1;
2236 return 0;
2237}
2238#endif
2239
2240 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002241vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242{
2243 if (name == NULL)
2244 return FALSE;
2245 return (STRNICMP(name, "iris-ansi", 9) == 0
2246 || STRCMP(name, "builtin_iris-ansi") == 0);
2247}
2248
2249 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002250vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251{
2252 if (name == NULL)
2253 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002254 /* catch VT100 - VT5xx */
2255 return ((STRNICMP(name, "vt", 2) == 0
2256 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 || STRCMP(name, "builtin_vt320") == 0);
2258}
2259
2260/*
2261 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2262 * This should include all windowed terminal emulators.
2263 */
2264 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002265vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266{
2267 if (name == NULL)
2268 return FALSE;
2269 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2270 return TRUE;
2271 return ( STRNICMP(name, "hpterm", 6) == 0
2272 || STRNICMP(name, "sun-cmd", 7) == 0
2273 || STRNICMP(name, "screen", 6) == 0
2274 || STRNICMP(name, "dtterm", 6) == 0);
2275}
2276
2277/*
2278 * Insert user name in s[len].
2279 * Return OK if a name found.
2280 */
2281 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002282mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283{
2284#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002285 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 return OK;
2287#else
2288 return mch_get_uname(getuid(), s, len);
2289#endif
2290}
2291
2292/*
2293 * Insert user name for "uid" in s[len].
2294 * Return OK if a name found.
2295 */
2296 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002297mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298{
2299#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2300 struct passwd *pw;
2301
2302 if ((pw = getpwuid(uid)) != NULL
2303 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2304 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002305 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 return OK;
2307 }
2308#endif
2309 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2310 return FAIL; /* a number is not a name */
2311}
2312
2313/*
2314 * Insert host name is s[len].
2315 */
2316
2317#ifdef HAVE_SYS_UTSNAME_H
2318 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002319mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320{
2321 struct utsname vutsname;
2322
2323 if (uname(&vutsname) < 0)
2324 *s = NUL;
2325 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002326 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327}
2328#else /* HAVE_SYS_UTSNAME_H */
2329
2330# ifdef HAVE_SYS_SYSTEMINFO_H
2331# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2332# endif
2333
2334 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002335mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336{
2337# ifdef VAXC
2338 vaxc$gethostname((char *)s, len);
2339# else
2340 gethostname((char *)s, len);
2341# endif
2342 s[len - 1] = NUL; /* make sure it's terminated */
2343}
2344#endif /* HAVE_SYS_UTSNAME_H */
2345
2346/*
2347 * return process ID
2348 */
2349 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002350mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351{
2352 return (long)getpid();
2353}
2354
2355#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002356static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357
2358 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002359strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360{
2361 extern int sys_nerr;
2362 extern char *sys_errlist[];
2363 static char er[20];
2364
2365 if (err > 0 && err < sys_nerr)
2366 return (sys_errlist[err]);
2367 sprintf(er, "Error %d", err);
2368 return er;
2369}
2370#endif
2371
2372/*
2373 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2374 * Return OK for success, FAIL for failure.
2375 */
2376 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002377mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378{
2379#if defined(USE_GETCWD)
2380 if (getcwd((char *)buf, len) == NULL)
2381 {
2382 STRCPY(buf, strerror(errno));
2383 return FAIL;
2384 }
2385 return OK;
2386#else
2387 return (getwd((char *)buf) != NULL ? OK : FAIL);
2388#endif
2389}
2390
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002392 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 *
2394 * return FAIL for failure, OK for success
2395 */
2396 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002397mch_FullName(
2398 char_u *fname,
2399 char_u *buf,
2400 int len,
2401 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
2403 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002404#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 int fd = -1;
2406 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002407#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 char_u olddir[MAXPATHL];
2409 char_u *p;
2410 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002411#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002412 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2413 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002414#endif
2415
Bram Moolenaar38323e42007-03-06 19:22:53 +00002416#ifdef VMS
2417 fname = vms_fixfilename(fname);
2418#endif
2419
Bram Moolenaara2442432007-04-26 14:26:37 +00002420#ifdef __CYGWIN__
2421 /*
2422 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2423 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002424# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002425 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2426 * a forward slash. */
2427 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2428 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002429# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002430 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002431# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002432 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002433#endif
2434
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002435 /* Expand it if forced or not an absolute path.
2436 * Do not do it for "/file", the result is always "/". */
2437 if ((force || !mch_isFullName(fname))
2438 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 {
2440 /*
2441 * If the file name has a path, change to that directory for a moment,
2442 * and then do the getwd() (and get back to where we were).
2443 * This will get the correct path name with "../" things.
2444 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002445 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002447#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 /*
2449 * Use fchdir() if possible, it's said to be faster and more
2450 * reliable. But on SunOS 4 it might not work. Check this by
2451 * doing a fchdir() right now.
2452 */
2453 if (!dont_fchdir)
2454 {
2455 fd = open(".", O_RDONLY | O_EXTRA, 0);
2456 if (fd >= 0 && fchdir(fd) < 0)
2457 {
2458 close(fd);
2459 fd = -1;
2460 dont_fchdir = TRUE; /* don't try again */
2461 }
2462 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464
2465 /* Only change directory when we are sure we can return to where
2466 * we are now. After doing "su" chdir(".") might not work. */
2467 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002468#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002470#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 (mch_dirname(olddir, MAXPATHL) == FAIL
2472 || mch_chdir((char *)olddir) != 0))
2473 {
2474 p = NULL; /* can't get current dir: don't chdir */
2475 retval = FAIL;
2476 }
2477 else
2478 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 /* The directory is copied into buf[], to be able to remove
2480 * the file name without changing it (could be a string in
2481 * read-only memory) */
2482 if (p - fname >= len)
2483 retval = FAIL;
2484 else
2485 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002486 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 if (mch_chdir((char *)buf))
2488 retval = FAIL;
2489 else
2490 fname = p + 1;
2491 *buf = NUL;
2492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 }
2494 }
2495 if (mch_dirname(buf, len) == FAIL)
2496 {
2497 retval = FAIL;
2498 *buf = NUL;
2499 }
2500 if (p != NULL)
2501 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002502#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 if (fd >= 0)
2504 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002505 if (p_verbose >= 5)
2506 {
2507 verbose_enter();
2508 MSG("fchdir() to previous dir");
2509 verbose_leave();
2510 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 l = fchdir(fd);
2512 close(fd);
2513 }
2514 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002515#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 l = mch_chdir((char *)olddir);
2517 if (l != 0)
2518 EMSG(_(e_prev_dir));
2519 }
2520
2521 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002522 if (l >= len - 1)
2523 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002524#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002525 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002527 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002530
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002532 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 return FAIL;
2534
2535 /* Do not append ".", "/dir/." is equal to "/dir". */
2536 if (STRCMP(fname, ".") != 0)
2537 STRCAT(buf, fname);
2538
2539 return OK;
2540}
2541
2542/*
2543 * Return TRUE if "fname" does not depend on the current directory.
2544 */
2545 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002546mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547{
2548#ifdef __EMX__
2549 return _fnisabs(fname);
2550#else
2551# ifdef VMS
2552 return ( fname[0] == '/' || fname[0] == '.' ||
2553 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2554 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2555 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2556# else
2557 return (*fname == '/' || *fname == '~');
2558# endif
2559#endif
2560}
2561
Bram Moolenaar24552be2005-12-10 20:17:30 +00002562#if defined(USE_FNAME_CASE) || defined(PROTO)
2563/*
2564 * Set the case of the file name, if it already exists. This will cause the
2565 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002566 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002567 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002568 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002569fname_case(
2570 char_u *name,
2571 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002572{
2573 struct stat st;
2574 char_u *slash, *tail;
2575 DIR *dirp;
2576 struct dirent *dp;
2577
2578 if (lstat((char *)name, &st) >= 0)
2579 {
2580 /* Open the directory where the file is located. */
2581 slash = vim_strrchr(name, '/');
2582 if (slash == NULL)
2583 {
2584 dirp = opendir(".");
2585 tail = name;
2586 }
2587 else
2588 {
2589 *slash = NUL;
2590 dirp = opendir((char *)name);
2591 *slash = '/';
2592 tail = slash + 1;
2593 }
2594
2595 if (dirp != NULL)
2596 {
2597 while ((dp = readdir(dirp)) != NULL)
2598 {
2599 /* Only accept names that differ in case and are the same byte
2600 * length. TODO: accept different length name. */
2601 if (STRICMP(tail, dp->d_name) == 0
2602 && STRLEN(tail) == STRLEN(dp->d_name))
2603 {
2604 char_u newname[MAXPATHL + 1];
2605 struct stat st2;
2606
2607 /* Verify the inode is equal. */
2608 vim_strncpy(newname, name, MAXPATHL);
2609 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2610 MAXPATHL - (tail - name));
2611 if (lstat((char *)newname, &st2) >= 0
2612 && st.st_ino == st2.st_ino
2613 && st.st_dev == st2.st_dev)
2614 {
2615 STRCPY(tail, dp->d_name);
2616 break;
2617 }
2618 }
2619 }
2620
2621 closedir(dirp);
2622 }
2623 }
2624}
2625#endif
2626
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627/*
2628 * Get file permissions for 'name'.
2629 * Returns -1 when it doesn't exist.
2630 */
2631 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002632mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633{
2634 struct stat statb;
2635
2636 /* Keep the #ifdef outside of stat(), it may be a macro. */
2637#ifdef VMS
2638 if (stat((char *)vms_fixfilename(name), &statb))
2639#else
2640 if (stat((char *)name, &statb))
2641#endif
2642 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002643#ifdef __INTERIX
2644 /* The top bit makes the value negative, which means the file doesn't
2645 * exist. Remove the bit, we don't use it. */
2646 return statb.st_mode & ~S_ADDACE;
2647#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002649#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650}
2651
2652/*
2653 * set file permission for 'name' to 'perm'
2654 *
2655 * return FAIL for failure, OK otherwise
2656 */
2657 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002658mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659{
2660 return (chmod((char *)
2661#ifdef VMS
2662 vms_fixfilename(name),
2663#else
2664 name,
2665#endif
2666 (mode_t)perm) == 0 ? OK : FAIL);
2667}
2668
2669#if defined(HAVE_ACL) || defined(PROTO)
2670# ifdef HAVE_SYS_ACL_H
2671# include <sys/acl.h>
2672# endif
2673# ifdef HAVE_SYS_ACCESS_H
2674# include <sys/access.h>
2675# endif
2676
2677# ifdef HAVE_SOLARIS_ACL
2678typedef struct vim_acl_solaris_T {
2679 int acl_cnt;
2680 aclent_t *acl_entry;
2681} vim_acl_solaris_T;
2682# endif
2683
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002684#if defined(HAVE_SELINUX) || defined(PROTO)
2685/*
2686 * Copy security info from "from_file" to "to_file".
2687 */
2688 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002689mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002690{
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 Moolenaar5bd32f42014-04-02 14:05:38 +02002738#if defined(HAVE_SMACK) && !defined(PROTO)
2739/*
2740 * Copy security info from "from_file" to "to_file".
2741 */
2742 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002743mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002744{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002745 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002746 {
2747 XATTR_NAME_SMACK,
2748 XATTR_NAME_SMACKEXEC,
2749 XATTR_NAME_SMACKMMAP
2750 };
2751
2752 char buffer[SMACK_LABEL_LEN];
2753 const char *name;
2754 int index;
2755 int ret;
2756 ssize_t size;
2757
2758 if (from_file == NULL)
2759 return;
2760
2761 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2762 / sizeof(smack_copied_attributes)[0]) ; index++)
2763 {
2764 /* get the name of the attribute to copy */
2765 name = smack_copied_attributes[index];
2766
2767 /* get the value of the attribute in buffer */
2768 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2769 if (size >= 0)
2770 {
2771 /* copy the attribute value of buffer */
2772 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2773 if (ret < 0)
2774 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002775 vim_snprintf((char *)IObuff, IOSIZE,
2776 _("Could not set security context %s for %s"),
2777 name, to_file);
2778 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002779 msg_putchar('\n');
2780 }
2781 }
2782 else
2783 {
2784 /* what reason of not having the attribute value? */
2785 switch (errno)
2786 {
2787 case ENOTSUP:
2788 /* extended attributes aren't supported or enabled */
2789 /* should a message be echoed? not sure... */
2790 return; /* leave because it isn't usefull to continue */
2791
2792 case ERANGE:
2793 default:
2794 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002795 vim_snprintf((char *)IObuff, IOSIZE,
2796 _("Could not get security context %s for %s. Removing it!"),
2797 name, from_file);
2798 msg_puts(IObuff);
2799 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002800 /* FALLTHROUGH to remove the attribute */
2801
2802 case ENODATA:
2803 /* no attribute of this name */
2804 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002805 /* Silently ignore errors, apparently this happens when
2806 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002807 break;
2808 }
2809 }
2810 }
2811}
2812#endif /* HAVE_SMACK */
2813
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814/*
2815 * Return a pointer to the ACL of file "fname" in allocated memory.
2816 * Return NULL if the ACL is not available for whatever reason.
2817 */
2818 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002819mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820{
2821 vim_acl_T ret = NULL;
2822#ifdef HAVE_POSIX_ACL
2823 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2824#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002825#ifdef HAVE_SOLARIS_ZFS_ACL
2826 acl_t *aclent;
2827
2828 if (acl_get((char *)fname, 0, &aclent) < 0)
2829 return NULL;
2830 ret = (vim_acl_T)aclent;
2831#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832#ifdef HAVE_SOLARIS_ACL
2833 vim_acl_solaris_T *aclent;
2834
2835 aclent = malloc(sizeof(vim_acl_solaris_T));
2836 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2837 {
2838 free(aclent);
2839 return NULL;
2840 }
2841 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2842 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2843 {
2844 free(aclent->acl_entry);
2845 free(aclent);
2846 return NULL;
2847 }
2848 ret = (vim_acl_T)aclent;
2849#else
2850#if defined(HAVE_AIX_ACL)
2851 int aclsize;
2852 struct acl *aclent;
2853
2854 aclsize = sizeof(struct acl);
2855 aclent = malloc(aclsize);
2856 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2857 {
2858 if (errno == ENOSPC)
2859 {
2860 aclsize = aclent->acl_len;
2861 aclent = realloc(aclent, aclsize);
2862 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2863 {
2864 free(aclent);
2865 return NULL;
2866 }
2867 }
2868 else
2869 {
2870 free(aclent);
2871 return NULL;
2872 }
2873 }
2874 ret = (vim_acl_T)aclent;
2875#endif /* HAVE_AIX_ACL */
2876#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002877#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878#endif /* HAVE_POSIX_ACL */
2879 return ret;
2880}
2881
2882/*
2883 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2884 */
2885 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002886mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887{
2888 if (aclent == NULL)
2889 return;
2890#ifdef HAVE_POSIX_ACL
2891 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2892#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002893#ifdef HAVE_SOLARIS_ZFS_ACL
2894 acl_set((char *)fname, (acl_t *)aclent);
2895#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896#ifdef HAVE_SOLARIS_ACL
2897 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2898 ((vim_acl_solaris_T *)aclent)->acl_entry);
2899#else
2900#ifdef HAVE_AIX_ACL
2901 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2902#endif /* HAVE_AIX_ACL */
2903#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002904#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905#endif /* HAVE_POSIX_ACL */
2906}
2907
2908 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002909mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910{
2911 if (aclent == NULL)
2912 return;
2913#ifdef HAVE_POSIX_ACL
2914 acl_free((acl_t)aclent);
2915#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002916#ifdef HAVE_SOLARIS_ZFS_ACL
2917 acl_free((acl_t *)aclent);
2918#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919#ifdef HAVE_SOLARIS_ACL
2920 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2921 free(aclent);
2922#else
2923#ifdef HAVE_AIX_ACL
2924 free(aclent);
2925#endif /* HAVE_AIX_ACL */
2926#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002927#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928#endif /* HAVE_POSIX_ACL */
2929}
2930#endif
2931
2932/*
2933 * Set hidden flag for "name".
2934 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002936mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937{
2938 /* can't hide a file */
2939}
2940
2941/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002942 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 * return FALSE if "name" is not a directory
2944 * return FALSE for error
2945 */
2946 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002947mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948{
2949 struct stat statb;
2950
2951 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2952 return FALSE;
2953 if (stat((char *)name, &statb))
2954 return FALSE;
2955#ifdef _POSIX_SOURCE
2956 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2957#else
2958 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2959#endif
2960}
2961
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002962/*
2963 * return TRUE if "name" is a directory, NOT a symlink to a directory
2964 * return FALSE if "name" is not a directory
2965 * return FALSE for error
2966 */
2967 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002968mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002969{
2970 struct stat statb;
2971
2972 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2973 return FALSE;
2974 if (lstat((char *)name, &statb))
2975 return FALSE;
2976#ifdef _POSIX_SOURCE
2977 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2978#else
2979 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2980#endif
2981}
2982
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002983static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984
2985/*
2986 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2987 */
2988 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01002989executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990{
2991 struct stat st;
2992
2993 if (stat((char *)name, &st))
2994 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01002995#ifdef VMS
2996 /* Like on Unix system file can have executable rights but not necessarily
2997 * be an executable, but on Unix is not a default for an ordianry file to
2998 * have an executable flag - on VMS it is in most cases.
2999 * Therefore, this check does not have any sense - let keep us to the
3000 * conventions instead:
3001 * *.COM and *.EXE files are the executables - the rest are not. This is
3002 * not ideal but better then it was.
3003 */
3004 int vms_executable = 0;
3005 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3006 {
3007 if (strstr(vms_tolower((char*)name),".exe") != NULL
3008 || strstr(vms_tolower((char*)name),".com")!= NULL)
3009 vms_executable = 1;
3010 }
3011 return vms_executable;
3012#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003014#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015}
3016
3017/*
3018 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003019 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 * Return -1 if unknown.
3021 */
3022 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003023mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024{
3025 char_u *buf;
3026 char_u *p, *e;
3027 int retval;
3028
Bram Moolenaarb5971142015-03-21 17:32:19 +01003029 /* When "use_path" is false and if it's an absolute or relative path don't
3030 * need to use $PATH. */
3031 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3032 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003033 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003034 /* There must be a path separator, files in the current directory
3035 * can't be executed. */
3036 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003037 {
3038 if (path != NULL)
3039 {
3040 if (name[0] == '.')
3041 *path = FullName_save(name, TRUE);
3042 else
3043 *path = vim_strsave(name);
3044 }
3045 return TRUE;
3046 }
3047 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003048 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049
3050 p = (char_u *)getenv("PATH");
3051 if (p == NULL || *p == NUL)
3052 return -1;
3053 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3054 if (buf == NULL)
3055 return -1;
3056
3057 /*
3058 * Walk through all entries in $PATH to check if "name" exists there and
3059 * is an executable file.
3060 */
3061 for (;;)
3062 {
3063 e = (char_u *)strchr((char *)p, ':');
3064 if (e == NULL)
3065 e = p + STRLEN(p);
3066 if (e - p <= 1) /* empty entry means current dir */
3067 STRCPY(buf, "./");
3068 else
3069 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003070 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 add_pathsep(buf);
3072 }
3073 STRCAT(buf, name);
3074 retval = executable_file(buf);
3075 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003076 {
3077 if (path != NULL)
3078 {
3079 if (buf[0] == '.')
3080 *path = FullName_save(buf, TRUE);
3081 else
3082 *path = vim_strsave(buf);
3083 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003085 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086
3087 if (*e != ':')
3088 break;
3089 p = e + 1;
3090 }
3091
3092 vim_free(buf);
3093 return retval;
3094}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095
3096/*
3097 * Check what "name" is:
3098 * NODE_NORMAL: file or directory (or doesn't exist)
3099 * NODE_WRITABLE: writable device, socket, fifo, etc.
3100 * NODE_OTHER: non-writable things
3101 */
3102 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003103mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104{
3105 struct stat st;
3106
3107 if (stat((char *)name, &st))
3108 return NODE_NORMAL;
3109 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3110 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3112 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 /* Everything else is writable? */
3114 return NODE_WRITABLE;
3115}
3116
3117 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003118mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119{
3120#ifdef HAVE_CHECK_STACK_GROWTH
3121 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 check_stack_growth((char *)&i);
3124
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003125# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 get_stack_limit();
3127# endif
3128
3129#endif
3130
3131 /*
3132 * Setup an alternative stack for signals. Helps to catch signals when
3133 * running out of stack space.
3134 * Use of sigaltstack() is preferred, it's more portable.
3135 * Ignore any errors.
3136 */
3137#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003138 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 init_signal_stack();
3140#endif
3141}
3142
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003143#if defined(EXITFREE) || defined(PROTO)
3144 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003145mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003146{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003147# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3148 if (clip_star.owned)
3149 clip_lose_selection(&clip_star);
3150 if (clip_plus.owned)
3151 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003152# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003153# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003154 if (xterm_Shell != (Widget)0)
3155 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003156# ifndef LESSTIF_VERSION
3157 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003158 if (xterm_dpy != NULL)
3159 XtCloseDisplay(xterm_dpy);
3160 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003161 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003162 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003163# ifdef FEAT_X11
3164 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3165# endif
3166 }
3167# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003168# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003169# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003170 if (x11_display != NULL
3171# ifdef FEAT_XCLIPBOARD
3172 && x11_display != xterm_dpy
3173# endif
3174 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003175 XCloseDisplay(x11_display);
3176# endif
3177# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3178 vim_free(signal_stack);
3179 signal_stack = NULL;
3180# endif
3181# ifdef FEAT_TITLE
3182 vim_free(oldtitle);
3183 vim_free(oldicon);
3184# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003185}
3186#endif
3187
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003188static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189
3190/*
3191 * Output a newline when exiting.
3192 * Make sure the newline goes to the same stream as the text.
3193 */
3194 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003195exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003197 if (silent_mode)
3198 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 if (newline_on_exit || msg_didout)
3200 {
3201 if (msg_use_printf())
3202 {
3203 if (info_message)
3204 mch_msg("\n");
3205 else
3206 mch_errmsg("\r\n");
3207 }
3208 else
3209 out_char('\n');
3210 }
3211 else
3212 {
3213 restore_cterm_colors(); /* get original colors back */
3214 msg_clr_eos_force(); /* clear the rest of the display */
3215 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3216 }
3217}
3218
3219 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003220mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221{
3222 exiting = TRUE;
3223
3224#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3225 x11_export_final_selection();
3226#endif
3227
3228#ifdef FEAT_GUI
3229 if (!gui.in_use)
3230#endif
3231 {
3232 settmode(TMODE_COOK);
3233#ifdef FEAT_TITLE
3234 mch_restore_title(3); /* restore xterm title and icon name */
3235#endif
3236 /*
3237 * When t_ti is not empty but it doesn't cause swapping terminal
3238 * pages, need to output a newline when msg_didout is set. But when
3239 * t_ti does swap pages it should not go to the shell page. Do this
3240 * before stoptermcap().
3241 */
3242 if (swapping_screen() && !newline_on_exit)
3243 exit_scroll();
3244
3245 /* Stop termcap: May need to check for T_CRV response, which
3246 * requires RAW mode. */
3247 stoptermcap();
3248
3249 /*
3250 * A newline is only required after a message in the alternate screen.
3251 * This is set to TRUE by wait_return().
3252 */
3253 if (!swapping_screen() || newline_on_exit)
3254 exit_scroll();
3255
3256 /* Cursor may have been switched off without calling starttermcap()
3257 * when doing "vim -u vimrc" and vimrc contains ":q". */
3258 if (full_screen)
3259 cursor_on();
3260 }
3261 out_flush();
3262 ml_close_all(TRUE); /* remove all memfiles */
3263 may_core_dump();
3264#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 gui_exit(r);
3267#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003268
Bram Moolenaar56718732006-03-15 22:53:57 +00003269#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003270 mac_conv_cleanup();
3271#endif
3272
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273#ifdef __QNX__
3274 /* A core dump won't be created if the signal handler
3275 * doesn't return, so we can't call exit() */
3276 if (deadly_signal != 0)
3277 return;
3278#endif
3279
Bram Moolenaar009b2592004-10-24 19:18:58 +00003280#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003281 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003282#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003283
3284#ifdef EXITFREE
3285 free_all_mem();
3286#endif
3287
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288 exit(r);
3289}
3290
3291 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003292may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293{
3294 if (deadly_signal != 0)
3295 {
3296 signal(deadly_signal, SIG_DFL);
3297 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3298 }
3299}
3300
3301#ifndef VMS
3302
3303 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003304mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305{
3306 static int first = TRUE;
3307
3308 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3309#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3310 /*
3311 * for "new" tty systems
3312 */
3313# ifdef HAVE_TERMIOS_H
3314 static struct termios told;
3315 struct termios tnew;
3316# else
3317 static struct termio told;
3318 struct termio tnew;
3319# endif
3320
3321 if (first)
3322 {
3323 first = FALSE;
3324# if defined(HAVE_TERMIOS_H)
3325 tcgetattr(read_cmd_fd, &told);
3326# else
3327 ioctl(read_cmd_fd, TCGETA, &told);
3328# endif
3329 }
3330
3331 tnew = told;
3332 if (tmode == TMODE_RAW)
3333 {
3334 /*
3335 * ~ICRNL enables typing ^V^M
3336 */
3337 tnew.c_iflag &= ~ICRNL;
3338 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3339# if defined(IEXTEN) && !defined(__MINT__)
3340 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3341 /* but it breaks function keys on MINT */
3342# endif
3343 );
3344# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3345 tnew.c_oflag &= ~ONLCR;
3346# endif
3347 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3348 tnew.c_cc[VTIME] = 0; /* don't wait */
3349 }
3350 else if (tmode == TMODE_SLEEP)
3351 tnew.c_lflag &= ~(ECHO);
3352
3353# if defined(HAVE_TERMIOS_H)
3354 {
3355 int n = 10;
3356
3357 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3358 * few times. */
3359 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3360 && errno == EINTR && n > 0)
3361 --n;
3362 }
3363# else
3364 ioctl(read_cmd_fd, TCSETA, &tnew);
3365# endif
3366
3367#else
3368
3369 /*
3370 * for "old" tty systems
3371 */
3372# ifndef TIOCSETN
3373# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3374# endif
3375 static struct sgttyb ttybold;
3376 struct sgttyb ttybnew;
3377
3378 if (first)
3379 {
3380 first = FALSE;
3381 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3382 }
3383
3384 ttybnew = ttybold;
3385 if (tmode == TMODE_RAW)
3386 {
3387 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3388 ttybnew.sg_flags |= RAW;
3389 }
3390 else if (tmode == TMODE_SLEEP)
3391 ttybnew.sg_flags &= ~(ECHO);
3392 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3393#endif
3394 curr_tmode = tmode;
3395}
3396
3397/*
3398 * Try to get the code for "t_kb" from the stty setting
3399 *
3400 * Even if termcap claims a backspace key, the user's setting *should*
3401 * prevail. stty knows more about reality than termcap does, and if
3402 * somebody's usual erase key is DEL (which, for most BSD users, it will
3403 * be), they're going to get really annoyed if their erase key starts
3404 * doing forward deletes for no reason. (Eric Fischer)
3405 */
3406 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003407get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408{
3409 char_u buf[2];
3410 char_u *p;
3411
3412 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3413#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3414 /* for "new" tty systems */
3415# ifdef HAVE_TERMIOS_H
3416 struct termios keys;
3417# else
3418 struct termio keys;
3419# endif
3420
3421# if defined(HAVE_TERMIOS_H)
3422 if (tcgetattr(read_cmd_fd, &keys) != -1)
3423# else
3424 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3425# endif
3426 {
3427 buf[0] = keys.c_cc[VERASE];
3428 intr_char = keys.c_cc[VINTR];
3429#else
3430 /* for "old" tty systems */
3431 struct sgttyb keys;
3432
3433 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3434 {
3435 buf[0] = keys.sg_erase;
3436 intr_char = keys.sg_kill;
3437#endif
3438 buf[1] = NUL;
3439 add_termcode((char_u *)"kb", buf, FALSE);
3440
3441 /*
3442 * If <BS> and <DEL> are now the same, redefine <DEL>.
3443 */
3444 p = find_termcode((char_u *)"kD");
3445 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3446 do_fixdel(NULL);
3447 }
3448#if 0
3449 } /* to keep cindent happy */
3450#endif
3451}
3452
3453#endif /* VMS */
3454
3455#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3456/*
3457 * Set mouse clicks on or off.
3458 */
3459 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003460mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461{
3462 static int ison = FALSE;
3463 int xterm_mouse_vers;
3464
3465 if (on == ison) /* return quickly if nothing to do */
3466 return;
3467
3468 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003469
3470# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003471 if (ttym_flags == TTYM_URXVT)
3472 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003473 out_str_nf((char_u *)
3474 (on
3475 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3476 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3477 ison = on;
3478 }
3479# endif
3480
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003481# ifdef FEAT_MOUSE_SGR
3482 if (ttym_flags == TTYM_SGR)
3483 {
3484 out_str_nf((char_u *)
3485 (on
3486 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3487 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3488 ison = on;
3489 }
3490# endif
3491
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492 if (xterm_mouse_vers > 0)
3493 {
3494 if (on) /* enable mouse events, use mouse tracking if available */
3495 out_str_nf((char_u *)
3496 (xterm_mouse_vers > 1
3497 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3498 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3499 else /* disable mouse events, could probably always send the same */
3500 out_str_nf((char_u *)
3501 (xterm_mouse_vers > 1
3502 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3503 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3504 ison = on;
3505 }
3506
3507# ifdef FEAT_MOUSE_DEC
3508 else if (ttym_flags == TTYM_DEC)
3509 {
3510 if (on) /* enable mouse events */
3511 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3512 else /* disable mouse events */
3513 out_str_nf((char_u *)"\033['z");
3514 ison = on;
3515 }
3516# endif
3517
3518# ifdef FEAT_MOUSE_GPM
3519 else
3520 {
3521 if (on)
3522 {
3523 if (gpm_open())
3524 ison = TRUE;
3525 }
3526 else
3527 {
3528 gpm_close();
3529 ison = FALSE;
3530 }
3531 }
3532# endif
3533
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003534# ifdef FEAT_SYSMOUSE
3535 else
3536 {
3537 if (on)
3538 {
3539 if (sysmouse_open() == OK)
3540 ison = TRUE;
3541 }
3542 else
3543 {
3544 sysmouse_close();
3545 ison = FALSE;
3546 }
3547 }
3548# endif
3549
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550# ifdef FEAT_MOUSE_JSB
3551 else
3552 {
3553 if (on)
3554 {
3555 /* D - Enable Mouse up/down messages
3556 * L - Enable Left Button Reporting
3557 * M - Enable Middle Button Reporting
3558 * R - Enable Right Button Reporting
3559 * K - Enable SHIFT and CTRL key Reporting
3560 * + - Enable Advanced messaging of mouse moves and up/down messages
3561 * Q - Quiet No Ack
3562 * # - Numeric value of mouse pointer required
3563 * 0 = Multiview 2000 cursor, used as standard
3564 * 1 = Windows Arrow
3565 * 2 = Windows I Beam
3566 * 3 = Windows Hour Glass
3567 * 4 = Windows Cross Hair
3568 * 5 = Windows UP Arrow
3569 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003570# ifdef JSBTERM_MOUSE_NONADVANCED
3571 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3573 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003574# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3576 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 ison = TRUE;
3579 }
3580 else
3581 {
3582 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3583 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3584 ison = FALSE;
3585 }
3586 }
3587# endif
3588# ifdef FEAT_MOUSE_PTERM
3589 else
3590 {
3591 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3592 if (on)
3593 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3594 else
3595 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3596 ison = on;
3597 }
3598# endif
3599}
3600
3601/*
3602 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3603 */
3604 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003605check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606{
3607# ifdef FEAT_MOUSE_XTERM
3608 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003609# ifdef FEAT_MOUSE_URXVT
3610 && use_xterm_mouse() != 3
3611# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612# ifdef FEAT_GUI
3613 && !gui.in_use
3614# endif
3615 )
3616 {
3617 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003618 ? IF_EB("\233M", CSI_STR "M")
3619 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620 if (*p_mouse != NUL)
3621 {
3622 /* force mouse off and maybe on to send possibly new mouse
3623 * activation sequence to the xterm, with(out) drag tracing. */
3624 mch_setmouse(FALSE);
3625 setmouse();
3626 }
3627 }
3628 else
3629 del_mouse_termcode(KS_MOUSE);
3630# endif
3631
3632# ifdef FEAT_MOUSE_GPM
3633 if (!use_xterm_mouse()
3634# ifdef FEAT_GUI
3635 && !gui.in_use
3636# endif
3637 )
3638 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3639# endif
3640
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003641# ifdef FEAT_SYSMOUSE
3642 if (!use_xterm_mouse()
3643# ifdef FEAT_GUI
3644 && !gui.in_use
3645# endif
3646 )
3647 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3648# endif
3649
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003651 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 if (!use_xterm_mouse()
3653# ifdef FEAT_GUI
3654 && !gui.in_use
3655# endif
3656 )
3657 set_mouse_termcode(KS_JSBTERM_MOUSE,
3658 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3659 else
3660 del_mouse_termcode(KS_JSBTERM_MOUSE);
3661# endif
3662
3663# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003664 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665 * define it in the GUI or when using an xterm. */
3666 if (!use_xterm_mouse()
3667# ifdef FEAT_GUI
3668 && !gui.in_use
3669# endif
3670 )
3671 set_mouse_termcode(KS_NETTERM_MOUSE,
3672 (char_u *)IF_EB("\033}", ESC_STR "}"));
3673 else
3674 del_mouse_termcode(KS_NETTERM_MOUSE);
3675# endif
3676
3677# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003678 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003679 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680# ifdef FEAT_GUI
3681 && !gui.in_use
3682# endif
3683 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003684 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3685 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686 else
3687 del_mouse_termcode(KS_DEC_MOUSE);
3688# endif
3689# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003690 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003691 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692# ifdef FEAT_GUI
3693 && !gui.in_use
3694# endif
3695 )
3696 set_mouse_termcode(KS_PTERM_MOUSE,
3697 (char_u *) IF_EB("\033[", ESC_STR "["));
3698 else
3699 del_mouse_termcode(KS_PTERM_MOUSE);
3700# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003701# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003702 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003703 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003704# ifdef FEAT_GUI
3705 && !gui.in_use
3706# endif
3707 )
3708 {
3709 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3710 ? IF_EB("\233", CSI_STR)
3711 : IF_EB("\033[", ESC_STR "[")));
3712
3713 if (*p_mouse != NUL)
3714 {
3715 mch_setmouse(FALSE);
3716 setmouse();
3717 }
3718 }
3719 else
3720 del_mouse_termcode(KS_URXVT_MOUSE);
3721# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003722# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003723 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003724 if (use_xterm_mouse() == 4
3725# ifdef FEAT_GUI
3726 && !gui.in_use
3727# endif
3728 )
3729 {
3730 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3731 ? IF_EB("\233<", CSI_STR "<")
3732 : IF_EB("\033[<", ESC_STR "[<")));
3733
3734 if (*p_mouse != NUL)
3735 {
3736 mch_setmouse(FALSE);
3737 setmouse();
3738 }
3739 }
3740 else
3741 del_mouse_termcode(KS_SGR_MOUSE);
3742# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743}
3744#endif
3745
3746/*
3747 * set screen mode, always fails.
3748 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003750mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751{
3752 EMSG(_(e_screenmode));
3753 return FAIL;
3754}
3755
3756#ifndef VMS
3757
3758/*
3759 * Try to get the current window size:
3760 * 1. with an ioctl(), most accurate method
3761 * 2. from the environment variables LINES and COLUMNS
3762 * 3. from the termcap
3763 * 4. keep using the old values
3764 * Return OK when size could be determined, FAIL otherwise.
3765 */
3766 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003767mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768{
3769 long rows = 0;
3770 long columns = 0;
3771 char_u *p;
3772
3773 /*
3774 * For OS/2 use _scrsize().
3775 */
3776# ifdef __EMX__
3777 {
3778 int s[2];
3779
3780 _scrsize(s);
3781 columns = s[0];
3782 rows = s[1];
3783 }
3784# endif
3785
3786 /*
3787 * 1. try using an ioctl. It is the most accurate method.
3788 *
3789 * Try using TIOCGWINSZ first, some systems that have it also define
3790 * TIOCGSIZE but don't have a struct ttysize.
3791 */
3792# ifdef TIOCGWINSZ
3793 {
3794 struct winsize ws;
3795 int fd = 1;
3796
3797 /* When stdout is not a tty, use stdin for the ioctl(). */
3798 if (!isatty(fd) && isatty(read_cmd_fd))
3799 fd = read_cmd_fd;
3800 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3801 {
3802 columns = ws.ws_col;
3803 rows = ws.ws_row;
3804 }
3805 }
3806# else /* TIOCGWINSZ */
3807# ifdef TIOCGSIZE
3808 {
3809 struct ttysize ts;
3810 int fd = 1;
3811
3812 /* When stdout is not a tty, use stdin for the ioctl(). */
3813 if (!isatty(fd) && isatty(read_cmd_fd))
3814 fd = read_cmd_fd;
3815 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3816 {
3817 columns = ts.ts_cols;
3818 rows = ts.ts_lines;
3819 }
3820 }
3821# endif /* TIOCGSIZE */
3822# endif /* TIOCGWINSZ */
3823
3824 /*
3825 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003826 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3827 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003829 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830 {
3831 if ((p = (char_u *)getenv("LINES")))
3832 rows = atoi((char *)p);
3833 if ((p = (char_u *)getenv("COLUMNS")))
3834 columns = atoi((char *)p);
3835 }
3836
3837#ifdef HAVE_TGETENT
3838 /*
3839 * 3. try reading "co" and "li" entries from termcap
3840 */
3841 if (columns == 0 || rows == 0)
3842 getlinecol(&columns, &rows);
3843#endif
3844
3845 /*
3846 * 4. If everything fails, use the old values
3847 */
3848 if (columns <= 0 || rows <= 0)
3849 return FAIL;
3850
3851 Rows = rows;
3852 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003853 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 return OK;
3855}
3856
3857/*
3858 * Try to set the window size to Rows and Columns.
3859 */
3860 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003861mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862{
3863 if (*T_CWS)
3864 {
3865 /*
3866 * NOTE: if you get an error here that term_set_winsize() is
3867 * undefined, check the output of configure. It could probably not
3868 * find a ncurses, termcap or termlib library.
3869 */
3870 term_set_winsize((int)Rows, (int)Columns);
3871 out_flush();
3872 screen_start(); /* don't know where cursor is now */
3873 }
3874}
3875
3876#endif /* VMS */
3877
3878/*
3879 * Rows and/or Columns has changed.
3880 */
3881 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003882mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883{
3884 /* Nothing to do. */
3885}
3886
Bram Moolenaar205b8862011-09-07 15:04:31 +02003887/*
3888 * Wait for process "child" to end.
3889 * Return "child" if it exited properly, <= 0 on error.
3890 */
3891 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003892wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003893{
3894 pid_t wait_pid = 0;
3895
3896 while (wait_pid != child)
3897 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003898 /* When compiled with Python threads are probably used, in which case
3899 * wait() sometimes hangs for no obvious reason. Use waitpid()
3900 * instead and loop (like the GUI). Also needed for other interfaces,
3901 * they might call system(). */
3902# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003903 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003904# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003905 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003906# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003907 if (wait_pid == 0)
3908 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003909 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003910 mch_delay(10L, TRUE);
3911 continue;
3912 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003913 if (wait_pid <= 0
3914# ifdef ECHILD
3915 && errno == ECHILD
3916# endif
3917 )
3918 break;
3919 }
3920 return wait_pid;
3921}
3922
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003923#if defined(FEAT_JOB_CHANNEL) || !defined(USE_SYSTEM) || defined(PROTO)
Bram Moolenaar72801402016-02-09 11:37:50 +01003924/*
3925 * Parse "cmd" and put the white-separated parts in "argv".
3926 * "argv" is an allocated array with "argc" entries.
3927 * Returns FAIL when out of memory.
3928 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01003929 int
3930mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
3931{
3932 int i;
3933 char_u *p;
3934 int inquote;
3935
3936 /*
3937 * Do this loop twice:
3938 * 1: find number of arguments
3939 * 2: separate them and build argv[]
3940 */
3941 for (i = 0; i < 2; ++i)
3942 {
3943 p = cmd;
3944 inquote = FALSE;
3945 *argc = 0;
3946 for (;;)
3947 {
3948 if (i == 1)
3949 (*argv)[*argc] = (char *)p;
3950 ++*argc;
3951 while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
3952 {
3953 if (*p == '"')
3954 inquote = !inquote;
3955 ++p;
3956 }
3957 if (*p == NUL)
3958 break;
3959 if (i == 1)
3960 *p++ = NUL;
3961 p = skipwhite(p);
3962 }
3963 if (*argv == NULL)
3964 {
3965 if (use_shcf)
3966 {
3967 /* Account for possible multiple args in p_shcf. */
3968 p = p_shcf;
3969 for (;;)
3970 {
3971 p = skiptowhite(p);
3972 if (*p == NUL)
3973 break;
3974 ++*argc;
3975 p = skipwhite(p);
3976 }
3977 }
3978
3979 *argv = (char **)alloc((unsigned)((*argc + 4) * sizeof(char *)));
3980 if (*argv == NULL) /* out of memory */
3981 return FAIL;
3982 }
3983 }
3984 return OK;
3985}
3986#endif
3987
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003988#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01003989 static void
3990set_child_environment(void)
3991{
3992# ifdef HAVE_SETENV
3993 char envbuf[50];
3994# else
3995 static char envbuf_Rows[20];
3996 static char envbuf_Columns[20];
3997# endif
3998
3999 /* Simulate to have a dumb terminal (for now) */
4000# ifdef HAVE_SETENV
4001 setenv("TERM", "dumb", 1);
4002 sprintf((char *)envbuf, "%ld", Rows);
4003 setenv("ROWS", (char *)envbuf, 1);
4004 sprintf((char *)envbuf, "%ld", Rows);
4005 setenv("LINES", (char *)envbuf, 1);
4006 sprintf((char *)envbuf, "%ld", Columns);
4007 setenv("COLUMNS", (char *)envbuf, 1);
4008# else
4009 /*
4010 * Putenv does not copy the string, it has to remain valid.
4011 * Use a static array to avoid losing allocated memory.
4012 */
4013 putenv("TERM=dumb");
4014 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4015 putenv(envbuf_Rows);
4016 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4017 putenv(envbuf_Rows);
4018 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4019 putenv(envbuf_Columns);
4020# endif
4021}
4022#endif
4023
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004025mch_call_shell(
4026 char_u *cmd,
4027 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028{
4029#ifdef VMS
4030 char *ifn = NULL;
4031 char *ofn = NULL;
4032#endif
4033 int tmode = cur_tmode;
4034#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
4035 int x;
4036# ifndef __EMX__
4037 char_u *newcmd; /* only needed for unix */
4038# else
4039 /*
4040 * Set the preferred shell in the EMXSHELL environment variable (but
4041 * only if it is different from what is already in the environment).
4042 * Emx then takes care of whether to use "/c" or "-c" in an
4043 * intelligent way. Simply pass the whole thing to emx's system() call.
4044 * Emx also starts an interactive shell if system() is passed an empty
4045 * string.
4046 */
4047 char_u *p, *old;
4048
4049 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4050 {
4051 /* should check HAVE_SETENV, but I know we don't have it. */
4052 p = alloc(10 + strlen(p_sh));
4053 if (p)
4054 {
4055 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4056 putenv((char *)p); /* don't free the pointer! */
4057 }
4058 }
4059# endif
4060
4061 out_flush();
4062
4063 if (options & SHELL_COOKED)
4064 settmode(TMODE_COOK); /* set to normal mode */
4065
Bram Moolenaar62b42182010-09-21 22:09:37 +02004066# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004067 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004068 loose_clipboard();
4069# endif
4070
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071# ifdef __EMX__
4072 if (cmd == NULL)
4073 x = system(""); /* this starts an interactive shell in emx */
4074 else
4075 x = system((char *)cmd);
4076 /* system() returns -1 when error occurs in starting shell */
4077 if (x == -1 && !emsg_silent)
4078 {
4079 MSG_PUTS(_("\nCannot execute shell "));
4080 msg_outtrans(p_sh);
4081 msg_putchar('\n');
4082 }
4083# else /* not __EMX__ */
4084 if (cmd == NULL)
4085 x = system((char *)p_sh);
4086 else
4087 {
4088# ifdef VMS
4089 if (ofn = strchr((char *)cmd, '>'))
4090 *ofn++ = '\0';
4091 if (ifn = strchr((char *)cmd, '<'))
4092 {
4093 char *p;
4094
4095 *ifn++ = '\0';
4096 p = strchr(ifn,' '); /* chop off any trailing spaces */
4097 if (p)
4098 *p = '\0';
4099 }
4100 if (ofn)
4101 x = vms_sys((char *)cmd, ofn, ifn);
4102 else
4103 x = system((char *)cmd);
4104# else
4105 newcmd = lalloc(STRLEN(p_sh)
4106 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4107 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4108 if (newcmd == NULL)
4109 x = 0;
4110 else
4111 {
4112 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4113 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4114 (char *)p_shcf,
4115 (char *)cmd);
4116 x = system((char *)newcmd);
4117 vim_free(newcmd);
4118 }
4119# endif
4120 }
4121# ifdef VMS
4122 x = vms_sys_status(x);
4123# endif
4124 if (emsg_silent)
4125 ;
4126 else if (x == 127)
4127 MSG_PUTS(_("\nCannot execute shell sh\n"));
4128# endif /* __EMX__ */
4129 else if (x && !(options & SHELL_SILENT))
4130 {
4131 MSG_PUTS(_("\nshell returned "));
4132 msg_outnum((long)x);
4133 msg_putchar('\n');
4134 }
4135
4136 if (tmode == TMODE_RAW)
4137 settmode(TMODE_RAW); /* set to raw mode */
4138# ifdef FEAT_TITLE
4139 resettitle();
4140# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004141# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4142 restore_clipboard();
4143# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 return x;
4145
4146#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4147
Bram Moolenaardf177f62005-02-22 08:39:57 +00004148# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4149 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150
Bram Moolenaar835dc632016-02-07 14:27:38 +01004151 char_u *newcmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004153 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 pid_t wait_pid = 0;
4155# ifdef HAVE_UNION_WAIT
4156 union wait status;
4157# else
4158 int status = -1;
4159# endif
4160 int retval = -1;
4161 char **argv = NULL;
4162 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004163 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 int i;
4165 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004167# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 int pty_slave_fd = -1;
4169 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004170# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004171 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 int fd_fromshell[2];
4173 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004174 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175
Bram Moolenaar62b42182010-09-21 22:09:37 +02004176 newcmd = vim_strsave(p_sh);
4177 if (newcmd == NULL) /* out of memory */
4178 goto error;
4179
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 out_flush();
4181 if (options & SHELL_COOKED)
4182 settmode(TMODE_COOK); /* set to normal mode */
4183
Bram Moolenaar835dc632016-02-07 14:27:38 +01004184 if (mch_parse_cmd(newcmd, TRUE, &argv, &argc) == FAIL)
4185 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004186
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 if (cmd != NULL)
4188 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004189 char_u *s;
4190
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 if (extra_shell_arg != NULL)
4192 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004193
4194 /* Break 'shellcmdflag' into white separated parts. This doesn't
4195 * handle quoted strings, they are very unlikely to appear. */
4196 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4197 if (p_shcf_copy == NULL) /* out of memory */
4198 goto error;
4199 s = p_shcf_copy;
4200 p = p_shcf;
4201 while (*p != NUL)
4202 {
4203 argv[argc++] = (char *)s;
4204 while (*p && *p != ' ' && *p != TAB)
4205 *s++ = *p++;
4206 *s++ = NUL;
4207 p = skipwhite(p);
4208 }
4209
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 argv[argc++] = (char *)cmd;
4211 }
4212 argv[argc] = NULL;
4213
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004215 * For the GUI, when writing the output into the buffer and when reading
4216 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4217 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004219 if ((options & (SHELL_READ|SHELL_WRITE))
4220# ifdef FEAT_GUI
4221 || (gui.in_use && show_shell_mess)
4222# endif
4223 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004225# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004226 /*
4227 * Try to open a master pty.
4228 * If this works, open the slave pty.
4229 * If the slave can't be opened, close the master pty.
4230 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004231 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232 {
4233 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004234 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004236 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4237 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4238 * adding O_NOCTTY always works when defined. */
4239#ifdef O_NOCTTY
4240 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4241#else
4242 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4243#endif
4244 if (pty_slave_fd < 0)
4245 {
4246 close(pty_master_fd);
4247 pty_master_fd = -1;
4248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249 }
4250 }
4251 /*
4252 * If not opening a pty or it didn't work, try using pipes.
4253 */
4254 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004255# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256 {
4257 pipe_error = (pipe(fd_toshell) < 0);
4258 if (!pipe_error) /* pipe create OK */
4259 {
4260 pipe_error = (pipe(fd_fromshell) < 0);
4261 if (pipe_error) /* pipe create failed */
4262 {
4263 close(fd_toshell[0]);
4264 close(fd_toshell[1]);
4265 }
4266 }
4267 if (pipe_error)
4268 {
4269 MSG_PUTS(_("\nCannot create pipes\n"));
4270 out_flush();
4271 }
4272 }
4273 }
4274
4275 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 {
4277# ifdef __BEOS__
4278 beos_cleanup_read_thread();
4279# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004280
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4282 {
4283 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004284 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004286 || (gui.in_use && show_shell_mess)
4287# endif
4288 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004290# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 if (pty_master_fd >= 0) /* close the pseudo tty */
4292 {
4293 close(pty_master_fd);
4294 close(pty_slave_fd);
4295 }
4296 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004297# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 {
4299 close(fd_toshell[0]);
4300 close(fd_toshell[1]);
4301 close(fd_fromshell[0]);
4302 close(fd_fromshell[1]);
4303 }
4304 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 }
4306 else if (pid == 0) /* child */
4307 {
4308 reset_signals(); /* handle signals normally */
4309
4310 if (!show_shell_mess || (options & SHELL_EXPAND))
4311 {
4312 int fd;
4313
4314 /*
4315 * Don't want to show any message from the shell. Can't just
4316 * close stdout and stderr though, because some systems will
4317 * break if you try to write to them after that, so we must
4318 * use dup() to replace them with something else -- webb
4319 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4320 * waiting for input.
4321 */
4322 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4323 fclose(stdin);
4324 fclose(stdout);
4325 fclose(stderr);
4326
4327 /*
4328 * If any of these open()'s and dup()'s fail, we just continue
4329 * anyway. It's not fatal, and on most systems it will make
4330 * no difference at all. On a few it will cause the execvp()
4331 * to exit with a non-zero status even when the completion
4332 * could be done, which is nothing too serious. If the open()
4333 * or dup() failed we'd just do the same thing ourselves
4334 * anyway -- webb
4335 */
4336 if (fd >= 0)
4337 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004338 ignored = dup(fd); /* To replace stdin (fd 0) */
4339 ignored = dup(fd); /* To replace stdout (fd 1) */
4340 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341
4342 /* Don't need this now that we've duplicated it */
4343 close(fd);
4344 }
4345 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004346 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004348 || gui.in_use
4349# endif
4350 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 {
4352
Bram Moolenaardf177f62005-02-22 08:39:57 +00004353# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004354 /* Create our own process group, so that the child and all its
4355 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004356 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004357 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004358 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004359 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004360# if defined(SIGHUP)
4361 /* When doing "!xterm&" and 'shell' is bash: the shell
4362 * will exit and send SIGHUP to all processes in its
4363 * group, killing the just started process. Ignore SIGHUP
4364 * to avoid that. (suggested by Simon Schubert)
4365 */
4366 signal(SIGHUP, SIG_IGN);
4367# endif
4368 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004369# endif
4370# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004371 if (pty_slave_fd >= 0)
4372 {
4373 /* push stream discipline modules */
4374 if (options & SHELL_COOKED)
4375 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004377 /* Try to become controlling tty (probably doesn't work,
4378 * unless run by root) */
4379 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004381 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004382# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004383 set_child_environment();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004384
Bram Moolenaara5792f52005-11-23 21:25:05 +00004385 /*
4386 * stderr is only redirected when using the GUI, so that a
4387 * program like gpg can still access the terminal to get a
4388 * passphrase using stderr.
4389 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004390# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391 if (pty_master_fd >= 0)
4392 {
4393 close(pty_master_fd); /* close master side of pty */
4394
4395 /* set up stdin/stdout/stderr for the child */
4396 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004397 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004399 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004400 if (gui.in_use)
4401 {
4402 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004403 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004404 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405
4406 close(pty_slave_fd); /* has been dupped, close it now */
4407 }
4408 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004409# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 {
4411 /* set up stdin for the child */
4412 close(fd_toshell[1]);
4413 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004414 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 close(fd_toshell[0]);
4416
4417 /* set up stdout for the child */
4418 close(fd_fromshell[0]);
4419 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004420 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421 close(fd_fromshell[1]);
4422
Bram Moolenaara5792f52005-11-23 21:25:05 +00004423# ifdef FEAT_GUI
4424 if (gui.in_use)
4425 {
4426 /* set up stderr for the child */
4427 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004428 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004429 }
4430# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 }
4432 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004433
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 /*
4435 * There is no type cast for the argv, because the type may be
4436 * different on different machines. This may cause a warning
4437 * message with strict compilers, don't worry about it.
4438 * Call _exit() instead of exit() to avoid closing the connection
4439 * to the X server (esp. with GTK, which uses atexit()).
4440 */
4441 execvp(argv[0], argv);
4442 _exit(EXEC_FAILED); /* exec failed, return failure code */
4443 }
4444 else /* parent */
4445 {
4446 /*
4447 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004448 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 */
4450 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004451 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452
4453 /*
4454 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004455 * This is also used to pipe stdin/stdout to/from the external
4456 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004458 if ((options & (SHELL_READ|SHELL_WRITE))
4459# ifdef FEAT_GUI
4460 || (gui.in_use && show_shell_mess)
4461# endif
4462 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004464# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004466# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004468# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4470 int ta_len = 0; /* valid bytes in ta_buf[] */
4471 int len;
4472 int p_more_save;
4473 int old_State;
4474 int c;
4475 int toshell_fd;
4476 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004477 garray_T ga;
4478 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004479# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4480 struct timeval start_tv;
4481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482
Bram Moolenaardf177f62005-02-22 08:39:57 +00004483# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 if (pty_master_fd >= 0)
4485 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 fromshell_fd = pty_master_fd;
4487 toshell_fd = dup(pty_master_fd);
4488 }
4489 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004490# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491 {
4492 close(fd_toshell[0]);
4493 close(fd_fromshell[1]);
4494 toshell_fd = fd_toshell[1];
4495 fromshell_fd = fd_fromshell[0];
4496 }
4497
4498 /*
4499 * Write to the child if there are typed characters.
4500 * Read from the child if there are characters available.
4501 * Repeat the reading a few times if more characters are
4502 * available. Need to check for typed keys now and then, but
4503 * not too often (delays when no chars are available).
4504 * This loop is quit if no characters can be read from the pty
4505 * (WaitForChar detected special condition), or there are no
4506 * characters available and the child has exited.
4507 * Only check if the child has exited when there is no more
4508 * output. The child may exit before all the output has
4509 * been printed.
4510 *
4511 * Currently this busy loops!
4512 * This can probably dead-lock when the write blocks!
4513 */
4514 p_more_save = p_more;
4515 p_more = FALSE;
4516 old_State = State;
4517 State = EXTERNCMD; /* don't redraw at window resize */
4518
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004519 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004520 {
4521 /* Fork a process that will write the lines to the
4522 * external program. */
4523 if ((wpid = fork()) == -1)
4524 {
4525 MSG_PUTS(_("\nCannot fork\n"));
4526 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004527 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004528 {
4529 linenr_T lnum = curbuf->b_op_start.lnum;
4530 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004531 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004532 size_t l;
4533
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004534 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004535 for (;;)
4536 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004537 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004538 if (l == 0)
4539 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004540 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004541 /* NL -> NUL translation */
4542 len = write(toshell_fd, "", (size_t)1);
4543 else
4544 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004545 char_u *s = vim_strchr(lp + written, NL);
4546
Bram Moolenaar89d40322006-08-29 15:30:07 +00004547 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004548 s == NULL ? l
4549 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004550 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004551 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004552 {
4553 /* Finished a line, add a NL, unless this line
4554 * should not have one. */
4555 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004556 || (!curbuf->b_p_bin
4557 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004558 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004559 && (lnum !=
4560 curbuf->b_ml.ml_line_count
4561 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004562 ignored = write(toshell_fd, "\n",
4563 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004564 ++lnum;
4565 if (lnum > curbuf->b_op_end.lnum)
4566 {
4567 /* finished all the lines, close pipe */
4568 close(toshell_fd);
4569 toshell_fd = -1;
4570 break;
4571 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004572 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004573 written = 0;
4574 }
4575 else if (len > 0)
4576 written += len;
4577 }
4578 _exit(0);
4579 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004580 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004581 {
4582 close(toshell_fd);
4583 toshell_fd = -1;
4584 }
4585 }
4586
4587 if (options & SHELL_READ)
4588 ga_init2(&ga, 1, BUFLEN);
4589
4590 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004591# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4592 gettimeofday(&start_tv, NULL);
4593# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594 for (;;)
4595 {
4596 /*
4597 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004598 * if there are any.
4599 * Don't do this if we are expanding wild cards (would eat
4600 * typeahead).
4601 * Don't do this when filtering and terminal is in cooked
4602 * mode, the shell command will handle the I/O. Avoids
4603 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004604 * Don't get characters when the child has already
4605 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004606 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004607 * while (noread_cnt > 4), avoids that ":r !ls" eats
4608 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609 */
4610 len = 0;
4611 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004612 && ((options &
4613 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4614 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004615# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004616 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004617# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004618 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004619 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004620 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004622 if (ta_len == 0)
4623 {
4624 /* Get extra characters when we don't have any.
4625 * Reset the counter and timer. */
4626 noread_cnt = 0;
4627# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4628 gettimeofday(&start_tv, NULL);
4629# endif
4630 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4631 }
4632 if (ta_len > 0 || len > 0)
4633 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 /*
4635 * For pipes:
4636 * Check for CTRL-C: send interrupt signal to child.
4637 * Check for CTRL-D: EOF, close pipe to child.
4638 */
4639 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4640 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004641# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 /*
4643 * Send SIGINT to the child's group or all
4644 * processes in our group.
4645 */
4646 if (ta_buf[ta_len] == Ctrl_C
4647 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004648 {
4649# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004650 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004651# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004653# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004654 if (wpid > 0)
4655 kill(wpid, SIGINT);
4656 }
4657# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004658 if (pty_master_fd < 0 && toshell_fd >= 0
4659 && ta_buf[ta_len] == Ctrl_D)
4660 {
4661 close(toshell_fd);
4662 toshell_fd = -1;
4663 }
4664 }
4665
4666 /* replace K_BS by <BS> and K_DEL by <DEL> */
4667 for (i = ta_len; i < ta_len + len; ++i)
4668 {
4669 if (ta_buf[i] == CSI && len - i > 2)
4670 {
4671 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4672 if (c == K_DEL || c == K_KDEL || c == K_BS)
4673 {
4674 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4675 (size_t)(len - i - 2));
4676 if (c == K_DEL || c == K_KDEL)
4677 ta_buf[i] = DEL;
4678 else
4679 ta_buf[i] = Ctrl_H;
4680 len -= 2;
4681 }
4682 }
4683 else if (ta_buf[i] == '\r')
4684 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004685# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004687 i += (*mb_ptr2len_len)(ta_buf + i,
4688 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690 }
4691
4692 /*
4693 * For pipes: echo the typed characters.
4694 * For a pty this does not seem to work.
4695 */
4696 if (pty_master_fd < 0)
4697 {
4698 for (i = ta_len; i < ta_len + len; ++i)
4699 {
4700 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4701 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004702# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703 else if (has_mbyte)
4704 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004705 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706
4707 msg_outtrans_len(ta_buf + i, l);
4708 i += l - 1;
4709 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 else
4712 msg_outtrans_len(ta_buf + i, 1);
4713 }
4714 windgoto(msg_row, msg_col);
4715 out_flush();
4716 }
4717
4718 ta_len += len;
4719
4720 /*
4721 * Write the characters to the child, unless EOF has
4722 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004723 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004724 * When writing buffer lines, drop the typed
4725 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004727 if (options & SHELL_WRITE)
4728 ta_len = 0;
4729 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730 {
4731 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4732 if (len > 0)
4733 {
4734 ta_len -= len;
4735 mch_memmove(ta_buf, ta_buf + len, ta_len);
4736 }
4737 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739 }
4740
Bram Moolenaardf177f62005-02-22 08:39:57 +00004741 if (got_int)
4742 {
4743 /* CTRL-C sends a signal to the child, we ignore it
4744 * ourselves */
4745# ifdef HAVE_SETSID
4746 kill(-pid, SIGINT);
4747# else
4748 kill(0, SIGINT);
4749# endif
4750 if (wpid > 0)
4751 kill(wpid, SIGINT);
4752 got_int = FALSE;
4753 }
4754
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 /*
4756 * Check if the child has any characters to be printed.
4757 * Read them and write them to our window. Repeat this as
4758 * long as there is something to do, avoid the 10ms wait
4759 * for mch_inchar(), or sending typeahead characters to
4760 * the external process.
4761 * TODO: This should handle escape sequences, compatible
4762 * to some terminal (vt52?).
4763 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004764 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4766 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004767 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004768# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004770# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004772# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 );
4774 if (len <= 0) /* end of file or error */
4775 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004776
4777 noread_cnt = 0;
4778 if (options & SHELL_READ)
4779 {
4780 /* Do NUL -> NL translation, append NL separated
4781 * lines to the current buffer. */
4782 for (i = 0; i < len; ++i)
4783 {
4784 if (buffer[i] == NL)
4785 append_ga_line(&ga);
4786 else if (buffer[i] == NUL)
4787 ga_append(&ga, NL);
4788 else
4789 ga_append(&ga, buffer[i]);
4790 }
4791 }
4792# ifdef FEAT_MBYTE
4793 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 {
4795 int l;
4796
Bram Moolenaardf177f62005-02-22 08:39:57 +00004797 len += buffer_off;
4798 buffer[len] = NUL;
4799
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 /* Check if the last character in buffer[] is
4801 * incomplete, keep these bytes for the next
4802 * round. */
4803 for (p = buffer; p < buffer + len; p += l)
4804 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004805 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 if (l == 0)
4807 l = 1; /* NUL byte? */
4808 else if (MB_BYTE2LEN(*p) != l)
4809 break;
4810 }
4811 if (p == buffer) /* no complete character */
4812 {
4813 /* avoid getting stuck at an illegal byte */
4814 if (len >= 12)
4815 ++p;
4816 else
4817 {
4818 buffer_off = len;
4819 continue;
4820 }
4821 }
4822 c = *p;
4823 *p = NUL;
4824 msg_puts(buffer);
4825 if (p < buffer + len)
4826 {
4827 *p = c;
4828 buffer_off = (buffer + len) - p;
4829 mch_memmove(buffer, p, buffer_off);
4830 continue;
4831 }
4832 buffer_off = 0;
4833 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004834# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 {
4837 buffer[len] = NUL;
4838 msg_puts(buffer);
4839 }
4840
4841 windgoto(msg_row, msg_col);
4842 cursor_on();
4843 out_flush();
4844 if (got_int)
4845 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004846
4847# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4848 {
4849 struct timeval now_tv;
4850 long msec;
4851
4852 /* Avoid that we keep looping here without
4853 * checking for a CTRL-C for a long time. Don't
4854 * break out too often to avoid losing typeahead. */
4855 gettimeofday(&now_tv, NULL);
4856 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4857 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4858 if (msec > 2000)
4859 {
4860 noread_cnt = 5;
4861 break;
4862 }
4863 }
4864# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865 }
4866
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004867 /* If we already detected the child has finished break the
4868 * loop now. */
4869 if (wait_pid == pid)
4870 break;
4871
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 /*
4873 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004874 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004876# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004877 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004878# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004880# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4882 || (wait_pid == pid && WIFEXITED(status)))
4883 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004884 /* Don't break the loop yet, try reading more
4885 * characters from "fromshell_fd" first. When using
4886 * pipes there might still be something to read and
4887 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004890 else
4891 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004892
Bram Moolenaar95a51352013-03-21 22:53:50 +01004893# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004894 /* Handle any X events, e.g. serving the clipboard. */
4895 clip_update();
4896# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 }
4898finished:
4899 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004900 if (options & SHELL_READ)
4901 {
4902 if (ga.ga_len > 0)
4903 {
4904 append_ga_line(&ga);
4905 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004906 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004907 }
4908 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004909 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004910 ga_clear(&ga);
4911 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 /*
4914 * Give all typeahead that wasn't used back to ui_inchar().
4915 */
4916 if (ta_len)
4917 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 State = old_State;
4919 if (toshell_fd >= 0)
4920 close(toshell_fd);
4921 close(fromshell_fd);
4922 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004923# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004924 else
4925 {
4926 /*
4927 * Similar to the loop above, but only handle X events, no
4928 * I/O.
4929 */
4930 for (;;)
4931 {
4932 if (got_int)
4933 {
4934 /* CTRL-C sends a signal to the child, we ignore it
4935 * ourselves */
4936# ifdef HAVE_SETSID
4937 kill(-pid, SIGINT);
4938# else
4939 kill(0, SIGINT);
4940# endif
4941 got_int = FALSE;
4942 }
4943# ifdef __NeXT__
4944 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4945# else
4946 wait_pid = waitpid(pid, &status, WNOHANG);
4947# endif
4948 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4949 || (wait_pid == pid && WIFEXITED(status)))
4950 {
4951 wait_pid = pid;
4952 break;
4953 }
4954
4955 /* Handle any X events, e.g. serving the clipboard. */
4956 clip_update();
4957
4958 mch_delay(10L, TRUE);
4959 }
4960 }
4961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962
4963 /*
4964 * Wait until our child has exited.
4965 * Ignore wait() returning pids of other children and returning
4966 * because of some signal like SIGWINCH.
4967 * Don't wait if wait_pid was already set above, indicating the
4968 * child already exited.
4969 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004970 if (wait_pid != pid)
4971 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972
Bram Moolenaar624891f2010-10-13 16:22:09 +02004973# ifdef FEAT_GUI
4974 /* Close slave side of pty. Only do this after the child has
4975 * exited, otherwise the child may hang when it tries to write on
4976 * the pty. */
4977 if (pty_master_fd >= 0)
4978 close(pty_slave_fd);
4979# endif
4980
Bram Moolenaardf177f62005-02-22 08:39:57 +00004981 /* Make sure the child that writes to the external program is
4982 * dead. */
4983 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004984 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004985 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004986 wait4pid(wpid, NULL);
4987 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004988
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 /*
4990 * Set to raw mode right now, otherwise a CTRL-C after
4991 * catch_signals() will kill Vim.
4992 */
4993 if (tmode == TMODE_RAW)
4994 settmode(TMODE_RAW);
4995 did_settmode = TRUE;
4996 set_signals();
4997
4998 if (WIFEXITED(status))
4999 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005000 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005002 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003 {
5004 if (retval == EXEC_FAILED)
5005 {
5006 MSG_PUTS(_("\nCannot execute shell "));
5007 msg_outtrans(p_sh);
5008 msg_putchar('\n');
5009 }
5010 else if (!(options & SHELL_SILENT))
5011 {
5012 MSG_PUTS(_("\nshell returned "));
5013 msg_outnum((long)retval);
5014 msg_putchar('\n');
5015 }
5016 }
5017 }
5018 else
5019 MSG_PUTS(_("\nCommand terminated\n"));
5020 }
5021 }
5022 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005023 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024
5025error:
5026 if (!did_settmode)
5027 if (tmode == TMODE_RAW)
5028 settmode(TMODE_RAW); /* set to raw mode */
5029# ifdef FEAT_TITLE
5030 resettitle();
5031# endif
5032 vim_free(newcmd);
5033
5034 return retval;
5035
5036#endif /* USE_SYSTEM */
5037}
5038
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005039#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005040 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005041mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005042{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005043 pid_t pid;
5044 int fd_in[2]; /* for stdin */
5045 int fd_out[2]; /* for stdout */
5046 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005047 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005048 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5049 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5050 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005051 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005052 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5053 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005054 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005055
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005056 if (use_out_for_err && use_null_for_out)
5057 use_null_for_err = TRUE;
5058
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005059 /* default is to fail */
5060 job->jv_status = JOB_FAILED;
5061 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005062 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005063 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005064 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005065 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005066 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005067
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005068 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005069 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005070 if (use_file_for_in)
5071 {
5072 char_u *fname = options->jo_io_name[PART_IN];
5073
5074 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5075 if (fd_in[0] < 0)
5076 {
5077 EMSG2(_(e_notopen), fname);
5078 goto failed;
5079 }
5080 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005081 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005082 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005083
5084 if (use_file_for_out)
5085 {
5086 char_u *fname = options->jo_io_name[PART_OUT];
5087
5088 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5089 if (fd_out[1] < 0)
5090 {
5091 EMSG2(_(e_notopen), fname);
5092 goto failed;
5093 }
5094 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005095 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005096 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005097
5098 if (use_file_for_err)
5099 {
5100 char_u *fname = options->jo_io_name[PART_ERR];
5101
5102 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5103 if (fd_err[1] < 0)
5104 {
5105 EMSG2(_(e_notopen), fname);
5106 goto failed;
5107 }
5108 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005109 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005110 goto failed;
5111
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005112 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5113 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005114 if (options->jo_set & JO_CHANNEL)
5115 {
5116 channel = options->jo_channel;
5117 if (channel != NULL)
5118 ++channel->ch_refcount;
5119 }
5120 else
5121 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005122 if (channel == NULL)
5123 goto failed;
5124 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005125
5126 pid = fork(); /* maybe we should use vfork() */
5127 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005128 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005129 /* failed to fork */
5130 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005131 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005132
5133 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005134 {
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005135 int null_fd = -1;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005136
Bram Moolenaar835dc632016-02-07 14:27:38 +01005137 /* child */
5138 reset_signals(); /* handle signals normally */
5139
5140# ifdef HAVE_SETSID
5141 /* Create our own process group, so that the child and all its
5142 * children can be kill()ed. Don't do this when using pipes,
5143 * because stdin is not a tty, we would lose /dev/tty. */
5144 (void)setsid();
5145# endif
5146
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005147 set_child_environment();
5148
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005149 if (use_null_for_in || use_null_for_out || use_null_for_err)
5150 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5151
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005152 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005153 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005154 {
5155 close(0);
5156 ignored = dup(null_fd);
5157 }
5158 else
5159 {
5160 if (!use_file_for_in)
5161 close(fd_in[1]);
5162 close(0);
5163 ignored = dup(fd_in[0]);
5164 close(fd_in[0]);
5165 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005166
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005167 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005168 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005169 {
5170 close(2);
5171 ignored = dup(null_fd);
5172 }
5173 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005174 {
5175 close(2);
5176 ignored = dup(fd_out[1]);
5177 }
5178 else
5179 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005180 if (!use_file_for_err)
5181 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005182 close(2);
5183 ignored = dup(fd_err[1]);
5184 close(fd_err[1]);
5185 }
5186
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005187 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005188 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005189 {
5190 close(0);
5191 ignored = dup(null_fd);
5192 }
5193 else
5194 {
5195 if (!use_file_for_out)
5196 close(fd_out[0]);
5197 close(1);
5198 ignored = dup(fd_out[1]);
5199 close(fd_out[1]);
5200 }
5201 if (null_fd >= 0)
5202 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005203
Bram Moolenaar835dc632016-02-07 14:27:38 +01005204 /* See above for type of argv. */
5205 execvp(argv[0], argv);
5206
5207 perror("executing job failed");
5208 _exit(EXEC_FAILED); /* exec failed, return failure code */
5209 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005210
5211 /* parent */
5212 job->jv_pid = pid;
5213 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005214 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005215
5216 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005217 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005218 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005219 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005220 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005221 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005222 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005223 if (channel != NULL)
5224 {
5225 channel_set_pipes(channel,
5226 use_file_for_in || use_null_for_in
5227 ? INVALID_FD : fd_in[1],
5228 use_file_for_out || use_null_for_out
5229 ? INVALID_FD : fd_out[0],
5230 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005231 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005232 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005233 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005234
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005235 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005236 return;
5237
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005238failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005239 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005240 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005241 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005242 if (fd_in[1] >= 0)
5243 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005244 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005245 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005246 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005247 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005248 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005249 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005250 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005251 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005252}
5253
5254 char *
5255mch_job_status(job_T *job)
5256{
5257# ifdef HAVE_UNION_WAIT
5258 union wait status;
5259# else
5260 int status = -1;
5261# endif
5262 pid_t wait_pid = 0;
5263
5264# ifdef __NeXT__
5265 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5266# else
5267 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5268# endif
5269 if (wait_pid == -1)
5270 {
5271 /* process must have exited */
5272 job->jv_status = JOB_ENDED;
5273 return "dead";
5274 }
5275 if (wait_pid == 0)
5276 return "run";
5277 if (WIFEXITED(status))
5278 {
5279 /* LINTED avoid "bitwise operation on signed value" */
5280 job->jv_exitval = WEXITSTATUS(status);
5281 job->jv_status = JOB_ENDED;
5282 return "dead";
5283 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005284 if (WIFSIGNALED(status))
5285 {
5286 job->jv_exitval = -1;
5287 job->jv_status = JOB_ENDED;
5288 return "dead";
5289 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005290 return "run";
5291}
5292
5293 int
5294mch_stop_job(job_T *job, char_u *how)
5295{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005296 int sig = -1;
5297 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005298
Bram Moolenaar923d9262016-02-25 20:56:01 +01005299 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005300 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005301 else if (STRCMP(how, "hup") == 0)
5302 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005303 else if (STRCMP(how, "quit") == 0)
5304 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005305 else if (STRCMP(how, "int") == 0)
5306 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005307 else if (STRCMP(how, "kill") == 0)
5308 sig = SIGKILL;
5309 else if (isdigit(*how))
5310 sig = atoi((char *)how);
5311 else
5312 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005313
Bram Moolenaar72801402016-02-09 11:37:50 +01005314 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005315 job_pid = job->jv_pid;
5316 if (job_pid == getpgid(job_pid))
5317 job_pid = -job_pid;
5318
5319 kill(job_pid, sig);
5320
Bram Moolenaar835dc632016-02-07 14:27:38 +01005321 return OK;
5322}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005323
5324/*
5325 * Clear the data related to "job".
5326 */
5327 void
5328mch_clear_job(job_T *job)
5329{
5330 /* call waitpid because child process may become zombie */
5331# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005332 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005333# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005334 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005335# endif
5336}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005337#endif
5338
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339/*
5340 * Check for CTRL-C typed by reading all available characters.
5341 * In cooked mode we should get SIGINT, no need to check.
5342 */
5343 void
Bram Moolenaar05540972016-01-30 20:31:25 +01005344mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345{
5346 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
5347 fill_input_buf(FALSE);
5348}
5349
5350/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005351 * Wait "msec" msec until a character is available from the mouse, keyboard,
5352 * from inbuf[].
5353 * "msec" == -1 will block forever.
5354 * Invokes timer callbacks when needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355 * When a GUI is being used, this will never get called -- webb
5356 */
5357 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01005358WaitForChar(long msec)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005360#ifdef FEAT_TIMERS
5361 long due_time;
5362 long remaining = msec;
5363
5364 /* When waiting very briefly don't trigger timers. */
5365 if (msec >= 0 && msec < 10L)
5366 return WaitForCharOrMouse(msec);
5367
5368 while (msec < 0 || remaining > 0)
5369 {
5370 /* Trigger timers and then get the time in msec until the next one is
5371 * due. Wait up to that time. */
5372 due_time = check_due_timer();
5373 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5374 due_time = remaining;
5375 if (WaitForCharOrMouse(due_time))
5376 return TRUE;
5377 if (msec > 0)
5378 remaining -= due_time;
5379 }
5380 return FALSE;
5381#else
5382 return WaitForCharOrMouse(msec);
5383#endif
5384}
5385
5386/*
5387 * Wait "msec" msec until a character is available from the mouse or keyboard
5388 * or from inbuf[].
5389 * "msec" == -1 will block forever.
5390 * When a GUI is being used, this will never get called -- webb
5391 */
5392 static int
5393WaitForCharOrMouse(long msec)
5394{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005395#ifdef FEAT_MOUSE_GPM
5396 int gpm_process_wanted;
5397#endif
5398#ifdef FEAT_XCLIPBOARD
5399 int rest;
5400#endif
5401 int avail;
5402
5403 if (input_available()) /* something in inbuf[] */
5404 return 1;
5405
5406#if defined(FEAT_MOUSE_DEC)
5407 /* May need to query the mouse position. */
5408 if (WantQueryMouse)
5409 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005410 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5412 }
5413#endif
5414
5415 /*
5416 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5417 * events. This is a bit complicated, because they might both be defined.
5418 */
5419#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5420# ifdef FEAT_XCLIPBOARD
5421 rest = 0;
5422 if (do_xterm_trace())
5423 rest = msec;
5424# endif
5425 do
5426 {
5427# ifdef FEAT_XCLIPBOARD
5428 if (rest != 0)
5429 {
5430 msec = XT_TRACE_DELAY;
5431 if (rest >= 0 && rest < XT_TRACE_DELAY)
5432 msec = rest;
5433 if (rest >= 0)
5434 rest -= msec;
5435 }
5436# endif
5437# ifdef FEAT_MOUSE_GPM
5438 gpm_process_wanted = 0;
5439 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5440# else
5441 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5442# endif
5443 if (!avail)
5444 {
5445 if (input_available())
5446 return 1;
5447# ifdef FEAT_XCLIPBOARD
5448 if (rest == 0 || !do_xterm_trace())
5449# endif
5450 break;
5451 }
5452 }
5453 while (FALSE
5454# ifdef FEAT_MOUSE_GPM
5455 || (gpm_process_wanted && mch_gpm_process() == 0)
5456# endif
5457# ifdef FEAT_XCLIPBOARD
5458 || (!avail && rest != 0)
5459# endif
5460 );
5461
5462#else
5463 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5464#endif
5465 return avail;
5466}
5467
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005468#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469/*
5470 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005471 * "msec" == 0 will check for characters once.
5472 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005473 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005475 * Or when a clientserver message is on the queue.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477#if defined(__BEOS__)
5478 int
5479#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005480 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005481#endif
Bram Moolenaar05540972016-01-30 20:31:25 +01005482RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005483{
5484 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005485 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005486#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005487 static int busy = FALSE;
5488
5489 /* May retry getting characters after an event was handled. */
5490# define MAY_LOOP
5491
5492# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5493 /* Remember at what time we started, so that we know how much longer we
5494 * should wait after being interrupted. */
5495# define USE_START_TV
5496 struct timeval start_tv;
5497
5498 if (msec > 0 && (
5499# ifdef FEAT_XCLIPBOARD
5500 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005501# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 ||
5503# endif
5504# endif
5505# ifdef USE_XSMP
5506 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005507# ifdef FEAT_MZSCHEME
5508 ||
5509# endif
5510# endif
5511# ifdef FEAT_MZSCHEME
5512 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005513# endif
5514 ))
5515 gettimeofday(&start_tv, NULL);
5516# endif
5517
5518 /* Handle being called recursively. This may happen for the session
5519 * manager stuff, it may save the file, which does a breakcheck. */
5520 if (busy)
5521 return 0;
5522#endif
5523
5524#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005525 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526#endif
5527 {
5528#ifdef MAY_LOOP
5529 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005530# ifdef FEAT_MZSCHEME
5531 int mzquantum_used = FALSE;
5532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533#endif
5534#ifndef HAVE_SELECT
Bram Moolenaare0874f82016-01-24 20:36:41 +01005535 struct pollfd fds[6 + MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536 int nfd;
5537# ifdef FEAT_XCLIPBOARD
5538 int xterm_idx = -1;
5539# endif
5540# ifdef FEAT_MOUSE_GPM
5541 int gpm_idx = -1;
5542# endif
5543# ifdef USE_XSMP
5544 int xsmp_idx = -1;
5545# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005546 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005548# ifdef FEAT_MZSCHEME
5549 mzvim_check_threads();
5550 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5551 {
5552 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5553 mzquantum_used = TRUE;
5554 }
5555# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 fds[0].fd = fd;
5557 fds[0].events = POLLIN;
5558 nfd = 1;
5559
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005561 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 if (xterm_Shell != (Widget)0)
5563 {
5564 xterm_idx = nfd;
5565 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5566 fds[nfd].events = POLLIN;
5567 nfd++;
5568 }
5569# endif
5570# ifdef FEAT_MOUSE_GPM
5571 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5572 {
5573 gpm_idx = nfd;
5574 fds[nfd].fd = gpm_fd;
5575 fds[nfd].events = POLLIN;
5576 nfd++;
5577 }
5578# endif
5579# ifdef USE_XSMP
5580 if (xsmp_icefd != -1)
5581 {
5582 xsmp_idx = nfd;
5583 fds[nfd].fd = xsmp_icefd;
5584 fds[nfd].events = POLLIN;
5585 nfd++;
5586 }
5587# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005588#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005589 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005590#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005592 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005593
5594 result = ret > 0 && (fds[0].revents & POLLIN);
5595
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005596# ifdef FEAT_MZSCHEME
5597 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005598 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005599 finished = FALSE;
5600# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602# ifdef FEAT_XCLIPBOARD
5603 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5604 {
5605 xterm_update(); /* Maybe we should hand out clipboard */
5606 if (--ret == 0 && !input_available())
5607 /* Try again */
5608 finished = FALSE;
5609 }
5610# endif
5611# ifdef FEAT_MOUSE_GPM
5612 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5613 {
5614 *check_for_gpm = 1;
5615 }
5616# endif
5617# ifdef USE_XSMP
5618 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5619 {
5620 if (fds[xsmp_idx].revents & POLLIN)
5621 {
5622 busy = TRUE;
5623 xsmp_handle_requests();
5624 busy = FALSE;
5625 }
5626 else if (fds[xsmp_idx].revents & POLLHUP)
5627 {
5628 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005629 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630 xsmp_close();
5631 }
5632 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005633 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 }
5635# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005636#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005637 if (ret > 0)
5638 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005639#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640
5641
5642#else /* HAVE_SELECT */
5643
5644 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005645 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 fd_set rfds, efds;
5647 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005648 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005650# ifdef FEAT_MZSCHEME
5651 mzvim_check_threads();
5652 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5653 {
5654 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5655 mzquantum_used = TRUE;
5656 }
5657# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658# ifdef __EMX__
5659 /* don't check for incoming chars if not in raw mode, because select()
5660 * always returns TRUE then (in some version of emx.dll) */
5661 if (curr_tmode != TMODE_RAW)
5662 return 0;
5663# endif
5664
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005665 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005667 tv.tv_sec = towait / 1000;
5668 tv.tv_usec = (towait % 1000) * (1000000/1000);
5669 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005671 else
5672 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673
5674 /*
5675 * Select on ready for reading and exceptional condition (end of file).
5676 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005677select_eintr:
5678 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679 FD_ZERO(&efds);
5680 FD_SET(fd, &rfds);
5681# if !defined(__QNX__) && !defined(__CYGWIN32__)
5682 /* For QNX select() always returns 1 if this is set. Why? */
5683 FD_SET(fd, &efds);
5684# endif
5685 maxfd = fd;
5686
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005688 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 if (xterm_Shell != (Widget)0)
5690 {
5691 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5692 if (maxfd < ConnectionNumber(xterm_dpy))
5693 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005694
5695 /* An event may have already been read but not handled. In
5696 * particulary, XFlush may cause this. */
5697 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 }
5699# endif
5700# ifdef FEAT_MOUSE_GPM
5701 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5702 {
5703 FD_SET(gpm_fd, &rfds);
5704 FD_SET(gpm_fd, &efds);
5705 if (maxfd < gpm_fd)
5706 maxfd = gpm_fd;
5707 }
5708# endif
5709# ifdef USE_XSMP
5710 if (xsmp_icefd != -1)
5711 {
5712 FD_SET(xsmp_icefd, &rfds);
5713 FD_SET(xsmp_icefd, &efds);
5714 if (maxfd < xsmp_icefd)
5715 maxfd = xsmp_icefd;
5716 }
5717# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005718# ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005719 maxfd = channel_select_setup(maxfd, &rfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005720# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005722 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005723 result = ret > 0 && FD_ISSET(fd, &rfds);
5724 if (result)
5725 --ret;
5726
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005727# ifdef EINTR
5728 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005729 {
5730 /* Check whether window has been resized, EINTR may be caused by
5731 * SIGWINCH. */
5732 if (do_resize)
5733 handle_resize();
5734
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005735 /* Interrupted by a signal, need to try again. We ignore msec
5736 * here, because we do want to check even after a timeout if
5737 * characters are available. Needed for reading output of an
5738 * external command after the process has finished. */
5739 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005740 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005741# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005742# ifdef __TANDEM
5743 if (ret == -1 && errno == ENOTSUP)
5744 {
5745 FD_ZERO(&rfds);
5746 FD_ZERO(&efds);
5747 ret = 0;
5748 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005749# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005750# ifdef FEAT_MZSCHEME
5751 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005752 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005753 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754# endif
5755
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756# ifdef FEAT_XCLIPBOARD
5757 if (ret > 0 && xterm_Shell != (Widget)0
5758 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5759 {
5760 xterm_update(); /* Maybe we should hand out clipboard */
5761 /* continue looping when we only got the X event and the input
5762 * buffer is empty */
5763 if (--ret == 0 && !input_available())
5764 {
5765 /* Try again */
5766 finished = FALSE;
5767 }
5768 }
5769# endif
5770# ifdef FEAT_MOUSE_GPM
5771 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5772 {
5773 if (FD_ISSET(gpm_fd, &efds))
5774 gpm_close();
5775 else if (FD_ISSET(gpm_fd, &rfds))
5776 *check_for_gpm = 1;
5777 }
5778# endif
5779# ifdef USE_XSMP
5780 if (ret > 0 && xsmp_icefd != -1)
5781 {
5782 if (FD_ISSET(xsmp_icefd, &efds))
5783 {
5784 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005785 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 xsmp_close();
5787 if (--ret == 0)
5788 finished = FALSE; /* keep going if event was only one */
5789 }
5790 else if (FD_ISSET(xsmp_icefd, &rfds))
5791 {
5792 busy = TRUE;
5793 xsmp_handle_requests();
5794 busy = FALSE;
5795 if (--ret == 0)
5796 finished = FALSE; /* keep going if event was only one */
5797 }
5798 }
5799# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005800#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005801 if (ret > 0)
5802 ret = channel_select_check(ret, &rfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005803#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804
5805#endif /* HAVE_SELECT */
5806
5807#ifdef MAY_LOOP
5808 if (finished || msec == 0)
5809 break;
5810
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005811# ifdef FEAT_CLIENTSERVER
5812 if (server_waiting())
5813 break;
5814# endif
5815
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816 /* We're going to loop around again, find out for how long */
5817 if (msec > 0)
5818 {
5819# ifdef USE_START_TV
5820 struct timeval mtv;
5821
5822 /* Compute remaining wait time. */
5823 gettimeofday(&mtv, NULL);
5824 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5825 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5826# else
5827 /* Guess we got interrupted halfway. */
5828 msec = msec / 2;
5829# endif
5830 if (msec <= 0)
5831 break; /* waited long enough */
5832 }
5833#endif
5834 }
5835
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005836 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837}
5838
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005841 * Expand a path into all matching files and/or directories. Handles "*",
5842 * "?", "[a-z]", "**", etc.
5843 * "path" has backslashes before chars that are not to be expanded.
5844 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 */
5846 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005847mch_expandpath(
5848 garray_T *gap,
5849 char_u *path,
5850 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851{
Bram Moolenaar02743632005-07-25 20:42:36 +00005852 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853}
5854#endif
5855
5856/*
5857 * mch_expand_wildcards() - this code does wild-card pattern matching using
5858 * the shell
5859 *
5860 * return OK for success, FAIL for error (you may lose some memory) and put
5861 * an error message in *file.
5862 *
5863 * num_pat is number of input patterns
5864 * pat is array of pointers to input patterns
5865 * num_file is pointer to number of matched file names
5866 * file is pointer to array of pointers to matched file names
5867 */
5868
5869#ifndef SEEK_SET
5870# define SEEK_SET 0
5871#endif
5872#ifndef SEEK_END
5873# define SEEK_END 2
5874#endif
5875
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005876#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005877
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005879mch_expand_wildcards(
5880 int num_pat,
5881 char_u **pat,
5882 int *num_file,
5883 char_u ***file,
5884 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885{
5886 int i;
5887 size_t len;
5888 char_u *p;
5889 int dir;
5890#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005891 /*
5892 * This is the OS/2 implementation.
5893 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894# define EXPL_ALLOC_INC 16
5895 char_u **expl_files;
5896 size_t files_alloced, files_free;
5897 char_u *buf;
5898 int has_wildcard;
5899
5900 *num_file = 0; /* default: no files found */
5901 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5902 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5903 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5904 if (*file == NULL)
5905 return FAIL;
5906
5907 for (; num_pat > 0; num_pat--, pat++)
5908 {
5909 expl_files = NULL;
5910 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5911 /* expand environment var or home dir */
5912 buf = expand_env_save(*pat);
5913 else
5914 buf = vim_strsave(*pat);
5915 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005916 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 if (has_wildcard) /* yes, so expand them */
5918 expl_files = (char_u **)_fnexplode(buf);
5919
5920 /*
5921 * return value of buf if no wildcards left,
5922 * OR if no match AND EW_NOTFOUND is set.
5923 */
5924 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5925 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5926 { /* simply save the current contents of *buf */
5927 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5928 if (expl_files != NULL)
5929 {
5930 expl_files[0] = vim_strsave(buf);
5931 expl_files[1] = NULL;
5932 }
5933 }
5934 vim_free(buf);
5935
5936 /*
5937 * Count number of names resulting from expansion,
5938 * At the same time add a backslash to the end of names that happen to
5939 * be directories, and replace slashes with backslashes.
5940 */
5941 if (expl_files)
5942 {
5943 for (i = 0; (p = expl_files[i]) != NULL; i++)
5944 {
5945 dir = mch_isdir(p);
5946 /* If we don't want dirs and this is one, skip it */
5947 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5948 continue;
5949
Bram Moolenaara2031822006-03-07 22:29:51 +00005950 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01005951 if (!dir && (flags & EW_EXEC)
5952 && !mch_can_exe(p, NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00005953 continue;
5954
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 if (--files_free == 0)
5956 {
5957 /* need more room in table of pointers */
5958 files_alloced += EXPL_ALLOC_INC;
5959 *file = (char_u **)vim_realloc(*file,
5960 sizeof(char_u **) * files_alloced);
5961 if (*file == NULL)
5962 {
5963 EMSG(_(e_outofmem));
5964 *num_file = 0;
5965 return FAIL;
5966 }
5967 files_free = EXPL_ALLOC_INC;
5968 }
5969 slash_adjust(p);
5970 if (dir)
5971 {
5972 /* For a directory we add a '/', unless it's already
5973 * there. */
5974 len = STRLEN(p);
5975 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5976 {
5977 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005978 if (!after_pathsep((*file)[*num_file],
5979 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980 {
5981 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005982 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983 }
5984 }
5985 }
5986 else
5987 {
5988 (*file)[*num_file] = vim_strsave(p);
5989 }
5990
5991 /*
5992 * Error message already given by either alloc or vim_strsave.
5993 * Should return FAIL, but returning OK works also.
5994 */
5995 if ((*file)[*num_file] == NULL)
5996 break;
5997 (*num_file)++;
5998 }
5999 _fnexplodefree((char **)expl_files);
6000 }
6001 }
6002 return OK;
6003
6004#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006005 /*
6006 * This is the non-OS/2 implementation (really Unix).
6007 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 int j;
6009 char_u *tempname;
6010 char_u *command;
6011 FILE *fd;
6012 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006013#define STYLE_ECHO 0 /* use "echo", the default */
6014#define STYLE_GLOB 1 /* use "glob", for csh */
6015#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6016#define STYLE_PRINT 3 /* use "print -N", for zsh */
6017#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6018 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019 int shell_style = STYLE_ECHO;
6020 int check_spaces;
6021 static int did_find_nul = FALSE;
6022 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006023 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006024 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025
6026 *num_file = 0; /* default: no files found */
6027 *file = NULL;
6028
6029 /*
6030 * If there are no wildcards, just copy the names to allocated memory.
6031 * Saves a lot of time, because we don't have to start a new shell.
6032 */
6033 if (!have_wildcard(num_pat, pat))
6034 return save_patterns(num_pat, pat, num_file, file);
6035
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006036# ifdef HAVE_SANDBOX
6037 /* Don't allow any shell command in the sandbox. */
6038 if (sandbox != 0 && check_secure())
6039 return FAIL;
6040# endif
6041
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 /*
6043 * Don't allow the use of backticks in secure and restricted mode.
6044 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006045 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 for (i = 0; i < num_pat; ++i)
6047 if (vim_strchr(pat[i], '`') != NULL
6048 && (check_restricted() || check_secure()))
6049 return FAIL;
6050
6051 /*
6052 * get a name for the temp file
6053 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006054 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 {
6056 EMSG(_(e_notmp));
6057 return FAIL;
6058 }
6059
6060 /*
6061 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006062 * file.
6063 * STYLE_BT: NL separated
6064 * If expanding `cmd` execute it directly.
6065 * STYLE_GLOB: NUL separated
6066 * If we use *csh, "glob" will work better than "echo".
6067 * STYLE_PRINT: NL or NUL separated
6068 * If we use *zsh, "print -N" will work better than "glob".
6069 * STYLE_VIMGLOB: NL separated
6070 * If we use *sh*, we define "vimglob()".
6071 * STYLE_ECHO: space separated.
6072 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 */
6074 if (num_pat == 1 && *pat[0] == '`'
6075 && (len = STRLEN(pat[0])) > 2
6076 && *(pat[0] + len - 1) == '`')
6077 shell_style = STYLE_BT;
6078 else if ((len = STRLEN(p_sh)) >= 3)
6079 {
6080 if (STRCMP(p_sh + len - 3, "csh") == 0)
6081 shell_style = STYLE_GLOB;
6082 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6083 shell_style = STYLE_PRINT;
6084 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006085 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6086 "sh") != NULL)
6087 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088
Bram Moolenaarc7247912008-01-13 12:54:11 +00006089 /* Compute the length of the command. We need 2 extra bytes: for the
6090 * optional '&' and for the NUL.
6091 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006093 if (shell_style == STYLE_VIMGLOB)
6094 len += STRLEN(sh_vimglob_func);
6095
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006096 for (i = 0; i < num_pat; ++i)
6097 {
6098 /* Count the length of the patterns in the same way as they are put in
6099 * "command" below. */
6100#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006102#else
6103 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006104 for (j = 0; pat[i][j] != NUL; ++j)
6105 {
6106 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6107 ++len; /* may add a backslash */
6108 ++len;
6109 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006110#endif
6111 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 command = alloc(len);
6113 if (command == NULL)
6114 {
6115 /* out of memory */
6116 vim_free(tempname);
6117 return FAIL;
6118 }
6119
6120 /*
6121 * Build the shell command:
6122 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6123 * recognizes this).
6124 * - Add the shell command to print the expanded names.
6125 * - Add the temp file name.
6126 * - Add the file name patterns.
6127 */
6128 if (shell_style == STYLE_BT)
6129 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006130 /* change `command; command& ` to (command; command ) */
6131 STRCPY(command, "(");
6132 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006134 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 while (p > command && vim_iswhite(*p))
6136 --p;
6137 if (*p == '&') /* remove trailing '&' */
6138 {
6139 ampersent = TRUE;
6140 *p = ' ';
6141 }
6142 STRCAT(command, ">");
6143 }
6144 else
6145 {
6146 if (flags & EW_NOTFOUND)
6147 STRCPY(command, "set nonomatch; ");
6148 else
6149 STRCPY(command, "unset nonomatch; ");
6150 if (shell_style == STYLE_GLOB)
6151 STRCAT(command, "glob >");
6152 else if (shell_style == STYLE_PRINT)
6153 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006154 else if (shell_style == STYLE_VIMGLOB)
6155 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 else
6157 STRCAT(command, "echo >");
6158 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006159
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006161
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 if (shell_style != STYLE_BT)
6163 for (i = 0; i < num_pat; ++i)
6164 {
6165 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006166 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006167 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168#ifdef USE_SYSTEM
6169 STRCAT(command, " \"");
6170 STRCAT(command, pat[i]);
6171 STRCAT(command, "\"");
6172#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006173 int intick = FALSE;
6174
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 p = command + STRLEN(command);
6176 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006177 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006178 {
6179 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006180 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006181 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6182 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006183 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006184 * backslash inside backticks, before a special character
6185 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006186 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006187 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6188 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006189 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006190 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006191 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006192 else if (!intick
6193 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6194 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006195 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006196 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6197 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006198 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006199
6200 /* Copy one character. */
6201 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 *p = NUL;
6204#endif
6205 }
6206 if (flags & EW_SILENT)
6207 show_shell_mess = FALSE;
6208 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006209 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210
6211 /*
6212 * Using zsh -G: If a pattern has no matches, it is just deleted from
6213 * the argument list, otherwise zsh gives an error message and doesn't
6214 * expand any other pattern.
6215 */
6216 if (shell_style == STYLE_PRINT)
6217 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6218
6219 /*
6220 * If we use -f then shell variables set in .cshrc won't get expanded.
6221 * vi can do it, so we will too, but it is only necessary if there is a "$"
6222 * in one of the patterns, otherwise we can still use the fast option.
6223 */
6224 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6225 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6226
6227 /*
6228 * execute the shell command
6229 */
6230 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6231
6232 /* When running in the background, give it some time to create the temp
6233 * file, but don't wait for it to finish. */
6234 if (ampersent)
6235 mch_delay(10L, TRUE);
6236
6237 extra_shell_arg = NULL; /* cleanup */
6238 show_shell_mess = TRUE;
6239 vim_free(command);
6240
Bram Moolenaarc7247912008-01-13 12:54:11 +00006241 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 {
6243 mch_remove(tempname);
6244 vim_free(tempname);
6245 /*
6246 * With interactive completion, the error message is not printed.
6247 * However with USE_SYSTEM, I don't know how to turn off error messages
6248 * from the shell, so screen may still get messed up -- webb.
6249 */
6250#ifndef USE_SYSTEM
6251 if (!(flags & EW_SILENT))
6252#endif
6253 {
6254 redraw_later_clear(); /* probably messed up screen */
6255 msg_putchar('\n'); /* clear bottom line quickly */
6256 cmdline_row = Rows - 1; /* continue on last line */
6257#ifdef USE_SYSTEM
6258 if (!(flags & EW_SILENT))
6259#endif
6260 {
6261 MSG(_(e_wildexpand));
6262 msg_start(); /* don't overwrite this message */
6263 }
6264 }
6265 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6266 * EW_NOTFOUND is given */
6267 if (shell_style == STYLE_BT)
6268 return FAIL;
6269 goto notfound;
6270 }
6271
6272 /*
6273 * read the names from the file into memory
6274 */
6275 fd = fopen((char *)tempname, READBIN);
6276 if (fd == NULL)
6277 {
6278 /* Something went wrong, perhaps a file name with a special char. */
6279 if (!(flags & EW_SILENT))
6280 {
6281 MSG(_(e_wildexpand));
6282 msg_start(); /* don't overwrite this message */
6283 }
6284 vim_free(tempname);
6285 goto notfound;
6286 }
6287 fseek(fd, 0L, SEEK_END);
6288 len = ftell(fd); /* get size of temp file */
6289 fseek(fd, 0L, SEEK_SET);
6290 buffer = alloc(len + 1);
6291 if (buffer == NULL)
6292 {
6293 /* out of memory */
6294 mch_remove(tempname);
6295 vim_free(tempname);
6296 fclose(fd);
6297 return FAIL;
6298 }
6299 i = fread((char *)buffer, 1, len, fd);
6300 fclose(fd);
6301 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006302 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 {
6304 /* unexpected read error */
6305 EMSG2(_(e_notread), tempname);
6306 vim_free(tempname);
6307 vim_free(buffer);
6308 return FAIL;
6309 }
6310 vim_free(tempname);
6311
Bram Moolenaarc7247912008-01-13 12:54:11 +00006312# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6314 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006315 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6317 *p++ = buffer[i];
6318 len = p - buffer;
6319# endif
6320
6321
6322 /* file names are separated with Space */
6323 if (shell_style == STYLE_ECHO)
6324 {
6325 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6326 p = buffer;
6327 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6328 {
6329 while (*p != ' ' && *p != '\n')
6330 ++p;
6331 p = skipwhite(p); /* skip to next entry */
6332 }
6333 }
6334 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006335 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 {
6337 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6338 p = buffer;
6339 for (i = 0; *p != NUL; ++i) /* count number of entries */
6340 {
6341 while (*p != '\n' && *p != NUL)
6342 ++p;
6343 if (*p != NUL)
6344 ++p;
6345 p = skipwhite(p); /* skip leading white space */
6346 }
6347 }
6348 /* file names are separated with NUL */
6349 else
6350 {
6351 /*
6352 * Some versions of zsh use spaces instead of NULs to separate
6353 * results. Only do this when there is no NUL before the end of the
6354 * buffer, otherwise we would never be able to use file names with
6355 * embedded spaces when zsh does use NULs.
6356 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6357 * don't check for spaces again.
6358 */
6359 check_spaces = FALSE;
6360 if (shell_style == STYLE_PRINT && !did_find_nul)
6361 {
6362 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006363 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006364 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 did_find_nul = TRUE;
6366 else
6367 check_spaces = TRUE;
6368 }
6369
6370 /*
6371 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6372 * already is one, for STYLE_GLOB it needs to be added.
6373 */
6374 if (len && buffer[len - 1] == NUL)
6375 --len;
6376 else
6377 buffer[len] = NUL;
6378 i = 0;
6379 for (p = buffer; p < buffer + len; ++p)
6380 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6381 {
6382 ++i;
6383 *p = NUL;
6384 }
6385 if (len)
6386 ++i; /* count last entry */
6387 }
6388 if (i == 0)
6389 {
6390 /*
6391 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6392 * /bin/sh will happily expand it to nothing rather than returning an
6393 * error; and hey, it's good to check anyway -- webb.
6394 */
6395 vim_free(buffer);
6396 goto notfound;
6397 }
6398 *num_file = i;
6399 *file = (char_u **)alloc(sizeof(char_u *) * i);
6400 if (*file == NULL)
6401 {
6402 /* out of memory */
6403 vim_free(buffer);
6404 return FAIL;
6405 }
6406
6407 /*
6408 * Isolate the individual file names.
6409 */
6410 p = buffer;
6411 for (i = 0; i < *num_file; ++i)
6412 {
6413 (*file)[i] = p;
6414 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006415 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6416 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006418 while (!(shell_style == STYLE_ECHO && *p == ' ')
6419 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006420 ++p;
6421 if (p == buffer + len) /* last entry */
6422 *p = NUL;
6423 else
6424 {
6425 *p++ = NUL;
6426 p = skipwhite(p); /* skip to next entry */
6427 }
6428 }
6429 else /* NUL separates */
6430 {
6431 while (*p && p < buffer + len) /* skip entry */
6432 ++p;
6433 ++p; /* skip NUL */
6434 }
6435 }
6436
6437 /*
6438 * Move the file names to allocated memory.
6439 */
6440 for (j = 0, i = 0; i < *num_file; ++i)
6441 {
6442 /* Require the files to exist. Helps when using /bin/sh */
6443 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6444 continue;
6445
6446 /* check if this entry should be included */
6447 dir = (mch_isdir((*file)[i]));
6448 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6449 continue;
6450
Bram Moolenaara2031822006-03-07 22:29:51 +00006451 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006452 if (!dir && (flags & EW_EXEC)
6453 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006454 continue;
6455
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6457 if (p)
6458 {
6459 STRCPY(p, (*file)[i]);
6460 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006461 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 (*file)[j++] = p;
6463 }
6464 }
6465 vim_free(buffer);
6466 *num_file = j;
6467
6468 if (*num_file == 0) /* rejected all entries */
6469 {
6470 vim_free(*file);
6471 *file = NULL;
6472 goto notfound;
6473 }
6474
6475 return OK;
6476
6477notfound:
6478 if (flags & EW_NOTFOUND)
6479 return save_patterns(num_pat, pat, num_file, file);
6480 return FAIL;
6481
6482#endif /* __EMX__ */
6483}
6484
6485#endif /* VMS */
6486
6487#ifndef __EMX__
6488 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006489save_patterns(
6490 int num_pat,
6491 char_u **pat,
6492 int *num_file,
6493 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494{
6495 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006496 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497
6498 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6499 if (*file == NULL)
6500 return FAIL;
6501 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006502 {
6503 s = vim_strsave(pat[i]);
6504 if (s != NULL)
6505 /* Be compatible with expand_filename(): halve the number of
6506 * backslashes. */
6507 backslash_halve(s);
6508 (*file)[i] = s;
6509 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 *num_file = num_pat;
6511 return OK;
6512}
6513#endif
6514
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515/*
6516 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6517 * expand.
6518 */
6519 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006520mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006522 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 if (*p == '\\' && p[1] != NUL)
6525 ++p;
6526 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 if (vim_strchr((char_u *)
6528#ifdef VMS
6529 "*?%"
6530#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532#endif
6533 , *p) != NULL)
6534 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 }
6536 return FALSE;
6537}
6538
6539/*
6540 * Return TRUE if the string "p" contains a wildcard.
6541 * Don't recognize '~' at the end as a wildcard.
6542 */
6543 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006544mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006546 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 if (*p == '\\' && p[1] != NUL)
6549 ++p;
6550 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 if (vim_strchr((char_u *)
6552#ifdef VMS
6553 "*?%$"
6554#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556#endif
6557 , *p) != NULL
6558 || (*p == '~' && p[1] != NUL))
6559 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 }
6561 return FALSE;
6562}
6563
6564#ifndef __EMX__
6565 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006566have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567{
6568 int i;
6569
6570 for (i = 0; i < num; i++)
6571 if (mch_has_wildcard(file[i]))
6572 return 1;
6573 return 0;
6574}
6575
6576 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006577have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578{
6579 int i;
6580
6581 for (i = 0; i < num; i++)
6582 if (vim_strchr(file[i], '$') != NULL)
6583 return TRUE;
6584 return FALSE;
6585}
6586#endif /* ifndef __EMX__ */
6587
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006588#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589/*
6590 * Scaled-down version of rename(), which is missing in Xenix.
6591 * This version can only move regular files and will fail if the
6592 * destination exists.
6593 */
6594 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006595mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596{
6597 struct stat st;
6598
6599 if (stat(dest, &st) >= 0) /* fail if destination exists */
6600 return -1;
6601 if (link(src, dest) != 0) /* link file to new name */
6602 return -1;
6603 if (mch_remove(src) == 0) /* delete link to old name */
6604 return 0;
6605 return -1;
6606}
6607#endif /* !HAVE_RENAME */
6608
6609#ifdef FEAT_MOUSE_GPM
6610/*
6611 * Initializes connection with gpm (if it isn't already opened)
6612 * Return 1 if succeeded (or connection already opened), 0 if failed
6613 */
6614 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006615gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616{
6617 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6618
6619 if (!gpm_flag)
6620 {
6621 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6622 gpm_connect.defaultMask = ~GPM_HARD;
6623 /* Default handling for mouse move*/
6624 gpm_connect.minMod = 0; /* Handle any modifier keys */
6625 gpm_connect.maxMod = 0xffff;
6626 if (Gpm_Open(&gpm_connect, 0) > 0)
6627 {
6628 /* gpm library tries to handling TSTP causes
6629 * problems. Anyways, we close connection to Gpm whenever
6630 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006631 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006633# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006635# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 return 1; /* succeed */
6637 }
6638 if (gpm_fd == -2)
6639 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6640 return 0;
6641 }
6642 return 1; /* already open */
6643}
6644
6645/*
6646 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 */
6648 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006649gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650{
6651 if (gpm_flag && gpm_fd >= 0) /* if Open */
6652 Gpm_Close();
6653}
6654
6655/* Reads gpm event and adds special keys to input buf. Returns length of
6656 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006657 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 */
6659 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006660mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661{
6662 int button;
6663 static Gpm_Event gpm_event;
6664 char_u string[6];
6665 int_u vim_modifiers;
6666 int row,col;
6667 unsigned char buttons_mask;
6668 unsigned char gpm_modifiers;
6669 static unsigned char old_buttons = 0;
6670
6671 Gpm_GetEvent(&gpm_event);
6672
6673#ifdef FEAT_GUI
6674 /* Don't put events in the input queue now. */
6675 if (hold_gui_events)
6676 return 0;
6677#endif
6678
6679 row = gpm_event.y - 1;
6680 col = gpm_event.x - 1;
6681
6682 string[0] = ESC; /* Our termcode */
6683 string[1] = 'M';
6684 string[2] = 'G';
6685 switch (GPM_BARE_EVENTS(gpm_event.type))
6686 {
6687 case GPM_DRAG:
6688 string[3] = MOUSE_DRAG;
6689 break;
6690 case GPM_DOWN:
6691 buttons_mask = gpm_event.buttons & ~old_buttons;
6692 old_buttons = gpm_event.buttons;
6693 switch (buttons_mask)
6694 {
6695 case GPM_B_LEFT:
6696 button = MOUSE_LEFT;
6697 break;
6698 case GPM_B_MIDDLE:
6699 button = MOUSE_MIDDLE;
6700 break;
6701 case GPM_B_RIGHT:
6702 button = MOUSE_RIGHT;
6703 break;
6704 default:
6705 return 0;
6706 /*Don't know what to do. Can more than one button be
6707 * reported in one event? */
6708 }
6709 string[3] = (char_u)(button | 0x20);
6710 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6711 break;
6712 case GPM_UP:
6713 string[3] = MOUSE_RELEASE;
6714 old_buttons &= ~gpm_event.buttons;
6715 break;
6716 default:
6717 return 0;
6718 }
6719 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6720 gpm_modifiers = gpm_event.modifiers;
6721 vim_modifiers = 0x0;
6722 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6723 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6724 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6725 */
6726 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6727 vim_modifiers |= MOUSE_SHIFT;
6728
6729 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6730 vim_modifiers |= MOUSE_CTRL;
6731 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6732 vim_modifiers |= MOUSE_ALT;
6733 string[3] |= vim_modifiers;
6734 string[4] = (char_u)(col + ' ' + 1);
6735 string[5] = (char_u)(row + ' ' + 1);
6736 add_to_input_buf(string, 6);
6737 return 6;
6738}
6739#endif /* FEAT_MOUSE_GPM */
6740
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006741#ifdef FEAT_SYSMOUSE
6742/*
6743 * Initialize connection with sysmouse.
6744 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6745 * output, any sysmouse output than will be processed via sig_sysmouse().
6746 * Return OK if succeeded, FAIL if failed.
6747 */
6748 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006749sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006750{
6751 struct mouse_info mouse;
6752
6753 mouse.operation = MOUSE_MODE;
6754 mouse.u.mode.mode = 0;
6755 mouse.u.mode.signal = SIGUSR2;
6756 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6757 {
6758 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6759 mouse.operation = MOUSE_SHOW;
6760 ioctl(1, CONS_MOUSECTL, &mouse);
6761 return OK;
6762 }
6763 return FAIL;
6764}
6765
6766/*
6767 * Stop processing SIGUSR2 signals, and also make sure that
6768 * virtual console do not send us any sysmouse related signal.
6769 */
6770 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006771sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006772{
6773 struct mouse_info mouse;
6774
6775 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6776 mouse.operation = MOUSE_MODE;
6777 mouse.u.mode.mode = 0;
6778 mouse.u.mode.signal = 0;
6779 ioctl(1, CONS_MOUSECTL, &mouse);
6780}
6781
6782/*
6783 * Gets info from sysmouse and adds special keys to input buf.
6784 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006785 static RETSIGTYPE
6786sig_sysmouse SIGDEFARG(sigarg)
6787{
6788 struct mouse_info mouse;
6789 struct video_info video;
6790 char_u string[6];
6791 int row, col;
6792 int button;
6793 int buttons;
6794 static int oldbuttons = 0;
6795
6796#ifdef FEAT_GUI
6797 /* Don't put events in the input queue now. */
6798 if (hold_gui_events)
6799 return;
6800#endif
6801
6802 mouse.operation = MOUSE_GETINFO;
6803 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6804 && ioctl(1, FBIO_MODEINFO, &video) != -1
6805 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6806 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6807 {
6808 row = mouse.u.data.y / video.vi_cheight;
6809 col = mouse.u.data.x / video.vi_cwidth;
6810 buttons = mouse.u.data.buttons;
6811 string[0] = ESC; /* Our termcode */
6812 string[1] = 'M';
6813 string[2] = 'S';
6814 if (oldbuttons == buttons && buttons != 0)
6815 {
6816 button = MOUSE_DRAG;
6817 }
6818 else
6819 {
6820 switch (buttons)
6821 {
6822 case 0:
6823 button = MOUSE_RELEASE;
6824 break;
6825 case 1:
6826 button = MOUSE_LEFT;
6827 break;
6828 case 2:
6829 button = MOUSE_MIDDLE;
6830 break;
6831 case 4:
6832 button = MOUSE_RIGHT;
6833 break;
6834 default:
6835 return;
6836 }
6837 oldbuttons = buttons;
6838 }
6839 string[3] = (char_u)(button);
6840 string[4] = (char_u)(col + ' ' + 1);
6841 string[5] = (char_u)(row + ' ' + 1);
6842 add_to_input_buf(string, 6);
6843 }
6844 return;
6845}
6846#endif /* FEAT_SYSMOUSE */
6847
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006849typedef char_u * (*STRPROCSTR)(char_u *);
6850typedef char_u * (*INTPROCSTR)(int);
6851typedef int (*STRPROCINT)(char_u *);
6852typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853
6854/*
6855 * Call a DLL routine which takes either a string or int param
6856 * and returns an allocated string.
6857 */
6858 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006859mch_libcall(
6860 char_u *libname,
6861 char_u *funcname,
6862 char_u *argstring, /* NULL when using a argint */
6863 int argint,
6864 char_u **string_result,/* NULL when using number_result */
6865 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866{
6867# if defined(USE_DLOPEN)
6868 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006869 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870# else
6871 shl_t hinstLib;
6872# endif
6873 STRPROCSTR ProcAdd;
6874 INTPROCSTR ProcAddI;
6875 char_u *retval_str = NULL;
6876 int retval_int = 0;
6877 int success = FALSE;
6878
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006879 /*
6880 * Get a handle to the DLL module.
6881 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006883 /* First clear any error, it's not cleared by the dlopen() call. */
6884 (void)dlerror();
6885
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 hinstLib = dlopen((char *)libname, RTLD_LAZY
6887# ifdef RTLD_LOCAL
6888 | RTLD_LOCAL
6889# endif
6890 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006891 if (hinstLib == NULL)
6892 {
6893 /* "dlerr" must be used before dlclose() */
6894 dlerr = (char *)dlerror();
6895 if (dlerr != NULL)
6896 EMSG2(_("dlerror = \"%s\""), dlerr);
6897 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898# else
6899 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6900# endif
6901
6902 /* If the handle is valid, try to get the function address. */
6903 if (hinstLib != NULL)
6904 {
6905# ifdef HAVE_SETJMP_H
6906 /*
6907 * Catch a crash when calling the library function. For example when
6908 * using a number where a string pointer is expected.
6909 */
6910 mch_startjmp();
6911 if (SETJMP(lc_jump_env) != 0)
6912 {
6913 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006914# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006915 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 mch_didjmp();
6918 }
6919 else
6920# endif
6921 {
6922 retval_str = NULL;
6923 retval_int = 0;
6924
6925 if (argstring != NULL)
6926 {
6927# if defined(USE_DLOPEN)
6928 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006929 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930# else
6931 if (shl_findsym(&hinstLib, (const char *)funcname,
6932 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6933 ProcAdd = NULL;
6934# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006935 if ((success = (ProcAdd != NULL
6936# if defined(USE_DLOPEN)
6937 && dlerr == NULL
6938# endif
6939 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 {
6941 if (string_result == NULL)
6942 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6943 else
6944 retval_str = (ProcAdd)(argstring);
6945 }
6946 }
6947 else
6948 {
6949# if defined(USE_DLOPEN)
6950 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006951 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952# else
6953 if (shl_findsym(&hinstLib, (const char *)funcname,
6954 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6955 ProcAddI = NULL;
6956# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006957 if ((success = (ProcAddI != NULL
6958# if defined(USE_DLOPEN)
6959 && dlerr == NULL
6960# endif
6961 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 {
6963 if (string_result == NULL)
6964 retval_int = ((INTPROCINT)ProcAddI)(argint);
6965 else
6966 retval_str = (ProcAddI)(argint);
6967 }
6968 }
6969
6970 /* Save the string before we free the library. */
6971 /* Assume that a "1" or "-1" result is an illegal pointer. */
6972 if (string_result == NULL)
6973 *number_result = retval_int;
6974 else if (retval_str != NULL
6975 && retval_str != (char_u *)1
6976 && retval_str != (char_u *)-1)
6977 *string_result = vim_strsave(retval_str);
6978 }
6979
6980# ifdef HAVE_SETJMP_H
6981 mch_endjmp();
6982# ifdef SIGHASARG
6983 if (lc_signal != 0)
6984 {
6985 int i;
6986
6987 /* try to find the name of this signal */
6988 for (i = 0; signal_info[i].sig != -1; i++)
6989 if (lc_signal == signal_info[i].sig)
6990 break;
6991 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6992 }
6993# endif
6994# endif
6995
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006997 /* "dlerr" must be used before dlclose() */
6998 if (dlerr != NULL)
6999 EMSG2(_("dlerror = \"%s\""), dlerr);
7000
7001 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 (void)dlclose(hinstLib);
7003# else
7004 (void)shl_unload(hinstLib);
7005# endif
7006 }
7007
7008 if (!success)
7009 {
7010 EMSG2(_(e_libcall), funcname);
7011 return FAIL;
7012 }
7013
7014 return OK;
7015}
7016#endif
7017
7018#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7019static int xterm_trace = -1; /* default: disabled */
7020static int xterm_button;
7021
7022/*
7023 * Setup a dummy window for X selections in a terminal.
7024 */
7025 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007026setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027{
7028 int z = 0;
7029 char *strp = "";
7030 Widget AppShell;
7031
7032 if (!x_connect_to_server())
7033 return;
7034
7035 open_app_context();
7036 if (app_context != NULL && xterm_Shell == (Widget)0)
7037 {
7038 int (*oldhandler)();
7039#if defined(HAVE_SETJMP_H)
7040 int (*oldIOhandler)();
7041#endif
7042# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7043 struct timeval start_tv;
7044
7045 if (p_verbose > 0)
7046 gettimeofday(&start_tv, NULL);
7047# endif
7048
7049 /* Ignore X errors while opening the display */
7050 oldhandler = XSetErrorHandler(x_error_check);
7051
7052#if defined(HAVE_SETJMP_H)
7053 /* Ignore X IO errors while opening the display */
7054 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7055 mch_startjmp();
7056 if (SETJMP(lc_jump_env) != 0)
7057 {
7058 mch_didjmp();
7059 xterm_dpy = NULL;
7060 }
7061 else
7062#endif
7063 {
7064 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7065 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7066#if defined(HAVE_SETJMP_H)
7067 mch_endjmp();
7068#endif
7069 }
7070
7071#if defined(HAVE_SETJMP_H)
7072 /* Now handle X IO errors normally. */
7073 (void)XSetIOErrorHandler(oldIOhandler);
7074#endif
7075 /* Now handle X errors normally. */
7076 (void)XSetErrorHandler(oldhandler);
7077
7078 if (xterm_dpy == NULL)
7079 {
7080 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007081 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 return;
7083 }
7084
7085 /* Catch terminating error of the X server connection. */
7086 (void)XSetIOErrorHandler(x_IOerror_handler);
7087
7088# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7089 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007090 {
7091 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007093 verbose_leave();
7094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095# endif
7096
7097 /* Create a Shell to make converters work. */
7098 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7099 applicationShellWidgetClass, xterm_dpy,
7100 NULL);
7101 if (AppShell == (Widget)0)
7102 return;
7103 xterm_Shell = XtVaCreatePopupShell("VIM",
7104 topLevelShellWidgetClass, AppShell,
7105 XtNmappedWhenManaged, 0,
7106 XtNwidth, 1,
7107 XtNheight, 1,
7108 NULL);
7109 if (xterm_Shell == (Widget)0)
7110 return;
7111
7112 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007113 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 if (x11_display == NULL)
7115 x11_display = xterm_dpy;
7116
7117 XtRealizeWidget(xterm_Shell);
7118 XSync(xterm_dpy, False);
7119 xterm_update();
7120 }
7121 if (xterm_Shell != (Widget)0)
7122 {
7123 clip_init(TRUE);
7124 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7125 x11_window = (Window)atol(strp);
7126 /* Check if $WINDOWID is valid. */
7127 if (test_x11_window(xterm_dpy) == FAIL)
7128 x11_window = 0;
7129 if (x11_window != 0)
7130 xterm_trace = 0;
7131 }
7132}
7133
7134 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007135start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136{
7137 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7138 return;
7139 xterm_trace = 1;
7140 xterm_button = button;
7141 do_xterm_trace();
7142}
7143
7144
7145 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007146stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147{
7148 if (xterm_trace < 0)
7149 return;
7150 xterm_trace = 0;
7151}
7152
7153/*
7154 * Query the xterm pointer and generate mouse termcodes if necessary
7155 * return TRUE if dragging is active, else FALSE
7156 */
7157 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007158do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007159{
7160 Window root, child;
7161 int root_x, root_y;
7162 int win_x, win_y;
7163 int row, col;
7164 int_u mask_return;
7165 char_u buf[50];
7166 char_u *strp;
7167 long got_hints;
7168 static char_u *mouse_code;
7169 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7170 static int prev_row = 0, prev_col = 0;
7171 static XSizeHints xterm_hints;
7172
7173 if (xterm_trace <= 0)
7174 return FALSE;
7175
7176 if (xterm_trace == 1)
7177 {
7178 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007179 * have changed recently. */
7180 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7181 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 || xterm_hints.width_inc <= 1
7183 || xterm_hints.height_inc <= 1)
7184 {
7185 xterm_trace = -1; /* Not enough data -- disable tracing */
7186 return FALSE;
7187 }
7188
7189 /* Rely on the same mouse code for the duration of this */
7190 mouse_code = find_termcode(mouse_name);
7191 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007192 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193 xterm_trace = 2;
7194
7195 /* Find the offset of the chars, there might be a scrollbar on the
7196 * left of the window and/or a menu on the top (eterm etc.) */
7197 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7198 &win_x, &win_y, &mask_return);
7199 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7200 - (xterm_hints.height_inc / 2);
7201 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7202 xterm_hints.y = 2;
7203 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7204 - (xterm_hints.width_inc / 2);
7205 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7206 xterm_hints.x = 2;
7207 return TRUE;
7208 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007209 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 {
7211 xterm_trace = 0;
7212 return FALSE;
7213 }
7214
7215 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7216 &win_x, &win_y, &mask_return);
7217
7218 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7219 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7220 if (row == prev_row && col == prev_col)
7221 return TRUE;
7222
7223 STRCPY(buf, mouse_code);
7224 strp = buf + STRLEN(buf);
7225 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7226 *strp++ = (char_u)(col + ' ' + 1);
7227 *strp++ = (char_u)(row + ' ' + 1);
7228 *strp = 0;
7229 add_to_input_buf(buf, STRLEN(buf));
7230
7231 prev_row = row;
7232 prev_col = col;
7233 return TRUE;
7234}
7235
7236# if defined(FEAT_GUI) || defined(PROTO)
7237/*
7238 * Destroy the display, window and app_context. Required for GTK.
7239 */
7240 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007241clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242{
7243 if (xterm_Shell != (Widget)0)
7244 {
7245 XtDestroyWidget(xterm_Shell);
7246 xterm_Shell = (Widget)0;
7247 }
7248 if (xterm_dpy != NULL)
7249 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007250# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 /* Lesstif and Solaris crash here, lose some memory */
7252 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007253# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 if (x11_display == xterm_dpy)
7255 x11_display = NULL;
7256 xterm_dpy = NULL;
7257 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007258# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 if (app_context != (XtAppContext)NULL)
7260 {
7261 /* Lesstif and Solaris crash here, lose some memory */
7262 XtDestroyApplicationContext(app_context);
7263 app_context = (XtAppContext)NULL;
7264 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007265# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266}
7267# endif
7268
7269/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007270 * Catch up with GUI or X events.
7271 */
7272 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007273clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007274{
7275# ifdef FEAT_GUI
7276 if (gui.in_use)
7277 gui_mch_update();
7278 else
7279# endif
7280 if (xterm_Shell != (Widget)0)
7281 xterm_update();
7282}
7283
7284/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 * Catch up with any queued X events. This may put keyboard input into the
7286 * input buffer, call resize call-backs, trigger timers etc. If there is
7287 * nothing in the X event queue (& no timers pending), then we return
7288 * immediately.
7289 */
7290 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007291xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292{
7293 XEvent event;
7294
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007295 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007297 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007299 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007300 break;
7301
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007302 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007303 {
7304 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007305 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007306#ifdef FEAT_CLIENTSERVER
7307 {
7308 XPropertyEvent *e = (XPropertyEvent *)&event;
7309
7310 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007312 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007313 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007315 XtDispatchEvent(&event);
7316 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007317 else
7318 {
7319 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007320 XtAppProcessEvent(app_context, mask);
7321 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 }
7323}
7324
7325 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007326clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327{
7328 if (xterm_Shell != (Widget)0)
7329 return clip_x11_own_selection(xterm_Shell, cbd);
7330 return FAIL;
7331}
7332
7333 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007334clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335{
7336 if (xterm_Shell != (Widget)0)
7337 clip_x11_lose_selection(xterm_Shell, cbd);
7338}
7339
7340 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007341clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342{
7343 if (xterm_Shell != (Widget)0)
7344 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7345}
7346
7347 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007348clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349{
7350 clip_x11_set_selection(cbd);
7351}
7352#endif
7353
7354
7355#if defined(USE_XSMP) || defined(PROTO)
7356/*
7357 * Code for X Session Management Protocol.
7358 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007359static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7360static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7361static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7362static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7363static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364
7365
7366# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007367static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007368
7369/*
7370 * This is our chance to ask the user if they want to save,
7371 * or abort the logout
7372 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007374xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375{
7376 cmdmod_T save_cmdmod;
7377 int cancel_shutdown = False;
7378
7379 save_cmdmod = cmdmod;
7380 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007381 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382 /* Mustn't logout */
7383 cancel_shutdown = True;
7384 cmdmod = save_cmdmod;
7385 setcursor(); /* position cursor */
7386 out_flush();
7387
7388 /* Done interaction */
7389 SmcInteractDone(smc_conn, cancel_shutdown);
7390
7391 /* Finish off
7392 * Only end save-yourself here if we're not cancelling shutdown;
7393 * we'll get a cancelled callback later in which we'll end it.
7394 * Hopefully get around glitchy SMs (like GNOME-1)
7395 */
7396 if (!cancel_shutdown)
7397 {
7398 xsmp.save_yourself = False;
7399 SmcSaveYourselfDone(smc_conn, True);
7400 }
7401}
7402# endif
7403
7404/*
7405 * Callback that starts save-yourself.
7406 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007408xsmp_handle_save_yourself(
7409 SmcConn smc_conn,
7410 SmPointer client_data UNUSED,
7411 int save_type UNUSED,
7412 Bool shutdown,
7413 int interact_style UNUSED,
7414 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415{
7416 /* Handle already being in saveyourself */
7417 if (xsmp.save_yourself)
7418 SmcSaveYourselfDone(smc_conn, True);
7419 xsmp.save_yourself = True;
7420 xsmp.shutdown = shutdown;
7421
7422 /* First up, preserve all files */
7423 out_flush();
7424 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7425
7426 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007427 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428
7429# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7430 /* Now see if we can ask about unsaved files */
7431 if (shutdown && !fast && gui.in_use)
7432 /* Need to interact with user, but need SM's permission */
7433 SmcInteractRequest(smc_conn, SmDialogError,
7434 xsmp_handle_interaction, client_data);
7435 else
7436# endif
7437 {
7438 /* Can stop the cycle here */
7439 SmcSaveYourselfDone(smc_conn, True);
7440 xsmp.save_yourself = False;
7441 }
7442}
7443
7444
7445/*
7446 * Callback to warn us of imminent death.
7447 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007449xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450{
7451 xsmp_close();
7452
7453 /* quit quickly leaving swapfiles for modified buffers behind */
7454 getout_preserve_modified(0);
7455}
7456
7457
7458/*
7459 * Callback to tell us that save-yourself has completed.
7460 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007462xsmp_save_complete(
7463 SmcConn smc_conn UNUSED,
7464 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465{
7466 xsmp.save_yourself = False;
7467}
7468
7469
7470/*
7471 * Callback to tell us that an instigated shutdown was cancelled
7472 * (maybe even by us)
7473 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007475xsmp_shutdown_cancelled(
7476 SmcConn smc_conn,
7477 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478{
7479 if (xsmp.save_yourself)
7480 SmcSaveYourselfDone(smc_conn, True);
7481 xsmp.save_yourself = False;
7482 xsmp.shutdown = False;
7483}
7484
7485
7486/*
7487 * Callback to tell us that a new ICE connection has been established.
7488 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007490xsmp_ice_connection(
7491 IceConn iceConn,
7492 IcePointer clientData UNUSED,
7493 Bool opening,
7494 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495{
7496 /* Intercept creation of ICE connection fd */
7497 if (opening)
7498 {
7499 xsmp_icefd = IceConnectionNumber(iceConn);
7500 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7501 }
7502}
7503
7504
7505/* Handle any ICE processing that's required; return FAIL if SM lost */
7506 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007507xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508{
7509 Bool rep;
7510
7511 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7512 == IceProcessMessagesIOError)
7513 {
7514 /* Lost ICE */
7515 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007516 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 xsmp_close();
7518 return FAIL;
7519 }
7520 else
7521 return OK;
7522}
7523
7524static int dummy;
7525
7526/* Set up X Session Management Protocol */
7527 void
7528xsmp_init(void)
7529{
7530 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531 SmcCallbacks smcallbacks;
7532#if 0
7533 SmPropValue smname;
7534 SmProp smnameprop;
7535 SmProp *smprops[1];
7536#endif
7537
7538 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007539 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540
7541 xsmp.save_yourself = xsmp.shutdown = False;
7542
7543 /* Set up SM callbacks - must have all, even if they're not used */
7544 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7545 smcallbacks.save_yourself.client_data = NULL;
7546 smcallbacks.die.callback = xsmp_die;
7547 smcallbacks.die.client_data = NULL;
7548 smcallbacks.save_complete.callback = xsmp_save_complete;
7549 smcallbacks.save_complete.client_data = NULL;
7550 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7551 smcallbacks.shutdown_cancelled.client_data = NULL;
7552
7553 /* Set up a watch on ICE connection creations. The "dummy" argument is
7554 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7555 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7556 {
7557 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007558 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 return;
7560 }
7561
7562 /* Create an SM connection */
7563 xsmp.smcconn = SmcOpenConnection(
7564 NULL,
7565 NULL,
7566 SmProtoMajor,
7567 SmProtoMinor,
7568 SmcSaveYourselfProcMask | SmcDieProcMask
7569 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7570 &smcallbacks,
7571 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007572 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 sizeof(errorstring),
7574 errorstring);
7575 if (xsmp.smcconn == NULL)
7576 {
7577 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007578
Bram Moolenaar071d4272004-06-13 20:20:40 +00007579 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007580 {
7581 vim_snprintf(errorreport, sizeof(errorreport),
7582 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7583 verb_msg((char_u *)errorreport);
7584 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 return;
7586 }
7587 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7588
7589#if 0
7590 /* ID ourselves */
7591 smname.value = "vim";
7592 smname.length = 3;
7593 smnameprop.name = "SmProgram";
7594 smnameprop.type = "SmARRAY8";
7595 smnameprop.num_vals = 1;
7596 smnameprop.vals = &smname;
7597
7598 smprops[0] = &smnameprop;
7599 SmcSetProperties(xsmp.smcconn, 1, smprops);
7600#endif
7601}
7602
7603
7604/* Shut down XSMP comms. */
7605 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007606xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007607{
7608 if (xsmp_icefd != -1)
7609 {
7610 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007611 if (xsmp.clientid != NULL)
7612 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007613 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 xsmp_icefd = -1;
7615 }
7616}
7617#endif /* USE_XSMP */
7618
7619
7620#ifdef EBCDIC
7621/* Translate character to its CTRL- value */
7622char CtrlTable[] =
7623{
7624/* 00 - 5E */
7625 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7626 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7627 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7628 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7629 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7630 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7631/* ^ */ 0x1E,
7632/* - */ 0x1F,
7633/* 61 - 6C */
7634 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7635/* _ */ 0x1F,
7636/* 6E - 80 */
7637 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7638/* a */ 0x01,
7639/* b */ 0x02,
7640/* c */ 0x03,
7641/* d */ 0x37,
7642/* e */ 0x2D,
7643/* f */ 0x2E,
7644/* g */ 0x2F,
7645/* h */ 0x16,
7646/* i */ 0x05,
7647/* 8A - 90 */
7648 0, 0, 0, 0, 0, 0, 0,
7649/* j */ 0x15,
7650/* k */ 0x0B,
7651/* l */ 0x0C,
7652/* m */ 0x0D,
7653/* n */ 0x0E,
7654/* o */ 0x0F,
7655/* p */ 0x10,
7656/* q */ 0x11,
7657/* r */ 0x12,
7658/* 9A - A1 */
7659 0, 0, 0, 0, 0, 0, 0, 0,
7660/* s */ 0x13,
7661/* t */ 0x3C,
7662/* u */ 0x3D,
7663/* v */ 0x32,
7664/* w */ 0x26,
7665/* x */ 0x18,
7666/* y */ 0x19,
7667/* z */ 0x3F,
7668/* AA - AC */
7669 0, 0, 0,
7670/* [ */ 0x27,
7671/* AE - BC */
7672 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7673/* ] */ 0x1D,
7674/* BE - C0 */ 0, 0, 0,
7675/* A */ 0x01,
7676/* B */ 0x02,
7677/* C */ 0x03,
7678/* D */ 0x37,
7679/* E */ 0x2D,
7680/* F */ 0x2E,
7681/* G */ 0x2F,
7682/* H */ 0x16,
7683/* I */ 0x05,
7684/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7685/* J */ 0x15,
7686/* K */ 0x0B,
7687/* L */ 0x0C,
7688/* M */ 0x0D,
7689/* N */ 0x0E,
7690/* O */ 0x0F,
7691/* P */ 0x10,
7692/* Q */ 0x11,
7693/* R */ 0x12,
7694/* DA - DF */ 0, 0, 0, 0, 0, 0,
7695/* \ */ 0x1C,
7696/* E1 */ 0,
7697/* S */ 0x13,
7698/* T */ 0x3C,
7699/* U */ 0x3D,
7700/* V */ 0x32,
7701/* W */ 0x26,
7702/* X */ 0x18,
7703/* Y */ 0x19,
7704/* Z */ 0x3F,
7705/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7706 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7707};
7708
7709char MetaCharTable[]=
7710{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7711 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7712 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7713 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7714 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7715};
7716
7717
7718/* TODO: Use characters NOT numbers!!! */
7719char CtrlCharTable[]=
7720{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7721 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7722 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7723 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7724 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7725};
7726
7727
7728#endif