blob: 57eb0506609ff3982a65ddc88e44cf4b8da16717 [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 Moolenaar8fdd7212016-03-26 19:41:48 +0100179static int WaitForCharOrMouse(long, int *break_loop);
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100180#if defined(__BEOS__) || defined(VMS)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100181int RealWaitForChar(int, long, int *, int *break_loop);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182#else
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100183static int RealWaitForChar(int, long, int *, int *break_loop);
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 */
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100369 RealWaitForChar(read_cmd_fd, p_wd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370}
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 {
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200400 while (!WaitForChar(wtime)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 {
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 */
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200423 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 {
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 Moolenaar40b1b542016-04-20 20:18:23 +0200451 if (!WaitForChar(-1L))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200452 {
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/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200485 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 */
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 Moolenaar8fdd7212016-03-26 19:41:48 +01004765 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 {
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)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004848 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004849 {
4850 struct timeval now_tv;
4851 long msec;
4852
4853 /* Avoid that we keep looping here without
4854 * checking for a CTRL-C for a long time. Don't
4855 * break out too often to avoid losing typeahead. */
4856 gettimeofday(&now_tv, NULL);
4857 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004858 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004859 if (msec > 2000)
4860 {
4861 noread_cnt = 5;
4862 break;
4863 }
4864 }
4865# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866 }
4867
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004868 /* If we already detected the child has finished, continue
4869 * reading output for a short while. Some text may be
4870 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004871 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004872 {
4873 if (noread_cnt < 5)
4874 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004875 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004876 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004877
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 /*
4879 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004880 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004882# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004883 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004884# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004885 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004886# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4888 || (wait_pid == pid && WIFEXITED(status)))
4889 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004890 /* Don't break the loop yet, try reading more
4891 * characters from "fromshell_fd" first. When using
4892 * pipes there might still be something to read and
4893 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004896 else
4897 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004898
Bram Moolenaar95a51352013-03-21 22:53:50 +01004899# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004900 /* Handle any X events, e.g. serving the clipboard. */
4901 clip_update();
4902# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 }
4904finished:
4905 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004906 if (options & SHELL_READ)
4907 {
4908 if (ga.ga_len > 0)
4909 {
4910 append_ga_line(&ga);
4911 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004912 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004913 }
4914 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004915 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004916 ga_clear(&ga);
4917 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 /*
4920 * Give all typeahead that wasn't used back to ui_inchar().
4921 */
4922 if (ta_len)
4923 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 State = old_State;
4925 if (toshell_fd >= 0)
4926 close(toshell_fd);
4927 close(fromshell_fd);
4928 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004929# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004930 else
4931 {
4932 /*
4933 * Similar to the loop above, but only handle X events, no
4934 * I/O.
4935 */
4936 for (;;)
4937 {
4938 if (got_int)
4939 {
4940 /* CTRL-C sends a signal to the child, we ignore it
4941 * ourselves */
4942# ifdef HAVE_SETSID
4943 kill(-pid, SIGINT);
4944# else
4945 kill(0, SIGINT);
4946# endif
4947 got_int = FALSE;
4948 }
4949# ifdef __NeXT__
4950 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4951# else
4952 wait_pid = waitpid(pid, &status, WNOHANG);
4953# endif
4954 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4955 || (wait_pid == pid && WIFEXITED(status)))
4956 {
4957 wait_pid = pid;
4958 break;
4959 }
4960
4961 /* Handle any X events, e.g. serving the clipboard. */
4962 clip_update();
4963
4964 mch_delay(10L, TRUE);
4965 }
4966 }
4967# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968
4969 /*
4970 * Wait until our child has exited.
4971 * Ignore wait() returning pids of other children and returning
4972 * because of some signal like SIGWINCH.
4973 * Don't wait if wait_pid was already set above, indicating the
4974 * child already exited.
4975 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004976 if (wait_pid != pid)
4977 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978
Bram Moolenaar624891f2010-10-13 16:22:09 +02004979# ifdef FEAT_GUI
4980 /* Close slave side of pty. Only do this after the child has
4981 * exited, otherwise the child may hang when it tries to write on
4982 * the pty. */
4983 if (pty_master_fd >= 0)
4984 close(pty_slave_fd);
4985# endif
4986
Bram Moolenaardf177f62005-02-22 08:39:57 +00004987 /* Make sure the child that writes to the external program is
4988 * dead. */
4989 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004990 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004991 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004992 wait4pid(wpid, NULL);
4993 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004994
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 /*
4996 * Set to raw mode right now, otherwise a CTRL-C after
4997 * catch_signals() will kill Vim.
4998 */
4999 if (tmode == TMODE_RAW)
5000 settmode(TMODE_RAW);
5001 did_settmode = TRUE;
5002 set_signals();
5003
5004 if (WIFEXITED(status))
5005 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005006 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005008 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 {
5010 if (retval == EXEC_FAILED)
5011 {
5012 MSG_PUTS(_("\nCannot execute shell "));
5013 msg_outtrans(p_sh);
5014 msg_putchar('\n');
5015 }
5016 else if (!(options & SHELL_SILENT))
5017 {
5018 MSG_PUTS(_("\nshell returned "));
5019 msg_outnum((long)retval);
5020 msg_putchar('\n');
5021 }
5022 }
5023 }
5024 else
5025 MSG_PUTS(_("\nCommand terminated\n"));
5026 }
5027 }
5028 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005029 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030
5031error:
5032 if (!did_settmode)
5033 if (tmode == TMODE_RAW)
5034 settmode(TMODE_RAW); /* set to raw mode */
5035# ifdef FEAT_TITLE
5036 resettitle();
5037# endif
5038 vim_free(newcmd);
5039
5040 return retval;
5041
5042#endif /* USE_SYSTEM */
5043}
5044
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005045#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005046 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005047mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005048{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005049 pid_t pid;
5050 int fd_in[2]; /* for stdin */
5051 int fd_out[2]; /* for stdout */
5052 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005053 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005054 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5055 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5056 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005057 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005058 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5059 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005060 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005061
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005062 if (use_out_for_err && use_null_for_out)
5063 use_null_for_err = TRUE;
5064
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005065 /* default is to fail */
5066 job->jv_status = JOB_FAILED;
5067 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005068 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005069 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005070 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005071 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005072 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005073
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005074 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005075 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005076 if (use_file_for_in)
5077 {
5078 char_u *fname = options->jo_io_name[PART_IN];
5079
5080 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5081 if (fd_in[0] < 0)
5082 {
5083 EMSG2(_(e_notopen), fname);
5084 goto failed;
5085 }
5086 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005087 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005088 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005089
5090 if (use_file_for_out)
5091 {
5092 char_u *fname = options->jo_io_name[PART_OUT];
5093
5094 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5095 if (fd_out[1] < 0)
5096 {
5097 EMSG2(_(e_notopen), fname);
5098 goto failed;
5099 }
5100 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005101 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005102 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005103
5104 if (use_file_for_err)
5105 {
5106 char_u *fname = options->jo_io_name[PART_ERR];
5107
5108 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5109 if (fd_err[1] < 0)
5110 {
5111 EMSG2(_(e_notopen), fname);
5112 goto failed;
5113 }
5114 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005115 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005116 goto failed;
5117
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005118 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5119 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005120 if (options->jo_set & JO_CHANNEL)
5121 {
5122 channel = options->jo_channel;
5123 if (channel != NULL)
5124 ++channel->ch_refcount;
5125 }
5126 else
5127 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005128 if (channel == NULL)
5129 goto failed;
5130 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005131
5132 pid = fork(); /* maybe we should use vfork() */
5133 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005134 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005135 /* failed to fork */
5136 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005137 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005138
5139 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005140 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005141 int null_fd = -1;
5142 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005143
Bram Moolenaar835dc632016-02-07 14:27:38 +01005144 /* child */
5145 reset_signals(); /* handle signals normally */
5146
5147# ifdef HAVE_SETSID
5148 /* Create our own process group, so that the child and all its
5149 * children can be kill()ed. Don't do this when using pipes,
5150 * because stdin is not a tty, we would lose /dev/tty. */
5151 (void)setsid();
5152# endif
5153
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005154 set_child_environment();
5155
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005156 if (use_null_for_in || use_null_for_out || use_null_for_err)
5157 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5158
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005159 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005160 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005161 {
5162 close(0);
5163 ignored = dup(null_fd);
5164 }
5165 else
5166 {
5167 if (!use_file_for_in)
5168 close(fd_in[1]);
5169 close(0);
5170 ignored = dup(fd_in[0]);
5171 close(fd_in[0]);
5172 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005173
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005174 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005175 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005176 {
5177 close(2);
5178 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005179 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005180 }
5181 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005182 {
5183 close(2);
5184 ignored = dup(fd_out[1]);
5185 }
5186 else
5187 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005188 if (!use_file_for_err)
5189 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005190 close(2);
5191 ignored = dup(fd_err[1]);
5192 close(fd_err[1]);
5193 }
5194
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005195 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005196 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005197 {
5198 close(0);
5199 ignored = dup(null_fd);
5200 }
5201 else
5202 {
5203 if (!use_file_for_out)
5204 close(fd_out[0]);
5205 close(1);
5206 ignored = dup(fd_out[1]);
5207 close(fd_out[1]);
5208 }
5209 if (null_fd >= 0)
5210 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005211
Bram Moolenaar835dc632016-02-07 14:27:38 +01005212 /* See above for type of argv. */
5213 execvp(argv[0], argv);
5214
Bram Moolenaar4694a172016-04-21 14:05:23 +02005215 if (stderr_works)
5216 perror("executing job failed");
Bram Moolenaar835dc632016-02-07 14:27:38 +01005217 _exit(EXEC_FAILED); /* exec failed, return failure code */
5218 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005219
5220 /* parent */
5221 job->jv_pid = pid;
5222 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005223 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005224
5225 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005226 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005227 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005228 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005229 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005230 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005231 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005232 if (channel != NULL)
5233 {
5234 channel_set_pipes(channel,
5235 use_file_for_in || use_null_for_in
5236 ? INVALID_FD : fd_in[1],
5237 use_file_for_out || use_null_for_out
5238 ? INVALID_FD : fd_out[0],
5239 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005240 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005241 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005242 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005243
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005244 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005245 return;
5246
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005247failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005248 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005249 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005250 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005251 if (fd_in[1] >= 0)
5252 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005253 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005254 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005255 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005256 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005257 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005258 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005259 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005260 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005261}
5262
5263 char *
5264mch_job_status(job_T *job)
5265{
5266# ifdef HAVE_UNION_WAIT
5267 union wait status;
5268# else
5269 int status = -1;
5270# endif
5271 pid_t wait_pid = 0;
5272
5273# ifdef __NeXT__
5274 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5275# else
5276 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5277# endif
5278 if (wait_pid == -1)
5279 {
5280 /* process must have exited */
5281 job->jv_status = JOB_ENDED;
5282 return "dead";
5283 }
5284 if (wait_pid == 0)
5285 return "run";
5286 if (WIFEXITED(status))
5287 {
5288 /* LINTED avoid "bitwise operation on signed value" */
5289 job->jv_exitval = WEXITSTATUS(status);
5290 job->jv_status = JOB_ENDED;
5291 return "dead";
5292 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005293 if (WIFSIGNALED(status))
5294 {
5295 job->jv_exitval = -1;
5296 job->jv_status = JOB_ENDED;
5297 return "dead";
5298 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005299 return "run";
5300}
5301
5302 int
5303mch_stop_job(job_T *job, char_u *how)
5304{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005305 int sig = -1;
5306 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005307
Bram Moolenaar923d9262016-02-25 20:56:01 +01005308 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005309 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005310 else if (STRCMP(how, "hup") == 0)
5311 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005312 else if (STRCMP(how, "quit") == 0)
5313 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005314 else if (STRCMP(how, "int") == 0)
5315 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005316 else if (STRCMP(how, "kill") == 0)
5317 sig = SIGKILL;
5318 else if (isdigit(*how))
5319 sig = atoi((char *)how);
5320 else
5321 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005322
Bram Moolenaar72801402016-02-09 11:37:50 +01005323 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005324 job_pid = job->jv_pid;
5325 if (job_pid == getpgid(job_pid))
5326 job_pid = -job_pid;
5327
5328 kill(job_pid, sig);
5329
Bram Moolenaar835dc632016-02-07 14:27:38 +01005330 return OK;
5331}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005332
5333/*
5334 * Clear the data related to "job".
5335 */
5336 void
5337mch_clear_job(job_T *job)
5338{
5339 /* call waitpid because child process may become zombie */
5340# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005341 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005342# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005343 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005344# endif
5345}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005346#endif
5347
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348/*
5349 * Check for CTRL-C typed by reading all available characters.
5350 * In cooked mode we should get SIGINT, no need to check.
5351 */
5352 void
Bram Moolenaar05540972016-01-30 20:31:25 +01005353mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005354{
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005355 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356 fill_input_buf(FALSE);
5357}
5358
5359/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005360 * Wait "msec" msec until a character is available from the mouse, keyboard,
5361 * from inbuf[].
5362 * "msec" == -1 will block forever.
5363 * Invokes timer callbacks when needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005365 * Returns TRUE when a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005366 */
5367 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01005368WaitForChar(long msec)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005370#ifdef FEAT_TIMERS
5371 long due_time;
5372 long remaining = msec;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005373 int break_loop = FALSE;
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005374 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005375
5376 /* When waiting very briefly don't trigger timers. */
5377 if (msec >= 0 && msec < 10L)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005378 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005379
5380 while (msec < 0 || remaining > 0)
5381 {
5382 /* Trigger timers and then get the time in msec until the next one is
5383 * due. Wait up to that time. */
5384 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005385 if (typebuf.tb_change_cnt != tb_change_cnt)
5386 {
5387 /* timer may have used feedkeys() */
5388 return FALSE;
5389 }
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005390 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5391 due_time = remaining;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005392 if (WaitForCharOrMouse(due_time, &break_loop))
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005393 return TRUE;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005394 if (break_loop)
5395 /* Nothing available, but need to return so that side effects get
5396 * handled, such as handling a message on a channel. */
5397 return FALSE;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005398 if (msec > 0)
5399 remaining -= due_time;
5400 }
5401 return FALSE;
5402#else
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005403 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005404#endif
5405}
5406
5407/*
5408 * Wait "msec" msec until a character is available from the mouse or keyboard
5409 * or from inbuf[].
5410 * "msec" == -1 will block forever.
5411 * When a GUI is being used, this will never get called -- webb
5412 */
5413 static int
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005414WaitForCharOrMouse(long msec, int *break_loop)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005415{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416#ifdef FEAT_MOUSE_GPM
5417 int gpm_process_wanted;
5418#endif
5419#ifdef FEAT_XCLIPBOARD
5420 int rest;
5421#endif
5422 int avail;
5423
5424 if (input_available()) /* something in inbuf[] */
5425 return 1;
5426
5427#if defined(FEAT_MOUSE_DEC)
5428 /* May need to query the mouse position. */
5429 if (WantQueryMouse)
5430 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005431 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5433 }
5434#endif
5435
5436 /*
5437 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5438 * events. This is a bit complicated, because they might both be defined.
5439 */
5440#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5441# ifdef FEAT_XCLIPBOARD
5442 rest = 0;
5443 if (do_xterm_trace())
5444 rest = msec;
5445# endif
5446 do
5447 {
5448# ifdef FEAT_XCLIPBOARD
5449 if (rest != 0)
5450 {
5451 msec = XT_TRACE_DELAY;
5452 if (rest >= 0 && rest < XT_TRACE_DELAY)
5453 msec = rest;
5454 if (rest >= 0)
5455 rest -= msec;
5456 }
5457# endif
5458# ifdef FEAT_MOUSE_GPM
5459 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005460 avail = RealWaitForChar(read_cmd_fd, msec,
5461 &gpm_process_wanted, break_loop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462# else
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005463 avail = RealWaitForChar(read_cmd_fd, msec, NULL, break_loop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464# endif
5465 if (!avail)
5466 {
5467 if (input_available())
5468 return 1;
5469# ifdef FEAT_XCLIPBOARD
5470 if (rest == 0 || !do_xterm_trace())
5471# endif
5472 break;
5473 }
5474 }
5475 while (FALSE
5476# ifdef FEAT_MOUSE_GPM
5477 || (gpm_process_wanted && mch_gpm_process() == 0)
5478# endif
5479# ifdef FEAT_XCLIPBOARD
5480 || (!avail && rest != 0)
5481# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005482 )
5483 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484
5485#else
Bram Moolenaare1581302016-03-26 21:04:48 +01005486 avail = RealWaitForChar(read_cmd_fd, msec, NULL, break_loop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005487#endif
5488 return avail;
5489}
5490
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005491#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492/*
5493 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005494 * "msec" == 0 will check for characters once.
5495 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005498 * Or when a clientserver message is on the queue.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500#if defined(__BEOS__)
5501 int
5502#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005503 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005504#endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005505RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *break_loop)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005506{
5507 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005508 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005509#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 static int busy = FALSE;
5511
5512 /* May retry getting characters after an event was handled. */
5513# define MAY_LOOP
5514
5515# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5516 /* Remember at what time we started, so that we know how much longer we
5517 * should wait after being interrupted. */
5518# define USE_START_TV
5519 struct timeval start_tv;
5520
5521 if (msec > 0 && (
5522# ifdef FEAT_XCLIPBOARD
5523 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005524# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005525 ||
5526# endif
5527# endif
5528# ifdef USE_XSMP
5529 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005530# ifdef FEAT_MZSCHEME
5531 ||
5532# endif
5533# endif
5534# ifdef FEAT_MZSCHEME
5535 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536# endif
5537 ))
5538 gettimeofday(&start_tv, NULL);
5539# endif
5540
5541 /* Handle being called recursively. This may happen for the session
5542 * manager stuff, it may save the file, which does a breakcheck. */
5543 if (busy)
5544 return 0;
5545#endif
5546
5547#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005548 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549#endif
5550 {
5551#ifdef MAY_LOOP
5552 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005553# ifdef FEAT_MZSCHEME
5554 int mzquantum_used = FALSE;
5555# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556#endif
5557#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005558 /* each channel may use in, out and err */
5559 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 int nfd;
5561# ifdef FEAT_XCLIPBOARD
5562 int xterm_idx = -1;
5563# endif
5564# ifdef FEAT_MOUSE_GPM
5565 int gpm_idx = -1;
5566# endif
5567# ifdef USE_XSMP
5568 int xsmp_idx = -1;
5569# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005570 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005572# ifdef FEAT_MZSCHEME
5573 mzvim_check_threads();
5574 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5575 {
5576 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5577 mzquantum_used = TRUE;
5578 }
5579# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 fds[0].fd = fd;
5581 fds[0].events = POLLIN;
5582 nfd = 1;
5583
Bram Moolenaar071d4272004-06-13 20:20:40 +00005584# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005585 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 if (xterm_Shell != (Widget)0)
5587 {
5588 xterm_idx = nfd;
5589 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5590 fds[nfd].events = POLLIN;
5591 nfd++;
5592 }
5593# endif
5594# ifdef FEAT_MOUSE_GPM
5595 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5596 {
5597 gpm_idx = nfd;
5598 fds[nfd].fd = gpm_fd;
5599 fds[nfd].events = POLLIN;
5600 nfd++;
5601 }
5602# endif
5603# ifdef USE_XSMP
5604 if (xsmp_icefd != -1)
5605 {
5606 xsmp_idx = nfd;
5607 fds[nfd].fd = xsmp_icefd;
5608 fds[nfd].events = POLLIN;
5609 nfd++;
5610 }
5611# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005612#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005613 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005614#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005616 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005617
5618 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005619 if (break_loop != NULL && ret > 0)
5620 *break_loop = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005621
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005622# ifdef FEAT_MZSCHEME
5623 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005624 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005625 finished = FALSE;
5626# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628# ifdef FEAT_XCLIPBOARD
5629 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5630 {
5631 xterm_update(); /* Maybe we should hand out clipboard */
5632 if (--ret == 0 && !input_available())
5633 /* Try again */
5634 finished = FALSE;
5635 }
5636# endif
5637# ifdef FEAT_MOUSE_GPM
5638 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5639 {
5640 *check_for_gpm = 1;
5641 }
5642# endif
5643# ifdef USE_XSMP
5644 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5645 {
5646 if (fds[xsmp_idx].revents & POLLIN)
5647 {
5648 busy = TRUE;
5649 xsmp_handle_requests();
5650 busy = FALSE;
5651 }
5652 else if (fds[xsmp_idx].revents & POLLHUP)
5653 {
5654 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005655 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 xsmp_close();
5657 }
5658 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005659 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 }
5661# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005662#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005663 if (ret > 0)
5664 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666
5667
5668#else /* HAVE_SELECT */
5669
5670 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005671 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005672 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005674 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005676# ifdef FEAT_MZSCHEME
5677 mzvim_check_threads();
5678 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5679 {
5680 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5681 mzquantum_used = TRUE;
5682 }
5683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684# ifdef __EMX__
5685 /* don't check for incoming chars if not in raw mode, because select()
5686 * always returns TRUE then (in some version of emx.dll) */
5687 if (curr_tmode != TMODE_RAW)
5688 return 0;
5689# endif
5690
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005691 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005693 tv.tv_sec = towait / 1000;
5694 tv.tv_usec = (towait % 1000) * (1000000/1000);
5695 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005697 else
5698 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699
5700 /*
5701 * Select on ready for reading and exceptional condition (end of file).
5702 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005703select_eintr:
5704 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005705 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 FD_ZERO(&efds);
5707 FD_SET(fd, &rfds);
5708# if !defined(__QNX__) && !defined(__CYGWIN32__)
5709 /* For QNX select() always returns 1 if this is set. Why? */
5710 FD_SET(fd, &efds);
5711# endif
5712 maxfd = fd;
5713
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005715 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 if (xterm_Shell != (Widget)0)
5717 {
5718 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5719 if (maxfd < ConnectionNumber(xterm_dpy))
5720 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005721
5722 /* An event may have already been read but not handled. In
5723 * particulary, XFlush may cause this. */
5724 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 }
5726# endif
5727# ifdef FEAT_MOUSE_GPM
5728 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5729 {
5730 FD_SET(gpm_fd, &rfds);
5731 FD_SET(gpm_fd, &efds);
5732 if (maxfd < gpm_fd)
5733 maxfd = gpm_fd;
5734 }
5735# endif
5736# ifdef USE_XSMP
5737 if (xsmp_icefd != -1)
5738 {
5739 FD_SET(xsmp_icefd, &rfds);
5740 FD_SET(xsmp_icefd, &efds);
5741 if (maxfd < xsmp_icefd)
5742 maxfd = xsmp_icefd;
5743 }
5744# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005745# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005746 maxfd = channel_select_setup(maxfd, &rfds, &wfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005747# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005749 ret = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005750 result = ret > 0 && FD_ISSET(fd, &rfds);
5751 if (result)
5752 --ret;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005753 if (break_loop != NULL && ret > 0)
5754 *break_loop = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005755
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005756# ifdef EINTR
5757 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005758 {
5759 /* Check whether window has been resized, EINTR may be caused by
5760 * SIGWINCH. */
5761 if (do_resize)
5762 handle_resize();
5763
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005764 /* Interrupted by a signal, need to try again. We ignore msec
5765 * here, because we do want to check even after a timeout if
5766 * characters are available. Needed for reading output of an
5767 * external command after the process has finished. */
5768 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005769 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005770# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005771# ifdef __TANDEM
5772 if (ret == -1 && errno == ENOTSUP)
5773 {
5774 FD_ZERO(&rfds);
5775 FD_ZERO(&efds);
5776 ret = 0;
5777 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005778# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005779# ifdef FEAT_MZSCHEME
5780 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005781 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005782 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783# endif
5784
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785# ifdef FEAT_XCLIPBOARD
5786 if (ret > 0 && xterm_Shell != (Widget)0
5787 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5788 {
5789 xterm_update(); /* Maybe we should hand out clipboard */
5790 /* continue looping when we only got the X event and the input
5791 * buffer is empty */
5792 if (--ret == 0 && !input_available())
5793 {
5794 /* Try again */
5795 finished = FALSE;
5796 }
5797 }
5798# endif
5799# ifdef FEAT_MOUSE_GPM
5800 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5801 {
5802 if (FD_ISSET(gpm_fd, &efds))
5803 gpm_close();
5804 else if (FD_ISSET(gpm_fd, &rfds))
5805 *check_for_gpm = 1;
5806 }
5807# endif
5808# ifdef USE_XSMP
5809 if (ret > 0 && xsmp_icefd != -1)
5810 {
5811 if (FD_ISSET(xsmp_icefd, &efds))
5812 {
5813 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005814 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 xsmp_close();
5816 if (--ret == 0)
5817 finished = FALSE; /* keep going if event was only one */
5818 }
5819 else if (FD_ISSET(xsmp_icefd, &rfds))
5820 {
5821 busy = TRUE;
5822 xsmp_handle_requests();
5823 busy = FALSE;
5824 if (--ret == 0)
5825 finished = FALSE; /* keep going if event was only one */
5826 }
5827 }
5828# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005829#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005830 if (ret > 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005831 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005832#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833
5834#endif /* HAVE_SELECT */
5835
5836#ifdef MAY_LOOP
5837 if (finished || msec == 0)
5838 break;
5839
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005840# ifdef FEAT_CLIENTSERVER
5841 if (server_waiting())
5842 break;
5843# endif
5844
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 /* We're going to loop around again, find out for how long */
5846 if (msec > 0)
5847 {
5848# ifdef USE_START_TV
5849 struct timeval mtv;
5850
5851 /* Compute remaining wait time. */
5852 gettimeofday(&mtv, NULL);
5853 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5854 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5855# else
5856 /* Guess we got interrupted halfway. */
5857 msec = msec / 2;
5858# endif
5859 if (msec <= 0)
5860 break; /* waited long enough */
5861 }
5862#endif
5863 }
5864
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005865 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866}
5867
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005870 * Expand a path into all matching files and/or directories. Handles "*",
5871 * "?", "[a-z]", "**", etc.
5872 * "path" has backslashes before chars that are not to be expanded.
5873 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874 */
5875 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005876mch_expandpath(
5877 garray_T *gap,
5878 char_u *path,
5879 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880{
Bram Moolenaar02743632005-07-25 20:42:36 +00005881 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882}
5883#endif
5884
5885/*
5886 * mch_expand_wildcards() - this code does wild-card pattern matching using
5887 * the shell
5888 *
5889 * return OK for success, FAIL for error (you may lose some memory) and put
5890 * an error message in *file.
5891 *
5892 * num_pat is number of input patterns
5893 * pat is array of pointers to input patterns
5894 * num_file is pointer to number of matched file names
5895 * file is pointer to array of pointers to matched file names
5896 */
5897
5898#ifndef SEEK_SET
5899# define SEEK_SET 0
5900#endif
5901#ifndef SEEK_END
5902# define SEEK_END 2
5903#endif
5904
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005905#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005906
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005908mch_expand_wildcards(
5909 int num_pat,
5910 char_u **pat,
5911 int *num_file,
5912 char_u ***file,
5913 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914{
5915 int i;
5916 size_t len;
5917 char_u *p;
5918 int dir;
5919#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005920 /*
5921 * This is the OS/2 implementation.
5922 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923# define EXPL_ALLOC_INC 16
5924 char_u **expl_files;
5925 size_t files_alloced, files_free;
5926 char_u *buf;
5927 int has_wildcard;
5928
5929 *num_file = 0; /* default: no files found */
5930 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5931 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5932 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5933 if (*file == NULL)
5934 return FAIL;
5935
5936 for (; num_pat > 0; num_pat--, pat++)
5937 {
5938 expl_files = NULL;
5939 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5940 /* expand environment var or home dir */
5941 buf = expand_env_save(*pat);
5942 else
5943 buf = vim_strsave(*pat);
5944 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005945 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 if (has_wildcard) /* yes, so expand them */
5947 expl_files = (char_u **)_fnexplode(buf);
5948
5949 /*
5950 * return value of buf if no wildcards left,
5951 * OR if no match AND EW_NOTFOUND is set.
5952 */
5953 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5954 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5955 { /* simply save the current contents of *buf */
5956 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5957 if (expl_files != NULL)
5958 {
5959 expl_files[0] = vim_strsave(buf);
5960 expl_files[1] = NULL;
5961 }
5962 }
5963 vim_free(buf);
5964
5965 /*
5966 * Count number of names resulting from expansion,
5967 * At the same time add a backslash to the end of names that happen to
5968 * be directories, and replace slashes with backslashes.
5969 */
5970 if (expl_files)
5971 {
5972 for (i = 0; (p = expl_files[i]) != NULL; i++)
5973 {
5974 dir = mch_isdir(p);
5975 /* If we don't want dirs and this is one, skip it */
5976 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5977 continue;
5978
Bram Moolenaara2031822006-03-07 22:29:51 +00005979 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01005980 if (!dir && (flags & EW_EXEC)
5981 && !mch_can_exe(p, NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00005982 continue;
5983
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 if (--files_free == 0)
5985 {
5986 /* need more room in table of pointers */
5987 files_alloced += EXPL_ALLOC_INC;
5988 *file = (char_u **)vim_realloc(*file,
5989 sizeof(char_u **) * files_alloced);
5990 if (*file == NULL)
5991 {
5992 EMSG(_(e_outofmem));
5993 *num_file = 0;
5994 return FAIL;
5995 }
5996 files_free = EXPL_ALLOC_INC;
5997 }
5998 slash_adjust(p);
5999 if (dir)
6000 {
6001 /* For a directory we add a '/', unless it's already
6002 * there. */
6003 len = STRLEN(p);
6004 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
6005 {
6006 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00006007 if (!after_pathsep((*file)[*num_file],
6008 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 {
6010 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006011 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012 }
6013 }
6014 }
6015 else
6016 {
6017 (*file)[*num_file] = vim_strsave(p);
6018 }
6019
6020 /*
6021 * Error message already given by either alloc or vim_strsave.
6022 * Should return FAIL, but returning OK works also.
6023 */
6024 if ((*file)[*num_file] == NULL)
6025 break;
6026 (*num_file)++;
6027 }
6028 _fnexplodefree((char **)expl_files);
6029 }
6030 }
6031 return OK;
6032
6033#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006034 /*
6035 * This is the non-OS/2 implementation (really Unix).
6036 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 int j;
6038 char_u *tempname;
6039 char_u *command;
6040 FILE *fd;
6041 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006042#define STYLE_ECHO 0 /* use "echo", the default */
6043#define STYLE_GLOB 1 /* use "glob", for csh */
6044#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6045#define STYLE_PRINT 3 /* use "print -N", for zsh */
6046#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6047 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 int shell_style = STYLE_ECHO;
6049 int check_spaces;
6050 static int did_find_nul = FALSE;
6051 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006052 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006053 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054
6055 *num_file = 0; /* default: no files found */
6056 *file = NULL;
6057
6058 /*
6059 * If there are no wildcards, just copy the names to allocated memory.
6060 * Saves a lot of time, because we don't have to start a new shell.
6061 */
6062 if (!have_wildcard(num_pat, pat))
6063 return save_patterns(num_pat, pat, num_file, file);
6064
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006065# ifdef HAVE_SANDBOX
6066 /* Don't allow any shell command in the sandbox. */
6067 if (sandbox != 0 && check_secure())
6068 return FAIL;
6069# endif
6070
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 /*
6072 * Don't allow the use of backticks in secure and restricted mode.
6073 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006074 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 for (i = 0; i < num_pat; ++i)
6076 if (vim_strchr(pat[i], '`') != NULL
6077 && (check_restricted() || check_secure()))
6078 return FAIL;
6079
6080 /*
6081 * get a name for the temp file
6082 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006083 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 {
6085 EMSG(_(e_notmp));
6086 return FAIL;
6087 }
6088
6089 /*
6090 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006091 * file.
6092 * STYLE_BT: NL separated
6093 * If expanding `cmd` execute it directly.
6094 * STYLE_GLOB: NUL separated
6095 * If we use *csh, "glob" will work better than "echo".
6096 * STYLE_PRINT: NL or NUL separated
6097 * If we use *zsh, "print -N" will work better than "glob".
6098 * STYLE_VIMGLOB: NL separated
6099 * If we use *sh*, we define "vimglob()".
6100 * STYLE_ECHO: space separated.
6101 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 */
6103 if (num_pat == 1 && *pat[0] == '`'
6104 && (len = STRLEN(pat[0])) > 2
6105 && *(pat[0] + len - 1) == '`')
6106 shell_style = STYLE_BT;
6107 else if ((len = STRLEN(p_sh)) >= 3)
6108 {
6109 if (STRCMP(p_sh + len - 3, "csh") == 0)
6110 shell_style = STYLE_GLOB;
6111 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6112 shell_style = STYLE_PRINT;
6113 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006114 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6115 "sh") != NULL)
6116 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117
Bram Moolenaarc7247912008-01-13 12:54:11 +00006118 /* Compute the length of the command. We need 2 extra bytes: for the
6119 * optional '&' and for the NUL.
6120 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006122 if (shell_style == STYLE_VIMGLOB)
6123 len += STRLEN(sh_vimglob_func);
6124
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006125 for (i = 0; i < num_pat; ++i)
6126 {
6127 /* Count the length of the patterns in the same way as they are put in
6128 * "command" below. */
6129#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006131#else
6132 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006133 for (j = 0; pat[i][j] != NUL; ++j)
6134 {
6135 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6136 ++len; /* may add a backslash */
6137 ++len;
6138 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006139#endif
6140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 command = alloc(len);
6142 if (command == NULL)
6143 {
6144 /* out of memory */
6145 vim_free(tempname);
6146 return FAIL;
6147 }
6148
6149 /*
6150 * Build the shell command:
6151 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6152 * recognizes this).
6153 * - Add the shell command to print the expanded names.
6154 * - Add the temp file name.
6155 * - Add the file name patterns.
6156 */
6157 if (shell_style == STYLE_BT)
6158 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006159 /* change `command; command& ` to (command; command ) */
6160 STRCPY(command, "(");
6161 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006163 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 while (p > command && vim_iswhite(*p))
6165 --p;
6166 if (*p == '&') /* remove trailing '&' */
6167 {
6168 ampersent = TRUE;
6169 *p = ' ';
6170 }
6171 STRCAT(command, ">");
6172 }
6173 else
6174 {
6175 if (flags & EW_NOTFOUND)
6176 STRCPY(command, "set nonomatch; ");
6177 else
6178 STRCPY(command, "unset nonomatch; ");
6179 if (shell_style == STYLE_GLOB)
6180 STRCAT(command, "glob >");
6181 else if (shell_style == STYLE_PRINT)
6182 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006183 else if (shell_style == STYLE_VIMGLOB)
6184 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 else
6186 STRCAT(command, "echo >");
6187 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006188
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006190
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 if (shell_style != STYLE_BT)
6192 for (i = 0; i < num_pat; ++i)
6193 {
6194 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006195 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006196 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197#ifdef USE_SYSTEM
6198 STRCAT(command, " \"");
6199 STRCAT(command, pat[i]);
6200 STRCAT(command, "\"");
6201#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006202 int intick = FALSE;
6203
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 p = command + STRLEN(command);
6205 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006206 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006207 {
6208 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006209 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006210 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6211 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006212 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006213 * backslash inside backticks, before a special character
6214 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006215 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006216 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6217 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006218 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006219 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006220 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006221 else if (!intick
6222 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6223 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006224 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006225 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6226 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006227 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006228
6229 /* Copy one character. */
6230 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006231 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 *p = NUL;
6233#endif
6234 }
6235 if (flags & EW_SILENT)
6236 show_shell_mess = FALSE;
6237 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006238 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239
6240 /*
6241 * Using zsh -G: If a pattern has no matches, it is just deleted from
6242 * the argument list, otherwise zsh gives an error message and doesn't
6243 * expand any other pattern.
6244 */
6245 if (shell_style == STYLE_PRINT)
6246 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6247
6248 /*
6249 * If we use -f then shell variables set in .cshrc won't get expanded.
6250 * vi can do it, so we will too, but it is only necessary if there is a "$"
6251 * in one of the patterns, otherwise we can still use the fast option.
6252 */
6253 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6254 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6255
6256 /*
6257 * execute the shell command
6258 */
6259 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6260
6261 /* When running in the background, give it some time to create the temp
6262 * file, but don't wait for it to finish. */
6263 if (ampersent)
6264 mch_delay(10L, TRUE);
6265
6266 extra_shell_arg = NULL; /* cleanup */
6267 show_shell_mess = TRUE;
6268 vim_free(command);
6269
Bram Moolenaarc7247912008-01-13 12:54:11 +00006270 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 {
6272 mch_remove(tempname);
6273 vim_free(tempname);
6274 /*
6275 * With interactive completion, the error message is not printed.
6276 * However with USE_SYSTEM, I don't know how to turn off error messages
6277 * from the shell, so screen may still get messed up -- webb.
6278 */
6279#ifndef USE_SYSTEM
6280 if (!(flags & EW_SILENT))
6281#endif
6282 {
6283 redraw_later_clear(); /* probably messed up screen */
6284 msg_putchar('\n'); /* clear bottom line quickly */
6285 cmdline_row = Rows - 1; /* continue on last line */
6286#ifdef USE_SYSTEM
6287 if (!(flags & EW_SILENT))
6288#endif
6289 {
6290 MSG(_(e_wildexpand));
6291 msg_start(); /* don't overwrite this message */
6292 }
6293 }
6294 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6295 * EW_NOTFOUND is given */
6296 if (shell_style == STYLE_BT)
6297 return FAIL;
6298 goto notfound;
6299 }
6300
6301 /*
6302 * read the names from the file into memory
6303 */
6304 fd = fopen((char *)tempname, READBIN);
6305 if (fd == NULL)
6306 {
6307 /* Something went wrong, perhaps a file name with a special char. */
6308 if (!(flags & EW_SILENT))
6309 {
6310 MSG(_(e_wildexpand));
6311 msg_start(); /* don't overwrite this message */
6312 }
6313 vim_free(tempname);
6314 goto notfound;
6315 }
6316 fseek(fd, 0L, SEEK_END);
6317 len = ftell(fd); /* get size of temp file */
6318 fseek(fd, 0L, SEEK_SET);
6319 buffer = alloc(len + 1);
6320 if (buffer == NULL)
6321 {
6322 /* out of memory */
6323 mch_remove(tempname);
6324 vim_free(tempname);
6325 fclose(fd);
6326 return FAIL;
6327 }
6328 i = fread((char *)buffer, 1, len, fd);
6329 fclose(fd);
6330 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006331 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 {
6333 /* unexpected read error */
6334 EMSG2(_(e_notread), tempname);
6335 vim_free(tempname);
6336 vim_free(buffer);
6337 return FAIL;
6338 }
6339 vim_free(tempname);
6340
Bram Moolenaarc7247912008-01-13 12:54:11 +00006341# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6343 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006344 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6346 *p++ = buffer[i];
6347 len = p - buffer;
6348# endif
6349
6350
6351 /* file names are separated with Space */
6352 if (shell_style == STYLE_ECHO)
6353 {
6354 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6355 p = buffer;
6356 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6357 {
6358 while (*p != ' ' && *p != '\n')
6359 ++p;
6360 p = skipwhite(p); /* skip to next entry */
6361 }
6362 }
6363 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006364 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 {
6366 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6367 p = buffer;
6368 for (i = 0; *p != NUL; ++i) /* count number of entries */
6369 {
6370 while (*p != '\n' && *p != NUL)
6371 ++p;
6372 if (*p != NUL)
6373 ++p;
6374 p = skipwhite(p); /* skip leading white space */
6375 }
6376 }
6377 /* file names are separated with NUL */
6378 else
6379 {
6380 /*
6381 * Some versions of zsh use spaces instead of NULs to separate
6382 * results. Only do this when there is no NUL before the end of the
6383 * buffer, otherwise we would never be able to use file names with
6384 * embedded spaces when zsh does use NULs.
6385 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6386 * don't check for spaces again.
6387 */
6388 check_spaces = FALSE;
6389 if (shell_style == STYLE_PRINT && !did_find_nul)
6390 {
6391 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006392 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006393 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 did_find_nul = TRUE;
6395 else
6396 check_spaces = TRUE;
6397 }
6398
6399 /*
6400 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6401 * already is one, for STYLE_GLOB it needs to be added.
6402 */
6403 if (len && buffer[len - 1] == NUL)
6404 --len;
6405 else
6406 buffer[len] = NUL;
6407 i = 0;
6408 for (p = buffer; p < buffer + len; ++p)
6409 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6410 {
6411 ++i;
6412 *p = NUL;
6413 }
6414 if (len)
6415 ++i; /* count last entry */
6416 }
6417 if (i == 0)
6418 {
6419 /*
6420 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6421 * /bin/sh will happily expand it to nothing rather than returning an
6422 * error; and hey, it's good to check anyway -- webb.
6423 */
6424 vim_free(buffer);
6425 goto notfound;
6426 }
6427 *num_file = i;
6428 *file = (char_u **)alloc(sizeof(char_u *) * i);
6429 if (*file == NULL)
6430 {
6431 /* out of memory */
6432 vim_free(buffer);
6433 return FAIL;
6434 }
6435
6436 /*
6437 * Isolate the individual file names.
6438 */
6439 p = buffer;
6440 for (i = 0; i < *num_file; ++i)
6441 {
6442 (*file)[i] = p;
6443 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006444 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6445 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006447 while (!(shell_style == STYLE_ECHO && *p == ' ')
6448 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449 ++p;
6450 if (p == buffer + len) /* last entry */
6451 *p = NUL;
6452 else
6453 {
6454 *p++ = NUL;
6455 p = skipwhite(p); /* skip to next entry */
6456 }
6457 }
6458 else /* NUL separates */
6459 {
6460 while (*p && p < buffer + len) /* skip entry */
6461 ++p;
6462 ++p; /* skip NUL */
6463 }
6464 }
6465
6466 /*
6467 * Move the file names to allocated memory.
6468 */
6469 for (j = 0, i = 0; i < *num_file; ++i)
6470 {
6471 /* Require the files to exist. Helps when using /bin/sh */
6472 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6473 continue;
6474
6475 /* check if this entry should be included */
6476 dir = (mch_isdir((*file)[i]));
6477 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6478 continue;
6479
Bram Moolenaara2031822006-03-07 22:29:51 +00006480 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006481 if (!dir && (flags & EW_EXEC)
6482 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006483 continue;
6484
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6486 if (p)
6487 {
6488 STRCPY(p, (*file)[i]);
6489 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006490 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 (*file)[j++] = p;
6492 }
6493 }
6494 vim_free(buffer);
6495 *num_file = j;
6496
6497 if (*num_file == 0) /* rejected all entries */
6498 {
6499 vim_free(*file);
6500 *file = NULL;
6501 goto notfound;
6502 }
6503
6504 return OK;
6505
6506notfound:
6507 if (flags & EW_NOTFOUND)
6508 return save_patterns(num_pat, pat, num_file, file);
6509 return FAIL;
6510
6511#endif /* __EMX__ */
6512}
6513
6514#endif /* VMS */
6515
6516#ifndef __EMX__
6517 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006518save_patterns(
6519 int num_pat,
6520 char_u **pat,
6521 int *num_file,
6522 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523{
6524 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006525 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526
6527 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6528 if (*file == NULL)
6529 return FAIL;
6530 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006531 {
6532 s = vim_strsave(pat[i]);
6533 if (s != NULL)
6534 /* Be compatible with expand_filename(): halve the number of
6535 * backslashes. */
6536 backslash_halve(s);
6537 (*file)[i] = s;
6538 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 *num_file = num_pat;
6540 return OK;
6541}
6542#endif
6543
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544/*
6545 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6546 * expand.
6547 */
6548 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006549mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006551 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 if (*p == '\\' && p[1] != NUL)
6554 ++p;
6555 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 if (vim_strchr((char_u *)
6557#ifdef VMS
6558 "*?%"
6559#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561#endif
6562 , *p) != NULL)
6563 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 }
6565 return FALSE;
6566}
6567
6568/*
6569 * Return TRUE if the string "p" contains a wildcard.
6570 * Don't recognize '~' at the end as a wildcard.
6571 */
6572 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006573mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006575 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 if (*p == '\\' && p[1] != NUL)
6578 ++p;
6579 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 if (vim_strchr((char_u *)
6581#ifdef VMS
6582 "*?%$"
6583#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585#endif
6586 , *p) != NULL
6587 || (*p == '~' && p[1] != NUL))
6588 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 }
6590 return FALSE;
6591}
6592
6593#ifndef __EMX__
6594 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006595have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596{
6597 int i;
6598
6599 for (i = 0; i < num; i++)
6600 if (mch_has_wildcard(file[i]))
6601 return 1;
6602 return 0;
6603}
6604
6605 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006606have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607{
6608 int i;
6609
6610 for (i = 0; i < num; i++)
6611 if (vim_strchr(file[i], '$') != NULL)
6612 return TRUE;
6613 return FALSE;
6614}
6615#endif /* ifndef __EMX__ */
6616
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006617#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618/*
6619 * Scaled-down version of rename(), which is missing in Xenix.
6620 * This version can only move regular files and will fail if the
6621 * destination exists.
6622 */
6623 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006624mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625{
6626 struct stat st;
6627
6628 if (stat(dest, &st) >= 0) /* fail if destination exists */
6629 return -1;
6630 if (link(src, dest) != 0) /* link file to new name */
6631 return -1;
6632 if (mch_remove(src) == 0) /* delete link to old name */
6633 return 0;
6634 return -1;
6635}
6636#endif /* !HAVE_RENAME */
6637
6638#ifdef FEAT_MOUSE_GPM
6639/*
6640 * Initializes connection with gpm (if it isn't already opened)
6641 * Return 1 if succeeded (or connection already opened), 0 if failed
6642 */
6643 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006644gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645{
6646 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6647
6648 if (!gpm_flag)
6649 {
6650 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6651 gpm_connect.defaultMask = ~GPM_HARD;
6652 /* Default handling for mouse move*/
6653 gpm_connect.minMod = 0; /* Handle any modifier keys */
6654 gpm_connect.maxMod = 0xffff;
6655 if (Gpm_Open(&gpm_connect, 0) > 0)
6656 {
6657 /* gpm library tries to handling TSTP causes
6658 * problems. Anyways, we close connection to Gpm whenever
6659 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006660 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006662# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006664# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 return 1; /* succeed */
6666 }
6667 if (gpm_fd == -2)
6668 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6669 return 0;
6670 }
6671 return 1; /* already open */
6672}
6673
6674/*
6675 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 */
6677 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006678gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679{
6680 if (gpm_flag && gpm_fd >= 0) /* if Open */
6681 Gpm_Close();
6682}
6683
6684/* Reads gpm event and adds special keys to input buf. Returns length of
6685 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006686 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 */
6688 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006689mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690{
6691 int button;
6692 static Gpm_Event gpm_event;
6693 char_u string[6];
6694 int_u vim_modifiers;
6695 int row,col;
6696 unsigned char buttons_mask;
6697 unsigned char gpm_modifiers;
6698 static unsigned char old_buttons = 0;
6699
6700 Gpm_GetEvent(&gpm_event);
6701
6702#ifdef FEAT_GUI
6703 /* Don't put events in the input queue now. */
6704 if (hold_gui_events)
6705 return 0;
6706#endif
6707
6708 row = gpm_event.y - 1;
6709 col = gpm_event.x - 1;
6710
6711 string[0] = ESC; /* Our termcode */
6712 string[1] = 'M';
6713 string[2] = 'G';
6714 switch (GPM_BARE_EVENTS(gpm_event.type))
6715 {
6716 case GPM_DRAG:
6717 string[3] = MOUSE_DRAG;
6718 break;
6719 case GPM_DOWN:
6720 buttons_mask = gpm_event.buttons & ~old_buttons;
6721 old_buttons = gpm_event.buttons;
6722 switch (buttons_mask)
6723 {
6724 case GPM_B_LEFT:
6725 button = MOUSE_LEFT;
6726 break;
6727 case GPM_B_MIDDLE:
6728 button = MOUSE_MIDDLE;
6729 break;
6730 case GPM_B_RIGHT:
6731 button = MOUSE_RIGHT;
6732 break;
6733 default:
6734 return 0;
6735 /*Don't know what to do. Can more than one button be
6736 * reported in one event? */
6737 }
6738 string[3] = (char_u)(button | 0x20);
6739 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6740 break;
6741 case GPM_UP:
6742 string[3] = MOUSE_RELEASE;
6743 old_buttons &= ~gpm_event.buttons;
6744 break;
6745 default:
6746 return 0;
6747 }
6748 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6749 gpm_modifiers = gpm_event.modifiers;
6750 vim_modifiers = 0x0;
6751 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6752 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6753 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6754 */
6755 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6756 vim_modifiers |= MOUSE_SHIFT;
6757
6758 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6759 vim_modifiers |= MOUSE_CTRL;
6760 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6761 vim_modifiers |= MOUSE_ALT;
6762 string[3] |= vim_modifiers;
6763 string[4] = (char_u)(col + ' ' + 1);
6764 string[5] = (char_u)(row + ' ' + 1);
6765 add_to_input_buf(string, 6);
6766 return 6;
6767}
6768#endif /* FEAT_MOUSE_GPM */
6769
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006770#ifdef FEAT_SYSMOUSE
6771/*
6772 * Initialize connection with sysmouse.
6773 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6774 * output, any sysmouse output than will be processed via sig_sysmouse().
6775 * Return OK if succeeded, FAIL if failed.
6776 */
6777 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006778sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006779{
6780 struct mouse_info mouse;
6781
6782 mouse.operation = MOUSE_MODE;
6783 mouse.u.mode.mode = 0;
6784 mouse.u.mode.signal = SIGUSR2;
6785 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6786 {
6787 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6788 mouse.operation = MOUSE_SHOW;
6789 ioctl(1, CONS_MOUSECTL, &mouse);
6790 return OK;
6791 }
6792 return FAIL;
6793}
6794
6795/*
6796 * Stop processing SIGUSR2 signals, and also make sure that
6797 * virtual console do not send us any sysmouse related signal.
6798 */
6799 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006800sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006801{
6802 struct mouse_info mouse;
6803
6804 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6805 mouse.operation = MOUSE_MODE;
6806 mouse.u.mode.mode = 0;
6807 mouse.u.mode.signal = 0;
6808 ioctl(1, CONS_MOUSECTL, &mouse);
6809}
6810
6811/*
6812 * Gets info from sysmouse and adds special keys to input buf.
6813 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006814 static RETSIGTYPE
6815sig_sysmouse SIGDEFARG(sigarg)
6816{
6817 struct mouse_info mouse;
6818 struct video_info video;
6819 char_u string[6];
6820 int row, col;
6821 int button;
6822 int buttons;
6823 static int oldbuttons = 0;
6824
6825#ifdef FEAT_GUI
6826 /* Don't put events in the input queue now. */
6827 if (hold_gui_events)
6828 return;
6829#endif
6830
6831 mouse.operation = MOUSE_GETINFO;
6832 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6833 && ioctl(1, FBIO_MODEINFO, &video) != -1
6834 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6835 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6836 {
6837 row = mouse.u.data.y / video.vi_cheight;
6838 col = mouse.u.data.x / video.vi_cwidth;
6839 buttons = mouse.u.data.buttons;
6840 string[0] = ESC; /* Our termcode */
6841 string[1] = 'M';
6842 string[2] = 'S';
6843 if (oldbuttons == buttons && buttons != 0)
6844 {
6845 button = MOUSE_DRAG;
6846 }
6847 else
6848 {
6849 switch (buttons)
6850 {
6851 case 0:
6852 button = MOUSE_RELEASE;
6853 break;
6854 case 1:
6855 button = MOUSE_LEFT;
6856 break;
6857 case 2:
6858 button = MOUSE_MIDDLE;
6859 break;
6860 case 4:
6861 button = MOUSE_RIGHT;
6862 break;
6863 default:
6864 return;
6865 }
6866 oldbuttons = buttons;
6867 }
6868 string[3] = (char_u)(button);
6869 string[4] = (char_u)(col + ' ' + 1);
6870 string[5] = (char_u)(row + ' ' + 1);
6871 add_to_input_buf(string, 6);
6872 }
6873 return;
6874}
6875#endif /* FEAT_SYSMOUSE */
6876
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006878typedef char_u * (*STRPROCSTR)(char_u *);
6879typedef char_u * (*INTPROCSTR)(int);
6880typedef int (*STRPROCINT)(char_u *);
6881typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882
6883/*
6884 * Call a DLL routine which takes either a string or int param
6885 * and returns an allocated string.
6886 */
6887 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006888mch_libcall(
6889 char_u *libname,
6890 char_u *funcname,
6891 char_u *argstring, /* NULL when using a argint */
6892 int argint,
6893 char_u **string_result,/* NULL when using number_result */
6894 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895{
6896# if defined(USE_DLOPEN)
6897 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006898 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899# else
6900 shl_t hinstLib;
6901# endif
6902 STRPROCSTR ProcAdd;
6903 INTPROCSTR ProcAddI;
6904 char_u *retval_str = NULL;
6905 int retval_int = 0;
6906 int success = FALSE;
6907
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006908 /*
6909 * Get a handle to the DLL module.
6910 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006912 /* First clear any error, it's not cleared by the dlopen() call. */
6913 (void)dlerror();
6914
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 hinstLib = dlopen((char *)libname, RTLD_LAZY
6916# ifdef RTLD_LOCAL
6917 | RTLD_LOCAL
6918# endif
6919 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006920 if (hinstLib == NULL)
6921 {
6922 /* "dlerr" must be used before dlclose() */
6923 dlerr = (char *)dlerror();
6924 if (dlerr != NULL)
6925 EMSG2(_("dlerror = \"%s\""), dlerr);
6926 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927# else
6928 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6929# endif
6930
6931 /* If the handle is valid, try to get the function address. */
6932 if (hinstLib != NULL)
6933 {
6934# ifdef HAVE_SETJMP_H
6935 /*
6936 * Catch a crash when calling the library function. For example when
6937 * using a number where a string pointer is expected.
6938 */
6939 mch_startjmp();
6940 if (SETJMP(lc_jump_env) != 0)
6941 {
6942 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006943# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006944 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006945# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 mch_didjmp();
6947 }
6948 else
6949# endif
6950 {
6951 retval_str = NULL;
6952 retval_int = 0;
6953
6954 if (argstring != NULL)
6955 {
6956# if defined(USE_DLOPEN)
6957 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006958 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959# else
6960 if (shl_findsym(&hinstLib, (const char *)funcname,
6961 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6962 ProcAdd = NULL;
6963# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006964 if ((success = (ProcAdd != NULL
6965# if defined(USE_DLOPEN)
6966 && dlerr == NULL
6967# endif
6968 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 {
6970 if (string_result == NULL)
6971 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6972 else
6973 retval_str = (ProcAdd)(argstring);
6974 }
6975 }
6976 else
6977 {
6978# if defined(USE_DLOPEN)
6979 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006980 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981# else
6982 if (shl_findsym(&hinstLib, (const char *)funcname,
6983 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6984 ProcAddI = NULL;
6985# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006986 if ((success = (ProcAddI != NULL
6987# if defined(USE_DLOPEN)
6988 && dlerr == NULL
6989# endif
6990 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 {
6992 if (string_result == NULL)
6993 retval_int = ((INTPROCINT)ProcAddI)(argint);
6994 else
6995 retval_str = (ProcAddI)(argint);
6996 }
6997 }
6998
6999 /* Save the string before we free the library. */
7000 /* Assume that a "1" or "-1" result is an illegal pointer. */
7001 if (string_result == NULL)
7002 *number_result = retval_int;
7003 else if (retval_str != NULL
7004 && retval_str != (char_u *)1
7005 && retval_str != (char_u *)-1)
7006 *string_result = vim_strsave(retval_str);
7007 }
7008
7009# ifdef HAVE_SETJMP_H
7010 mch_endjmp();
7011# ifdef SIGHASARG
7012 if (lc_signal != 0)
7013 {
7014 int i;
7015
7016 /* try to find the name of this signal */
7017 for (i = 0; signal_info[i].sig != -1; i++)
7018 if (lc_signal == signal_info[i].sig)
7019 break;
7020 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
7021 }
7022# endif
7023# endif
7024
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007026 /* "dlerr" must be used before dlclose() */
7027 if (dlerr != NULL)
7028 EMSG2(_("dlerror = \"%s\""), dlerr);
7029
7030 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 (void)dlclose(hinstLib);
7032# else
7033 (void)shl_unload(hinstLib);
7034# endif
7035 }
7036
7037 if (!success)
7038 {
7039 EMSG2(_(e_libcall), funcname);
7040 return FAIL;
7041 }
7042
7043 return OK;
7044}
7045#endif
7046
7047#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7048static int xterm_trace = -1; /* default: disabled */
7049static int xterm_button;
7050
7051/*
7052 * Setup a dummy window for X selections in a terminal.
7053 */
7054 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007055setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056{
7057 int z = 0;
7058 char *strp = "";
7059 Widget AppShell;
7060
7061 if (!x_connect_to_server())
7062 return;
7063
7064 open_app_context();
7065 if (app_context != NULL && xterm_Shell == (Widget)0)
7066 {
7067 int (*oldhandler)();
7068#if defined(HAVE_SETJMP_H)
7069 int (*oldIOhandler)();
7070#endif
7071# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7072 struct timeval start_tv;
7073
7074 if (p_verbose > 0)
7075 gettimeofday(&start_tv, NULL);
7076# endif
7077
7078 /* Ignore X errors while opening the display */
7079 oldhandler = XSetErrorHandler(x_error_check);
7080
7081#if defined(HAVE_SETJMP_H)
7082 /* Ignore X IO errors while opening the display */
7083 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7084 mch_startjmp();
7085 if (SETJMP(lc_jump_env) != 0)
7086 {
7087 mch_didjmp();
7088 xterm_dpy = NULL;
7089 }
7090 else
7091#endif
7092 {
7093 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7094 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7095#if defined(HAVE_SETJMP_H)
7096 mch_endjmp();
7097#endif
7098 }
7099
7100#if defined(HAVE_SETJMP_H)
7101 /* Now handle X IO errors normally. */
7102 (void)XSetIOErrorHandler(oldIOhandler);
7103#endif
7104 /* Now handle X errors normally. */
7105 (void)XSetErrorHandler(oldhandler);
7106
7107 if (xterm_dpy == NULL)
7108 {
7109 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007110 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 return;
7112 }
7113
7114 /* Catch terminating error of the X server connection. */
7115 (void)XSetIOErrorHandler(x_IOerror_handler);
7116
7117# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7118 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007119 {
7120 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007122 verbose_leave();
7123 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124# endif
7125
7126 /* Create a Shell to make converters work. */
7127 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7128 applicationShellWidgetClass, xterm_dpy,
7129 NULL);
7130 if (AppShell == (Widget)0)
7131 return;
7132 xterm_Shell = XtVaCreatePopupShell("VIM",
7133 topLevelShellWidgetClass, AppShell,
7134 XtNmappedWhenManaged, 0,
7135 XtNwidth, 1,
7136 XtNheight, 1,
7137 NULL);
7138 if (xterm_Shell == (Widget)0)
7139 return;
7140
7141 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007142 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 if (x11_display == NULL)
7144 x11_display = xterm_dpy;
7145
7146 XtRealizeWidget(xterm_Shell);
7147 XSync(xterm_dpy, False);
7148 xterm_update();
7149 }
7150 if (xterm_Shell != (Widget)0)
7151 {
7152 clip_init(TRUE);
7153 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7154 x11_window = (Window)atol(strp);
7155 /* Check if $WINDOWID is valid. */
7156 if (test_x11_window(xterm_dpy) == FAIL)
7157 x11_window = 0;
7158 if (x11_window != 0)
7159 xterm_trace = 0;
7160 }
7161}
7162
7163 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007164start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165{
7166 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7167 return;
7168 xterm_trace = 1;
7169 xterm_button = button;
7170 do_xterm_trace();
7171}
7172
7173
7174 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007175stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176{
7177 if (xterm_trace < 0)
7178 return;
7179 xterm_trace = 0;
7180}
7181
7182/*
7183 * Query the xterm pointer and generate mouse termcodes if necessary
7184 * return TRUE if dragging is active, else FALSE
7185 */
7186 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007187do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188{
7189 Window root, child;
7190 int root_x, root_y;
7191 int win_x, win_y;
7192 int row, col;
7193 int_u mask_return;
7194 char_u buf[50];
7195 char_u *strp;
7196 long got_hints;
7197 static char_u *mouse_code;
7198 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7199 static int prev_row = 0, prev_col = 0;
7200 static XSizeHints xterm_hints;
7201
7202 if (xterm_trace <= 0)
7203 return FALSE;
7204
7205 if (xterm_trace == 1)
7206 {
7207 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007208 * have changed recently. */
7209 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7210 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 || xterm_hints.width_inc <= 1
7212 || xterm_hints.height_inc <= 1)
7213 {
7214 xterm_trace = -1; /* Not enough data -- disable tracing */
7215 return FALSE;
7216 }
7217
7218 /* Rely on the same mouse code for the duration of this */
7219 mouse_code = find_termcode(mouse_name);
7220 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007221 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222 xterm_trace = 2;
7223
7224 /* Find the offset of the chars, there might be a scrollbar on the
7225 * left of the window and/or a menu on the top (eterm etc.) */
7226 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7227 &win_x, &win_y, &mask_return);
7228 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7229 - (xterm_hints.height_inc / 2);
7230 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7231 xterm_hints.y = 2;
7232 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7233 - (xterm_hints.width_inc / 2);
7234 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7235 xterm_hints.x = 2;
7236 return TRUE;
7237 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007238 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 {
7240 xterm_trace = 0;
7241 return FALSE;
7242 }
7243
7244 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7245 &win_x, &win_y, &mask_return);
7246
7247 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7248 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7249 if (row == prev_row && col == prev_col)
7250 return TRUE;
7251
7252 STRCPY(buf, mouse_code);
7253 strp = buf + STRLEN(buf);
7254 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7255 *strp++ = (char_u)(col + ' ' + 1);
7256 *strp++ = (char_u)(row + ' ' + 1);
7257 *strp = 0;
7258 add_to_input_buf(buf, STRLEN(buf));
7259
7260 prev_row = row;
7261 prev_col = col;
7262 return TRUE;
7263}
7264
7265# if defined(FEAT_GUI) || defined(PROTO)
7266/*
7267 * Destroy the display, window and app_context. Required for GTK.
7268 */
7269 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007270clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271{
7272 if (xterm_Shell != (Widget)0)
7273 {
7274 XtDestroyWidget(xterm_Shell);
7275 xterm_Shell = (Widget)0;
7276 }
7277 if (xterm_dpy != NULL)
7278 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007279# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 /* Lesstif and Solaris crash here, lose some memory */
7281 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007282# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 if (x11_display == xterm_dpy)
7284 x11_display = NULL;
7285 xterm_dpy = NULL;
7286 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007287# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 if (app_context != (XtAppContext)NULL)
7289 {
7290 /* Lesstif and Solaris crash here, lose some memory */
7291 XtDestroyApplicationContext(app_context);
7292 app_context = (XtAppContext)NULL;
7293 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007294# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295}
7296# endif
7297
7298/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007299 * Catch up with GUI or X events.
7300 */
7301 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007302clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007303{
7304# ifdef FEAT_GUI
7305 if (gui.in_use)
7306 gui_mch_update();
7307 else
7308# endif
7309 if (xterm_Shell != (Widget)0)
7310 xterm_update();
7311}
7312
7313/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314 * Catch up with any queued X events. This may put keyboard input into the
7315 * input buffer, call resize call-backs, trigger timers etc. If there is
7316 * nothing in the X event queue (& no timers pending), then we return
7317 * immediately.
7318 */
7319 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007320xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321{
7322 XEvent event;
7323
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007324 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007326 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007328 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007329 break;
7330
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007331 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007332 {
7333 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007334 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007335#ifdef FEAT_CLIENTSERVER
7336 {
7337 XPropertyEvent *e = (XPropertyEvent *)&event;
7338
7339 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007341 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007342 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007344 XtDispatchEvent(&event);
7345 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007346 else
7347 {
7348 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007349 XtAppProcessEvent(app_context, mask);
7350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 }
7352}
7353
7354 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007355clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356{
7357 if (xterm_Shell != (Widget)0)
7358 return clip_x11_own_selection(xterm_Shell, cbd);
7359 return FAIL;
7360}
7361
7362 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007363clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364{
7365 if (xterm_Shell != (Widget)0)
7366 clip_x11_lose_selection(xterm_Shell, cbd);
7367}
7368
7369 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007370clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371{
7372 if (xterm_Shell != (Widget)0)
7373 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7374}
7375
7376 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007377clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378{
7379 clip_x11_set_selection(cbd);
7380}
7381#endif
7382
7383
7384#if defined(USE_XSMP) || defined(PROTO)
7385/*
7386 * Code for X Session Management Protocol.
7387 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007388static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7389static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7390static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7391static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7392static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393
7394
7395# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007396static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397
7398/*
7399 * This is our chance to ask the user if they want to save,
7400 * or abort the logout
7401 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007403xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404{
7405 cmdmod_T save_cmdmod;
7406 int cancel_shutdown = False;
7407
7408 save_cmdmod = cmdmod;
7409 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007410 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 /* Mustn't logout */
7412 cancel_shutdown = True;
7413 cmdmod = save_cmdmod;
7414 setcursor(); /* position cursor */
7415 out_flush();
7416
7417 /* Done interaction */
7418 SmcInteractDone(smc_conn, cancel_shutdown);
7419
7420 /* Finish off
7421 * Only end save-yourself here if we're not cancelling shutdown;
7422 * we'll get a cancelled callback later in which we'll end it.
7423 * Hopefully get around glitchy SMs (like GNOME-1)
7424 */
7425 if (!cancel_shutdown)
7426 {
7427 xsmp.save_yourself = False;
7428 SmcSaveYourselfDone(smc_conn, True);
7429 }
7430}
7431# endif
7432
7433/*
7434 * Callback that starts save-yourself.
7435 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007437xsmp_handle_save_yourself(
7438 SmcConn smc_conn,
7439 SmPointer client_data UNUSED,
7440 int save_type UNUSED,
7441 Bool shutdown,
7442 int interact_style UNUSED,
7443 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444{
7445 /* Handle already being in saveyourself */
7446 if (xsmp.save_yourself)
7447 SmcSaveYourselfDone(smc_conn, True);
7448 xsmp.save_yourself = True;
7449 xsmp.shutdown = shutdown;
7450
7451 /* First up, preserve all files */
7452 out_flush();
7453 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7454
7455 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007456 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457
7458# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7459 /* Now see if we can ask about unsaved files */
7460 if (shutdown && !fast && gui.in_use)
7461 /* Need to interact with user, but need SM's permission */
7462 SmcInteractRequest(smc_conn, SmDialogError,
7463 xsmp_handle_interaction, client_data);
7464 else
7465# endif
7466 {
7467 /* Can stop the cycle here */
7468 SmcSaveYourselfDone(smc_conn, True);
7469 xsmp.save_yourself = False;
7470 }
7471}
7472
7473
7474/*
7475 * Callback to warn us of imminent death.
7476 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007478xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479{
7480 xsmp_close();
7481
7482 /* quit quickly leaving swapfiles for modified buffers behind */
7483 getout_preserve_modified(0);
7484}
7485
7486
7487/*
7488 * Callback to tell us that save-yourself has completed.
7489 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007491xsmp_save_complete(
7492 SmcConn smc_conn UNUSED,
7493 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494{
7495 xsmp.save_yourself = False;
7496}
7497
7498
7499/*
7500 * Callback to tell us that an instigated shutdown was cancelled
7501 * (maybe even by us)
7502 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007504xsmp_shutdown_cancelled(
7505 SmcConn smc_conn,
7506 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507{
7508 if (xsmp.save_yourself)
7509 SmcSaveYourselfDone(smc_conn, True);
7510 xsmp.save_yourself = False;
7511 xsmp.shutdown = False;
7512}
7513
7514
7515/*
7516 * Callback to tell us that a new ICE connection has been established.
7517 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007519xsmp_ice_connection(
7520 IceConn iceConn,
7521 IcePointer clientData UNUSED,
7522 Bool opening,
7523 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524{
7525 /* Intercept creation of ICE connection fd */
7526 if (opening)
7527 {
7528 xsmp_icefd = IceConnectionNumber(iceConn);
7529 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7530 }
7531}
7532
7533
7534/* Handle any ICE processing that's required; return FAIL if SM lost */
7535 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007536xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537{
7538 Bool rep;
7539
7540 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7541 == IceProcessMessagesIOError)
7542 {
7543 /* Lost ICE */
7544 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007545 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 xsmp_close();
7547 return FAIL;
7548 }
7549 else
7550 return OK;
7551}
7552
7553static int dummy;
7554
7555/* Set up X Session Management Protocol */
7556 void
7557xsmp_init(void)
7558{
7559 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 SmcCallbacks smcallbacks;
7561#if 0
7562 SmPropValue smname;
7563 SmProp smnameprop;
7564 SmProp *smprops[1];
7565#endif
7566
7567 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007568 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569
7570 xsmp.save_yourself = xsmp.shutdown = False;
7571
7572 /* Set up SM callbacks - must have all, even if they're not used */
7573 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7574 smcallbacks.save_yourself.client_data = NULL;
7575 smcallbacks.die.callback = xsmp_die;
7576 smcallbacks.die.client_data = NULL;
7577 smcallbacks.save_complete.callback = xsmp_save_complete;
7578 smcallbacks.save_complete.client_data = NULL;
7579 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7580 smcallbacks.shutdown_cancelled.client_data = NULL;
7581
7582 /* Set up a watch on ICE connection creations. The "dummy" argument is
7583 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7584 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7585 {
7586 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007587 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007588 return;
7589 }
7590
7591 /* Create an SM connection */
7592 xsmp.smcconn = SmcOpenConnection(
7593 NULL,
7594 NULL,
7595 SmProtoMajor,
7596 SmProtoMinor,
7597 SmcSaveYourselfProcMask | SmcDieProcMask
7598 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7599 &smcallbacks,
7600 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007601 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 sizeof(errorstring),
7603 errorstring);
7604 if (xsmp.smcconn == NULL)
7605 {
7606 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007607
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007609 {
7610 vim_snprintf(errorreport, sizeof(errorreport),
7611 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7612 verb_msg((char_u *)errorreport);
7613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 return;
7615 }
7616 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7617
7618#if 0
7619 /* ID ourselves */
7620 smname.value = "vim";
7621 smname.length = 3;
7622 smnameprop.name = "SmProgram";
7623 smnameprop.type = "SmARRAY8";
7624 smnameprop.num_vals = 1;
7625 smnameprop.vals = &smname;
7626
7627 smprops[0] = &smnameprop;
7628 SmcSetProperties(xsmp.smcconn, 1, smprops);
7629#endif
7630}
7631
7632
7633/* Shut down XSMP comms. */
7634 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007635xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636{
7637 if (xsmp_icefd != -1)
7638 {
7639 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007640 if (xsmp.clientid != NULL)
7641 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007642 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 xsmp_icefd = -1;
7644 }
7645}
7646#endif /* USE_XSMP */
7647
7648
7649#ifdef EBCDIC
7650/* Translate character to its CTRL- value */
7651char CtrlTable[] =
7652{
7653/* 00 - 5E */
7654 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7655 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7656 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7657 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7658 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7659 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7660/* ^ */ 0x1E,
7661/* - */ 0x1F,
7662/* 61 - 6C */
7663 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7664/* _ */ 0x1F,
7665/* 6E - 80 */
7666 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7667/* a */ 0x01,
7668/* b */ 0x02,
7669/* c */ 0x03,
7670/* d */ 0x37,
7671/* e */ 0x2D,
7672/* f */ 0x2E,
7673/* g */ 0x2F,
7674/* h */ 0x16,
7675/* i */ 0x05,
7676/* 8A - 90 */
7677 0, 0, 0, 0, 0, 0, 0,
7678/* j */ 0x15,
7679/* k */ 0x0B,
7680/* l */ 0x0C,
7681/* m */ 0x0D,
7682/* n */ 0x0E,
7683/* o */ 0x0F,
7684/* p */ 0x10,
7685/* q */ 0x11,
7686/* r */ 0x12,
7687/* 9A - A1 */
7688 0, 0, 0, 0, 0, 0, 0, 0,
7689/* s */ 0x13,
7690/* t */ 0x3C,
7691/* u */ 0x3D,
7692/* v */ 0x32,
7693/* w */ 0x26,
7694/* x */ 0x18,
7695/* y */ 0x19,
7696/* z */ 0x3F,
7697/* AA - AC */
7698 0, 0, 0,
7699/* [ */ 0x27,
7700/* AE - BC */
7701 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7702/* ] */ 0x1D,
7703/* BE - C0 */ 0, 0, 0,
7704/* A */ 0x01,
7705/* B */ 0x02,
7706/* C */ 0x03,
7707/* D */ 0x37,
7708/* E */ 0x2D,
7709/* F */ 0x2E,
7710/* G */ 0x2F,
7711/* H */ 0x16,
7712/* I */ 0x05,
7713/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7714/* J */ 0x15,
7715/* K */ 0x0B,
7716/* L */ 0x0C,
7717/* M */ 0x0D,
7718/* N */ 0x0E,
7719/* O */ 0x0F,
7720/* P */ 0x10,
7721/* Q */ 0x11,
7722/* R */ 0x12,
7723/* DA - DF */ 0, 0, 0, 0, 0, 0,
7724/* \ */ 0x1C,
7725/* E1 */ 0,
7726/* S */ 0x13,
7727/* T */ 0x3C,
7728/* U */ 0x3D,
7729/* V */ 0x32,
7730/* W */ 0x26,
7731/* X */ 0x18,
7732/* Y */ 0x19,
7733/* Z */ 0x3F,
7734/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7735 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7736};
7737
7738char MetaCharTable[]=
7739{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7740 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7741 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7742 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7743 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7744};
7745
7746
7747/* TODO: Use characters NOT numbers!!! */
7748char CtrlCharTable[]=
7749{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7750 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7751 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7752 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7753 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7754};
7755
7756
7757#endif