blob: 05691841392794e1b139d01df09987fc29986fdd [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
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 Moolenaarcda77642016-06-04 13:32:35 +0200178static int WaitForChar(long msec, int *interrupted);
179static int WaitForCharOrMouse(long msec, int *interrupted);
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100180#if defined(__BEOS__) || defined(VMS)
Bram Moolenaarcda77642016-06-04 13:32:35 +0200181int RealWaitForChar(int, long, int *, int *interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182#else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200183static int RealWaitForChar(int, long, int *, int *interrupted);
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 Moolenaarbb09ceb2016-10-18 16:27:23 +0200214#ifdef HAVE_SIGPROCMASK
215# define SIGSET_DECL(set) sigset_t set;
216# define BLOCK_SIGNALS(set) block_signals(set)
217# define UNBLOCK_SIGNALS(set) unblock_signals(set)
218#else
219# define SIGSET_DECL(set)
220# define BLOCK_SIGNALS(set) do { /**/ } while (0)
221# define UNBLOCK_SIGNALS(set) do { /**/ } while (0)
222#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100223static int have_wildcard(int, char_u **);
224static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100226static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227
228#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000229# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230#endif
231
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000232/* volatile because it is used in signal handler sig_winch(). */
233static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234static char_u *extra_shell_arg = NULL;
235static int show_shell_mess = TRUE;
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000236/* volatile because it is used in signal handler deathtrap(). */
237static volatile int deadly_signal = 0; /* The signal we caught */
238/* volatile because it is used in signal handler deathtrap(). */
239static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240
241static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
242
243#ifdef USE_XSMP
244typedef struct
245{
246 SmcConn smcconn; /* The SM connection ID */
247 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200248 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 Bool save_yourself; /* If we're in the middle of a save_yourself */
250 Bool shutdown; /* If we're in shutdown mode */
251} xsmp_config_T;
252
253static xsmp_config_T xsmp;
254#endif
255
256#ifdef SYS_SIGLIST_DECLARED
257/*
258 * I have seen
259 * extern char *_sys_siglist[NSIG];
260 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
261 * that describe the signals. That is nearly what we want here. But
262 * autoconf does only check for sys_siglist (without the underscore), I
263 * do not want to change everything today.... jw.
264 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
265 */
266#endif
267
268static struct signalinfo
269{
270 int sig; /* Signal number, eg. SIGSEGV etc */
271 char *name; /* Signal name (not char_u!). */
272 char deadly; /* Catch as a deadly signal? */
273} signal_info[] =
274{
275#ifdef SIGHUP
276 {SIGHUP, "HUP", TRUE},
277#endif
278#ifdef SIGQUIT
279 {SIGQUIT, "QUIT", TRUE},
280#endif
281#ifdef SIGILL
282 {SIGILL, "ILL", TRUE},
283#endif
284#ifdef SIGTRAP
285 {SIGTRAP, "TRAP", TRUE},
286#endif
287#ifdef SIGABRT
288 {SIGABRT, "ABRT", TRUE},
289#endif
290#ifdef SIGEMT
291 {SIGEMT, "EMT", TRUE},
292#endif
293#ifdef SIGFPE
294 {SIGFPE, "FPE", TRUE},
295#endif
296#ifdef SIGBUS
297 {SIGBUS, "BUS", TRUE},
298#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100299#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
300 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000301 {SIGSEGV, "SEGV", TRUE},
302#endif
303#ifdef SIGSYS
304 {SIGSYS, "SYS", TRUE},
305#endif
306#ifdef SIGALRM
307 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
308#endif
309#ifdef SIGTERM
310 {SIGTERM, "TERM", TRUE},
311#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100312#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000313 {SIGVTALRM, "VTALRM", TRUE},
314#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000315#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
316 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
317 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 {SIGPROF, "PROF", TRUE},
319#endif
320#ifdef SIGXCPU
321 {SIGXCPU, "XCPU", TRUE},
322#endif
323#ifdef SIGXFSZ
324 {SIGXFSZ, "XFSZ", TRUE},
325#endif
326#ifdef SIGUSR1
327 {SIGUSR1, "USR1", TRUE},
328#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000329#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
330 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 {SIGUSR2, "USR2", TRUE},
332#endif
333#ifdef SIGINT
334 {SIGINT, "INT", FALSE},
335#endif
336#ifdef SIGWINCH
337 {SIGWINCH, "WINCH", FALSE},
338#endif
339#ifdef SIGTSTP
340 {SIGTSTP, "TSTP", FALSE},
341#endif
342#ifdef SIGPIPE
343 {SIGPIPE, "PIPE", FALSE},
344#endif
345 {-1, "Unknown!", FALSE}
346};
347
Bram Moolenaar25724922009-07-14 15:38:41 +0000348 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100349mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000350{
351 if (p_verbose >= 5)
352 {
353 verbose_enter();
354 smsg((char_u *)"chdir(%s)", path);
355 verbose_leave();
356 }
357# ifdef VMS
358 return chdir(vms_fixfilename(path));
359# else
360 return chdir(path);
361# endif
362}
363
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000364/*
365 * Write s[len] to the screen.
366 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100368mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000370 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 if (p_wd) /* Unix is too fast, slow down a bit more */
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100372 RealWaitForChar(read_cmd_fd, p_wd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373}
374
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200375#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
376/*
377 * Return time in msec since "start_tv".
378 */
379 static long
380elapsed(struct timeval *start_tv)
381{
382 struct timeval now_tv;
383
384 gettimeofday(&now_tv, NULL);
385 return (now_tv.tv_sec - start_tv->tv_sec) * 1000L
386 + (now_tv.tv_usec - start_tv->tv_usec) / 1000L;
387}
388#endif
389
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000391 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 * Get a characters from the keyboard.
393 * Return the number of characters that are available.
394 * If wtime == 0 do not wait for characters.
395 * If wtime == n wait a short time for characters.
396 * If wtime == -1 wait forever for characters.
397 */
398 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100399mch_inchar(
400 char_u *buf,
401 int maxlen,
402 long wtime, /* don't use "time", MIPS cannot handle it */
403 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404{
405 int len;
Bram Moolenaarcda77642016-06-04 13:32:35 +0200406 int interrupted = FALSE;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200407 long wait_time;
408#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
409 struct timeval start_tv;
410
411 gettimeofday(&start_tv, NULL);
412#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000413
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200414#ifdef MESSAGE_QUEUE
415 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200416#endif
417
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 /* Check if window changed size while we were busy, perhaps the ":set
419 * columns=99" command was used. */
420 while (do_resize)
421 handle_resize();
422
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200423 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200425 if (wtime >= 0)
426 wait_time = wtime;
427 else
428 wait_time = p_ut;
429#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
430 wait_time -= elapsed(&start_tv);
431 if (wait_time >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200433#endif
434 if (WaitForChar(wait_time, &interrupted))
435 break;
436
Bram Moolenaarcda77642016-06-04 13:32:35 +0200437 /* no character available */
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100438 if (do_resize)
Bram Moolenaarcda77642016-06-04 13:32:35 +0200439 {
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100440 handle_resize();
Bram Moolenaarcda77642016-06-04 13:32:35 +0200441 continue;
442 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100443#ifdef FEAT_CLIENTSERVER
Bram Moolenaarcda77642016-06-04 13:32:35 +0200444 if (server_waiting())
445 {
446 parse_queued_messages();
447 continue;
448 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100449#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200450#ifdef MESSAGE_QUEUE
Bram Moolenaarcda77642016-06-04 13:32:35 +0200451 if (interrupted)
452 {
453 parse_queued_messages();
454 continue;
455 }
Bram Moolenaar67c53842010-05-22 18:28:27 +0200456#endif
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200457#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 }
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200459#endif
460 if (wtime >= 0)
461 /* no character available within "wtime" */
462 return 0;
463
464 /* wtime == -1: no character available within 'updatetime' */
465#ifdef FEAT_AUTOCMD
466 if (trigger_cursorhold() && maxlen >= 3
467 && !typebuf_changed(tb_change_cnt))
468 {
469 buf[0] = K_SPECIAL;
470 buf[1] = KS_EXTRA;
471 buf[2] = (int)KE_CURSORHOLD;
472 return 3;
473 }
474#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 /*
476 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000477 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 * Also done when interrupted by SIGWINCH.
479 */
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200480 before_blocking();
481 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 }
483
Bram Moolenaarcda77642016-06-04 13:32:35 +0200484 /* repeat until we got a character */
485 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 {
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200487 long wtime_now = -1L;
488
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489 while (do_resize) /* window changed size */
490 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200491
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200492#ifdef MESSAGE_QUEUE
493 parse_queued_messages();
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200494
495# ifdef FEAT_JOB_CHANNEL
496 if (has_pending_job())
497 {
498 /* Don't wait longer than a few seconds, checking for a finished
499 * job requires polling. */
500 if (p_ut > 9000L)
501 wtime_now = 1000L;
502 else
503 wtime_now = 10000L - p_ut;
504 }
505# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200506#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200508 * We want to be interrupted by the winch signal
509 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200511 if (!WaitForChar(wtime_now, &interrupted))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200512 {
513 if (do_resize) /* interrupted by SIGWINCH signal */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200514 continue;
515#ifdef MESSAGE_QUEUE
516 if (interrupted || wtime_now > 0)
517 {
518 parse_queued_messages();
519 continue;
520 }
521#endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200522 return 0;
523 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524
525 /* If input was put directly in typeahead buffer bail out here. */
526 if (typebuf_changed(tb_change_cnt))
527 return 0;
528
529 /*
530 * For some terminals we only get one character at a time.
531 * We want the get all available characters, so we could keep on
532 * trying until none is available
533 * For some other terminals this is quite slow, that's why we don't do
534 * it.
535 */
536 len = read_from_input_buf(buf, (long)maxlen);
537 if (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 return len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 }
540}
541
542 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100543handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544{
545 do_resize = FALSE;
546 shell_resized();
547}
548
549/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200550 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551 */
552 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100553mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000554{
Bram Moolenaarcda77642016-06-04 13:32:35 +0200555 return WaitForChar(0L, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556}
557
558#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
559# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000560# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561# endif
562# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
563# include <sys/sysctl.h>
564# endif
565# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
566# include <sys/sysinfo.h>
567# endif
568
569/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000570 * Return total amount of memory available in Kbyte.
571 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100574mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000575{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000577 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200579# ifdef HAVE_SYSCTL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 int mib[2], physmem;
581 size_t len;
582
583 /* BSD way of getting the amount of RAM available. */
584 mib[0] = CTL_HW;
585 mib[1] = HW_USERMEM;
586 len = sizeof(physmem);
587 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
588 mem = (long_u)physmem;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200591# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592 if (mem == 0)
593 {
594 struct sysinfo sinfo;
595
596 /* Linux way of getting amount of RAM available */
597 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000598 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200599# ifdef HAVE_SYSINFO_MEM_UNIT
Bram Moolenaar914572a2007-05-01 11:37:47 +0000600 /* avoid overflow as much as possible */
601 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
602 {
603 sinfo.mem_unit = sinfo.mem_unit >> 1;
604 --shiftright;
605 }
606 mem = sinfo.totalram * sinfo.mem_unit;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200607# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 mem = sinfo.totalram;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200609# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000610 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200612# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200614# ifdef HAVE_SYSCONF
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 if (mem == 0)
616 {
617 long pagesize, pagecount;
618
619 /* Solaris way of getting amount of RAM available */
620 pagesize = sysconf(_SC_PAGESIZE);
621 pagecount = sysconf(_SC_PHYS_PAGES);
622 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000623 {
624 /* avoid overflow as much as possible */
625 while (shiftright > 0 && (pagesize & 1) == 0)
626 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000627 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000628 --shiftright;
629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200633# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634
635 /* Return the minimum of the physical memory and the user limit, because
636 * using more than the user limit may cause Vim to be terminated. */
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200637# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 {
639 struct rlimit rlp;
640
641 if (getrlimit(RLIMIT_DATA, &rlp) == 0
642 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200643# ifdef RLIM_INFINITY
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644 && rlp.rlim_cur != RLIM_INFINITY
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200645# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000646 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000648 {
649 mem = (long_u)rlp.rlim_cur;
650 shiftright = 10;
651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200653# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654
655 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000656 return mem >> shiftright;
657 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658}
659#endif
660
661 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100662mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663{
664 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000665#ifdef FEAT_MZSCHEME
666 long total = msec; /* remember original value */
667#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668
669 if (ignoreinput)
670 {
671 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000672 * here. But we don't want QUIT to kill us (CTRL-\ used in a
673 * shell may produce SIGQUIT). */
674 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 old_tmode = curr_tmode;
676 if (curr_tmode == TMODE_RAW)
677 settmode(TMODE_SLEEP);
678
679 /*
680 * Everybody sleeps in a different way...
681 * Prefer nanosleep(), some versions of usleep() can only sleep up to
682 * one second.
683 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000684#ifdef FEAT_MZSCHEME
685 do
686 {
687 /* if total is large enough, wait by portions in p_mzq */
688 if (total > p_mzq)
689 msec = p_mzq;
690 else
691 msec = total;
692 total -= msec;
693#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694#ifdef HAVE_NANOSLEEP
695 {
696 struct timespec ts;
697
698 ts.tv_sec = msec / 1000;
699 ts.tv_nsec = (msec % 1000) * 1000000;
700 (void)nanosleep(&ts, NULL);
701 }
702#else
703# ifdef HAVE_USLEEP
704 while (msec >= 1000)
705 {
706 usleep((unsigned int)(999 * 1000));
707 msec -= 999;
708 }
709 usleep((unsigned int)(msec * 1000));
710# else
711# ifndef HAVE_SELECT
712 poll(NULL, 0, (int)msec);
713# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 {
715 struct timeval tv;
716
717 tv.tv_sec = msec / 1000;
718 tv.tv_usec = (msec % 1000) * 1000;
719 /*
720 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
721 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
722 */
723 select(0, NULL, NULL, NULL, &tv);
724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725# endif /* HAVE_SELECT */
726# endif /* HAVE_NANOSLEEP */
727#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000728#ifdef FEAT_MZSCHEME
729 }
730 while (total > 0);
731#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732
733 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000734 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 }
736 else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200737 WaitForChar(msec, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738}
739
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000740#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
742# define HAVE_CHECK_STACK_GROWTH
743/*
744 * Support for checking for an almost-out-of-stack-space situation.
745 */
746
747/*
748 * Return a pointer to an item on the stack. Used to find out if the stack
749 * grows up or down.
750 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100751static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752static int stack_grows_downwards;
753
754/*
755 * Find out if the stack grows upwards or downwards.
756 * "p" points to a variable on the stack of the caller.
757 */
758 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 int i;
762
763 stack_grows_downwards = (p > (char *)&i);
764}
765#endif
766
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000767#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768static char *stack_limit = NULL;
769
770#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
771# include <pthread.h>
772# include <pthread_np.h>
773#endif
774
775/*
776 * Find out until how var the stack can grow without getting into trouble.
777 * Called when starting up and when switching to the signal stack in
778 * deathtrap().
779 */
780 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100781get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782{
783 struct rlimit rlp;
784 int i;
785 long lim;
786
787 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
788 * limit doesn't fit in a long (rlim_cur might be "long long"). */
789 if (getrlimit(RLIMIT_STACK, &rlp) == 0
790 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
791# ifdef RLIM_INFINITY
792 && rlp.rlim_cur != RLIM_INFINITY
793# endif
794 )
795 {
796 lim = (long)rlp.rlim_cur;
797#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
798 {
799 pthread_attr_t attr;
800 size_t size;
801
802 /* On FreeBSD the initial thread always has a fixed stack size, no
803 * matter what the limits are set to. Normally it's 1 Mbyte. */
804 pthread_attr_init(&attr);
805 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
806 {
807 pthread_attr_getstacksize(&attr, &size);
808 if (lim > (long)size)
809 lim = (long)size;
810 }
811 pthread_attr_destroy(&attr);
812 }
813#endif
814 if (stack_grows_downwards)
815 {
816 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
817 if (stack_limit >= (char *)&i)
818 /* overflow, set to 1/16 of current stack position */
819 stack_limit = (char *)((long)&i / 16L);
820 }
821 else
822 {
823 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
824 if (stack_limit <= (char *)&i)
825 stack_limit = NULL; /* overflow */
826 }
827 }
828}
829
830/*
831 * Return FAIL when running out of stack space.
832 * "p" must point to any variable local to the caller that's on the stack.
833 */
834 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100835mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836{
837 if (stack_limit != NULL)
838 {
839 if (stack_grows_downwards)
840 {
841 if (p < stack_limit)
842 return FAIL;
843 }
844 else if (p > stack_limit)
845 return FAIL;
846 }
847 return OK;
848}
849#endif
850
851#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
852/*
853 * Support for using the signal stack.
854 * This helps when we run out of stack space, which causes a SIGSEGV. The
855 * signal handler then must run on another stack, since the normal stack is
856 * completely full.
857 */
858
Bram Moolenaar39766a72013-11-03 00:41:00 +0100859#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100860# include <AvailabilityMacros.h>
861#endif
862
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863#ifndef SIGSTKSZ
864# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
865#endif
866
867# ifdef HAVE_SIGALTSTACK
868static stack_t sigstk; /* for sigaltstack() */
869# else
870static struct sigstack sigstk; /* for sigstack() */
871# endif
872
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100873static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874static char *signal_stack;
875
876 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100877init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878{
879 if (signal_stack != NULL)
880 {
881# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000882# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
883 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
885 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100886 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887# endif
888
889# ifdef HAVE_SS_BASE
890 sigstk.ss_base = signal_stack;
891# else
892 sigstk.ss_sp = signal_stack;
893# endif
894 sigstk.ss_size = SIGSTKSZ;
895 sigstk.ss_flags = 0;
896 (void)sigaltstack(&sigstk, NULL);
897# else
898 sigstk.ss_sp = signal_stack;
899 if (stack_grows_downwards)
900 sigstk.ss_sp += SIGSTKSZ - 1;
901 sigstk.ss_onstack = 0;
902 (void)sigstack(&sigstk, NULL);
903# endif
904 }
905}
906#endif
907
908/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000909 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910 * will barf when the second argument to signal() is ``wrong''.
911 * Let me try it with a few tricky defines from my own osdef.h (jw).
912 */
913#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914 static RETSIGTYPE
915sig_winch SIGDEFARG(sigarg)
916{
917 /* this is not required on all systems, but it doesn't hurt anybody */
918 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
919 do_resize = TRUE;
920 SIGRETURN;
921}
922#endif
923
924#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925 static RETSIGTYPE
926catch_sigint SIGDEFARG(sigarg)
927{
928 /* this is not required on all systems, but it doesn't hurt anybody */
929 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
930 got_int = TRUE;
931 SIGRETURN;
932}
933#endif
934
935#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936 static RETSIGTYPE
937catch_sigpwr SIGDEFARG(sigarg)
938{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000939 /* this is not required on all systems, but it doesn't hurt anybody */
940 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 /*
942 * I'm not sure we get the SIGPWR signal when the system is really going
943 * down or when the batteries are almost empty. Just preserve the swap
944 * files and don't exit, that can't do any harm.
945 */
946 ml_sync_all(FALSE, FALSE);
947 SIGRETURN;
948}
949#endif
950
951#ifdef SET_SIG_ALARM
952/*
953 * signal function for alarm().
954 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 static RETSIGTYPE
956sig_alarm SIGDEFARG(sigarg)
957{
958 /* doesn't do anything, just to break a system call */
959 sig_alarm_called = TRUE;
960 SIGRETURN;
961}
962#endif
963
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000964#if (defined(HAVE_SETJMP_H) \
965 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
966 || defined(FEAT_LIBCALL))) \
967 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968/*
969 * A simplistic version of setjmp() that only allows one level of using.
970 * Don't call twice before calling mch_endjmp()!.
971 * Usage:
972 * mch_startjmp();
973 * if (SETJMP(lc_jump_env) != 0)
974 * {
975 * mch_didjmp();
976 * EMSG("crash!");
977 * }
978 * else
979 * {
980 * do_the_work;
981 * mch_endjmp();
982 * }
983 * Note: Can't move SETJMP() here, because a function calling setjmp() must
984 * not return before the saved environment is used.
985 * Returns OK for normal return, FAIL when the protected code caused a
986 * problem and LONGJMP() was used.
987 */
988 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100989mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990{
991#ifdef SIGHASARG
992 lc_signal = 0;
993#endif
994 lc_active = TRUE;
995}
996
997 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100998mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999{
1000 lc_active = FALSE;
1001}
1002
1003 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001004mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001005{
1006# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
1007 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
1008 * otherwise catching the signal only works once. */
1009 init_signal_stack();
1010# endif
1011}
1012#endif
1013
1014/*
1015 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001016 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001018 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
1019 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 */
1021 static RETSIGTYPE
1022deathtrap SIGDEFARG(sigarg)
1023{
1024 static int entered = 0; /* count the number of times we got here.
1025 Note: when memory has been corrupted
1026 this may get an arbitrary value! */
1027#ifdef SIGHASARG
1028 int i;
1029#endif
1030
1031#if defined(HAVE_SETJMP_H)
1032 /*
1033 * Catch a crash in protected code.
1034 * Restores the environment saved in lc_jump_env, which looks like
1035 * SETJMP() returns 1.
1036 */
1037 if (lc_active)
1038 {
1039# if defined(SIGHASARG)
1040 lc_signal = sigarg;
1041# endif
1042 lc_active = FALSE; /* don't jump again */
1043 LONGJMP(lc_jump_env, 1);
1044 /* NOTREACHED */
1045 }
1046#endif
1047
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001048#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001049# ifdef SIGQUIT
1050 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1051 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1052 * pressing CTRL-\, but we don't want Vim to exit then. */
1053 if (in_mch_delay && sigarg == SIGQUIT)
1054 SIGRETURN;
1055# endif
1056
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001057 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1058 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1059 * free(). Calling free() again may then cause a crash. */
1060 if (entered == 0
1061 && (0
1062# ifdef SIGHUP
1063 || sigarg == SIGHUP
1064# endif
1065# ifdef SIGQUIT
1066 || sigarg == SIGQUIT
1067# endif
1068# ifdef SIGTERM
1069 || sigarg == SIGTERM
1070# endif
1071# ifdef SIGPWR
1072 || sigarg == SIGPWR
1073# endif
1074# ifdef SIGUSR1
1075 || sigarg == SIGUSR1
1076# endif
1077# ifdef SIGUSR2
1078 || sigarg == SIGUSR2
1079# endif
1080 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001081 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001082 SIGRETURN;
1083#endif
1084
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 /* Remember how often we have been called. */
1086 ++entered;
1087
Bram Moolenaare429e702016-06-10 19:49:14 +02001088#ifdef FEAT_AUTOCMD
1089 /* Executing autocommands is likely to use more stack space than we have
1090 * available in the signal stack. */
1091 block_autocmds();
1092#endif
1093
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094#ifdef FEAT_EVAL
1095 /* Set the v:dying variable. */
1096 set_vim_var_nr(VV_DYING, (long)entered);
1097#endif
1098
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001099#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 /* Since we are now using the signal stack, need to reset the stack
1101 * limit. Otherwise using a regexp will fail. */
1102 get_stack_limit();
1103#endif
1104
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001105#if 0
1106 /* This is for opening gdb the moment Vim crashes.
1107 * You need to manually adjust the file name and Vim executable name.
1108 * Suggested by SungHyun Nam. */
1109 {
1110# define VI_GDB_FILE "/tmp/vimgdb"
1111# define VIM_NAME "/usr/bin/vim"
1112 FILE *fp = fopen(VI_GDB_FILE, "w");
1113 if (fp)
1114 {
1115 fprintf(fp,
1116 "file %s\n"
1117 "attach %d\n"
1118 "set height 1000\n"
1119 "bt full\n"
1120 , VIM_NAME, getpid());
1121 fclose(fp);
1122 system("xterm -e gdb -x "VI_GDB_FILE);
1123 unlink(VI_GDB_FILE);
1124 }
1125 }
1126#endif
1127
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128#ifdef SIGHASARG
1129 /* try to find the name of this signal */
1130 for (i = 0; signal_info[i].sig != -1; i++)
1131 if (sigarg == signal_info[i].sig)
1132 break;
1133 deadly_signal = sigarg;
1134#endif
1135
1136 full_screen = FALSE; /* don't write message to the GUI, it might be
1137 * part of the problem... */
1138 /*
1139 * If something goes wrong after entering here, we may get here again.
1140 * When this happens, give a message and try to exit nicely (resetting the
1141 * terminal mode, etc.)
1142 * When this happens twice, just exit, don't even try to give a message,
1143 * stack may be corrupt or something weird.
1144 * When this still happens again (or memory was corrupted in such a way
1145 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1146 */
1147 if (entered >= 3)
1148 {
1149 reset_signals(); /* don't catch any signals anymore */
1150 may_core_dump();
1151 if (entered >= 4)
1152 _exit(8);
1153 exit(7);
1154 }
1155 if (entered == 2)
1156 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001157 /* No translation, it may call malloc(). */
1158 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001159 out_flush();
1160 getout(1);
1161 }
1162
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001163 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001165 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166 signal_info[i].name);
1167#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001168 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001170
1171 /* Preserve files and exit. This sets the really_exiting flag to prevent
1172 * calling free(). */
1173 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174
Bram Moolenaare429e702016-06-10 19:49:14 +02001175 /* NOTREACHED */
1176
Bram Moolenaar009b2592004-10-24 19:18:58 +00001177#ifdef NBDEBUG
1178 reset_signals();
1179 may_core_dump();
1180 abort();
1181#endif
1182
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 SIGRETURN;
1184}
1185
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001186#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187/*
1188 * On Solaris with multi-threading, suspending might not work immediately.
1189 * Catch the SIGCONT signal, which will be used as an indication whether the
1190 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001191 *
1192 * On Linux, signal is not always handled immediately either.
1193 * See https://bugs.launchpad.net/bugs/291373
1194 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001195 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001197static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001198static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199
1200/*
1201 * signal handler for SIGCONT
1202 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 static RETSIGTYPE
1204sigcont_handler SIGDEFARG(sigarg)
1205{
1206 sigcont_received = TRUE;
1207 SIGRETURN;
1208}
1209#endif
1210
Bram Moolenaar62b42182010-09-21 22:09:37 +02001211# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001212static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001213# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001214static void save_clipboard(void);
1215static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001216
1217static void *clip_star_save = NULL;
1218static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001219# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001220
1221/*
1222 * Called when Vim is going to sleep or execute a shell command.
1223 * We can't respond to requests for the X selections. Lose them, otherwise
1224 * other applications will hang. But first copy the text to cut buffer 0.
1225 */
1226 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001227loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001228{
1229 if (clip_star.owned || clip_plus.owned)
1230 {
1231 x11_export_final_selection();
1232 if (clip_star.owned)
1233 clip_lose_selection(&clip_star);
1234 if (clip_plus.owned)
1235 clip_lose_selection(&clip_plus);
1236 if (x11_display != NULL)
1237 XFlush(x11_display);
1238 }
1239}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001240
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001241# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001242/*
1243 * Save clipboard text to restore later.
1244 */
1245 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001246save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001247{
1248 if (clip_star.owned)
1249 clip_star_save = get_register('*', TRUE);
1250 if (clip_plus.owned)
1251 clip_plus_save = get_register('+', TRUE);
1252}
1253
1254/*
1255 * Restore clipboard text if no one own the X selection.
1256 */
1257 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001258restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001259{
1260 if (clip_star_save != NULL)
1261 {
1262 if (!clip_gen_owner_exists(&clip_star))
1263 put_register('*', clip_star_save);
1264 else
1265 free_register(clip_star_save);
1266 clip_star_save = NULL;
1267 }
1268 if (clip_plus_save != NULL)
1269 {
1270 if (!clip_gen_owner_exists(&clip_plus))
1271 put_register('+', clip_plus_save);
1272 else
1273 free_register(clip_plus_save);
1274 clip_plus_save = NULL;
1275 }
1276}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001277# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001278#endif
1279
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280/*
1281 * If the machine has job control, use it to suspend the program,
1282 * otherwise fake it by starting a new shell.
1283 */
1284 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001285mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286{
1287 /* BeOS does have SIGTSTP, but it doesn't work. */
1288#if defined(SIGTSTP) && !defined(__BEOS__)
1289 out_flush(); /* needed to make cursor visible on some systems */
1290 settmode(TMODE_COOK);
1291 out_flush(); /* needed to disable mouse on some systems */
1292
1293# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001294 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001295# endif
1296
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001297# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298 sigcont_received = FALSE;
1299# endif
1300 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001301# if defined(_REENTRANT) && defined(SIGCONT)
1302 /*
1303 * Wait for the SIGCONT signal to be handled. It generally happens
1304 * immediately, but somehow not all the time. Do not call pause()
1305 * because there would be race condition which would hang Vim if
1306 * signal happened in between the test of sigcont_received and the
1307 * call to pause(). If signal is not yet received, call sleep(0)
1308 * to just yield CPU. Signal should then be received. If somehow
1309 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1310 * further if signal is not received after 1+2+3+4 ms (not expected
1311 * to happen).
1312 */
1313 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001314 long wait_time;
1315 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001316 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001317 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319# endif
1320
1321# ifdef FEAT_TITLE
1322 /*
1323 * Set oldtitle to NULL, so the current title is obtained again.
1324 */
1325 vim_free(oldtitle);
1326 oldtitle = NULL;
1327# endif
1328 settmode(TMODE_RAW);
1329 need_check_timestamps = TRUE;
1330 did_check_timestamps = FALSE;
1331#else
1332 suspend_shell();
1333#endif
1334}
1335
1336 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001337mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001338{
1339 Columns = 80;
1340 Rows = 24;
1341
1342 out_flush();
1343 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001344
Bram Moolenaar56718732006-03-15 22:53:57 +00001345#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001346 mac_conv_init();
1347#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001348#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1349 win_clip_init();
1350#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351}
1352
1353 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001354set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355{
1356#if defined(SIGWINCH)
1357 /*
1358 * WINDOW CHANGE signal is handled with sig_winch().
1359 */
1360 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1361#endif
1362
1363 /*
1364 * We want the STOP signal to work, to make mch_suspend() work.
1365 * For "rvim" the STOP signal is ignored.
1366 */
1367#ifdef SIGTSTP
1368 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1369#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001370#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 signal(SIGCONT, sigcont_handler);
1372#endif
1373
1374 /*
1375 * We want to ignore breaking of PIPEs.
1376 */
1377#ifdef SIGPIPE
1378 signal(SIGPIPE, SIG_IGN);
1379#endif
1380
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001382 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383#endif
1384
1385 /*
1386 * Ignore alarm signals (Perl's alarm() generates it).
1387 */
1388#ifdef SIGALRM
1389 signal(SIGALRM, SIG_IGN);
1390#endif
1391
1392 /*
1393 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1394 * work will be lost.
1395 */
1396#ifdef SIGPWR
1397 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1398#endif
1399
1400 /*
1401 * Arrange for other signals to gracefully shutdown Vim.
1402 */
1403 catch_signals(deathtrap, SIG_ERR);
1404
1405#if defined(FEAT_GUI) && defined(SIGHUP)
1406 /*
1407 * When the GUI is running, ignore the hangup signal.
1408 */
1409 if (gui.in_use)
1410 signal(SIGHUP, SIG_IGN);
1411#endif
1412}
1413
Bram Moolenaardf177f62005-02-22 08:39:57 +00001414#if defined(SIGINT) || defined(PROTO)
1415/*
1416 * Catch CTRL-C (only works while in Cooked mode).
1417 */
1418 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001419catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001420{
1421 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1422}
1423#endif
1424
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001426reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427{
1428 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001429#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 /* SIGCONT isn't in the list, because its default action is ignore */
1431 signal(SIGCONT, SIG_DFL);
1432#endif
1433}
1434
1435 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001436catch_signals(
1437 RETSIGTYPE (*func_deadly)(),
1438 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439{
1440 int i;
1441
1442 for (i = 0; signal_info[i].sig != -1; i++)
1443 if (signal_info[i].deadly)
1444 {
1445#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1446 struct sigaction sa;
1447
1448 /* Setup to use the alternate stack for the signal function. */
1449 sa.sa_handler = func_deadly;
1450 sigemptyset(&sa.sa_mask);
1451# if defined(__linux__) && defined(_REENTRANT)
1452 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1453 * thread handling in combination with using the alternate stack:
1454 * pthread library functions try to use the stack pointer to
1455 * identify the current thread, causing a SEGV signal, which
1456 * recursively calls deathtrap() and hangs. */
1457 sa.sa_flags = 0;
1458# else
1459 sa.sa_flags = SA_ONSTACK;
1460# endif
1461 sigaction(signal_info[i].sig, &sa, NULL);
1462#else
1463# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1464 struct sigvec sv;
1465
1466 /* Setup to use the alternate stack for the signal function. */
1467 sv.sv_handler = func_deadly;
1468 sv.sv_mask = 0;
1469 sv.sv_flags = SV_ONSTACK;
1470 sigvec(signal_info[i].sig, &sv, NULL);
1471# else
1472 signal(signal_info[i].sig, func_deadly);
1473# endif
1474#endif
1475 }
1476 else if (func_other != SIG_ERR)
1477 signal(signal_info[i].sig, func_other);
1478}
1479
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001480#ifdef HAVE_SIGPROCMASK
1481 static void
1482block_signals(sigset_t *set)
1483{
1484 sigset_t newset;
1485 int i;
1486
1487 sigemptyset(&newset);
1488
1489 for (i = 0; signal_info[i].sig != -1; i++)
1490 sigaddset(&newset, signal_info[i].sig);
1491
1492# if defined(_REENTRANT) && defined(SIGCONT)
1493 /* SIGCONT isn't in the list, because its default action is ignore */
1494 sigaddset(&newset, SIGCONT);
1495# endif
1496
1497 sigprocmask(SIG_BLOCK, &newset, set);
1498}
1499
1500 static void
1501unblock_signals(sigset_t *set)
1502{
1503 sigprocmask(SIG_SETMASK, set, NULL);
1504}
1505#endif
1506
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001508 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001509 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1510 * return TRUE
1511 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1512 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001513 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001514 * Returns TRUE when Vim should exit.
1515 */
1516 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001517vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001518{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001519 static int got_signal = 0;
1520 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001521
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001522 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001523 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001524 case SIGNAL_BLOCK: blocked = TRUE;
1525 break;
1526
1527 case SIGNAL_UNBLOCK: blocked = FALSE;
1528 if (got_signal != 0)
1529 {
1530 kill(getpid(), got_signal);
1531 got_signal = 0;
1532 }
1533 break;
1534
1535 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001536 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001537 got_signal = sig;
1538#ifdef SIGPWR
1539 if (sig != SIGPWR)
1540#endif
1541 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001542 break;
1543 }
1544 return FALSE;
1545}
1546
1547/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 * Check_win checks whether we have an interactive stdout.
1549 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001551mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 if (isatty(1))
1554 return OK;
1555 return FAIL;
1556}
1557
1558/*
1559 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1560 */
1561 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001562mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563{
1564 if (isatty(read_cmd_fd))
1565 return TRUE;
1566 return FALSE;
1567}
1568
1569#ifdef FEAT_X11
1570
1571# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1572 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1573
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001574static void xopen_message(struct timeval *start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575
1576/*
1577 * Give a message about the elapsed time for opening the X window.
1578 */
1579 static void
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001580xopen_message(struct timeval *start_tv)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581{
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001582 smsg((char_u *)_("Opening the X display took %ld msec"), elapsed(start_tv));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583}
1584# endif
1585#endif
1586
1587#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1588/*
1589 * A few functions shared by X11 title and clipboard code.
1590 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001591static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1592static int x_error_check(Display *dpy, XErrorEvent *error_event);
1593static int x_connect_to_server(void);
1594static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595
1596static int got_x_error = FALSE;
1597
1598/*
1599 * X Error handler, otherwise X just exits! (very rude) -- webb
1600 */
1601 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001602x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001604 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 STRCAT(IObuff, _("\nVim: Got X error\n"));
1606
1607 /* We cannot print a message and continue, because no X calls are allowed
1608 * here (causes my system to hang). Silently continuing might be an
1609 * alternative... */
1610 preserve_exit(); /* preserve files and exit */
1611
1612 return 0; /* NOTREACHED */
1613}
1614
1615/*
1616 * Another X Error handler, just used to check for errors.
1617 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001619x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620{
1621 got_x_error = TRUE;
1622 return 0;
1623}
1624
1625#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1626# if defined(HAVE_SETJMP_H)
1627/*
1628 * An X IO Error handler, used to catch error while opening the display.
1629 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001630static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001633x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634{
1635 /* This function should not return, it causes exit(). Longjump instead. */
1636 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001637# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001638 return 0; /* avoid the compiler complains about missing return value */
1639# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640}
1641# endif
1642
1643/*
1644 * An X IO Error handler, used to catch terminal errors.
1645 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001646static int x_IOerror_handler(Display *dpy);
1647static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001648static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001651x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652{
1653 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001654 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 x11_window = 0;
1656 x11_display = NULL;
1657 xterm_Shell = (Widget)0;
1658
1659 /* This function should not return, it causes exit(). Longjump instead. */
1660 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001661# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001662 return 0; /* avoid the compiler complains about missing return value */
1663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001665
1666/*
1667 * If the X11 connection was lost try to restore it.
1668 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001669 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001670 */
1671 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001672may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001673{
1674 if (xterm_dpy_was_reset)
1675 {
1676 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001677
1678# ifndef LESSTIF_VERSION
1679 /* This has been reported to avoid Vim getting stuck. */
1680 if (app_context != (XtAppContext)NULL)
1681 {
1682 XtDestroyApplicationContext(app_context);
1683 app_context = (XtAppContext)NULL;
1684 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1685 }
1686# endif
1687
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001688 setup_term_clip();
1689 get_x11_title(FALSE);
1690 }
1691}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692#endif
1693
1694/*
1695 * Return TRUE when connection to the X server is desired.
1696 */
1697 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001698x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700#if defined(FEAT_CLIENTSERVER)
1701 if (x_force_connect)
1702 return TRUE;
1703#endif
1704 if (x_no_connect)
1705 return FALSE;
1706
1707 /* Check for a match with "exclude:" from 'clipboard'. */
1708 if (clip_exclude_prog != NULL)
1709 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001710 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 return FALSE;
1712 }
1713 return TRUE;
1714}
1715
1716/*
1717 * Test if "dpy" and x11_window are valid by getting the window title.
1718 * I don't actually want it yet, so there may be a simpler call to use, but
1719 * this will cause the error handler x_error_check() to be called if anything
1720 * is wrong, such as the window pointer being invalid (as can happen when the
1721 * user changes his DISPLAY, but not his WINDOWID) -- webb
1722 */
1723 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001724test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725{
1726 int (*old_handler)();
1727 XTextProperty text_prop;
1728
1729 old_handler = XSetErrorHandler(x_error_check);
1730 got_x_error = FALSE;
1731 if (XGetWMName(dpy, x11_window, &text_prop))
1732 XFree((void *)text_prop.value);
1733 XSync(dpy, False);
1734 (void)XSetErrorHandler(old_handler);
1735
1736 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001737 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738
1739 return (got_x_error ? FAIL : OK);
1740}
1741#endif
1742
1743#ifdef FEAT_TITLE
1744
1745#ifdef FEAT_X11
1746
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001747static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748
1749/*
1750 * try to get x11 window and display
1751 *
1752 * return FAIL for failure, OK otherwise
1753 */
1754 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001755get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756{
1757 char *winid;
1758 static int result = -1;
1759#define XD_NONE 0 /* x11_display not set here */
1760#define XD_HERE 1 /* x11_display opened here */
1761#define XD_GUI 2 /* x11_display used from gui.dpy */
1762#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1763 static int x11_display_from = XD_NONE;
1764 static int did_set_error_handler = FALSE;
1765
1766 if (!did_set_error_handler)
1767 {
1768 /* X just exits if it finds an error otherwise! */
1769 (void)XSetErrorHandler(x_error_handler);
1770 did_set_error_handler = TRUE;
1771 }
1772
Bram Moolenaar9372a112005-12-06 19:59:18 +00001773#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 if (gui.in_use)
1775 {
1776 /*
1777 * If the X11 display was opened here before, for the window where Vim
1778 * was started, close that one now to avoid a memory leak.
1779 */
1780 if (x11_display_from == XD_HERE && x11_display != NULL)
1781 {
1782 XCloseDisplay(x11_display);
1783 x11_display_from = XD_NONE;
1784 }
1785 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1786 {
1787 x11_display_from = XD_GUI;
1788 return OK;
1789 }
1790 x11_display = NULL;
1791 return FAIL;
1792 }
1793 else if (x11_display_from == XD_GUI)
1794 {
1795 /* GUI must have stopped somehow, clear x11_display */
1796 x11_window = 0;
1797 x11_display = NULL;
1798 x11_display_from = XD_NONE;
1799 }
1800#endif
1801
1802 /* When started with the "-X" argument, don't try connecting. */
1803 if (!x_connect_to_server())
1804 return FAIL;
1805
1806 /*
1807 * If WINDOWID not set, should try another method to find out
1808 * what the current window number is. The only code I know for
1809 * this is very complicated.
1810 * We assume that zero is invalid for WINDOWID.
1811 */
1812 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1813 x11_window = (Window)atol(winid);
1814
1815#ifdef FEAT_XCLIPBOARD
1816 if (xterm_dpy != NULL && x11_window != 0)
1817 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001818 /* We may have checked it already, but Gnome terminal can move us to
1819 * another window, so we need to check every time. */
1820 if (x11_display_from != XD_XTERM)
1821 {
1822 /*
1823 * If the X11 display was opened here before, for the window where
1824 * Vim was started, close that one now to avoid a memory leak.
1825 */
1826 if (x11_display_from == XD_HERE && x11_display != NULL)
1827 XCloseDisplay(x11_display);
1828 x11_display = xterm_dpy;
1829 x11_display_from = XD_XTERM;
1830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 if (test_x11_window(x11_display) == FAIL)
1832 {
1833 /* probably bad $WINDOWID */
1834 x11_window = 0;
1835 x11_display = NULL;
1836 x11_display_from = XD_NONE;
1837 return FAIL;
1838 }
1839 return OK;
1840 }
1841#endif
1842
1843 if (x11_window == 0 || x11_display == NULL)
1844 result = -1;
1845
1846 if (result != -1) /* Have already been here and set this */
1847 return result; /* Don't do all these X calls again */
1848
1849 if (x11_window != 0 && x11_display == NULL)
1850 {
1851#ifdef SET_SIG_ALARM
1852 RETSIGTYPE (*sig_save)();
1853#endif
1854#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1855 struct timeval start_tv;
1856
1857 if (p_verbose > 0)
1858 gettimeofday(&start_tv, NULL);
1859#endif
1860
1861#ifdef SET_SIG_ALARM
1862 /*
1863 * Opening the Display may hang if the DISPLAY setting is wrong, or
1864 * the network connection is bad. Set an alarm timer to get out.
1865 */
1866 sig_alarm_called = FALSE;
1867 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1868 (RETSIGTYPE (*)())sig_alarm);
1869 alarm(2);
1870#endif
1871 x11_display = XOpenDisplay(NULL);
1872
1873#ifdef SET_SIG_ALARM
1874 alarm(0);
1875 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1876 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001877 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878#endif
1879 if (x11_display != NULL)
1880 {
1881# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1882 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001883 {
1884 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001886 verbose_leave();
1887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888# endif
1889 if (test_x11_window(x11_display) == FAIL)
1890 {
1891 /* Maybe window id is bad */
1892 x11_window = 0;
1893 XCloseDisplay(x11_display);
1894 x11_display = NULL;
1895 }
1896 else
1897 x11_display_from = XD_HERE;
1898 }
1899 }
1900 if (x11_window == 0 || x11_display == NULL)
1901 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001902
1903# ifdef FEAT_EVAL
1904 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1905# endif
1906
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 return (result = OK);
1908}
1909
1910/*
1911 * Determine original x11 Window Title
1912 */
1913 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001914get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001916 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917}
1918
1919/*
1920 * Determine original x11 Window icon
1921 */
1922 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001923get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924{
1925 int retval = FALSE;
1926
1927 retval = get_x11_thing(FALSE, test_only);
1928
1929 /* could not get old icon, use terminal name */
1930 if (oldicon == NULL && !test_only)
1931 {
1932 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001933 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001935 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 }
1937
1938 return retval;
1939}
1940
1941 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001942get_x11_thing(
1943 int get_title, /* get title string */
1944 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945{
1946 XTextProperty text_prop;
1947 int retval = FALSE;
1948 Status status;
1949
1950 if (get_x11_windis() == OK)
1951 {
1952 /* Get window/icon name if any */
1953 if (get_title)
1954 status = XGetWMName(x11_display, x11_window, &text_prop);
1955 else
1956 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1957
1958 /*
1959 * If terminal is xterm, then x11_window may be a child window of the
1960 * outer xterm window that actually contains the window/icon name, so
1961 * keep traversing up the tree until a window with a title/icon is
1962 * found.
1963 */
1964 /* Previously this was only done for xterm and alikes. I don't see a
1965 * reason why it would fail for other terminal emulators.
1966 * if (term_is_xterm) */
1967 {
1968 Window root;
1969 Window parent;
1970 Window win = x11_window;
1971 Window *children;
1972 unsigned int num_children;
1973
1974 while (!status || text_prop.value == NULL)
1975 {
1976 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1977 &num_children))
1978 break;
1979 if (children)
1980 XFree((void *)children);
1981 if (parent == root || parent == 0)
1982 break;
1983
1984 win = parent;
1985 if (get_title)
1986 status = XGetWMName(x11_display, win, &text_prop);
1987 else
1988 status = XGetWMIconName(x11_display, win, &text_prop);
1989 }
1990 }
1991 if (status && text_prop.value != NULL)
1992 {
1993 retval = TRUE;
1994 if (!test_only)
1995 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001996#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1997 if (text_prop.encoding == XA_STRING
1998# ifdef FEAT_MBYTE
1999 && !has_mbyte
2000# endif
2001 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 {
2003#endif
2004 if (get_title)
2005 oldtitle = vim_strsave((char_u *)text_prop.value);
2006 else
2007 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002008#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 }
2010 else
2011 {
2012 char **cl;
2013 Status transform_status;
2014 int n = 0;
2015
2016 transform_status = XmbTextPropertyToTextList(x11_display,
2017 &text_prop,
2018 &cl, &n);
2019 if (transform_status >= Success && n > 0 && cl[0])
2020 {
2021 if (get_title)
2022 oldtitle = vim_strsave((char_u *) cl[0]);
2023 else
2024 oldicon = vim_strsave((char_u *) cl[0]);
2025 XFreeStringList(cl);
2026 }
2027 else
2028 {
2029 if (get_title)
2030 oldtitle = vim_strsave((char_u *)text_prop.value);
2031 else
2032 oldicon = vim_strsave((char_u *)text_prop.value);
2033 }
2034 }
2035#endif
2036 }
2037 XFree((void *)text_prop.value);
2038 }
2039 }
2040 return retval;
2041}
2042
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002043/* Xutf8 functions are not avaialble on older systems. Note that on some
2044 * systems X_HAVE_UTF8_STRING may be defined in a header file but
2045 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
2046 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002048# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049# define USE_UTF8_STRING
2050# endif
2051#endif
2052
2053/*
2054 * Set x11 Window Title
2055 *
2056 * get_x11_windis() must be called before this and have returned OK
2057 */
2058 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002059set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060{
2061 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2062 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2063 * supported everywhere and STRING doesn't work for multi-byte titles.
2064 */
2065#ifdef USE_UTF8_STRING
2066 if (enc_utf8)
2067 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2068 NULL, NULL, 0, NULL, NULL, NULL);
2069 else
2070#endif
2071 {
2072#if XtSpecificationRelease >= 4
2073# ifdef FEAT_XFONTSET
2074 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2075 NULL, NULL, 0, NULL, NULL, NULL);
2076# else
2077 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002078 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079
2080 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002081 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 XSetWMProperties(x11_display, x11_window, &text_prop,
2083 NULL, NULL, 0, NULL, NULL, NULL);
2084# endif
2085#else
2086 XStoreName(x11_display, x11_window, (char *)title);
2087#endif
2088 }
2089 XFlush(x11_display);
2090}
2091
2092/*
2093 * Set x11 Window icon
2094 *
2095 * get_x11_windis() must be called before this and have returned OK
2096 */
2097 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002098set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099{
2100 /* See above for comments about using X*SetWMProperties(). */
2101#ifdef USE_UTF8_STRING
2102 if (enc_utf8)
2103 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2104 NULL, 0, NULL, NULL, NULL);
2105 else
2106#endif
2107 {
2108#if XtSpecificationRelease >= 4
2109# ifdef FEAT_XFONTSET
2110 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2111 NULL, 0, NULL, NULL, NULL);
2112# else
2113 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002114 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002116 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2118 NULL, 0, NULL, NULL, NULL);
2119# endif
2120#else
2121 XSetIconName(x11_display, x11_window, (char *)icon);
2122#endif
2123 }
2124 XFlush(x11_display);
2125}
2126
2127#else /* FEAT_X11 */
2128
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002130get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131{
2132 return FALSE;
2133}
2134
2135 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002136get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137{
2138 if (!test_only)
2139 {
2140 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002141 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002143 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 }
2145 return FALSE;
2146}
2147
2148#endif /* FEAT_X11 */
2149
2150 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002151mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152{
2153 return get_x11_title(TRUE);
2154}
2155
2156 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002157mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158{
2159 return get_x11_icon(TRUE);
2160}
2161
2162/*
2163 * Set the window title and icon.
2164 */
2165 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002166mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167{
2168 int type = 0;
2169 static int recursive = 0;
2170
2171 if (T_NAME == NULL) /* no terminal name (yet) */
2172 return;
2173 if (title == NULL && icon == NULL) /* nothing to do */
2174 return;
2175
2176 /* When one of the X11 functions causes a deadly signal, we get here again
2177 * recursively. Avoid hanging then (something is probably locked). */
2178 if (recursive)
2179 return;
2180 ++recursive;
2181
2182 /*
2183 * if the window ID and the display is known, we may use X11 calls
2184 */
2185#ifdef FEAT_X11
2186 if (get_x11_windis() == OK)
2187 type = 1;
2188#else
2189# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2190 if (gui.in_use)
2191 type = 1;
2192# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193#endif
2194
2195 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002196 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 * than x11 calls, because the x11 calls don't always work
2198 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 if ((type || *T_TS != NUL) && title != NULL)
2200 {
2201 if (oldtitle == NULL
2202#ifdef FEAT_GUI
2203 && !gui.in_use
2204#endif
2205 ) /* first call but not in GUI, save title */
2206 (void)get_x11_title(FALSE);
2207
2208 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2209 term_settitle(title);
2210#ifdef FEAT_X11
2211 else
2212# ifdef FEAT_GUI_GTK
2213 if (!gui.in_use) /* don't do this if GTK+ is running */
2214# endif
2215 set_x11_title(title); /* x11 */
2216#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002217#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2219 else
2220 gui_mch_settitle(title, icon);
2221#endif
2222 did_set_title = TRUE;
2223 }
2224
2225 if ((type || *T_CIS != NUL) && icon != NULL)
2226 {
2227 if (oldicon == NULL
2228#ifdef FEAT_GUI
2229 && !gui.in_use
2230#endif
2231 ) /* first call, save icon */
2232 get_x11_icon(FALSE);
2233
2234 if (*T_CIS != NUL)
2235 {
2236 out_str(T_CIS); /* set icon start */
2237 out_str_nf(icon);
2238 out_str(T_CIE); /* set icon end */
2239 out_flush();
2240 }
2241#ifdef FEAT_X11
2242 else
2243# ifdef FEAT_GUI_GTK
2244 if (!gui.in_use) /* don't do this if GTK+ is running */
2245# endif
2246 set_x11_icon(icon); /* x11 */
2247#endif
2248 did_set_icon = TRUE;
2249 }
2250 --recursive;
2251}
2252
2253/*
2254 * Restore the window/icon title.
2255 * "which" is one of:
2256 * 1 only restore title
2257 * 2 only restore icon
2258 * 3 restore title and icon
2259 */
2260 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002261mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262{
2263 /* only restore the title or icon when it has been set */
2264 mch_settitle(((which & 1) && did_set_title) ?
2265 (oldtitle ? oldtitle : p_titleold) : NULL,
2266 ((which & 2) && did_set_icon) ? oldicon : NULL);
2267}
2268
2269#endif /* FEAT_TITLE */
2270
2271/*
2272 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002273 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 */
2275 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002276vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277{
2278 if (name == NULL)
2279 return FALSE;
2280 return (STRNICMP(name, "xterm", 5) == 0
2281 || STRNICMP(name, "nxterm", 6) == 0
2282 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002283 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 || STRNICMP(name, "rxvt", 4) == 0
2285 || STRCMP(name, "builtin_xterm") == 0);
2286}
2287
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002288#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2289/*
2290 * Return TRUE if "name" appears to be that of a terminal
2291 * known to support the xterm-style mouse protocol.
2292 * Relies on term_is_xterm having been set to its correct value.
2293 */
2294 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002295use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002296{
2297 return (name != NULL
Bram Moolenaare56132b2016-08-14 18:23:21 +02002298 && (term_is_xterm
2299 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002300 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaare56132b2016-08-14 18:23:21 +02002301 || STRICMP(name, "st") == 0
2302 || STRNICMP(name, "st-", 3) == 0
2303 || STRNICMP(name, "stterm", 6) == 0));
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002304}
2305#endif
2306
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2308/*
2309 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2310 * Return 1 for "xterm".
2311 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002312 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002313 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 */
2315 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002316use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002318 if (ttym_flags == TTYM_SGR)
2319 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002320 if (ttym_flags == TTYM_URXVT)
2321 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 if (ttym_flags == TTYM_XTERM2)
2323 return 2;
2324 if (ttym_flags == TTYM_XTERM)
2325 return 1;
2326 return 0;
2327}
2328#endif
2329
2330 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002331vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332{
2333 if (name == NULL)
2334 return FALSE;
2335 return (STRNICMP(name, "iris-ansi", 9) == 0
2336 || STRCMP(name, "builtin_iris-ansi") == 0);
2337}
2338
2339 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002340vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341{
2342 if (name == NULL)
2343 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002344 /* catch VT100 - VT5xx */
2345 return ((STRNICMP(name, "vt", 2) == 0
2346 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 || STRCMP(name, "builtin_vt320") == 0);
2348}
2349
2350/*
2351 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2352 * This should include all windowed terminal emulators.
2353 */
2354 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002355vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356{
2357 if (name == NULL)
2358 return FALSE;
2359 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2360 return TRUE;
2361 return ( STRNICMP(name, "hpterm", 6) == 0
2362 || STRNICMP(name, "sun-cmd", 7) == 0
2363 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002364 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 || STRNICMP(name, "dtterm", 6) == 0);
2366}
2367
2368/*
2369 * Insert user name in s[len].
2370 * Return OK if a name found.
2371 */
2372 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002373mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374{
2375#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002376 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377 return OK;
2378#else
2379 return mch_get_uname(getuid(), s, len);
2380#endif
2381}
2382
2383/*
2384 * Insert user name for "uid" in s[len].
2385 * Return OK if a name found.
2386 */
2387 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002388mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389{
2390#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2391 struct passwd *pw;
2392
2393 if ((pw = getpwuid(uid)) != NULL
2394 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2395 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002396 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 return OK;
2398 }
2399#endif
2400 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2401 return FAIL; /* a number is not a name */
2402}
2403
2404/*
2405 * Insert host name is s[len].
2406 */
2407
2408#ifdef HAVE_SYS_UTSNAME_H
2409 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002410mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
2412 struct utsname vutsname;
2413
2414 if (uname(&vutsname) < 0)
2415 *s = NUL;
2416 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002417 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418}
2419#else /* HAVE_SYS_UTSNAME_H */
2420
2421# ifdef HAVE_SYS_SYSTEMINFO_H
2422# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2423# endif
2424
2425 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002426mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427{
2428# ifdef VAXC
2429 vaxc$gethostname((char *)s, len);
2430# else
2431 gethostname((char *)s, len);
2432# endif
2433 s[len - 1] = NUL; /* make sure it's terminated */
2434}
2435#endif /* HAVE_SYS_UTSNAME_H */
2436
2437/*
2438 * return process ID
2439 */
2440 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002441mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442{
2443 return (long)getpid();
2444}
2445
2446#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002447static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448
2449 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002450strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451{
2452 extern int sys_nerr;
2453 extern char *sys_errlist[];
2454 static char er[20];
2455
2456 if (err > 0 && err < sys_nerr)
2457 return (sys_errlist[err]);
2458 sprintf(er, "Error %d", err);
2459 return er;
2460}
2461#endif
2462
2463/*
2464 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2465 * Return OK for success, FAIL for failure.
2466 */
2467 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002468mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469{
2470#if defined(USE_GETCWD)
2471 if (getcwd((char *)buf, len) == NULL)
2472 {
2473 STRCPY(buf, strerror(errno));
2474 return FAIL;
2475 }
2476 return OK;
2477#else
2478 return (getwd((char *)buf) != NULL ? OK : FAIL);
2479#endif
2480}
2481
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002483 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 *
2485 * return FAIL for failure, OK for success
2486 */
2487 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002488mch_FullName(
2489 char_u *fname,
2490 char_u *buf,
2491 int len,
2492 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
2494 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002495#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 int fd = -1;
2497 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002498#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 char_u olddir[MAXPATHL];
2500 char_u *p;
2501 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002502#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002503 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2504 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002505#endif
2506
Bram Moolenaar38323e42007-03-06 19:22:53 +00002507#ifdef VMS
2508 fname = vms_fixfilename(fname);
2509#endif
2510
Bram Moolenaara2442432007-04-26 14:26:37 +00002511#ifdef __CYGWIN__
2512 /*
2513 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2514 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002515# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002516 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2517 * a forward slash. */
2518 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2519 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002520# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002521 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002522# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002523 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002524#endif
2525
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002526 /* Expand it if forced or not an absolute path.
2527 * Do not do it for "/file", the result is always "/". */
2528 if ((force || !mch_isFullName(fname))
2529 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 {
2531 /*
2532 * If the file name has a path, change to that directory for a moment,
2533 * and then do the getwd() (and get back to where we were).
2534 * This will get the correct path name with "../" things.
2535 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002536 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002538#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 /*
2540 * Use fchdir() if possible, it's said to be faster and more
2541 * reliable. But on SunOS 4 it might not work. Check this by
2542 * doing a fchdir() right now.
2543 */
2544 if (!dont_fchdir)
2545 {
2546 fd = open(".", O_RDONLY | O_EXTRA, 0);
2547 if (fd >= 0 && fchdir(fd) < 0)
2548 {
2549 close(fd);
2550 fd = -1;
2551 dont_fchdir = TRUE; /* don't try again */
2552 }
2553 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002554#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555
2556 /* Only change directory when we are sure we can return to where
2557 * we are now. After doing "su" chdir(".") might not work. */
2558 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002559#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002561#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 (mch_dirname(olddir, MAXPATHL) == FAIL
2563 || mch_chdir((char *)olddir) != 0))
2564 {
2565 p = NULL; /* can't get current dir: don't chdir */
2566 retval = FAIL;
2567 }
2568 else
2569 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570 /* The directory is copied into buf[], to be able to remove
2571 * the file name without changing it (could be a string in
2572 * read-only memory) */
2573 if (p - fname >= len)
2574 retval = FAIL;
2575 else
2576 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002577 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 if (mch_chdir((char *)buf))
2579 retval = FAIL;
2580 else
2581 fname = p + 1;
2582 *buf = NUL;
2583 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 }
2585 }
2586 if (mch_dirname(buf, len) == FAIL)
2587 {
2588 retval = FAIL;
2589 *buf = NUL;
2590 }
2591 if (p != NULL)
2592 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002593#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 if (fd >= 0)
2595 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002596 if (p_verbose >= 5)
2597 {
2598 verbose_enter();
2599 MSG("fchdir() to previous dir");
2600 verbose_leave();
2601 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 l = fchdir(fd);
2603 close(fd);
2604 }
2605 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002606#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607 l = mch_chdir((char *)olddir);
2608 if (l != 0)
2609 EMSG(_(e_prev_dir));
2610 }
2611
2612 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002613 if (l >= len - 1)
2614 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002615#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002616 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002618 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002619#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002621
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002623 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624 return FAIL;
2625
2626 /* Do not append ".", "/dir/." is equal to "/dir". */
2627 if (STRCMP(fname, ".") != 0)
2628 STRCAT(buf, fname);
2629
2630 return OK;
2631}
2632
2633/*
2634 * Return TRUE if "fname" does not depend on the current directory.
2635 */
2636 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002637mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638{
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002639#ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 return ( fname[0] == '/' || fname[0] == '.' ||
2641 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2642 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2643 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002644#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 return (*fname == '/' || *fname == '~');
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646#endif
2647}
2648
Bram Moolenaar24552be2005-12-10 20:17:30 +00002649#if defined(USE_FNAME_CASE) || defined(PROTO)
2650/*
2651 * Set the case of the file name, if it already exists. This will cause the
2652 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002653 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002654 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002655 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002656fname_case(
2657 char_u *name,
2658 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002659{
2660 struct stat st;
2661 char_u *slash, *tail;
2662 DIR *dirp;
2663 struct dirent *dp;
2664
2665 if (lstat((char *)name, &st) >= 0)
2666 {
2667 /* Open the directory where the file is located. */
2668 slash = vim_strrchr(name, '/');
2669 if (slash == NULL)
2670 {
2671 dirp = opendir(".");
2672 tail = name;
2673 }
2674 else
2675 {
2676 *slash = NUL;
2677 dirp = opendir((char *)name);
2678 *slash = '/';
2679 tail = slash + 1;
2680 }
2681
2682 if (dirp != NULL)
2683 {
2684 while ((dp = readdir(dirp)) != NULL)
2685 {
2686 /* Only accept names that differ in case and are the same byte
2687 * length. TODO: accept different length name. */
2688 if (STRICMP(tail, dp->d_name) == 0
2689 && STRLEN(tail) == STRLEN(dp->d_name))
2690 {
2691 char_u newname[MAXPATHL + 1];
2692 struct stat st2;
2693
2694 /* Verify the inode is equal. */
2695 vim_strncpy(newname, name, MAXPATHL);
2696 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2697 MAXPATHL - (tail - name));
2698 if (lstat((char *)newname, &st2) >= 0
2699 && st.st_ino == st2.st_ino
2700 && st.st_dev == st2.st_dev)
2701 {
2702 STRCPY(tail, dp->d_name);
2703 break;
2704 }
2705 }
2706 }
2707
2708 closedir(dirp);
2709 }
2710 }
2711}
2712#endif
2713
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714/*
2715 * Get file permissions for 'name'.
2716 * Returns -1 when it doesn't exist.
2717 */
2718 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002719mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720{
2721 struct stat statb;
2722
2723 /* Keep the #ifdef outside of stat(), it may be a macro. */
2724#ifdef VMS
2725 if (stat((char *)vms_fixfilename(name), &statb))
2726#else
2727 if (stat((char *)name, &statb))
2728#endif
2729 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002730#ifdef __INTERIX
2731 /* The top bit makes the value negative, which means the file doesn't
2732 * exist. Remove the bit, we don't use it. */
2733 return statb.st_mode & ~S_ADDACE;
2734#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002736#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737}
2738
2739/*
2740 * set file permission for 'name' to 'perm'
2741 *
2742 * return FAIL for failure, OK otherwise
2743 */
2744 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002745mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746{
2747 return (chmod((char *)
2748#ifdef VMS
2749 vms_fixfilename(name),
2750#else
2751 name,
2752#endif
2753 (mode_t)perm) == 0 ? OK : FAIL);
2754}
2755
2756#if defined(HAVE_ACL) || defined(PROTO)
2757# ifdef HAVE_SYS_ACL_H
2758# include <sys/acl.h>
2759# endif
2760# ifdef HAVE_SYS_ACCESS_H
2761# include <sys/access.h>
2762# endif
2763
2764# ifdef HAVE_SOLARIS_ACL
2765typedef struct vim_acl_solaris_T {
2766 int acl_cnt;
2767 aclent_t *acl_entry;
2768} vim_acl_solaris_T;
2769# endif
2770
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002771#if defined(HAVE_SELINUX) || defined(PROTO)
2772/*
2773 * Copy security info from "from_file" to "to_file".
2774 */
2775 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002776mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002777{
2778 if (from_file == NULL)
2779 return;
2780
2781 if (selinux_enabled == -1)
2782 selinux_enabled = is_selinux_enabled();
2783
2784 if (selinux_enabled > 0)
2785 {
2786 security_context_t from_context = NULL;
2787 security_context_t to_context = NULL;
2788
2789 if (getfilecon((char *)from_file, &from_context) < 0)
2790 {
2791 /* If the filesystem doesn't support extended attributes,
2792 the original had no special security context and the
2793 target cannot have one either. */
2794 if (errno == EOPNOTSUPP)
2795 return;
2796
2797 MSG_PUTS(_("\nCould not get security context for "));
2798 msg_outtrans(from_file);
2799 msg_putchar('\n');
2800 return;
2801 }
2802 if (getfilecon((char *)to_file, &to_context) < 0)
2803 {
2804 MSG_PUTS(_("\nCould not get security context for "));
2805 msg_outtrans(to_file);
2806 msg_putchar('\n');
2807 freecon (from_context);
2808 return ;
2809 }
2810 if (strcmp(from_context, to_context) != 0)
2811 {
2812 if (setfilecon((char *)to_file, from_context) < 0)
2813 {
2814 MSG_PUTS(_("\nCould not set security context for "));
2815 msg_outtrans(to_file);
2816 msg_putchar('\n');
2817 }
2818 }
2819 freecon(to_context);
2820 freecon(from_context);
2821 }
2822}
2823#endif /* HAVE_SELINUX */
2824
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002825#if defined(HAVE_SMACK) && !defined(PROTO)
2826/*
2827 * Copy security info from "from_file" to "to_file".
2828 */
2829 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002830mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002831{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002832 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002833 {
2834 XATTR_NAME_SMACK,
2835 XATTR_NAME_SMACKEXEC,
2836 XATTR_NAME_SMACKMMAP
2837 };
2838
2839 char buffer[SMACK_LABEL_LEN];
2840 const char *name;
2841 int index;
2842 int ret;
2843 ssize_t size;
2844
2845 if (from_file == NULL)
2846 return;
2847
2848 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2849 / sizeof(smack_copied_attributes)[0]) ; index++)
2850 {
2851 /* get the name of the attribute to copy */
2852 name = smack_copied_attributes[index];
2853
2854 /* get the value of the attribute in buffer */
2855 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2856 if (size >= 0)
2857 {
2858 /* copy the attribute value of buffer */
2859 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2860 if (ret < 0)
2861 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002862 vim_snprintf((char *)IObuff, IOSIZE,
2863 _("Could not set security context %s for %s"),
2864 name, to_file);
2865 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002866 msg_putchar('\n');
2867 }
2868 }
2869 else
2870 {
2871 /* what reason of not having the attribute value? */
2872 switch (errno)
2873 {
2874 case ENOTSUP:
2875 /* extended attributes aren't supported or enabled */
2876 /* should a message be echoed? not sure... */
2877 return; /* leave because it isn't usefull to continue */
2878
2879 case ERANGE:
2880 default:
2881 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002882 vim_snprintf((char *)IObuff, IOSIZE,
2883 _("Could not get security context %s for %s. Removing it!"),
2884 name, from_file);
2885 msg_puts(IObuff);
2886 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002887 /* FALLTHROUGH to remove the attribute */
2888
2889 case ENODATA:
2890 /* no attribute of this name */
2891 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002892 /* Silently ignore errors, apparently this happens when
2893 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002894 break;
2895 }
2896 }
2897 }
2898}
2899#endif /* HAVE_SMACK */
2900
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901/*
2902 * Return a pointer to the ACL of file "fname" in allocated memory.
2903 * Return NULL if the ACL is not available for whatever reason.
2904 */
2905 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002906mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907{
2908 vim_acl_T ret = NULL;
2909#ifdef HAVE_POSIX_ACL
2910 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2911#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002912#ifdef HAVE_SOLARIS_ZFS_ACL
2913 acl_t *aclent;
2914
2915 if (acl_get((char *)fname, 0, &aclent) < 0)
2916 return NULL;
2917 ret = (vim_acl_T)aclent;
2918#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919#ifdef HAVE_SOLARIS_ACL
2920 vim_acl_solaris_T *aclent;
2921
2922 aclent = malloc(sizeof(vim_acl_solaris_T));
2923 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2924 {
2925 free(aclent);
2926 return NULL;
2927 }
2928 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2929 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2930 {
2931 free(aclent->acl_entry);
2932 free(aclent);
2933 return NULL;
2934 }
2935 ret = (vim_acl_T)aclent;
2936#else
2937#if defined(HAVE_AIX_ACL)
2938 int aclsize;
2939 struct acl *aclent;
2940
2941 aclsize = sizeof(struct acl);
2942 aclent = malloc(aclsize);
2943 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2944 {
2945 if (errno == ENOSPC)
2946 {
2947 aclsize = aclent->acl_len;
2948 aclent = realloc(aclent, aclsize);
2949 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2950 {
2951 free(aclent);
2952 return NULL;
2953 }
2954 }
2955 else
2956 {
2957 free(aclent);
2958 return NULL;
2959 }
2960 }
2961 ret = (vim_acl_T)aclent;
2962#endif /* HAVE_AIX_ACL */
2963#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002964#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965#endif /* HAVE_POSIX_ACL */
2966 return ret;
2967}
2968
2969/*
2970 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2971 */
2972 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002973mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974{
2975 if (aclent == NULL)
2976 return;
2977#ifdef HAVE_POSIX_ACL
2978 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2979#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002980#ifdef HAVE_SOLARIS_ZFS_ACL
2981 acl_set((char *)fname, (acl_t *)aclent);
2982#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983#ifdef HAVE_SOLARIS_ACL
2984 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2985 ((vim_acl_solaris_T *)aclent)->acl_entry);
2986#else
2987#ifdef HAVE_AIX_ACL
2988 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2989#endif /* HAVE_AIX_ACL */
2990#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002991#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992#endif /* HAVE_POSIX_ACL */
2993}
2994
2995 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002996mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997{
2998 if (aclent == NULL)
2999 return;
3000#ifdef HAVE_POSIX_ACL
3001 acl_free((acl_t)aclent);
3002#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003003#ifdef HAVE_SOLARIS_ZFS_ACL
3004 acl_free((acl_t *)aclent);
3005#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006#ifdef HAVE_SOLARIS_ACL
3007 free(((vim_acl_solaris_T *)aclent)->acl_entry);
3008 free(aclent);
3009#else
3010#ifdef HAVE_AIX_ACL
3011 free(aclent);
3012#endif /* HAVE_AIX_ACL */
3013#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003014#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015#endif /* HAVE_POSIX_ACL */
3016}
3017#endif
3018
3019/*
3020 * Set hidden flag for "name".
3021 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003023mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024{
3025 /* can't hide a file */
3026}
3027
3028/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003029 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 * return FALSE if "name" is not a directory
3031 * return FALSE for error
3032 */
3033 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003034mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035{
3036 struct stat statb;
3037
3038 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3039 return FALSE;
3040 if (stat((char *)name, &statb))
3041 return FALSE;
3042#ifdef _POSIX_SOURCE
3043 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3044#else
3045 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3046#endif
3047}
3048
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003049/*
3050 * return TRUE if "name" is a directory, NOT a symlink to a directory
3051 * return FALSE if "name" is not a directory
3052 * return FALSE for error
3053 */
3054 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003055mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003056{
3057 struct stat statb;
3058
3059 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3060 return FALSE;
3061 if (lstat((char *)name, &statb))
3062 return FALSE;
3063#ifdef _POSIX_SOURCE
3064 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3065#else
3066 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3067#endif
3068}
3069
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003070static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071
3072/*
3073 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3074 */
3075 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003076executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077{
3078 struct stat st;
3079
3080 if (stat((char *)name, &st))
3081 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003082#ifdef VMS
3083 /* Like on Unix system file can have executable rights but not necessarily
3084 * be an executable, but on Unix is not a default for an ordianry file to
3085 * have an executable flag - on VMS it is in most cases.
3086 * Therefore, this check does not have any sense - let keep us to the
3087 * conventions instead:
3088 * *.COM and *.EXE files are the executables - the rest are not. This is
3089 * not ideal but better then it was.
3090 */
3091 int vms_executable = 0;
3092 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3093 {
3094 if (strstr(vms_tolower((char*)name),".exe") != NULL
3095 || strstr(vms_tolower((char*)name),".com")!= NULL)
3096 vms_executable = 1;
3097 }
3098 return vms_executable;
3099#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003101#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102}
3103
3104/*
3105 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003106 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 * Return -1 if unknown.
3108 */
3109 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003110mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111{
3112 char_u *buf;
3113 char_u *p, *e;
3114 int retval;
3115
Bram Moolenaarb5971142015-03-21 17:32:19 +01003116 /* When "use_path" is false and if it's an absolute or relative path don't
3117 * need to use $PATH. */
3118 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3119 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003120 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003121 /* There must be a path separator, files in the current directory
3122 * can't be executed. */
3123 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003124 {
3125 if (path != NULL)
3126 {
3127 if (name[0] == '.')
3128 *path = FullName_save(name, TRUE);
3129 else
3130 *path = vim_strsave(name);
3131 }
3132 return TRUE;
3133 }
3134 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136
3137 p = (char_u *)getenv("PATH");
3138 if (p == NULL || *p == NUL)
3139 return -1;
3140 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3141 if (buf == NULL)
3142 return -1;
3143
3144 /*
3145 * Walk through all entries in $PATH to check if "name" exists there and
3146 * is an executable file.
3147 */
3148 for (;;)
3149 {
3150 e = (char_u *)strchr((char *)p, ':');
3151 if (e == NULL)
3152 e = p + STRLEN(p);
3153 if (e - p <= 1) /* empty entry means current dir */
3154 STRCPY(buf, "./");
3155 else
3156 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003157 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 add_pathsep(buf);
3159 }
3160 STRCAT(buf, name);
3161 retval = executable_file(buf);
3162 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003163 {
3164 if (path != NULL)
3165 {
3166 if (buf[0] == '.')
3167 *path = FullName_save(buf, TRUE);
3168 else
3169 *path = vim_strsave(buf);
3170 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003172 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173
3174 if (*e != ':')
3175 break;
3176 p = e + 1;
3177 }
3178
3179 vim_free(buf);
3180 return retval;
3181}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182
3183/*
3184 * Check what "name" is:
3185 * NODE_NORMAL: file or directory (or doesn't exist)
3186 * NODE_WRITABLE: writable device, socket, fifo, etc.
3187 * NODE_OTHER: non-writable things
3188 */
3189 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003190mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191{
3192 struct stat st;
3193
3194 if (stat((char *)name, &st))
3195 return NODE_NORMAL;
3196 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3197 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3199 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 /* Everything else is writable? */
3201 return NODE_WRITABLE;
3202}
3203
3204 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003205mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206{
3207#ifdef HAVE_CHECK_STACK_GROWTH
3208 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 check_stack_growth((char *)&i);
3211
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003212# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 get_stack_limit();
3214# endif
3215
3216#endif
3217
3218 /*
3219 * Setup an alternative stack for signals. Helps to catch signals when
3220 * running out of stack space.
3221 * Use of sigaltstack() is preferred, it's more portable.
3222 * Ignore any errors.
3223 */
3224#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003225 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 init_signal_stack();
3227#endif
3228}
3229
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003230#if defined(EXITFREE) || defined(PROTO)
3231 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003232mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003233{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003234# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3235 if (clip_star.owned)
3236 clip_lose_selection(&clip_star);
3237 if (clip_plus.owned)
3238 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003239# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003240# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003241 if (xterm_Shell != (Widget)0)
3242 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003243# ifndef LESSTIF_VERSION
3244 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003245 if (xterm_dpy != NULL)
3246 XtCloseDisplay(xterm_dpy);
3247 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003248 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003249 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003250# ifdef FEAT_X11
3251 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3252# endif
3253 }
3254# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003255# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003256# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003257 if (x11_display != NULL
3258# ifdef FEAT_XCLIPBOARD
3259 && x11_display != xterm_dpy
3260# endif
3261 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003262 XCloseDisplay(x11_display);
3263# endif
3264# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3265 vim_free(signal_stack);
3266 signal_stack = NULL;
3267# endif
3268# ifdef FEAT_TITLE
3269 vim_free(oldtitle);
3270 vim_free(oldicon);
3271# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003272}
3273#endif
3274
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003275static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276
3277/*
3278 * Output a newline when exiting.
3279 * Make sure the newline goes to the same stream as the text.
3280 */
3281 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003282exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003284 if (silent_mode)
3285 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286 if (newline_on_exit || msg_didout)
3287 {
3288 if (msg_use_printf())
3289 {
3290 if (info_message)
3291 mch_msg("\n");
3292 else
3293 mch_errmsg("\r\n");
3294 }
3295 else
3296 out_char('\n');
3297 }
3298 else
3299 {
3300 restore_cterm_colors(); /* get original colors back */
3301 msg_clr_eos_force(); /* clear the rest of the display */
3302 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3303 }
3304}
3305
3306 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003307mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308{
3309 exiting = TRUE;
3310
3311#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3312 x11_export_final_selection();
3313#endif
3314
3315#ifdef FEAT_GUI
3316 if (!gui.in_use)
3317#endif
3318 {
3319 settmode(TMODE_COOK);
3320#ifdef FEAT_TITLE
3321 mch_restore_title(3); /* restore xterm title and icon name */
3322#endif
3323 /*
3324 * When t_ti is not empty but it doesn't cause swapping terminal
3325 * pages, need to output a newline when msg_didout is set. But when
3326 * t_ti does swap pages it should not go to the shell page. Do this
3327 * before stoptermcap().
3328 */
3329 if (swapping_screen() && !newline_on_exit)
3330 exit_scroll();
3331
3332 /* Stop termcap: May need to check for T_CRV response, which
3333 * requires RAW mode. */
3334 stoptermcap();
3335
3336 /*
3337 * A newline is only required after a message in the alternate screen.
3338 * This is set to TRUE by wait_return().
3339 */
3340 if (!swapping_screen() || newline_on_exit)
3341 exit_scroll();
3342
3343 /* Cursor may have been switched off without calling starttermcap()
3344 * when doing "vim -u vimrc" and vimrc contains ":q". */
3345 if (full_screen)
3346 cursor_on();
3347 }
3348 out_flush();
3349 ml_close_all(TRUE); /* remove all memfiles */
3350 may_core_dump();
3351#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 gui_exit(r);
3354#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003355
Bram Moolenaar56718732006-03-15 22:53:57 +00003356#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003357 mac_conv_cleanup();
3358#endif
3359
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360#ifdef __QNX__
3361 /* A core dump won't be created if the signal handler
3362 * doesn't return, so we can't call exit() */
3363 if (deadly_signal != 0)
3364 return;
3365#endif
3366
Bram Moolenaar009b2592004-10-24 19:18:58 +00003367#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003368 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003369#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003370
3371#ifdef EXITFREE
3372 free_all_mem();
3373#endif
3374
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 exit(r);
3376}
3377
3378 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003379may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380{
3381 if (deadly_signal != 0)
3382 {
3383 signal(deadly_signal, SIG_DFL);
3384 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3385 }
3386}
3387
3388#ifndef VMS
3389
3390 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003391mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392{
3393 static int first = TRUE;
3394
3395 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3396#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3397 /*
3398 * for "new" tty systems
3399 */
3400# ifdef HAVE_TERMIOS_H
3401 static struct termios told;
3402 struct termios tnew;
3403# else
3404 static struct termio told;
3405 struct termio tnew;
3406# endif
3407
3408 if (first)
3409 {
3410 first = FALSE;
3411# if defined(HAVE_TERMIOS_H)
3412 tcgetattr(read_cmd_fd, &told);
3413# else
3414 ioctl(read_cmd_fd, TCGETA, &told);
3415# endif
3416 }
3417
3418 tnew = told;
3419 if (tmode == TMODE_RAW)
3420 {
3421 /*
3422 * ~ICRNL enables typing ^V^M
3423 */
3424 tnew.c_iflag &= ~ICRNL;
3425 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3426# if defined(IEXTEN) && !defined(__MINT__)
3427 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3428 /* but it breaks function keys on MINT */
3429# endif
3430 );
3431# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3432 tnew.c_oflag &= ~ONLCR;
3433# endif
3434 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3435 tnew.c_cc[VTIME] = 0; /* don't wait */
3436 }
3437 else if (tmode == TMODE_SLEEP)
Bram Moolenaar40de4562016-07-01 15:03:46 +02003438 {
3439 /* Also reset ICANON here, otherwise on Solaris select() won't see
3440 * typeahead characters. */
3441 tnew.c_lflag &= ~(ICANON | ECHO);
3442 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3443 tnew.c_cc[VTIME] = 0; /* don't wait */
3444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445
3446# if defined(HAVE_TERMIOS_H)
3447 {
3448 int n = 10;
3449
3450 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3451 * few times. */
3452 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3453 && errno == EINTR && n > 0)
3454 --n;
3455 }
3456# else
3457 ioctl(read_cmd_fd, TCSETA, &tnew);
3458# endif
3459
3460#else
3461
3462 /*
3463 * for "old" tty systems
3464 */
3465# ifndef TIOCSETN
3466# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3467# endif
3468 static struct sgttyb ttybold;
3469 struct sgttyb ttybnew;
3470
3471 if (first)
3472 {
3473 first = FALSE;
3474 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3475 }
3476
3477 ttybnew = ttybold;
3478 if (tmode == TMODE_RAW)
3479 {
3480 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3481 ttybnew.sg_flags |= RAW;
3482 }
3483 else if (tmode == TMODE_SLEEP)
3484 ttybnew.sg_flags &= ~(ECHO);
3485 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3486#endif
3487 curr_tmode = tmode;
3488}
3489
3490/*
3491 * Try to get the code for "t_kb" from the stty setting
3492 *
3493 * Even if termcap claims a backspace key, the user's setting *should*
3494 * prevail. stty knows more about reality than termcap does, and if
3495 * somebody's usual erase key is DEL (which, for most BSD users, it will
3496 * be), they're going to get really annoyed if their erase key starts
3497 * doing forward deletes for no reason. (Eric Fischer)
3498 */
3499 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003500get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501{
3502 char_u buf[2];
3503 char_u *p;
3504
3505 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3506#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3507 /* for "new" tty systems */
3508# ifdef HAVE_TERMIOS_H
3509 struct termios keys;
3510# else
3511 struct termio keys;
3512# endif
3513
3514# if defined(HAVE_TERMIOS_H)
3515 if (tcgetattr(read_cmd_fd, &keys) != -1)
3516# else
3517 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3518# endif
3519 {
3520 buf[0] = keys.c_cc[VERASE];
3521 intr_char = keys.c_cc[VINTR];
3522#else
3523 /* for "old" tty systems */
3524 struct sgttyb keys;
3525
3526 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3527 {
3528 buf[0] = keys.sg_erase;
3529 intr_char = keys.sg_kill;
3530#endif
3531 buf[1] = NUL;
3532 add_termcode((char_u *)"kb", buf, FALSE);
3533
3534 /*
3535 * If <BS> and <DEL> are now the same, redefine <DEL>.
3536 */
3537 p = find_termcode((char_u *)"kD");
3538 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3539 do_fixdel(NULL);
3540 }
3541#if 0
3542 } /* to keep cindent happy */
3543#endif
3544}
3545
3546#endif /* VMS */
3547
3548#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3549/*
3550 * Set mouse clicks on or off.
3551 */
3552 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003553mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554{
3555 static int ison = FALSE;
3556 int xterm_mouse_vers;
3557
3558 if (on == ison) /* return quickly if nothing to do */
3559 return;
3560
3561 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003562
3563# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003564 if (ttym_flags == TTYM_URXVT)
3565 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003566 out_str_nf((char_u *)
3567 (on
3568 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3569 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3570 ison = on;
3571 }
3572# endif
3573
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003574# ifdef FEAT_MOUSE_SGR
3575 if (ttym_flags == TTYM_SGR)
3576 {
3577 out_str_nf((char_u *)
3578 (on
3579 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3580 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3581 ison = on;
3582 }
3583# endif
3584
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 if (xterm_mouse_vers > 0)
3586 {
3587 if (on) /* enable mouse events, use mouse tracking if available */
3588 out_str_nf((char_u *)
3589 (xterm_mouse_vers > 1
3590 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3591 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3592 else /* disable mouse events, could probably always send the same */
3593 out_str_nf((char_u *)
3594 (xterm_mouse_vers > 1
3595 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3596 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3597 ison = on;
3598 }
3599
3600# ifdef FEAT_MOUSE_DEC
3601 else if (ttym_flags == TTYM_DEC)
3602 {
3603 if (on) /* enable mouse events */
3604 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3605 else /* disable mouse events */
3606 out_str_nf((char_u *)"\033['z");
3607 ison = on;
3608 }
3609# endif
3610
3611# ifdef FEAT_MOUSE_GPM
3612 else
3613 {
3614 if (on)
3615 {
3616 if (gpm_open())
3617 ison = TRUE;
3618 }
3619 else
3620 {
3621 gpm_close();
3622 ison = FALSE;
3623 }
3624 }
3625# endif
3626
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003627# ifdef FEAT_SYSMOUSE
3628 else
3629 {
3630 if (on)
3631 {
3632 if (sysmouse_open() == OK)
3633 ison = TRUE;
3634 }
3635 else
3636 {
3637 sysmouse_close();
3638 ison = FALSE;
3639 }
3640 }
3641# endif
3642
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643# ifdef FEAT_MOUSE_JSB
3644 else
3645 {
3646 if (on)
3647 {
3648 /* D - Enable Mouse up/down messages
3649 * L - Enable Left Button Reporting
3650 * M - Enable Middle Button Reporting
3651 * R - Enable Right Button Reporting
3652 * K - Enable SHIFT and CTRL key Reporting
3653 * + - Enable Advanced messaging of mouse moves and up/down messages
3654 * Q - Quiet No Ack
3655 * # - Numeric value of mouse pointer required
3656 * 0 = Multiview 2000 cursor, used as standard
3657 * 1 = Windows Arrow
3658 * 2 = Windows I Beam
3659 * 3 = Windows Hour Glass
3660 * 4 = Windows Cross Hair
3661 * 5 = Windows UP Arrow
3662 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003663# ifdef JSBTERM_MOUSE_NONADVANCED
3664 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3666 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003667# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3669 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003670# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671 ison = TRUE;
3672 }
3673 else
3674 {
3675 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3676 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3677 ison = FALSE;
3678 }
3679 }
3680# endif
3681# ifdef FEAT_MOUSE_PTERM
3682 else
3683 {
3684 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3685 if (on)
3686 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3687 else
3688 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3689 ison = on;
3690 }
3691# endif
3692}
3693
3694/*
3695 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3696 */
3697 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003698check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699{
3700# ifdef FEAT_MOUSE_XTERM
3701 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003702# ifdef FEAT_MOUSE_URXVT
3703 && use_xterm_mouse() != 3
3704# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705# ifdef FEAT_GUI
3706 && !gui.in_use
3707# endif
3708 )
3709 {
3710 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003711 ? IF_EB("\233M", CSI_STR "M")
3712 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 if (*p_mouse != NUL)
3714 {
3715 /* force mouse off and maybe on to send possibly new mouse
3716 * activation sequence to the xterm, with(out) drag tracing. */
3717 mch_setmouse(FALSE);
3718 setmouse();
3719 }
3720 }
3721 else
3722 del_mouse_termcode(KS_MOUSE);
3723# endif
3724
3725# ifdef FEAT_MOUSE_GPM
3726 if (!use_xterm_mouse()
3727# ifdef FEAT_GUI
3728 && !gui.in_use
3729# endif
3730 )
3731 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3732# endif
3733
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003734# ifdef FEAT_SYSMOUSE
3735 if (!use_xterm_mouse()
3736# ifdef FEAT_GUI
3737 && !gui.in_use
3738# endif
3739 )
3740 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3741# endif
3742
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003744 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 if (!use_xterm_mouse()
3746# ifdef FEAT_GUI
3747 && !gui.in_use
3748# endif
3749 )
3750 set_mouse_termcode(KS_JSBTERM_MOUSE,
3751 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3752 else
3753 del_mouse_termcode(KS_JSBTERM_MOUSE);
3754# endif
3755
3756# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003757 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 * define it in the GUI or when using an xterm. */
3759 if (!use_xterm_mouse()
3760# ifdef FEAT_GUI
3761 && !gui.in_use
3762# endif
3763 )
3764 set_mouse_termcode(KS_NETTERM_MOUSE,
3765 (char_u *)IF_EB("\033}", ESC_STR "}"));
3766 else
3767 del_mouse_termcode(KS_NETTERM_MOUSE);
3768# endif
3769
3770# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003771 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003772 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773# ifdef FEAT_GUI
3774 && !gui.in_use
3775# endif
3776 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003777 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3778 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 else
3780 del_mouse_termcode(KS_DEC_MOUSE);
3781# endif
3782# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003783 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003784 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785# ifdef FEAT_GUI
3786 && !gui.in_use
3787# endif
3788 )
3789 set_mouse_termcode(KS_PTERM_MOUSE,
3790 (char_u *) IF_EB("\033[", ESC_STR "["));
3791 else
3792 del_mouse_termcode(KS_PTERM_MOUSE);
3793# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003794# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003795 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003796 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003797# ifdef FEAT_GUI
3798 && !gui.in_use
3799# endif
3800 )
3801 {
3802 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3803 ? IF_EB("\233", CSI_STR)
3804 : IF_EB("\033[", ESC_STR "[")));
3805
3806 if (*p_mouse != NUL)
3807 {
3808 mch_setmouse(FALSE);
3809 setmouse();
3810 }
3811 }
3812 else
3813 del_mouse_termcode(KS_URXVT_MOUSE);
3814# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003815# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003816 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003817 if (use_xterm_mouse() == 4
3818# ifdef FEAT_GUI
3819 && !gui.in_use
3820# endif
3821 )
3822 {
3823 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3824 ? IF_EB("\233<", CSI_STR "<")
3825 : IF_EB("\033[<", ESC_STR "[<")));
3826
3827 if (*p_mouse != NUL)
3828 {
3829 mch_setmouse(FALSE);
3830 setmouse();
3831 }
3832 }
3833 else
3834 del_mouse_termcode(KS_SGR_MOUSE);
3835# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836}
3837#endif
3838
3839/*
3840 * set screen mode, always fails.
3841 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003843mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844{
3845 EMSG(_(e_screenmode));
3846 return FAIL;
3847}
3848
3849#ifndef VMS
3850
3851/*
3852 * Try to get the current window size:
3853 * 1. with an ioctl(), most accurate method
3854 * 2. from the environment variables LINES and COLUMNS
3855 * 3. from the termcap
3856 * 4. keep using the old values
3857 * Return OK when size could be determined, FAIL otherwise.
3858 */
3859 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003860mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861{
3862 long rows = 0;
3863 long columns = 0;
3864 char_u *p;
3865
3866 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 * 1. try using an ioctl. It is the most accurate method.
3868 *
3869 * Try using TIOCGWINSZ first, some systems that have it also define
3870 * TIOCGSIZE but don't have a struct ttysize.
3871 */
3872# ifdef TIOCGWINSZ
3873 {
3874 struct winsize ws;
3875 int fd = 1;
3876
3877 /* When stdout is not a tty, use stdin for the ioctl(). */
3878 if (!isatty(fd) && isatty(read_cmd_fd))
3879 fd = read_cmd_fd;
3880 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3881 {
3882 columns = ws.ws_col;
3883 rows = ws.ws_row;
3884 }
3885 }
3886# else /* TIOCGWINSZ */
3887# ifdef TIOCGSIZE
3888 {
3889 struct ttysize ts;
3890 int fd = 1;
3891
3892 /* When stdout is not a tty, use stdin for the ioctl(). */
3893 if (!isatty(fd) && isatty(read_cmd_fd))
3894 fd = read_cmd_fd;
3895 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3896 {
3897 columns = ts.ts_cols;
3898 rows = ts.ts_lines;
3899 }
3900 }
3901# endif /* TIOCGSIZE */
3902# endif /* TIOCGWINSZ */
3903
3904 /*
3905 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003906 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3907 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003909 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 {
3911 if ((p = (char_u *)getenv("LINES")))
3912 rows = atoi((char *)p);
3913 if ((p = (char_u *)getenv("COLUMNS")))
3914 columns = atoi((char *)p);
3915 }
3916
3917#ifdef HAVE_TGETENT
3918 /*
3919 * 3. try reading "co" and "li" entries from termcap
3920 */
3921 if (columns == 0 || rows == 0)
3922 getlinecol(&columns, &rows);
3923#endif
3924
3925 /*
3926 * 4. If everything fails, use the old values
3927 */
3928 if (columns <= 0 || rows <= 0)
3929 return FAIL;
3930
3931 Rows = rows;
3932 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003933 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 return OK;
3935}
3936
3937/*
3938 * Try to set the window size to Rows and Columns.
3939 */
3940 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003941mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942{
3943 if (*T_CWS)
3944 {
3945 /*
3946 * NOTE: if you get an error here that term_set_winsize() is
3947 * undefined, check the output of configure. It could probably not
3948 * find a ncurses, termcap or termlib library.
3949 */
3950 term_set_winsize((int)Rows, (int)Columns);
3951 out_flush();
3952 screen_start(); /* don't know where cursor is now */
3953 }
3954}
3955
3956#endif /* VMS */
3957
3958/*
3959 * Rows and/or Columns has changed.
3960 */
3961 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003962mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963{
3964 /* Nothing to do. */
3965}
3966
Bram Moolenaar205b8862011-09-07 15:04:31 +02003967/*
3968 * Wait for process "child" to end.
3969 * Return "child" if it exited properly, <= 0 on error.
3970 */
3971 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003972wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003973{
3974 pid_t wait_pid = 0;
Bram Moolenaar0abe0522016-08-28 16:53:12 +02003975 long delay_msec = 1;
Bram Moolenaar205b8862011-09-07 15:04:31 +02003976
3977 while (wait_pid != child)
3978 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003979 /* When compiled with Python threads are probably used, in which case
3980 * wait() sometimes hangs for no obvious reason. Use waitpid()
3981 * instead and loop (like the GUI). Also needed for other interfaces,
3982 * they might call system(). */
3983# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003984 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003985# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003986 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003987# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003988 if (wait_pid == 0)
3989 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02003990 /* Wait for 1 to 10 msec before trying again. */
3991 mch_delay(delay_msec, TRUE);
3992 if (++delay_msec > 10)
3993 delay_msec = 10;
Bram Moolenaar205b8862011-09-07 15:04:31 +02003994 continue;
3995 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003996 if (wait_pid <= 0
3997# ifdef ECHILD
3998 && errno == ECHILD
3999# endif
4000 )
4001 break;
4002 }
4003 return wait_pid;
4004}
4005
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004006#if defined(FEAT_JOB_CHANNEL) || !defined(USE_SYSTEM) || defined(PROTO)
Bram Moolenaar72801402016-02-09 11:37:50 +01004007/*
4008 * Parse "cmd" and put the white-separated parts in "argv".
4009 * "argv" is an allocated array with "argc" entries.
4010 * Returns FAIL when out of memory.
4011 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01004012 int
4013mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
4014{
4015 int i;
4016 char_u *p;
4017 int inquote;
4018
4019 /*
4020 * Do this loop twice:
4021 * 1: find number of arguments
4022 * 2: separate them and build argv[]
4023 */
4024 for (i = 0; i < 2; ++i)
4025 {
Bram Moolenaar6231cb82016-04-26 19:42:42 +02004026 p = skipwhite(cmd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01004027 inquote = FALSE;
4028 *argc = 0;
4029 for (;;)
4030 {
4031 if (i == 1)
4032 (*argv)[*argc] = (char *)p;
4033 ++*argc;
4034 while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
4035 {
4036 if (*p == '"')
4037 inquote = !inquote;
4038 ++p;
4039 }
4040 if (*p == NUL)
4041 break;
4042 if (i == 1)
4043 *p++ = NUL;
4044 p = skipwhite(p);
4045 }
4046 if (*argv == NULL)
4047 {
4048 if (use_shcf)
4049 {
4050 /* Account for possible multiple args in p_shcf. */
4051 p = p_shcf;
4052 for (;;)
4053 {
4054 p = skiptowhite(p);
4055 if (*p == NUL)
4056 break;
4057 ++*argc;
4058 p = skipwhite(p);
4059 }
4060 }
4061
4062 *argv = (char **)alloc((unsigned)((*argc + 4) * sizeof(char *)));
4063 if (*argv == NULL) /* out of memory */
4064 return FAIL;
4065 }
4066 }
4067 return OK;
4068}
4069#endif
4070
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004071#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004072 static void
4073set_child_environment(void)
4074{
4075# ifdef HAVE_SETENV
4076 char envbuf[50];
4077# else
4078 static char envbuf_Rows[20];
4079 static char envbuf_Columns[20];
4080# endif
4081
4082 /* Simulate to have a dumb terminal (for now) */
4083# ifdef HAVE_SETENV
4084 setenv("TERM", "dumb", 1);
4085 sprintf((char *)envbuf, "%ld", Rows);
4086 setenv("ROWS", (char *)envbuf, 1);
4087 sprintf((char *)envbuf, "%ld", Rows);
4088 setenv("LINES", (char *)envbuf, 1);
4089 sprintf((char *)envbuf, "%ld", Columns);
4090 setenv("COLUMNS", (char *)envbuf, 1);
4091# else
4092 /*
4093 * Putenv does not copy the string, it has to remain valid.
4094 * Use a static array to avoid losing allocated memory.
4095 */
4096 putenv("TERM=dumb");
4097 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4098 putenv(envbuf_Rows);
4099 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4100 putenv(envbuf_Rows);
4101 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4102 putenv(envbuf_Columns);
4103# endif
4104}
4105#endif
4106
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004108mch_call_shell(
4109 char_u *cmd,
4110 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111{
4112#ifdef VMS
4113 char *ifn = NULL;
4114 char *ofn = NULL;
4115#endif
4116 int tmode = cur_tmode;
4117#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
Bram Moolenaarb2b050a2016-07-16 21:52:46 +02004118 char_u *newcmd; /* only needed for unix */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119
4120 out_flush();
4121
4122 if (options & SHELL_COOKED)
4123 settmode(TMODE_COOK); /* set to normal mode */
4124
Bram Moolenaar62b42182010-09-21 22:09:37 +02004125# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004126 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004127 loose_clipboard();
4128# endif
4129
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 if (cmd == NULL)
4131 x = system((char *)p_sh);
4132 else
4133 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004134# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 if (ofn = strchr((char *)cmd, '>'))
4136 *ofn++ = '\0';
4137 if (ifn = strchr((char *)cmd, '<'))
4138 {
4139 char *p;
4140
4141 *ifn++ = '\0';
4142 p = strchr(ifn,' '); /* chop off any trailing spaces */
4143 if (p)
4144 *p = '\0';
4145 }
4146 if (ofn)
4147 x = vms_sys((char *)cmd, ofn, ifn);
4148 else
4149 x = system((char *)cmd);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004150# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 newcmd = lalloc(STRLEN(p_sh)
4152 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4153 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4154 if (newcmd == NULL)
4155 x = 0;
4156 else
4157 {
4158 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4159 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4160 (char *)p_shcf,
4161 (char *)cmd);
4162 x = system((char *)newcmd);
4163 vim_free(newcmd);
4164 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004165# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 }
4167# ifdef VMS
4168 x = vms_sys_status(x);
4169# endif
4170 if (emsg_silent)
4171 ;
4172 else if (x == 127)
4173 MSG_PUTS(_("\nCannot execute shell sh\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 else if (x && !(options & SHELL_SILENT))
4175 {
4176 MSG_PUTS(_("\nshell returned "));
4177 msg_outnum((long)x);
4178 msg_putchar('\n');
4179 }
4180
4181 if (tmode == TMODE_RAW)
4182 settmode(TMODE_RAW); /* set to raw mode */
4183# ifdef FEAT_TITLE
4184 resettitle();
4185# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004186# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4187 restore_clipboard();
4188# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 return x;
4190
4191#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4192
Bram Moolenaardf177f62005-02-22 08:39:57 +00004193# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4194 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195
Bram Moolenaar835dc632016-02-07 14:27:38 +01004196 char_u *newcmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004198 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 pid_t wait_pid = 0;
4200# ifdef HAVE_UNION_WAIT
4201 union wait status;
4202# else
4203 int status = -1;
4204# endif
4205 int retval = -1;
4206 char **argv = NULL;
4207 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004208 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 int i;
4210 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004212# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004213 int pty_slave_fd = -1;
4214 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004215# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004216 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 int fd_fromshell[2];
4218 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004219 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220
Bram Moolenaar62b42182010-09-21 22:09:37 +02004221 newcmd = vim_strsave(p_sh);
4222 if (newcmd == NULL) /* out of memory */
4223 goto error;
4224
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225 out_flush();
4226 if (options & SHELL_COOKED)
4227 settmode(TMODE_COOK); /* set to normal mode */
4228
Bram Moolenaar835dc632016-02-07 14:27:38 +01004229 if (mch_parse_cmd(newcmd, TRUE, &argv, &argc) == FAIL)
4230 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004231
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232 if (cmd != NULL)
4233 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004234 char_u *s;
4235
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 if (extra_shell_arg != NULL)
4237 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004238
4239 /* Break 'shellcmdflag' into white separated parts. This doesn't
4240 * handle quoted strings, they are very unlikely to appear. */
4241 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4242 if (p_shcf_copy == NULL) /* out of memory */
4243 goto error;
4244 s = p_shcf_copy;
4245 p = p_shcf;
4246 while (*p != NUL)
4247 {
4248 argv[argc++] = (char *)s;
4249 while (*p && *p != ' ' && *p != TAB)
4250 *s++ = *p++;
4251 *s++ = NUL;
4252 p = skipwhite(p);
4253 }
4254
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255 argv[argc++] = (char *)cmd;
4256 }
4257 argv[argc] = NULL;
4258
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004260 * For the GUI, when writing the output into the buffer and when reading
4261 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4262 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004264 if ((options & (SHELL_READ|SHELL_WRITE))
4265# ifdef FEAT_GUI
4266 || (gui.in_use && show_shell_mess)
4267# endif
4268 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004270# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 /*
4272 * Try to open a master pty.
4273 * If this works, open the slave pty.
4274 * If the slave can't be opened, close the master pty.
4275 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004276 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 {
4278 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004279 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004281 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4282 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4283 * adding O_NOCTTY always works when defined. */
4284#ifdef O_NOCTTY
4285 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4286#else
4287 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4288#endif
4289 if (pty_slave_fd < 0)
4290 {
4291 close(pty_master_fd);
4292 pty_master_fd = -1;
4293 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 }
4295 }
4296 /*
4297 * If not opening a pty or it didn't work, try using pipes.
4298 */
4299 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004300# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 {
4302 pipe_error = (pipe(fd_toshell) < 0);
4303 if (!pipe_error) /* pipe create OK */
4304 {
4305 pipe_error = (pipe(fd_fromshell) < 0);
4306 if (pipe_error) /* pipe create failed */
4307 {
4308 close(fd_toshell[0]);
4309 close(fd_toshell[1]);
4310 }
4311 }
4312 if (pipe_error)
4313 {
4314 MSG_PUTS(_("\nCannot create pipes\n"));
4315 out_flush();
4316 }
4317 }
4318 }
4319
4320 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004322 SIGSET_DECL(curset)
4323
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324# ifdef __BEOS__
4325 beos_cleanup_read_thread();
4326# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004327
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004328 BLOCK_SIGNALS(&curset);
4329 pid = fork(); /* maybe we should use vfork() */
4330 if (pid == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004332 UNBLOCK_SIGNALS(&curset);
4333
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004335 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004337 || (gui.in_use && show_shell_mess)
4338# endif
4339 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004341# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 if (pty_master_fd >= 0) /* close the pseudo tty */
4343 {
4344 close(pty_master_fd);
4345 close(pty_slave_fd);
4346 }
4347 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004348# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004349 {
4350 close(fd_toshell[0]);
4351 close(fd_toshell[1]);
4352 close(fd_fromshell[0]);
4353 close(fd_fromshell[1]);
4354 }
4355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 }
4357 else if (pid == 0) /* child */
4358 {
4359 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004360 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361
4362 if (!show_shell_mess || (options & SHELL_EXPAND))
4363 {
4364 int fd;
4365
4366 /*
4367 * Don't want to show any message from the shell. Can't just
4368 * close stdout and stderr though, because some systems will
4369 * break if you try to write to them after that, so we must
4370 * use dup() to replace them with something else -- webb
4371 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4372 * waiting for input.
4373 */
4374 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4375 fclose(stdin);
4376 fclose(stdout);
4377 fclose(stderr);
4378
4379 /*
4380 * If any of these open()'s and dup()'s fail, we just continue
4381 * anyway. It's not fatal, and on most systems it will make
4382 * no difference at all. On a few it will cause the execvp()
4383 * to exit with a non-zero status even when the completion
4384 * could be done, which is nothing too serious. If the open()
4385 * or dup() failed we'd just do the same thing ourselves
4386 * anyway -- webb
4387 */
4388 if (fd >= 0)
4389 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004390 ignored = dup(fd); /* To replace stdin (fd 0) */
4391 ignored = dup(fd); /* To replace stdout (fd 1) */
4392 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393
4394 /* Don't need this now that we've duplicated it */
4395 close(fd);
4396 }
4397 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004398 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004400 || gui.in_use
4401# endif
4402 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 {
4404
Bram Moolenaardf177f62005-02-22 08:39:57 +00004405# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004406 /* Create our own process group, so that the child and all its
4407 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004408 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004409 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004410 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004411 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004412# if defined(SIGHUP)
4413 /* When doing "!xterm&" and 'shell' is bash: the shell
4414 * will exit and send SIGHUP to all processes in its
4415 * group, killing the just started process. Ignore SIGHUP
4416 * to avoid that. (suggested by Simon Schubert)
4417 */
4418 signal(SIGHUP, SIG_IGN);
4419# endif
4420 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004421# endif
4422# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004423 if (pty_slave_fd >= 0)
4424 {
4425 /* push stream discipline modules */
4426 if (options & SHELL_COOKED)
4427 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004429 /* Try to become controlling tty (probably doesn't work,
4430 * unless run by root) */
4431 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004433 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004434# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004435 set_child_environment();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436
Bram Moolenaara5792f52005-11-23 21:25:05 +00004437 /*
4438 * stderr is only redirected when using the GUI, so that a
4439 * program like gpg can still access the terminal to get a
4440 * passphrase using stderr.
4441 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004442# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 if (pty_master_fd >= 0)
4444 {
4445 close(pty_master_fd); /* close master side of pty */
4446
4447 /* set up stdin/stdout/stderr for the child */
4448 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004449 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004451 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004452 if (gui.in_use)
4453 {
4454 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004455 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457
4458 close(pty_slave_fd); /* has been dupped, close it now */
4459 }
4460 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462 {
4463 /* set up stdin for the child */
4464 close(fd_toshell[1]);
4465 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004466 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 close(fd_toshell[0]);
4468
4469 /* set up stdout for the child */
4470 close(fd_fromshell[0]);
4471 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004472 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 close(fd_fromshell[1]);
4474
Bram Moolenaara5792f52005-11-23 21:25:05 +00004475# ifdef FEAT_GUI
4476 if (gui.in_use)
4477 {
4478 /* set up stderr for the child */
4479 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004480 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004481 }
4482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 }
4484 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004485
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 /*
4487 * There is no type cast for the argv, because the type may be
4488 * different on different machines. This may cause a warning
4489 * message with strict compilers, don't worry about it.
4490 * Call _exit() instead of exit() to avoid closing the connection
4491 * to the X server (esp. with GTK, which uses atexit()).
4492 */
4493 execvp(argv[0], argv);
4494 _exit(EXEC_FAILED); /* exec failed, return failure code */
4495 }
4496 else /* parent */
4497 {
4498 /*
4499 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004500 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 */
4502 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004503 catch_int_signal();
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004504 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505
4506 /*
4507 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004508 * This is also used to pipe stdin/stdout to/from the external
4509 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004511 if ((options & (SHELL_READ|SHELL_WRITE))
4512# ifdef FEAT_GUI
4513 || (gui.in_use && show_shell_mess)
4514# endif
4515 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004517# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004519# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004521# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4523 int ta_len = 0; /* valid bytes in ta_buf[] */
4524 int len;
4525 int p_more_save;
4526 int old_State;
4527 int c;
4528 int toshell_fd;
4529 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004530 garray_T ga;
4531 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004532# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4533 struct timeval start_tv;
4534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535
Bram Moolenaardf177f62005-02-22 08:39:57 +00004536# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 if (pty_master_fd >= 0)
4538 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 fromshell_fd = pty_master_fd;
4540 toshell_fd = dup(pty_master_fd);
4541 }
4542 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 {
4545 close(fd_toshell[0]);
4546 close(fd_fromshell[1]);
4547 toshell_fd = fd_toshell[1];
4548 fromshell_fd = fd_fromshell[0];
4549 }
4550
4551 /*
4552 * Write to the child if there are typed characters.
4553 * Read from the child if there are characters available.
4554 * Repeat the reading a few times if more characters are
4555 * available. Need to check for typed keys now and then, but
4556 * not too often (delays when no chars are available).
4557 * This loop is quit if no characters can be read from the pty
4558 * (WaitForChar detected special condition), or there are no
4559 * characters available and the child has exited.
4560 * Only check if the child has exited when there is no more
4561 * output. The child may exit before all the output has
4562 * been printed.
4563 *
4564 * Currently this busy loops!
4565 * This can probably dead-lock when the write blocks!
4566 */
4567 p_more_save = p_more;
4568 p_more = FALSE;
4569 old_State = State;
4570 State = EXTERNCMD; /* don't redraw at window resize */
4571
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004572 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004573 {
4574 /* Fork a process that will write the lines to the
4575 * external program. */
4576 if ((wpid = fork()) == -1)
4577 {
4578 MSG_PUTS(_("\nCannot fork\n"));
4579 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004580 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004581 {
4582 linenr_T lnum = curbuf->b_op_start.lnum;
4583 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004584 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004585 size_t l;
4586
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004587 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004588 for (;;)
4589 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004590 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004591 if (l == 0)
4592 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004593 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004594 /* NL -> NUL translation */
4595 len = write(toshell_fd, "", (size_t)1);
4596 else
4597 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004598 char_u *s = vim_strchr(lp + written, NL);
4599
Bram Moolenaar89d40322006-08-29 15:30:07 +00004600 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004601 s == NULL ? l
4602 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004603 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004604 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004605 {
4606 /* Finished a line, add a NL, unless this line
4607 * should not have one. */
4608 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004609 || (!curbuf->b_p_bin
4610 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004611 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004612 && (lnum !=
4613 curbuf->b_ml.ml_line_count
4614 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004615 ignored = write(toshell_fd, "\n",
4616 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004617 ++lnum;
4618 if (lnum > curbuf->b_op_end.lnum)
4619 {
4620 /* finished all the lines, close pipe */
4621 close(toshell_fd);
4622 toshell_fd = -1;
4623 break;
4624 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004625 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004626 written = 0;
4627 }
4628 else if (len > 0)
4629 written += len;
4630 }
4631 _exit(0);
4632 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004633 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004634 {
4635 close(toshell_fd);
4636 toshell_fd = -1;
4637 }
4638 }
4639
4640 if (options & SHELL_READ)
4641 ga_init2(&ga, 1, BUFLEN);
4642
4643 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004644# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4645 gettimeofday(&start_tv, NULL);
4646# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647 for (;;)
4648 {
4649 /*
4650 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004651 * if there are any.
4652 * Don't do this if we are expanding wild cards (would eat
4653 * typeahead).
4654 * Don't do this when filtering and terminal is in cooked
4655 * mode, the shell command will handle the I/O. Avoids
4656 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004657 * Don't get characters when the child has already
4658 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004659 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004660 * while (noread_cnt > 4), avoids that ":r !ls" eats
4661 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662 */
4663 len = 0;
4664 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004665 && ((options &
4666 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4667 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004668# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004669 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004670# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004671 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004672 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004673 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004674 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004675 if (ta_len == 0)
4676 {
4677 /* Get extra characters when we don't have any.
4678 * Reset the counter and timer. */
4679 noread_cnt = 0;
4680# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4681 gettimeofday(&start_tv, NULL);
4682# endif
4683 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4684 }
4685 if (ta_len > 0 || len > 0)
4686 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 /*
4688 * For pipes:
4689 * Check for CTRL-C: send interrupt signal to child.
4690 * Check for CTRL-D: EOF, close pipe to child.
4691 */
4692 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4693 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004694# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 /*
4696 * Send SIGINT to the child's group or all
4697 * processes in our group.
4698 */
4699 if (ta_buf[ta_len] == Ctrl_C
4700 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004701 {
4702# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004704# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004707 if (wpid > 0)
4708 kill(wpid, SIGINT);
4709 }
4710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 if (pty_master_fd < 0 && toshell_fd >= 0
4712 && ta_buf[ta_len] == Ctrl_D)
4713 {
4714 close(toshell_fd);
4715 toshell_fd = -1;
4716 }
4717 }
4718
4719 /* replace K_BS by <BS> and K_DEL by <DEL> */
4720 for (i = ta_len; i < ta_len + len; ++i)
4721 {
4722 if (ta_buf[i] == CSI && len - i > 2)
4723 {
4724 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4725 if (c == K_DEL || c == K_KDEL || c == K_BS)
4726 {
4727 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4728 (size_t)(len - i - 2));
4729 if (c == K_DEL || c == K_KDEL)
4730 ta_buf[i] = DEL;
4731 else
4732 ta_buf[i] = Ctrl_H;
4733 len -= 2;
4734 }
4735 }
4736 else if (ta_buf[i] == '\r')
4737 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004738# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004740 i += (*mb_ptr2len_len)(ta_buf + i,
4741 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004742# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743 }
4744
4745 /*
4746 * For pipes: echo the typed characters.
4747 * For a pty this does not seem to work.
4748 */
4749 if (pty_master_fd < 0)
4750 {
4751 for (i = ta_len; i < ta_len + len; ++i)
4752 {
4753 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4754 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004755# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 else if (has_mbyte)
4757 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004758 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759
4760 msg_outtrans_len(ta_buf + i, l);
4761 i += l - 1;
4762 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 else
4765 msg_outtrans_len(ta_buf + i, 1);
4766 }
4767 windgoto(msg_row, msg_col);
4768 out_flush();
4769 }
4770
4771 ta_len += len;
4772
4773 /*
4774 * Write the characters to the child, unless EOF has
4775 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004776 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004777 * When writing buffer lines, drop the typed
4778 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004780 if (options & SHELL_WRITE)
4781 ta_len = 0;
4782 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 {
4784 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4785 if (len > 0)
4786 {
4787 ta_len -= len;
4788 mch_memmove(ta_buf, ta_buf + len, ta_len);
4789 }
4790 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 }
4793
Bram Moolenaardf177f62005-02-22 08:39:57 +00004794 if (got_int)
4795 {
4796 /* CTRL-C sends a signal to the child, we ignore it
4797 * ourselves */
4798# ifdef HAVE_SETSID
4799 kill(-pid, SIGINT);
4800# else
4801 kill(0, SIGINT);
4802# endif
4803 if (wpid > 0)
4804 kill(wpid, SIGINT);
4805 got_int = FALSE;
4806 }
4807
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 /*
4809 * Check if the child has any characters to be printed.
4810 * Read them and write them to our window. Repeat this as
4811 * long as there is something to do, avoid the 10ms wait
4812 * for mch_inchar(), or sending typeahead characters to
4813 * the external process.
4814 * TODO: This should handle escape sequences, compatible
4815 * to some terminal (vt52?).
4816 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004817 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01004818 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004820 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004821# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004823# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004825# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 );
4827 if (len <= 0) /* end of file or error */
4828 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004829
4830 noread_cnt = 0;
4831 if (options & SHELL_READ)
4832 {
4833 /* Do NUL -> NL translation, append NL separated
4834 * lines to the current buffer. */
4835 for (i = 0; i < len; ++i)
4836 {
4837 if (buffer[i] == NL)
4838 append_ga_line(&ga);
4839 else if (buffer[i] == NUL)
4840 ga_append(&ga, NL);
4841 else
4842 ga_append(&ga, buffer[i]);
4843 }
4844 }
4845# ifdef FEAT_MBYTE
4846 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 {
4848 int l;
4849
Bram Moolenaardf177f62005-02-22 08:39:57 +00004850 len += buffer_off;
4851 buffer[len] = NUL;
4852
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853 /* Check if the last character in buffer[] is
4854 * incomplete, keep these bytes for the next
4855 * round. */
4856 for (p = buffer; p < buffer + len; p += l)
4857 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004858 l = MB_CPTR2LEN(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 if (l == 0)
4860 l = 1; /* NUL byte? */
4861 else if (MB_BYTE2LEN(*p) != l)
4862 break;
4863 }
4864 if (p == buffer) /* no complete character */
4865 {
4866 /* avoid getting stuck at an illegal byte */
4867 if (len >= 12)
4868 ++p;
4869 else
4870 {
4871 buffer_off = len;
4872 continue;
4873 }
4874 }
4875 c = *p;
4876 *p = NUL;
4877 msg_puts(buffer);
4878 if (p < buffer + len)
4879 {
4880 *p = c;
4881 buffer_off = (buffer + len) - p;
4882 mch_memmove(buffer, p, buffer_off);
4883 continue;
4884 }
4885 buffer_off = 0;
4886 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004887# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 {
4890 buffer[len] = NUL;
4891 msg_puts(buffer);
4892 }
4893
4894 windgoto(msg_row, msg_col);
4895 cursor_on();
4896 out_flush();
4897 if (got_int)
4898 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004899
4900# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004901 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004902 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +02004903 long msec = elapsed(&start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004904
4905 /* Avoid that we keep looping here without
4906 * checking for a CTRL-C for a long time. Don't
4907 * break out too often to avoid losing typeahead. */
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004908 if (msec > 2000)
4909 {
4910 noread_cnt = 5;
4911 break;
4912 }
4913 }
4914# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 }
4916
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004917 /* If we already detected the child has finished, continue
4918 * reading output for a short while. Some text may be
4919 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004920 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004921 {
4922 if (noread_cnt < 5)
4923 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004924 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004925 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004926
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 /*
4928 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004929 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004931# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004932 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004933# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4937 || (wait_pid == pid && WIFEXITED(status)))
4938 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004939 /* Don't break the loop yet, try reading more
4940 * characters from "fromshell_fd" first. When using
4941 * pipes there might still be something to read and
4942 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004943 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004945 else
4946 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004947
Bram Moolenaar95a51352013-03-21 22:53:50 +01004948# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004949 /* Handle any X events, e.g. serving the clipboard. */
4950 clip_update();
4951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 }
4953finished:
4954 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004955 if (options & SHELL_READ)
4956 {
4957 if (ga.ga_len > 0)
4958 {
4959 append_ga_line(&ga);
4960 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004961 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004962 }
4963 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004964 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004965 ga_clear(&ga);
4966 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 /*
4969 * Give all typeahead that wasn't used back to ui_inchar().
4970 */
4971 if (ta_len)
4972 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 State = old_State;
4974 if (toshell_fd >= 0)
4975 close(toshell_fd);
4976 close(fromshell_fd);
4977 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004978# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004979 else
4980 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004981 long delay_msec = 1;
4982
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004983 /*
4984 * Similar to the loop above, but only handle X events, no
4985 * I/O.
4986 */
4987 for (;;)
4988 {
4989 if (got_int)
4990 {
4991 /* CTRL-C sends a signal to the child, we ignore it
4992 * ourselves */
4993# ifdef HAVE_SETSID
4994 kill(-pid, SIGINT);
4995# else
4996 kill(0, SIGINT);
4997# endif
4998 got_int = FALSE;
4999 }
5000# ifdef __NeXT__
5001 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
5002# else
5003 wait_pid = waitpid(pid, &status, WNOHANG);
5004# endif
5005 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5006 || (wait_pid == pid && WIFEXITED(status)))
5007 {
5008 wait_pid = pid;
5009 break;
5010 }
5011
5012 /* Handle any X events, e.g. serving the clipboard. */
5013 clip_update();
5014
Bram Moolenaar0abe0522016-08-28 16:53:12 +02005015 /* Wait for 1 to 10 msec. 1 is faster but gives the child
5016 * less time. */
5017 mch_delay(delay_msec, TRUE);
5018 if (++delay_msec > 10)
5019 delay_msec = 10;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005020 }
5021 }
5022# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023
5024 /*
5025 * Wait until our child has exited.
5026 * Ignore wait() returning pids of other children and returning
5027 * because of some signal like SIGWINCH.
5028 * Don't wait if wait_pid was already set above, indicating the
5029 * child already exited.
5030 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005031 if (wait_pid != pid)
5032 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033
Bram Moolenaar624891f2010-10-13 16:22:09 +02005034# ifdef FEAT_GUI
5035 /* Close slave side of pty. Only do this after the child has
5036 * exited, otherwise the child may hang when it tries to write on
5037 * the pty. */
5038 if (pty_master_fd >= 0)
5039 close(pty_slave_fd);
5040# endif
5041
Bram Moolenaardf177f62005-02-22 08:39:57 +00005042 /* Make sure the child that writes to the external program is
5043 * dead. */
5044 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005045 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005046 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005047 wait4pid(wpid, NULL);
5048 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005049
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 /*
5051 * Set to raw mode right now, otherwise a CTRL-C after
5052 * catch_signals() will kill Vim.
5053 */
5054 if (tmode == TMODE_RAW)
5055 settmode(TMODE_RAW);
5056 did_settmode = TRUE;
5057 set_signals();
5058
5059 if (WIFEXITED(status))
5060 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005061 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005062 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005063 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005064 {
5065 if (retval == EXEC_FAILED)
5066 {
5067 MSG_PUTS(_("\nCannot execute shell "));
5068 msg_outtrans(p_sh);
5069 msg_putchar('\n');
5070 }
5071 else if (!(options & SHELL_SILENT))
5072 {
5073 MSG_PUTS(_("\nshell returned "));
5074 msg_outnum((long)retval);
5075 msg_putchar('\n');
5076 }
5077 }
5078 }
5079 else
5080 MSG_PUTS(_("\nCommand terminated\n"));
5081 }
5082 }
5083 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005084 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085
5086error:
5087 if (!did_settmode)
5088 if (tmode == TMODE_RAW)
5089 settmode(TMODE_RAW); /* set to raw mode */
5090# ifdef FEAT_TITLE
5091 resettitle();
5092# endif
5093 vim_free(newcmd);
5094
5095 return retval;
5096
5097#endif /* USE_SYSTEM */
5098}
5099
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005100#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005101 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005102mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005103{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005104 pid_t pid;
5105 int fd_in[2]; /* for stdin */
5106 int fd_out[2]; /* for stdout */
5107 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005108 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005109 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5110 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5111 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005112 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005113 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5114 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005115 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005116 SIGSET_DECL(curset)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005117
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005118 if (use_out_for_err && use_null_for_out)
5119 use_null_for_err = TRUE;
5120
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005121 /* default is to fail */
5122 job->jv_status = JOB_FAILED;
5123 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005124 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005125 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005126 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005127 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005128 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005129
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005130 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005131 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005132 if (use_file_for_in)
5133 {
5134 char_u *fname = options->jo_io_name[PART_IN];
5135
5136 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5137 if (fd_in[0] < 0)
5138 {
5139 EMSG2(_(e_notopen), fname);
5140 goto failed;
5141 }
5142 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005143 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005144 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005145
5146 if (use_file_for_out)
5147 {
5148 char_u *fname = options->jo_io_name[PART_OUT];
5149
5150 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5151 if (fd_out[1] < 0)
5152 {
5153 EMSG2(_(e_notopen), fname);
5154 goto failed;
5155 }
5156 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005157 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005158 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005159
5160 if (use_file_for_err)
5161 {
5162 char_u *fname = options->jo_io_name[PART_ERR];
5163
5164 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5165 if (fd_err[1] < 0)
5166 {
5167 EMSG2(_(e_notopen), fname);
5168 goto failed;
5169 }
5170 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005171 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005172 goto failed;
5173
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005174 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5175 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005176 if (options->jo_set & JO_CHANNEL)
5177 {
5178 channel = options->jo_channel;
5179 if (channel != NULL)
5180 ++channel->ch_refcount;
5181 }
5182 else
5183 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005184 if (channel == NULL)
5185 goto failed;
5186 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005187
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005188 BLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005189 pid = fork(); /* maybe we should use vfork() */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005190 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005191 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005192 /* failed to fork */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005193 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005194 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005195 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005196 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005197 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005198 int null_fd = -1;
5199 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005200
Bram Moolenaar835dc632016-02-07 14:27:38 +01005201 /* child */
5202 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005203 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005204
5205# ifdef HAVE_SETSID
5206 /* Create our own process group, so that the child and all its
5207 * children can be kill()ed. Don't do this when using pipes,
5208 * because stdin is not a tty, we would lose /dev/tty. */
5209 (void)setsid();
5210# endif
5211
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005212 set_child_environment();
5213
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005214 if (use_null_for_in || use_null_for_out || use_null_for_err)
5215 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5216
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005217 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005218 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005219 {
5220 close(0);
5221 ignored = dup(null_fd);
5222 }
5223 else
5224 {
5225 if (!use_file_for_in)
5226 close(fd_in[1]);
5227 close(0);
5228 ignored = dup(fd_in[0]);
5229 close(fd_in[0]);
5230 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005231
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005232 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005233 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005234 {
5235 close(2);
5236 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005237 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005238 }
5239 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005240 {
5241 close(2);
5242 ignored = dup(fd_out[1]);
5243 }
5244 else
5245 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005246 if (!use_file_for_err)
5247 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005248 close(2);
5249 ignored = dup(fd_err[1]);
5250 close(fd_err[1]);
5251 }
5252
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005253 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005254 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005255 {
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005256 close(1);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005257 ignored = dup(null_fd);
5258 }
5259 else
5260 {
5261 if (!use_file_for_out)
5262 close(fd_out[0]);
5263 close(1);
5264 ignored = dup(fd_out[1]);
5265 close(fd_out[1]);
5266 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005267
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005268 if (null_fd >= 0)
5269 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005270
Bram Moolenaar835dc632016-02-07 14:27:38 +01005271 /* See above for type of argv. */
5272 execvp(argv[0], argv);
5273
Bram Moolenaar4694a172016-04-21 14:05:23 +02005274 if (stderr_works)
5275 perror("executing job failed");
Bram Moolenaarcda77642016-06-04 13:32:35 +02005276#ifdef EXITFREE
5277 /* calling free_all_mem() here causes problems. Ignore valgrind
5278 * reporting possibly leaked memory. */
5279#endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005280 _exit(EXEC_FAILED); /* exec failed, return failure code */
5281 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005282
5283 /* parent */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005284 UNBLOCK_SIGNALS(&curset);
5285
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005286 job->jv_pid = pid;
5287 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005288 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005289
5290 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005291 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005292 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005293 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005294 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005295 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005296 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005297 if (channel != NULL)
5298 {
5299 channel_set_pipes(channel,
5300 use_file_for_in || use_null_for_in
5301 ? INVALID_FD : fd_in[1],
5302 use_file_for_out || use_null_for_out
5303 ? INVALID_FD : fd_out[0],
5304 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005305 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005306 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005307 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005308
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005309 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005310 return;
5311
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005312failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005313 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005314 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005315 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005316 if (fd_in[1] >= 0)
5317 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005318 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005319 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005320 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005321 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005322 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005323 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005324 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005325 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005326}
5327
5328 char *
5329mch_job_status(job_T *job)
5330{
5331# ifdef HAVE_UNION_WAIT
5332 union wait status;
5333# else
5334 int status = -1;
5335# endif
5336 pid_t wait_pid = 0;
5337
5338# ifdef __NeXT__
5339 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5340# else
5341 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5342# endif
5343 if (wait_pid == -1)
5344 {
5345 /* process must have exited */
Bram Moolenaar97792de2016-10-15 18:36:49 +02005346 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005347 }
5348 if (wait_pid == 0)
5349 return "run";
5350 if (WIFEXITED(status))
5351 {
5352 /* LINTED avoid "bitwise operation on signed value" */
5353 job->jv_exitval = WEXITSTATUS(status);
Bram Moolenaar97792de2016-10-15 18:36:49 +02005354 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005355 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005356 if (WIFSIGNALED(status))
5357 {
5358 job->jv_exitval = -1;
Bram Moolenaar97792de2016-10-15 18:36:49 +02005359 goto return_dead;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005360 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005361 return "run";
Bram Moolenaar97792de2016-10-15 18:36:49 +02005362
5363return_dead:
5364 if (job->jv_status != JOB_ENDED)
5365 {
5366 ch_log(job->jv_channel, "Job ended");
5367 job->jv_status = JOB_ENDED;
5368 }
5369 return "dead";
5370}
5371
5372 job_T *
5373mch_detect_ended_job(job_T *job_list)
5374{
5375# ifdef HAVE_UNION_WAIT
5376 union wait status;
5377# else
5378 int status = -1;
5379# endif
5380 pid_t wait_pid = 0;
5381 job_T *job;
5382
5383# ifdef __NeXT__
5384 wait_pid = wait4(-1, &status, WNOHANG, (struct rusage *)0);
5385# else
5386 wait_pid = waitpid(-1, &status, WNOHANG);
5387# endif
5388 if (wait_pid <= 0)
5389 /* no process ended */
5390 return NULL;
5391 for (job = job_list; job != NULL; job = job->jv_next)
5392 {
5393 if (job->jv_pid == wait_pid)
5394 {
5395 if (WIFEXITED(status))
5396 /* LINTED avoid "bitwise operation on signed value" */
5397 job->jv_exitval = WEXITSTATUS(status);
5398 else if (WIFSIGNALED(status))
5399 job->jv_exitval = -1;
5400 if (job->jv_status != JOB_ENDED)
5401 {
5402 ch_log(job->jv_channel, "Job ended");
5403 job->jv_status = JOB_ENDED;
5404 }
5405 return job;
5406 }
5407 }
5408 return NULL;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005409}
5410
5411 int
5412mch_stop_job(job_T *job, char_u *how)
5413{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005414 int sig = -1;
5415 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005416
Bram Moolenaar923d9262016-02-25 20:56:01 +01005417 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005418 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005419 else if (STRCMP(how, "hup") == 0)
5420 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005421 else if (STRCMP(how, "quit") == 0)
5422 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005423 else if (STRCMP(how, "int") == 0)
5424 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005425 else if (STRCMP(how, "kill") == 0)
5426 sig = SIGKILL;
5427 else if (isdigit(*how))
5428 sig = atoi((char *)how);
5429 else
5430 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005431
Bram Moolenaar72801402016-02-09 11:37:50 +01005432 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005433 job_pid = job->jv_pid;
5434 if (job_pid == getpgid(job_pid))
5435 job_pid = -job_pid;
5436
5437 kill(job_pid, sig);
5438
Bram Moolenaar835dc632016-02-07 14:27:38 +01005439 return OK;
5440}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005441
5442/*
5443 * Clear the data related to "job".
5444 */
5445 void
5446mch_clear_job(job_T *job)
5447{
5448 /* call waitpid because child process may become zombie */
5449# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005450 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005451# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005452 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005453# endif
5454}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005455#endif
5456
Bram Moolenaar071d4272004-06-13 20:20:40 +00005457/*
5458 * Check for CTRL-C typed by reading all available characters.
5459 * In cooked mode we should get SIGINT, no need to check.
5460 */
5461 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005462mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463{
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005464 if ((curr_tmode == TMODE_RAW || force)
5465 && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466 fill_input_buf(FALSE);
5467}
5468
5469/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005470 * Wait "msec" msec until a character is available from the mouse, keyboard,
5471 * from inbuf[].
5472 * "msec" == -1 will block forever.
5473 * Invokes timer callbacks when needed.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005474 * "interrupted" (if not NULL) is set to TRUE when no character is available
5475 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005476 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005477 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478 */
5479 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005480WaitForChar(long msec, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005481{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005482#ifdef FEAT_TIMERS
5483 long due_time;
5484 long remaining = msec;
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005485 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005486
5487 /* When waiting very briefly don't trigger timers. */
5488 if (msec >= 0 && msec < 10L)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005489 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005490
5491 while (msec < 0 || remaining > 0)
5492 {
5493 /* Trigger timers and then get the time in msec until the next one is
5494 * due. Wait up to that time. */
5495 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005496 if (typebuf.tb_change_cnt != tb_change_cnt)
5497 {
5498 /* timer may have used feedkeys() */
5499 return FALSE;
5500 }
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005501 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5502 due_time = remaining;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005503 if (WaitForCharOrMouse(due_time, interrupted))
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005504 return TRUE;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005505 if (interrupted != NULL && *interrupted)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005506 /* Nothing available, but need to return so that side effects get
5507 * handled, such as handling a message on a channel. */
5508 return FALSE;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005509 if (msec > 0)
5510 remaining -= due_time;
5511 }
5512 return FALSE;
5513#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005514 return WaitForCharOrMouse(msec, interrupted);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005515#endif
5516}
5517
5518/*
5519 * Wait "msec" msec until a character is available from the mouse or keyboard
5520 * or from inbuf[].
5521 * "msec" == -1 will block forever.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005522 * "interrupted" (if not NULL) is set to TRUE when no character is available
5523 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005524 * When a GUI is being used, this will never get called -- webb
5525 */
5526 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005527WaitForCharOrMouse(long msec, int *interrupted)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005528{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529#ifdef FEAT_MOUSE_GPM
5530 int gpm_process_wanted;
5531#endif
5532#ifdef FEAT_XCLIPBOARD
5533 int rest;
5534#endif
5535 int avail;
5536
5537 if (input_available()) /* something in inbuf[] */
5538 return 1;
5539
5540#if defined(FEAT_MOUSE_DEC)
5541 /* May need to query the mouse position. */
5542 if (WantQueryMouse)
5543 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005544 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5546 }
5547#endif
5548
5549 /*
5550 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5551 * events. This is a bit complicated, because they might both be defined.
5552 */
5553#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5554# ifdef FEAT_XCLIPBOARD
5555 rest = 0;
5556 if (do_xterm_trace())
5557 rest = msec;
5558# endif
5559 do
5560 {
5561# ifdef FEAT_XCLIPBOARD
5562 if (rest != 0)
5563 {
5564 msec = XT_TRACE_DELAY;
5565 if (rest >= 0 && rest < XT_TRACE_DELAY)
5566 msec = rest;
5567 if (rest >= 0)
5568 rest -= msec;
5569 }
5570# endif
5571# ifdef FEAT_MOUSE_GPM
5572 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005573 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02005574 &gpm_process_wanted, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005576 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577# endif
5578 if (!avail)
5579 {
5580 if (input_available())
5581 return 1;
5582# ifdef FEAT_XCLIPBOARD
5583 if (rest == 0 || !do_xterm_trace())
5584# endif
5585 break;
5586 }
5587 }
5588 while (FALSE
5589# ifdef FEAT_MOUSE_GPM
5590 || (gpm_process_wanted && mch_gpm_process() == 0)
5591# endif
5592# ifdef FEAT_XCLIPBOARD
5593 || (!avail && rest != 0)
5594# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005595 )
5596 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597
5598#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005599 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600#endif
5601 return avail;
5602}
5603
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005604#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605/*
5606 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005607 * "msec" == 0 will check for characters once.
5608 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005611 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005612 * "interrupted" (if not NULL) is set to TRUE when no character is available
5613 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615#if defined(__BEOS__)
5616 int
5617#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005618 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005620RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621{
5622 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005623 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005624#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 static int busy = FALSE;
5626
5627 /* May retry getting characters after an event was handled. */
5628# define MAY_LOOP
5629
5630# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5631 /* Remember at what time we started, so that we know how much longer we
5632 * should wait after being interrupted. */
5633# define USE_START_TV
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005634 long start_msec = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 struct timeval start_tv;
5636
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005637 if (msec > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 gettimeofday(&start_tv, NULL);
5639# endif
5640
5641 /* Handle being called recursively. This may happen for the session
5642 * manager stuff, it may save the file, which does a breakcheck. */
5643 if (busy)
5644 return 0;
5645#endif
5646
5647#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005648 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649#endif
5650 {
5651#ifdef MAY_LOOP
5652 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005653# ifdef FEAT_MZSCHEME
5654 int mzquantum_used = FALSE;
5655# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656#endif
5657#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005658 /* each channel may use in, out and err */
5659 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 int nfd;
5661# ifdef FEAT_XCLIPBOARD
5662 int xterm_idx = -1;
5663# endif
5664# ifdef FEAT_MOUSE_GPM
5665 int gpm_idx = -1;
5666# endif
5667# ifdef USE_XSMP
5668 int xsmp_idx = -1;
5669# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005670 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005672# ifdef FEAT_MZSCHEME
5673 mzvim_check_threads();
5674 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5675 {
5676 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5677 mzquantum_used = TRUE;
5678 }
5679# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 fds[0].fd = fd;
5681 fds[0].events = POLLIN;
5682 nfd = 1;
5683
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005685 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 if (xterm_Shell != (Widget)0)
5687 {
5688 xterm_idx = nfd;
5689 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5690 fds[nfd].events = POLLIN;
5691 nfd++;
5692 }
5693# endif
5694# ifdef FEAT_MOUSE_GPM
5695 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5696 {
5697 gpm_idx = nfd;
5698 fds[nfd].fd = gpm_fd;
5699 fds[nfd].events = POLLIN;
5700 nfd++;
5701 }
5702# endif
5703# ifdef USE_XSMP
5704 if (xsmp_icefd != -1)
5705 {
5706 xsmp_idx = nfd;
5707 fds[nfd].fd = xsmp_icefd;
5708 fds[nfd].events = POLLIN;
5709 nfd++;
5710 }
5711# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005712#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005713 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005714#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005715 if (interrupted != NULL)
5716 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005718 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005719
5720 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02005721 if (result == 0 && interrupted != NULL && ret > 0)
5722 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005723
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005724# ifdef FEAT_MZSCHEME
5725 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005726 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005727 finished = FALSE;
5728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730# ifdef FEAT_XCLIPBOARD
5731 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5732 {
5733 xterm_update(); /* Maybe we should hand out clipboard */
5734 if (--ret == 0 && !input_available())
5735 /* Try again */
5736 finished = FALSE;
5737 }
5738# endif
5739# ifdef FEAT_MOUSE_GPM
5740 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5741 {
5742 *check_for_gpm = 1;
5743 }
5744# endif
5745# ifdef USE_XSMP
5746 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5747 {
5748 if (fds[xsmp_idx].revents & POLLIN)
5749 {
5750 busy = TRUE;
5751 xsmp_handle_requests();
5752 busy = FALSE;
5753 }
5754 else if (fds[xsmp_idx].revents & POLLHUP)
5755 {
5756 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005757 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 xsmp_close();
5759 }
5760 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005761 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762 }
5763# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005764#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005765 if (ret > 0)
5766 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005767#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769#else /* HAVE_SELECT */
5770
5771 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005772 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005773 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005775 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005777# ifdef FEAT_MZSCHEME
5778 mzvim_check_threads();
5779 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5780 {
5781 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5782 mzquantum_used = TRUE;
5783 }
5784# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005786 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005788 tv.tv_sec = towait / 1000;
5789 tv.tv_usec = (towait % 1000) * (1000000/1000);
5790 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005792 else
5793 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794
5795 /*
5796 * Select on ready for reading and exceptional condition (end of file).
5797 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005798select_eintr:
5799 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005800 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801 FD_ZERO(&efds);
5802 FD_SET(fd, &rfds);
5803# if !defined(__QNX__) && !defined(__CYGWIN32__)
5804 /* For QNX select() always returns 1 if this is set. Why? */
5805 FD_SET(fd, &efds);
5806# endif
5807 maxfd = fd;
5808
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005810 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 if (xterm_Shell != (Widget)0)
5812 {
5813 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5814 if (maxfd < ConnectionNumber(xterm_dpy))
5815 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005816
5817 /* An event may have already been read but not handled. In
5818 * particulary, XFlush may cause this. */
5819 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 }
5821# endif
5822# ifdef FEAT_MOUSE_GPM
5823 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5824 {
5825 FD_SET(gpm_fd, &rfds);
5826 FD_SET(gpm_fd, &efds);
5827 if (maxfd < gpm_fd)
5828 maxfd = gpm_fd;
5829 }
5830# endif
5831# ifdef USE_XSMP
5832 if (xsmp_icefd != -1)
5833 {
5834 FD_SET(xsmp_icefd, &rfds);
5835 FD_SET(xsmp_icefd, &efds);
5836 if (maxfd < xsmp_icefd)
5837 maxfd = xsmp_icefd;
5838 }
5839# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005840# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005841 maxfd = channel_select_setup(maxfd, &rfds, &wfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005842# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005843 if (interrupted != NULL)
5844 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005846 ret = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005847 result = ret > 0 && FD_ISSET(fd, &rfds);
5848 if (result)
5849 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005850 else if (interrupted != NULL && ret > 0)
5851 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005852
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005853# ifdef EINTR
5854 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005855 {
5856 /* Check whether window has been resized, EINTR may be caused by
5857 * SIGWINCH. */
5858 if (do_resize)
5859 handle_resize();
5860
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005861 /* Interrupted by a signal, need to try again. We ignore msec
5862 * here, because we do want to check even after a timeout if
5863 * characters are available. Needed for reading output of an
5864 * external command after the process has finished. */
5865 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005866 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005867# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005868# ifdef __TANDEM
5869 if (ret == -1 && errno == ENOTSUP)
5870 {
5871 FD_ZERO(&rfds);
5872 FD_ZERO(&efds);
5873 ret = 0;
5874 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005875# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005876# ifdef FEAT_MZSCHEME
5877 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005878 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005879 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880# endif
5881
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882# ifdef FEAT_XCLIPBOARD
5883 if (ret > 0 && xterm_Shell != (Widget)0
5884 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5885 {
5886 xterm_update(); /* Maybe we should hand out clipboard */
5887 /* continue looping when we only got the X event and the input
5888 * buffer is empty */
5889 if (--ret == 0 && !input_available())
5890 {
5891 /* Try again */
5892 finished = FALSE;
5893 }
5894 }
5895# endif
5896# ifdef FEAT_MOUSE_GPM
5897 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5898 {
5899 if (FD_ISSET(gpm_fd, &efds))
5900 gpm_close();
5901 else if (FD_ISSET(gpm_fd, &rfds))
5902 *check_for_gpm = 1;
5903 }
5904# endif
5905# ifdef USE_XSMP
5906 if (ret > 0 && xsmp_icefd != -1)
5907 {
5908 if (FD_ISSET(xsmp_icefd, &efds))
5909 {
5910 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005911 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 xsmp_close();
5913 if (--ret == 0)
5914 finished = FALSE; /* keep going if event was only one */
5915 }
5916 else if (FD_ISSET(xsmp_icefd, &rfds))
5917 {
5918 busy = TRUE;
5919 xsmp_handle_requests();
5920 busy = FALSE;
5921 if (--ret == 0)
5922 finished = FALSE; /* keep going if event was only one */
5923 }
5924 }
5925# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005926#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005927 if (ret > 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005928 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005929#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930
5931#endif /* HAVE_SELECT */
5932
5933#ifdef MAY_LOOP
5934 if (finished || msec == 0)
5935 break;
5936
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005937# ifdef FEAT_CLIENTSERVER
5938 if (server_waiting())
5939 break;
5940# endif
5941
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 /* We're going to loop around again, find out for how long */
5943 if (msec > 0)
5944 {
5945# ifdef USE_START_TV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 /* Compute remaining wait time. */
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005947 msec = start_msec - elapsed(&start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948# else
5949 /* Guess we got interrupted halfway. */
5950 msec = msec / 2;
5951# endif
5952 if (msec <= 0)
5953 break; /* waited long enough */
5954 }
5955#endif
5956 }
5957
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005958 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959}
5960
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005963 * Expand a path into all matching files and/or directories. Handles "*",
5964 * "?", "[a-z]", "**", etc.
5965 * "path" has backslashes before chars that are not to be expanded.
5966 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 */
5968 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005969mch_expandpath(
5970 garray_T *gap,
5971 char_u *path,
5972 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973{
Bram Moolenaar02743632005-07-25 20:42:36 +00005974 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975}
5976#endif
5977
5978/*
5979 * mch_expand_wildcards() - this code does wild-card pattern matching using
5980 * the shell
5981 *
5982 * return OK for success, FAIL for error (you may lose some memory) and put
5983 * an error message in *file.
5984 *
5985 * num_pat is number of input patterns
5986 * pat is array of pointers to input patterns
5987 * num_file is pointer to number of matched file names
5988 * file is pointer to array of pointers to matched file names
5989 */
5990
5991#ifndef SEEK_SET
5992# define SEEK_SET 0
5993#endif
5994#ifndef SEEK_END
5995# define SEEK_END 2
5996#endif
5997
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005998#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005999
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006001mch_expand_wildcards(
6002 int num_pat,
6003 char_u **pat,
6004 int *num_file,
6005 char_u ***file,
6006 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007{
6008 int i;
6009 size_t len;
6010 char_u *p;
6011 int dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012
Bram Moolenaarc7247912008-01-13 12:54:11 +00006013 /*
6014 * This is the non-OS/2 implementation (really Unix).
6015 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 int j;
6017 char_u *tempname;
6018 char_u *command;
6019 FILE *fd;
6020 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006021#define STYLE_ECHO 0 /* use "echo", the default */
6022#define STYLE_GLOB 1 /* use "glob", for csh */
6023#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6024#define STYLE_PRINT 3 /* use "print -N", for zsh */
6025#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6026 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 int shell_style = STYLE_ECHO;
6028 int check_spaces;
6029 static int did_find_nul = FALSE;
6030 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006031 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006032 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033
6034 *num_file = 0; /* default: no files found */
6035 *file = NULL;
6036
6037 /*
6038 * If there are no wildcards, just copy the names to allocated memory.
6039 * Saves a lot of time, because we don't have to start a new shell.
6040 */
6041 if (!have_wildcard(num_pat, pat))
6042 return save_patterns(num_pat, pat, num_file, file);
6043
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006044# ifdef HAVE_SANDBOX
6045 /* Don't allow any shell command in the sandbox. */
6046 if (sandbox != 0 && check_secure())
6047 return FAIL;
6048# endif
6049
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050 /*
6051 * Don't allow the use of backticks in secure and restricted mode.
6052 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006053 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 for (i = 0; i < num_pat; ++i)
6055 if (vim_strchr(pat[i], '`') != NULL
6056 && (check_restricted() || check_secure()))
6057 return FAIL;
6058
6059 /*
6060 * get a name for the temp file
6061 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006062 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063 {
6064 EMSG(_(e_notmp));
6065 return FAIL;
6066 }
6067
6068 /*
6069 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006070 * file.
6071 * STYLE_BT: NL separated
6072 * If expanding `cmd` execute it directly.
6073 * STYLE_GLOB: NUL separated
6074 * If we use *csh, "glob" will work better than "echo".
6075 * STYLE_PRINT: NL or NUL separated
6076 * If we use *zsh, "print -N" will work better than "glob".
6077 * STYLE_VIMGLOB: NL separated
6078 * If we use *sh*, we define "vimglob()".
6079 * STYLE_ECHO: space separated.
6080 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 */
6082 if (num_pat == 1 && *pat[0] == '`'
6083 && (len = STRLEN(pat[0])) > 2
6084 && *(pat[0] + len - 1) == '`')
6085 shell_style = STYLE_BT;
6086 else if ((len = STRLEN(p_sh)) >= 3)
6087 {
6088 if (STRCMP(p_sh + len - 3, "csh") == 0)
6089 shell_style = STYLE_GLOB;
6090 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6091 shell_style = STYLE_PRINT;
6092 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006093 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6094 "sh") != NULL)
6095 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006096
Bram Moolenaarc7247912008-01-13 12:54:11 +00006097 /* Compute the length of the command. We need 2 extra bytes: for the
6098 * optional '&' and for the NUL.
6099 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006101 if (shell_style == STYLE_VIMGLOB)
6102 len += STRLEN(sh_vimglob_func);
6103
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006104 for (i = 0; i < num_pat; ++i)
6105 {
6106 /* Count the length of the patterns in the same way as they are put in
6107 * "command" below. */
6108#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006110#else
6111 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006112 for (j = 0; pat[i][j] != NUL; ++j)
6113 {
6114 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6115 ++len; /* may add a backslash */
6116 ++len;
6117 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006118#endif
6119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 command = alloc(len);
6121 if (command == NULL)
6122 {
6123 /* out of memory */
6124 vim_free(tempname);
6125 return FAIL;
6126 }
6127
6128 /*
6129 * Build the shell command:
6130 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6131 * recognizes this).
6132 * - Add the shell command to print the expanded names.
6133 * - Add the temp file name.
6134 * - Add the file name patterns.
6135 */
6136 if (shell_style == STYLE_BT)
6137 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006138 /* change `command; command& ` to (command; command ) */
6139 STRCPY(command, "(");
6140 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006142 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 while (p > command && vim_iswhite(*p))
6144 --p;
6145 if (*p == '&') /* remove trailing '&' */
6146 {
6147 ampersent = TRUE;
6148 *p = ' ';
6149 }
6150 STRCAT(command, ">");
6151 }
6152 else
6153 {
6154 if (flags & EW_NOTFOUND)
6155 STRCPY(command, "set nonomatch; ");
6156 else
6157 STRCPY(command, "unset nonomatch; ");
6158 if (shell_style == STYLE_GLOB)
6159 STRCAT(command, "glob >");
6160 else if (shell_style == STYLE_PRINT)
6161 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006162 else if (shell_style == STYLE_VIMGLOB)
6163 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164 else
6165 STRCAT(command, "echo >");
6166 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006167
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006169
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 if (shell_style != STYLE_BT)
6171 for (i = 0; i < num_pat; ++i)
6172 {
6173 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006174 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006175 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176#ifdef USE_SYSTEM
6177 STRCAT(command, " \"");
6178 STRCAT(command, pat[i]);
6179 STRCAT(command, "\"");
6180#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006181 int intick = FALSE;
6182
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 p = command + STRLEN(command);
6184 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006185 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006186 {
6187 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006188 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006189 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6190 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006191 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006192 * backslash inside backticks, before a special character
6193 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006194 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006195 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6196 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006197 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006198 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006199 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006200 else if (!intick
6201 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6202 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006203 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006204 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6205 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006206 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006207
6208 /* Copy one character. */
6209 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006210 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 *p = NUL;
6212#endif
6213 }
6214 if (flags & EW_SILENT)
6215 show_shell_mess = FALSE;
6216 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006217 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218
6219 /*
6220 * Using zsh -G: If a pattern has no matches, it is just deleted from
6221 * the argument list, otherwise zsh gives an error message and doesn't
6222 * expand any other pattern.
6223 */
6224 if (shell_style == STYLE_PRINT)
6225 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6226
6227 /*
6228 * If we use -f then shell variables set in .cshrc won't get expanded.
6229 * vi can do it, so we will too, but it is only necessary if there is a "$"
6230 * in one of the patterns, otherwise we can still use the fast option.
6231 */
6232 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6233 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6234
6235 /*
6236 * execute the shell command
6237 */
6238 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6239
6240 /* When running in the background, give it some time to create the temp
6241 * file, but don't wait for it to finish. */
6242 if (ampersent)
6243 mch_delay(10L, TRUE);
6244
6245 extra_shell_arg = NULL; /* cleanup */
6246 show_shell_mess = TRUE;
6247 vim_free(command);
6248
Bram Moolenaarc7247912008-01-13 12:54:11 +00006249 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 {
6251 mch_remove(tempname);
6252 vim_free(tempname);
6253 /*
6254 * With interactive completion, the error message is not printed.
6255 * However with USE_SYSTEM, I don't know how to turn off error messages
6256 * from the shell, so screen may still get messed up -- webb.
6257 */
6258#ifndef USE_SYSTEM
6259 if (!(flags & EW_SILENT))
6260#endif
6261 {
6262 redraw_later_clear(); /* probably messed up screen */
6263 msg_putchar('\n'); /* clear bottom line quickly */
6264 cmdline_row = Rows - 1; /* continue on last line */
6265#ifdef USE_SYSTEM
6266 if (!(flags & EW_SILENT))
6267#endif
6268 {
6269 MSG(_(e_wildexpand));
6270 msg_start(); /* don't overwrite this message */
6271 }
6272 }
6273 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6274 * EW_NOTFOUND is given */
6275 if (shell_style == STYLE_BT)
6276 return FAIL;
6277 goto notfound;
6278 }
6279
6280 /*
6281 * read the names from the file into memory
6282 */
6283 fd = fopen((char *)tempname, READBIN);
6284 if (fd == NULL)
6285 {
6286 /* Something went wrong, perhaps a file name with a special char. */
6287 if (!(flags & EW_SILENT))
6288 {
6289 MSG(_(e_wildexpand));
6290 msg_start(); /* don't overwrite this message */
6291 }
6292 vim_free(tempname);
6293 goto notfound;
6294 }
6295 fseek(fd, 0L, SEEK_END);
6296 len = ftell(fd); /* get size of temp file */
6297 fseek(fd, 0L, SEEK_SET);
6298 buffer = alloc(len + 1);
6299 if (buffer == NULL)
6300 {
6301 /* out of memory */
6302 mch_remove(tempname);
6303 vim_free(tempname);
6304 fclose(fd);
6305 return FAIL;
6306 }
6307 i = fread((char *)buffer, 1, len, fd);
6308 fclose(fd);
6309 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006310 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 {
6312 /* unexpected read error */
6313 EMSG2(_(e_notread), tempname);
6314 vim_free(tempname);
6315 vim_free(buffer);
6316 return FAIL;
6317 }
6318 vim_free(tempname);
6319
Bram Moolenaarc7247912008-01-13 12:54:11 +00006320# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6322 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006323 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6325 *p++ = buffer[i];
6326 len = p - buffer;
6327# endif
6328
6329
6330 /* file names are separated with Space */
6331 if (shell_style == STYLE_ECHO)
6332 {
6333 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6334 p = buffer;
6335 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6336 {
6337 while (*p != ' ' && *p != '\n')
6338 ++p;
6339 p = skipwhite(p); /* skip to next entry */
6340 }
6341 }
6342 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006343 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 {
6345 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6346 p = buffer;
6347 for (i = 0; *p != NUL; ++i) /* count number of entries */
6348 {
6349 while (*p != '\n' && *p != NUL)
6350 ++p;
6351 if (*p != NUL)
6352 ++p;
6353 p = skipwhite(p); /* skip leading white space */
6354 }
6355 }
6356 /* file names are separated with NUL */
6357 else
6358 {
6359 /*
6360 * Some versions of zsh use spaces instead of NULs to separate
6361 * results. Only do this when there is no NUL before the end of the
6362 * buffer, otherwise we would never be able to use file names with
6363 * embedded spaces when zsh does use NULs.
6364 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6365 * don't check for spaces again.
6366 */
6367 check_spaces = FALSE;
6368 if (shell_style == STYLE_PRINT && !did_find_nul)
6369 {
6370 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006371 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006372 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 did_find_nul = TRUE;
6374 else
6375 check_spaces = TRUE;
6376 }
6377
6378 /*
6379 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6380 * already is one, for STYLE_GLOB it needs to be added.
6381 */
6382 if (len && buffer[len - 1] == NUL)
6383 --len;
6384 else
6385 buffer[len] = NUL;
6386 i = 0;
6387 for (p = buffer; p < buffer + len; ++p)
6388 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6389 {
6390 ++i;
6391 *p = NUL;
6392 }
6393 if (len)
6394 ++i; /* count last entry */
6395 }
6396 if (i == 0)
6397 {
6398 /*
6399 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6400 * /bin/sh will happily expand it to nothing rather than returning an
6401 * error; and hey, it's good to check anyway -- webb.
6402 */
6403 vim_free(buffer);
6404 goto notfound;
6405 }
6406 *num_file = i;
6407 *file = (char_u **)alloc(sizeof(char_u *) * i);
6408 if (*file == NULL)
6409 {
6410 /* out of memory */
6411 vim_free(buffer);
6412 return FAIL;
6413 }
6414
6415 /*
6416 * Isolate the individual file names.
6417 */
6418 p = buffer;
6419 for (i = 0; i < *num_file; ++i)
6420 {
6421 (*file)[i] = p;
6422 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006423 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6424 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006426 while (!(shell_style == STYLE_ECHO && *p == ' ')
6427 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 ++p;
6429 if (p == buffer + len) /* last entry */
6430 *p = NUL;
6431 else
6432 {
6433 *p++ = NUL;
6434 p = skipwhite(p); /* skip to next entry */
6435 }
6436 }
6437 else /* NUL separates */
6438 {
6439 while (*p && p < buffer + len) /* skip entry */
6440 ++p;
6441 ++p; /* skip NUL */
6442 }
6443 }
6444
6445 /*
6446 * Move the file names to allocated memory.
6447 */
6448 for (j = 0, i = 0; i < *num_file; ++i)
6449 {
6450 /* Require the files to exist. Helps when using /bin/sh */
6451 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6452 continue;
6453
6454 /* check if this entry should be included */
6455 dir = (mch_isdir((*file)[i]));
6456 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6457 continue;
6458
Bram Moolenaara2031822006-03-07 22:29:51 +00006459 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006460 if (!dir && (flags & EW_EXEC)
6461 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006462 continue;
6463
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6465 if (p)
6466 {
6467 STRCPY(p, (*file)[i]);
6468 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006469 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470 (*file)[j++] = p;
6471 }
6472 }
6473 vim_free(buffer);
6474 *num_file = j;
6475
6476 if (*num_file == 0) /* rejected all entries */
6477 {
6478 vim_free(*file);
6479 *file = NULL;
6480 goto notfound;
6481 }
6482
6483 return OK;
6484
6485notfound:
6486 if (flags & EW_NOTFOUND)
6487 return save_patterns(num_pat, pat, num_file, file);
6488 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489}
6490
6491#endif /* VMS */
6492
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006494save_patterns(
6495 int num_pat,
6496 char_u **pat,
6497 int *num_file,
6498 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499{
6500 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006501 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502
6503 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6504 if (*file == NULL)
6505 return FAIL;
6506 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006507 {
6508 s = vim_strsave(pat[i]);
6509 if (s != NULL)
6510 /* Be compatible with expand_filename(): halve the number of
6511 * backslashes. */
6512 backslash_halve(s);
6513 (*file)[i] = s;
6514 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 *num_file = num_pat;
6516 return OK;
6517}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519/*
6520 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6521 * expand.
6522 */
6523 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006524mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006526 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 if (*p == '\\' && p[1] != NUL)
6529 ++p;
6530 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 if (vim_strchr((char_u *)
6532#ifdef VMS
6533 "*?%"
6534#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536#endif
6537 , *p) != NULL)
6538 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 }
6540 return FALSE;
6541}
6542
6543/*
6544 * Return TRUE if the string "p" contains a wildcard.
6545 * Don't recognize '~' at the end as a wildcard.
6546 */
6547 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006548mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006550 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 if (*p == '\\' && p[1] != NUL)
6553 ++p;
6554 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 if (vim_strchr((char_u *)
6556#ifdef VMS
6557 "*?%$"
6558#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560#endif
6561 , *p) != NULL
6562 || (*p == '~' && p[1] != NUL))
6563 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 }
6565 return FALSE;
6566}
6567
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006569have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570{
6571 int i;
6572
6573 for (i = 0; i < num; i++)
6574 if (mch_has_wildcard(file[i]))
6575 return 1;
6576 return 0;
6577}
6578
6579 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006580have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581{
6582 int i;
6583
6584 for (i = 0; i < num; i++)
6585 if (vim_strchr(file[i], '$') != NULL)
6586 return TRUE;
6587 return FALSE;
6588}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006590#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591/*
6592 * Scaled-down version of rename(), which is missing in Xenix.
6593 * This version can only move regular files and will fail if the
6594 * destination exists.
6595 */
6596 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006597mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598{
6599 struct stat st;
6600
6601 if (stat(dest, &st) >= 0) /* fail if destination exists */
6602 return -1;
6603 if (link(src, dest) != 0) /* link file to new name */
6604 return -1;
6605 if (mch_remove(src) == 0) /* delete link to old name */
6606 return 0;
6607 return -1;
6608}
6609#endif /* !HAVE_RENAME */
6610
6611#ifdef FEAT_MOUSE_GPM
6612/*
6613 * Initializes connection with gpm (if it isn't already opened)
6614 * Return 1 if succeeded (or connection already opened), 0 if failed
6615 */
6616 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006617gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618{
6619 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6620
6621 if (!gpm_flag)
6622 {
6623 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6624 gpm_connect.defaultMask = ~GPM_HARD;
6625 /* Default handling for mouse move*/
6626 gpm_connect.minMod = 0; /* Handle any modifier keys */
6627 gpm_connect.maxMod = 0xffff;
6628 if (Gpm_Open(&gpm_connect, 0) > 0)
6629 {
6630 /* gpm library tries to handling TSTP causes
6631 * problems. Anyways, we close connection to Gpm whenever
6632 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006633 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006635# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006637# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 return 1; /* succeed */
6639 }
6640 if (gpm_fd == -2)
6641 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6642 return 0;
6643 }
6644 return 1; /* already open */
6645}
6646
6647/*
6648 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 */
6650 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006651gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652{
6653 if (gpm_flag && gpm_fd >= 0) /* if Open */
6654 Gpm_Close();
6655}
6656
6657/* Reads gpm event and adds special keys to input buf. Returns length of
6658 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006659 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 */
6661 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006662mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663{
6664 int button;
6665 static Gpm_Event gpm_event;
6666 char_u string[6];
6667 int_u vim_modifiers;
6668 int row,col;
6669 unsigned char buttons_mask;
6670 unsigned char gpm_modifiers;
6671 static unsigned char old_buttons = 0;
6672
6673 Gpm_GetEvent(&gpm_event);
6674
6675#ifdef FEAT_GUI
6676 /* Don't put events in the input queue now. */
6677 if (hold_gui_events)
6678 return 0;
6679#endif
6680
6681 row = gpm_event.y - 1;
6682 col = gpm_event.x - 1;
6683
6684 string[0] = ESC; /* Our termcode */
6685 string[1] = 'M';
6686 string[2] = 'G';
6687 switch (GPM_BARE_EVENTS(gpm_event.type))
6688 {
6689 case GPM_DRAG:
6690 string[3] = MOUSE_DRAG;
6691 break;
6692 case GPM_DOWN:
6693 buttons_mask = gpm_event.buttons & ~old_buttons;
6694 old_buttons = gpm_event.buttons;
6695 switch (buttons_mask)
6696 {
6697 case GPM_B_LEFT:
6698 button = MOUSE_LEFT;
6699 break;
6700 case GPM_B_MIDDLE:
6701 button = MOUSE_MIDDLE;
6702 break;
6703 case GPM_B_RIGHT:
6704 button = MOUSE_RIGHT;
6705 break;
6706 default:
6707 return 0;
6708 /*Don't know what to do. Can more than one button be
6709 * reported in one event? */
6710 }
6711 string[3] = (char_u)(button | 0x20);
6712 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6713 break;
6714 case GPM_UP:
6715 string[3] = MOUSE_RELEASE;
6716 old_buttons &= ~gpm_event.buttons;
6717 break;
6718 default:
6719 return 0;
6720 }
6721 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6722 gpm_modifiers = gpm_event.modifiers;
6723 vim_modifiers = 0x0;
6724 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6725 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6726 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6727 */
6728 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6729 vim_modifiers |= MOUSE_SHIFT;
6730
6731 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6732 vim_modifiers |= MOUSE_CTRL;
6733 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6734 vim_modifiers |= MOUSE_ALT;
6735 string[3] |= vim_modifiers;
6736 string[4] = (char_u)(col + ' ' + 1);
6737 string[5] = (char_u)(row + ' ' + 1);
6738 add_to_input_buf(string, 6);
6739 return 6;
6740}
6741#endif /* FEAT_MOUSE_GPM */
6742
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006743#ifdef FEAT_SYSMOUSE
6744/*
6745 * Initialize connection with sysmouse.
6746 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6747 * output, any sysmouse output than will be processed via sig_sysmouse().
6748 * Return OK if succeeded, FAIL if failed.
6749 */
6750 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006751sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006752{
6753 struct mouse_info mouse;
6754
6755 mouse.operation = MOUSE_MODE;
6756 mouse.u.mode.mode = 0;
6757 mouse.u.mode.signal = SIGUSR2;
6758 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6759 {
6760 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6761 mouse.operation = MOUSE_SHOW;
6762 ioctl(1, CONS_MOUSECTL, &mouse);
6763 return OK;
6764 }
6765 return FAIL;
6766}
6767
6768/*
6769 * Stop processing SIGUSR2 signals, and also make sure that
6770 * virtual console do not send us any sysmouse related signal.
6771 */
6772 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006773sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006774{
6775 struct mouse_info mouse;
6776
6777 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6778 mouse.operation = MOUSE_MODE;
6779 mouse.u.mode.mode = 0;
6780 mouse.u.mode.signal = 0;
6781 ioctl(1, CONS_MOUSECTL, &mouse);
6782}
6783
6784/*
6785 * Gets info from sysmouse and adds special keys to input buf.
6786 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006787 static RETSIGTYPE
6788sig_sysmouse SIGDEFARG(sigarg)
6789{
6790 struct mouse_info mouse;
6791 struct video_info video;
6792 char_u string[6];
6793 int row, col;
6794 int button;
6795 int buttons;
6796 static int oldbuttons = 0;
6797
6798#ifdef FEAT_GUI
6799 /* Don't put events in the input queue now. */
6800 if (hold_gui_events)
6801 return;
6802#endif
6803
6804 mouse.operation = MOUSE_GETINFO;
6805 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6806 && ioctl(1, FBIO_MODEINFO, &video) != -1
6807 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6808 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6809 {
6810 row = mouse.u.data.y / video.vi_cheight;
6811 col = mouse.u.data.x / video.vi_cwidth;
6812 buttons = mouse.u.data.buttons;
6813 string[0] = ESC; /* Our termcode */
6814 string[1] = 'M';
6815 string[2] = 'S';
6816 if (oldbuttons == buttons && buttons != 0)
6817 {
6818 button = MOUSE_DRAG;
6819 }
6820 else
6821 {
6822 switch (buttons)
6823 {
6824 case 0:
6825 button = MOUSE_RELEASE;
6826 break;
6827 case 1:
6828 button = MOUSE_LEFT;
6829 break;
6830 case 2:
6831 button = MOUSE_MIDDLE;
6832 break;
6833 case 4:
6834 button = MOUSE_RIGHT;
6835 break;
6836 default:
6837 return;
6838 }
6839 oldbuttons = buttons;
6840 }
6841 string[3] = (char_u)(button);
6842 string[4] = (char_u)(col + ' ' + 1);
6843 string[5] = (char_u)(row + ' ' + 1);
6844 add_to_input_buf(string, 6);
6845 }
6846 return;
6847}
6848#endif /* FEAT_SYSMOUSE */
6849
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006851typedef char_u * (*STRPROCSTR)(char_u *);
6852typedef char_u * (*INTPROCSTR)(int);
6853typedef int (*STRPROCINT)(char_u *);
6854typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855
6856/*
6857 * Call a DLL routine which takes either a string or int param
6858 * and returns an allocated string.
6859 */
6860 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006861mch_libcall(
6862 char_u *libname,
6863 char_u *funcname,
6864 char_u *argstring, /* NULL when using a argint */
6865 int argint,
6866 char_u **string_result,/* NULL when using number_result */
6867 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868{
6869# if defined(USE_DLOPEN)
6870 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006871 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872# else
6873 shl_t hinstLib;
6874# endif
6875 STRPROCSTR ProcAdd;
6876 INTPROCSTR ProcAddI;
6877 char_u *retval_str = NULL;
6878 int retval_int = 0;
6879 int success = FALSE;
6880
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006881 /*
6882 * Get a handle to the DLL module.
6883 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006885 /* First clear any error, it's not cleared by the dlopen() call. */
6886 (void)dlerror();
6887
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 hinstLib = dlopen((char *)libname, RTLD_LAZY
6889# ifdef RTLD_LOCAL
6890 | RTLD_LOCAL
6891# endif
6892 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006893 if (hinstLib == NULL)
6894 {
6895 /* "dlerr" must be used before dlclose() */
6896 dlerr = (char *)dlerror();
6897 if (dlerr != NULL)
6898 EMSG2(_("dlerror = \"%s\""), dlerr);
6899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900# else
6901 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6902# endif
6903
6904 /* If the handle is valid, try to get the function address. */
6905 if (hinstLib != NULL)
6906 {
6907# ifdef HAVE_SETJMP_H
6908 /*
6909 * Catch a crash when calling the library function. For example when
6910 * using a number where a string pointer is expected.
6911 */
6912 mch_startjmp();
6913 if (SETJMP(lc_jump_env) != 0)
6914 {
6915 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006916# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006917 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006918# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 mch_didjmp();
6920 }
6921 else
6922# endif
6923 {
6924 retval_str = NULL;
6925 retval_int = 0;
6926
6927 if (argstring != NULL)
6928 {
6929# if defined(USE_DLOPEN)
6930 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006931 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932# else
6933 if (shl_findsym(&hinstLib, (const char *)funcname,
6934 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6935 ProcAdd = NULL;
6936# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006937 if ((success = (ProcAdd != NULL
6938# if defined(USE_DLOPEN)
6939 && dlerr == NULL
6940# endif
6941 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 {
6943 if (string_result == NULL)
6944 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6945 else
6946 retval_str = (ProcAdd)(argstring);
6947 }
6948 }
6949 else
6950 {
6951# if defined(USE_DLOPEN)
6952 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006953 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954# else
6955 if (shl_findsym(&hinstLib, (const char *)funcname,
6956 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6957 ProcAddI = NULL;
6958# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006959 if ((success = (ProcAddI != NULL
6960# if defined(USE_DLOPEN)
6961 && dlerr == NULL
6962# endif
6963 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 {
6965 if (string_result == NULL)
6966 retval_int = ((INTPROCINT)ProcAddI)(argint);
6967 else
6968 retval_str = (ProcAddI)(argint);
6969 }
6970 }
6971
6972 /* Save the string before we free the library. */
6973 /* Assume that a "1" or "-1" result is an illegal pointer. */
6974 if (string_result == NULL)
6975 *number_result = retval_int;
6976 else if (retval_str != NULL
6977 && retval_str != (char_u *)1
6978 && retval_str != (char_u *)-1)
6979 *string_result = vim_strsave(retval_str);
6980 }
6981
6982# ifdef HAVE_SETJMP_H
6983 mch_endjmp();
6984# ifdef SIGHASARG
6985 if (lc_signal != 0)
6986 {
6987 int i;
6988
6989 /* try to find the name of this signal */
6990 for (i = 0; signal_info[i].sig != -1; i++)
6991 if (lc_signal == signal_info[i].sig)
6992 break;
6993 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6994 }
6995# endif
6996# endif
6997
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006999 /* "dlerr" must be used before dlclose() */
7000 if (dlerr != NULL)
7001 EMSG2(_("dlerror = \"%s\""), dlerr);
7002
7003 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 (void)dlclose(hinstLib);
7005# else
7006 (void)shl_unload(hinstLib);
7007# endif
7008 }
7009
7010 if (!success)
7011 {
7012 EMSG2(_(e_libcall), funcname);
7013 return FAIL;
7014 }
7015
7016 return OK;
7017}
7018#endif
7019
7020#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7021static int xterm_trace = -1; /* default: disabled */
7022static int xterm_button;
7023
7024/*
7025 * Setup a dummy window for X selections in a terminal.
7026 */
7027 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007028setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029{
7030 int z = 0;
7031 char *strp = "";
7032 Widget AppShell;
7033
7034 if (!x_connect_to_server())
7035 return;
7036
7037 open_app_context();
7038 if (app_context != NULL && xterm_Shell == (Widget)0)
7039 {
7040 int (*oldhandler)();
7041#if defined(HAVE_SETJMP_H)
7042 int (*oldIOhandler)();
7043#endif
7044# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7045 struct timeval start_tv;
7046
7047 if (p_verbose > 0)
7048 gettimeofday(&start_tv, NULL);
7049# endif
7050
7051 /* Ignore X errors while opening the display */
7052 oldhandler = XSetErrorHandler(x_error_check);
7053
7054#if defined(HAVE_SETJMP_H)
7055 /* Ignore X IO errors while opening the display */
7056 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7057 mch_startjmp();
7058 if (SETJMP(lc_jump_env) != 0)
7059 {
7060 mch_didjmp();
7061 xterm_dpy = NULL;
7062 }
7063 else
7064#endif
7065 {
7066 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7067 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7068#if defined(HAVE_SETJMP_H)
7069 mch_endjmp();
7070#endif
7071 }
7072
7073#if defined(HAVE_SETJMP_H)
7074 /* Now handle X IO errors normally. */
7075 (void)XSetIOErrorHandler(oldIOhandler);
7076#endif
7077 /* Now handle X errors normally. */
7078 (void)XSetErrorHandler(oldhandler);
7079
7080 if (xterm_dpy == NULL)
7081 {
7082 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007083 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 return;
7085 }
7086
7087 /* Catch terminating error of the X server connection. */
7088 (void)XSetIOErrorHandler(x_IOerror_handler);
7089
7090# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7091 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007092 {
7093 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007095 verbose_leave();
7096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097# endif
7098
7099 /* Create a Shell to make converters work. */
7100 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7101 applicationShellWidgetClass, xterm_dpy,
7102 NULL);
7103 if (AppShell == (Widget)0)
7104 return;
7105 xterm_Shell = XtVaCreatePopupShell("VIM",
7106 topLevelShellWidgetClass, AppShell,
7107 XtNmappedWhenManaged, 0,
7108 XtNwidth, 1,
7109 XtNheight, 1,
7110 NULL);
7111 if (xterm_Shell == (Widget)0)
7112 return;
7113
7114 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007115 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 if (x11_display == NULL)
7117 x11_display = xterm_dpy;
7118
7119 XtRealizeWidget(xterm_Shell);
7120 XSync(xterm_dpy, False);
7121 xterm_update();
7122 }
7123 if (xterm_Shell != (Widget)0)
7124 {
7125 clip_init(TRUE);
7126 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7127 x11_window = (Window)atol(strp);
7128 /* Check if $WINDOWID is valid. */
7129 if (test_x11_window(xterm_dpy) == FAIL)
7130 x11_window = 0;
7131 if (x11_window != 0)
7132 xterm_trace = 0;
7133 }
7134}
7135
7136 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007137start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138{
7139 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7140 return;
7141 xterm_trace = 1;
7142 xterm_button = button;
7143 do_xterm_trace();
7144}
7145
7146
7147 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007148stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149{
7150 if (xterm_trace < 0)
7151 return;
7152 xterm_trace = 0;
7153}
7154
7155/*
7156 * Query the xterm pointer and generate mouse termcodes if necessary
7157 * return TRUE if dragging is active, else FALSE
7158 */
7159 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007160do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161{
7162 Window root, child;
7163 int root_x, root_y;
7164 int win_x, win_y;
7165 int row, col;
7166 int_u mask_return;
7167 char_u buf[50];
7168 char_u *strp;
7169 long got_hints;
7170 static char_u *mouse_code;
7171 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7172 static int prev_row = 0, prev_col = 0;
7173 static XSizeHints xterm_hints;
7174
7175 if (xterm_trace <= 0)
7176 return FALSE;
7177
7178 if (xterm_trace == 1)
7179 {
7180 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007181 * have changed recently. */
7182 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7183 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184 || xterm_hints.width_inc <= 1
7185 || xterm_hints.height_inc <= 1)
7186 {
7187 xterm_trace = -1; /* Not enough data -- disable tracing */
7188 return FALSE;
7189 }
7190
7191 /* Rely on the same mouse code for the duration of this */
7192 mouse_code = find_termcode(mouse_name);
7193 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007194 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195 xterm_trace = 2;
7196
7197 /* Find the offset of the chars, there might be a scrollbar on the
7198 * left of the window and/or a menu on the top (eterm etc.) */
7199 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7200 &win_x, &win_y, &mask_return);
7201 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7202 - (xterm_hints.height_inc / 2);
7203 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7204 xterm_hints.y = 2;
7205 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7206 - (xterm_hints.width_inc / 2);
7207 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7208 xterm_hints.x = 2;
7209 return TRUE;
7210 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007211 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212 {
7213 xterm_trace = 0;
7214 return FALSE;
7215 }
7216
7217 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7218 &win_x, &win_y, &mask_return);
7219
7220 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7221 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7222 if (row == prev_row && col == prev_col)
7223 return TRUE;
7224
7225 STRCPY(buf, mouse_code);
7226 strp = buf + STRLEN(buf);
7227 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7228 *strp++ = (char_u)(col + ' ' + 1);
7229 *strp++ = (char_u)(row + ' ' + 1);
7230 *strp = 0;
7231 add_to_input_buf(buf, STRLEN(buf));
7232
7233 prev_row = row;
7234 prev_col = col;
7235 return TRUE;
7236}
7237
7238# if defined(FEAT_GUI) || defined(PROTO)
7239/*
7240 * Destroy the display, window and app_context. Required for GTK.
7241 */
7242 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007243clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244{
7245 if (xterm_Shell != (Widget)0)
7246 {
7247 XtDestroyWidget(xterm_Shell);
7248 xterm_Shell = (Widget)0;
7249 }
7250 if (xterm_dpy != NULL)
7251 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007252# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 /* Lesstif and Solaris crash here, lose some memory */
7254 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007255# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 if (x11_display == xterm_dpy)
7257 x11_display = NULL;
7258 xterm_dpy = NULL;
7259 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007260# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 if (app_context != (XtAppContext)NULL)
7262 {
7263 /* Lesstif and Solaris crash here, lose some memory */
7264 XtDestroyApplicationContext(app_context);
7265 app_context = (XtAppContext)NULL;
7266 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007267# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268}
7269# endif
7270
7271/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007272 * Catch up with GUI or X events.
7273 */
7274 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007275clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007276{
7277# ifdef FEAT_GUI
7278 if (gui.in_use)
7279 gui_mch_update();
7280 else
7281# endif
7282 if (xterm_Shell != (Widget)0)
7283 xterm_update();
7284}
7285
7286/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 * Catch up with any queued X events. This may put keyboard input into the
7288 * input buffer, call resize call-backs, trigger timers etc. If there is
7289 * nothing in the X event queue (& no timers pending), then we return
7290 * immediately.
7291 */
7292 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007293xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294{
7295 XEvent event;
7296
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007297 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007299 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007301 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007302 break;
7303
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007304 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007305 {
7306 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007307 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007308#ifdef FEAT_CLIENTSERVER
7309 {
7310 XPropertyEvent *e = (XPropertyEvent *)&event;
7311
7312 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007314 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007317 XtDispatchEvent(&event);
7318 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007319 else
7320 {
7321 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007322 XtAppProcessEvent(app_context, mask);
7323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 }
7325}
7326
7327 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007328clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329{
7330 if (xterm_Shell != (Widget)0)
7331 return clip_x11_own_selection(xterm_Shell, cbd);
7332 return FAIL;
7333}
7334
7335 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007336clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337{
7338 if (xterm_Shell != (Widget)0)
7339 clip_x11_lose_selection(xterm_Shell, cbd);
7340}
7341
7342 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007343clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344{
7345 if (xterm_Shell != (Widget)0)
7346 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7347}
7348
7349 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007350clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351{
7352 clip_x11_set_selection(cbd);
7353}
7354#endif
7355
7356
7357#if defined(USE_XSMP) || defined(PROTO)
7358/*
7359 * Code for X Session Management Protocol.
7360 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007361static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7362static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7363static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7364static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7365static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366
7367
7368# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007369static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370
7371/*
7372 * This is our chance to ask the user if they want to save,
7373 * or abort the logout
7374 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007376xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377{
7378 cmdmod_T save_cmdmod;
7379 int cancel_shutdown = False;
7380
7381 save_cmdmod = cmdmod;
7382 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007383 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 /* Mustn't logout */
7385 cancel_shutdown = True;
7386 cmdmod = save_cmdmod;
7387 setcursor(); /* position cursor */
7388 out_flush();
7389
7390 /* Done interaction */
7391 SmcInteractDone(smc_conn, cancel_shutdown);
7392
7393 /* Finish off
7394 * Only end save-yourself here if we're not cancelling shutdown;
7395 * we'll get a cancelled callback later in which we'll end it.
7396 * Hopefully get around glitchy SMs (like GNOME-1)
7397 */
7398 if (!cancel_shutdown)
7399 {
7400 xsmp.save_yourself = False;
7401 SmcSaveYourselfDone(smc_conn, True);
7402 }
7403}
7404# endif
7405
7406/*
7407 * Callback that starts save-yourself.
7408 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007410xsmp_handle_save_yourself(
7411 SmcConn smc_conn,
7412 SmPointer client_data UNUSED,
7413 int save_type UNUSED,
7414 Bool shutdown,
7415 int interact_style UNUSED,
7416 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417{
7418 /* Handle already being in saveyourself */
7419 if (xsmp.save_yourself)
7420 SmcSaveYourselfDone(smc_conn, True);
7421 xsmp.save_yourself = True;
7422 xsmp.shutdown = shutdown;
7423
7424 /* First up, preserve all files */
7425 out_flush();
7426 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7427
7428 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007429 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430
7431# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7432 /* Now see if we can ask about unsaved files */
7433 if (shutdown && !fast && gui.in_use)
7434 /* Need to interact with user, but need SM's permission */
7435 SmcInteractRequest(smc_conn, SmDialogError,
7436 xsmp_handle_interaction, client_data);
7437 else
7438# endif
7439 {
7440 /* Can stop the cycle here */
7441 SmcSaveYourselfDone(smc_conn, True);
7442 xsmp.save_yourself = False;
7443 }
7444}
7445
7446
7447/*
7448 * Callback to warn us of imminent death.
7449 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007451xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452{
7453 xsmp_close();
7454
7455 /* quit quickly leaving swapfiles for modified buffers behind */
7456 getout_preserve_modified(0);
7457}
7458
7459
7460/*
7461 * Callback to tell us that save-yourself has completed.
7462 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007464xsmp_save_complete(
7465 SmcConn smc_conn UNUSED,
7466 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467{
7468 xsmp.save_yourself = False;
7469}
7470
7471
7472/*
7473 * Callback to tell us that an instigated shutdown was cancelled
7474 * (maybe even by us)
7475 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007477xsmp_shutdown_cancelled(
7478 SmcConn smc_conn,
7479 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480{
7481 if (xsmp.save_yourself)
7482 SmcSaveYourselfDone(smc_conn, True);
7483 xsmp.save_yourself = False;
7484 xsmp.shutdown = False;
7485}
7486
7487
7488/*
7489 * Callback to tell us that a new ICE connection has been established.
7490 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007492xsmp_ice_connection(
7493 IceConn iceConn,
7494 IcePointer clientData UNUSED,
7495 Bool opening,
7496 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497{
7498 /* Intercept creation of ICE connection fd */
7499 if (opening)
7500 {
7501 xsmp_icefd = IceConnectionNumber(iceConn);
7502 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7503 }
7504}
7505
7506
7507/* Handle any ICE processing that's required; return FAIL if SM lost */
7508 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007509xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007510{
7511 Bool rep;
7512
7513 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7514 == IceProcessMessagesIOError)
7515 {
7516 /* Lost ICE */
7517 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007518 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 xsmp_close();
7520 return FAIL;
7521 }
7522 else
7523 return OK;
7524}
7525
7526static int dummy;
7527
7528/* Set up X Session Management Protocol */
7529 void
7530xsmp_init(void)
7531{
7532 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 SmcCallbacks smcallbacks;
7534#if 0
7535 SmPropValue smname;
7536 SmProp smnameprop;
7537 SmProp *smprops[1];
7538#endif
7539
7540 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007541 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007542
7543 xsmp.save_yourself = xsmp.shutdown = False;
7544
7545 /* Set up SM callbacks - must have all, even if they're not used */
7546 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7547 smcallbacks.save_yourself.client_data = NULL;
7548 smcallbacks.die.callback = xsmp_die;
7549 smcallbacks.die.client_data = NULL;
7550 smcallbacks.save_complete.callback = xsmp_save_complete;
7551 smcallbacks.save_complete.client_data = NULL;
7552 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7553 smcallbacks.shutdown_cancelled.client_data = NULL;
7554
7555 /* Set up a watch on ICE connection creations. The "dummy" argument is
7556 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7557 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7558 {
7559 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007560 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 return;
7562 }
7563
7564 /* Create an SM connection */
7565 xsmp.smcconn = SmcOpenConnection(
7566 NULL,
7567 NULL,
7568 SmProtoMajor,
7569 SmProtoMinor,
7570 SmcSaveYourselfProcMask | SmcDieProcMask
7571 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7572 &smcallbacks,
7573 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007574 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 sizeof(errorstring),
7576 errorstring);
7577 if (xsmp.smcconn == NULL)
7578 {
7579 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007580
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007582 {
7583 vim_snprintf(errorreport, sizeof(errorreport),
7584 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7585 verb_msg((char_u *)errorreport);
7586 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007587 return;
7588 }
7589 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7590
7591#if 0
7592 /* ID ourselves */
7593 smname.value = "vim";
7594 smname.length = 3;
7595 smnameprop.name = "SmProgram";
7596 smnameprop.type = "SmARRAY8";
7597 smnameprop.num_vals = 1;
7598 smnameprop.vals = &smname;
7599
7600 smprops[0] = &smnameprop;
7601 SmcSetProperties(xsmp.smcconn, 1, smprops);
7602#endif
7603}
7604
7605
7606/* Shut down XSMP comms. */
7607 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007608xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609{
7610 if (xsmp_icefd != -1)
7611 {
7612 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007613 if (xsmp.clientid != NULL)
7614 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007615 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 xsmp_icefd = -1;
7617 }
7618}
7619#endif /* USE_XSMP */
7620
7621
7622#ifdef EBCDIC
7623/* Translate character to its CTRL- value */
7624char CtrlTable[] =
7625{
7626/* 00 - 5E */
7627 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7628 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7629 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7630 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7631 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7632 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7633/* ^ */ 0x1E,
7634/* - */ 0x1F,
7635/* 61 - 6C */
7636 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7637/* _ */ 0x1F,
7638/* 6E - 80 */
7639 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7640/* a */ 0x01,
7641/* b */ 0x02,
7642/* c */ 0x03,
7643/* d */ 0x37,
7644/* e */ 0x2D,
7645/* f */ 0x2E,
7646/* g */ 0x2F,
7647/* h */ 0x16,
7648/* i */ 0x05,
7649/* 8A - 90 */
7650 0, 0, 0, 0, 0, 0, 0,
7651/* j */ 0x15,
7652/* k */ 0x0B,
7653/* l */ 0x0C,
7654/* m */ 0x0D,
7655/* n */ 0x0E,
7656/* o */ 0x0F,
7657/* p */ 0x10,
7658/* q */ 0x11,
7659/* r */ 0x12,
7660/* 9A - A1 */
7661 0, 0, 0, 0, 0, 0, 0, 0,
7662/* s */ 0x13,
7663/* t */ 0x3C,
7664/* u */ 0x3D,
7665/* v */ 0x32,
7666/* w */ 0x26,
7667/* x */ 0x18,
7668/* y */ 0x19,
7669/* z */ 0x3F,
7670/* AA - AC */
7671 0, 0, 0,
7672/* [ */ 0x27,
7673/* AE - BC */
7674 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7675/* ] */ 0x1D,
7676/* BE - C0 */ 0, 0, 0,
7677/* A */ 0x01,
7678/* B */ 0x02,
7679/* C */ 0x03,
7680/* D */ 0x37,
7681/* E */ 0x2D,
7682/* F */ 0x2E,
7683/* G */ 0x2F,
7684/* H */ 0x16,
7685/* I */ 0x05,
7686/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7687/* J */ 0x15,
7688/* K */ 0x0B,
7689/* L */ 0x0C,
7690/* M */ 0x0D,
7691/* N */ 0x0E,
7692/* O */ 0x0F,
7693/* P */ 0x10,
7694/* Q */ 0x11,
7695/* R */ 0x12,
7696/* DA - DF */ 0, 0, 0, 0, 0, 0,
7697/* \ */ 0x1C,
7698/* E1 */ 0,
7699/* S */ 0x13,
7700/* T */ 0x3C,
7701/* U */ 0x3D,
7702/* V */ 0x32,
7703/* W */ 0x26,
7704/* X */ 0x18,
7705/* Y */ 0x19,
7706/* Z */ 0x3F,
7707/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7708 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7709};
7710
7711char MetaCharTable[]=
7712{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7713 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7714 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7715 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7716 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7717};
7718
7719
7720/* TODO: Use characters NOT numbers!!! */
7721char CtrlCharTable[]=
7722{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7723 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7724 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7725 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7726 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7727};
7728
7729
7730#endif