blob: 6b26b062038417af668e8e2197bcc8ce8247e2a0 [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 Moolenaar01688ad2016-10-27 20:00:07 +0200407 int did_start_blocking = FALSE;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200408 long wait_time;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200409 long elapsed_time = 0;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200410#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
411 struct timeval start_tv;
412
413 gettimeofday(&start_tv, NULL);
414#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200416 /* repeat until we got a character or waited long enough */
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200417 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 {
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200419 /* Check if window changed size while we were busy, perhaps the ":set
420 * columns=99" command was used. */
421 while (do_resize)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000422 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200423
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200424#ifdef MESSAGE_QUEUE
425 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200426#endif
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200427 if (wtime < 0 && did_start_blocking)
428 /* blocking and already waited for p_ut */
429 wait_time = -1;
430 else
431 {
432 if (wtime >= 0)
433 wait_time = wtime;
434 else
435 /* going to block after p_ut */
436 wait_time = p_ut;
437#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
438 elapsed_time = elapsed(&start_tv);
439#endif
440 wait_time -= elapsed_time;
441 if (wait_time < 0)
442 {
443 if (wtime >= 0)
444 /* no character available within "wtime" */
445 return 0;
446
447 if (wtime < 0)
448 {
449 /* no character available within 'updatetime' */
450 did_start_blocking = TRUE;
451#ifdef FEAT_AUTOCMD
452 if (trigger_cursorhold() && maxlen >= 3
453 && !typebuf_changed(tb_change_cnt))
454 {
455 buf[0] = K_SPECIAL;
456 buf[1] = KS_EXTRA;
457 buf[2] = (int)KE_CURSORHOLD;
458 return 3;
459 }
460#endif
461 /*
462 * If there is no character available within 'updatetime'
463 * seconds flush all the swap files to disk.
464 * Also done when interrupted by SIGWINCH.
465 */
466 before_blocking();
467 continue;
468 }
469 }
470 }
471
472#ifdef FEAT_JOB_CHANNEL
473 /* Checking if a job ended requires polling. Do this every 100 msec. */
474 if (has_pending_job() && (wait_time < 0 || wait_time > 100L))
475 wait_time = 100L;
476#endif
477
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200479 * We want to be interrupted by the winch signal
480 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481 */
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200482 if (WaitForChar(wait_time, &interrupted))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200483 {
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200484 /* If input was put directly in typeahead buffer bail out here. */
485 if (typebuf_changed(tb_change_cnt))
486 return 0;
487
488 /*
489 * For some terminals we only get one character at a time.
490 * We want the get all available characters, so we could keep on
491 * trying until none is available
492 * For some other terminals this is quite slow, that's why we don't
493 * do it.
494 */
495 len = read_from_input_buf(buf, (long)maxlen);
496 if (len > 0)
497 return len;
498 continue;
Bram Moolenaar67c53842010-05-22 18:28:27 +0200499 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200501 /* no character available */
502#if !(defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H))
503 /* estimate the elapsed time */
504 elapsed += wait_time;
505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200507 if (do_resize /* interrupted by SIGWINCH signal */
508#ifdef FEAT_CLIENTSERVER
509 || server_waiting()
510#endif
511#ifdef MESSAGE_QUEUE
512 || interrupted
513#endif
514 || wait_time > 0
515 || !did_start_blocking)
516 continue;
517
518 /* no character available or interrupted */
519 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 }
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200521 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522}
523
524 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100525handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526{
527 do_resize = FALSE;
528 shell_resized();
529}
530
531/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200532 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 */
534 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100535mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536{
Bram Moolenaarcda77642016-06-04 13:32:35 +0200537 return WaitForChar(0L, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538}
539
540#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
541# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000542# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543# endif
544# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
545# include <sys/sysctl.h>
546# endif
547# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
548# include <sys/sysinfo.h>
549# endif
550
551/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000552 * Return total amount of memory available in Kbyte.
553 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000554 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100556mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000559 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200561# ifdef HAVE_SYSCTL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562 int mib[2], physmem;
563 size_t len;
564
565 /* BSD way of getting the amount of RAM available. */
566 mib[0] = CTL_HW;
567 mib[1] = HW_USERMEM;
568 len = sizeof(physmem);
569 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
570 mem = (long_u)physmem;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200571# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200573# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574 if (mem == 0)
575 {
576 struct sysinfo sinfo;
577
578 /* Linux way of getting amount of RAM available */
579 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000580 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200581# ifdef HAVE_SYSINFO_MEM_UNIT
Bram Moolenaar914572a2007-05-01 11:37:47 +0000582 /* avoid overflow as much as possible */
583 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
584 {
585 sinfo.mem_unit = sinfo.mem_unit >> 1;
586 --shiftright;
587 }
588 mem = sinfo.totalram * sinfo.mem_unit;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200589# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590 mem = sinfo.totalram;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200591# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200596# ifdef HAVE_SYSCONF
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597 if (mem == 0)
598 {
599 long pagesize, pagecount;
600
601 /* Solaris way of getting amount of RAM available */
602 pagesize = sysconf(_SC_PAGESIZE);
603 pagecount = sysconf(_SC_PHYS_PAGES);
604 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000605 {
606 /* avoid overflow as much as possible */
607 while (shiftright > 0 && (pagesize & 1) == 0)
608 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000609 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000610 --shiftright;
611 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200615# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616
617 /* Return the minimum of the physical memory and the user limit, because
618 * using more than the user limit may cause Vim to be terminated. */
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200619# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 {
621 struct rlimit rlp;
622
623 if (getrlimit(RLIMIT_DATA, &rlp) == 0
624 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200625# ifdef RLIM_INFINITY
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 && rlp.rlim_cur != RLIM_INFINITY
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200627# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000628 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000630 {
631 mem = (long_u)rlp.rlim_cur;
632 shiftright = 10;
633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200635# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636
637 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000638 return mem >> shiftright;
639 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640}
641#endif
642
643 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100644mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645{
646 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000647#ifdef FEAT_MZSCHEME
648 long total = msec; /* remember original value */
649#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650
651 if (ignoreinput)
652 {
653 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000654 * here. But we don't want QUIT to kill us (CTRL-\ used in a
655 * shell may produce SIGQUIT). */
656 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 old_tmode = curr_tmode;
658 if (curr_tmode == TMODE_RAW)
659 settmode(TMODE_SLEEP);
660
661 /*
662 * Everybody sleeps in a different way...
663 * Prefer nanosleep(), some versions of usleep() can only sleep up to
664 * one second.
665 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000666#ifdef FEAT_MZSCHEME
667 do
668 {
669 /* if total is large enough, wait by portions in p_mzq */
670 if (total > p_mzq)
671 msec = p_mzq;
672 else
673 msec = total;
674 total -= msec;
675#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676#ifdef HAVE_NANOSLEEP
677 {
678 struct timespec ts;
679
680 ts.tv_sec = msec / 1000;
681 ts.tv_nsec = (msec % 1000) * 1000000;
682 (void)nanosleep(&ts, NULL);
683 }
684#else
685# ifdef HAVE_USLEEP
686 while (msec >= 1000)
687 {
688 usleep((unsigned int)(999 * 1000));
689 msec -= 999;
690 }
691 usleep((unsigned int)(msec * 1000));
692# else
693# ifndef HAVE_SELECT
694 poll(NULL, 0, (int)msec);
695# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696 {
697 struct timeval tv;
698
699 tv.tv_sec = msec / 1000;
700 tv.tv_usec = (msec % 1000) * 1000;
701 /*
702 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
703 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
704 */
705 select(0, NULL, NULL, NULL, &tv);
706 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707# endif /* HAVE_SELECT */
708# endif /* HAVE_NANOSLEEP */
709#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000710#ifdef FEAT_MZSCHEME
711 }
712 while (total > 0);
713#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714
715 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000716 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 }
718 else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200719 WaitForChar(msec, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720}
721
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000722#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
724# define HAVE_CHECK_STACK_GROWTH
725/*
726 * Support for checking for an almost-out-of-stack-space situation.
727 */
728
729/*
730 * Return a pointer to an item on the stack. Used to find out if the stack
731 * grows up or down.
732 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100733static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000734static int stack_grows_downwards;
735
736/*
737 * Find out if the stack grows upwards or downwards.
738 * "p" points to a variable on the stack of the caller.
739 */
740 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100741check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742{
743 int i;
744
745 stack_grows_downwards = (p > (char *)&i);
746}
747#endif
748
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000749#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750static char *stack_limit = NULL;
751
752#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
753# include <pthread.h>
754# include <pthread_np.h>
755#endif
756
757/*
758 * Find out until how var the stack can grow without getting into trouble.
759 * Called when starting up and when switching to the signal stack in
760 * deathtrap().
761 */
762 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100763get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764{
765 struct rlimit rlp;
766 int i;
767 long lim;
768
769 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
770 * limit doesn't fit in a long (rlim_cur might be "long long"). */
771 if (getrlimit(RLIMIT_STACK, &rlp) == 0
772 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
773# ifdef RLIM_INFINITY
774 && rlp.rlim_cur != RLIM_INFINITY
775# endif
776 )
777 {
778 lim = (long)rlp.rlim_cur;
779#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
780 {
781 pthread_attr_t attr;
782 size_t size;
783
784 /* On FreeBSD the initial thread always has a fixed stack size, no
785 * matter what the limits are set to. Normally it's 1 Mbyte. */
786 pthread_attr_init(&attr);
787 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
788 {
789 pthread_attr_getstacksize(&attr, &size);
790 if (lim > (long)size)
791 lim = (long)size;
792 }
793 pthread_attr_destroy(&attr);
794 }
795#endif
796 if (stack_grows_downwards)
797 {
798 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
799 if (stack_limit >= (char *)&i)
800 /* overflow, set to 1/16 of current stack position */
801 stack_limit = (char *)((long)&i / 16L);
802 }
803 else
804 {
805 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
806 if (stack_limit <= (char *)&i)
807 stack_limit = NULL; /* overflow */
808 }
809 }
810}
811
812/*
813 * Return FAIL when running out of stack space.
814 * "p" must point to any variable local to the caller that's on the stack.
815 */
816 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100817mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818{
819 if (stack_limit != NULL)
820 {
821 if (stack_grows_downwards)
822 {
823 if (p < stack_limit)
824 return FAIL;
825 }
826 else if (p > stack_limit)
827 return FAIL;
828 }
829 return OK;
830}
831#endif
832
833#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
834/*
835 * Support for using the signal stack.
836 * This helps when we run out of stack space, which causes a SIGSEGV. The
837 * signal handler then must run on another stack, since the normal stack is
838 * completely full.
839 */
840
Bram Moolenaar39766a72013-11-03 00:41:00 +0100841#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100842# include <AvailabilityMacros.h>
843#endif
844
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845#ifndef SIGSTKSZ
846# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
847#endif
848
849# ifdef HAVE_SIGALTSTACK
850static stack_t sigstk; /* for sigaltstack() */
851# else
852static struct sigstack sigstk; /* for sigstack() */
853# endif
854
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100855static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856static char *signal_stack;
857
858 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100859init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860{
861 if (signal_stack != NULL)
862 {
863# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000864# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
865 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
867 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100868 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869# endif
870
871# ifdef HAVE_SS_BASE
872 sigstk.ss_base = signal_stack;
873# else
874 sigstk.ss_sp = signal_stack;
875# endif
876 sigstk.ss_size = SIGSTKSZ;
877 sigstk.ss_flags = 0;
878 (void)sigaltstack(&sigstk, NULL);
879# else
880 sigstk.ss_sp = signal_stack;
881 if (stack_grows_downwards)
882 sigstk.ss_sp += SIGSTKSZ - 1;
883 sigstk.ss_onstack = 0;
884 (void)sigstack(&sigstk, NULL);
885# endif
886 }
887}
888#endif
889
890/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000891 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 * will barf when the second argument to signal() is ``wrong''.
893 * Let me try it with a few tricky defines from my own osdef.h (jw).
894 */
895#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 static RETSIGTYPE
897sig_winch SIGDEFARG(sigarg)
898{
899 /* this is not required on all systems, but it doesn't hurt anybody */
900 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
901 do_resize = TRUE;
902 SIGRETURN;
903}
904#endif
905
906#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907 static RETSIGTYPE
908catch_sigint SIGDEFARG(sigarg)
909{
910 /* this is not required on all systems, but it doesn't hurt anybody */
911 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
912 got_int = TRUE;
913 SIGRETURN;
914}
915#endif
916
917#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918 static RETSIGTYPE
919catch_sigpwr SIGDEFARG(sigarg)
920{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000921 /* this is not required on all systems, but it doesn't hurt anybody */
922 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 /*
924 * I'm not sure we get the SIGPWR signal when the system is really going
925 * down or when the batteries are almost empty. Just preserve the swap
926 * files and don't exit, that can't do any harm.
927 */
928 ml_sync_all(FALSE, FALSE);
929 SIGRETURN;
930}
931#endif
932
933#ifdef SET_SIG_ALARM
934/*
935 * signal function for alarm().
936 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 static RETSIGTYPE
938sig_alarm SIGDEFARG(sigarg)
939{
940 /* doesn't do anything, just to break a system call */
941 sig_alarm_called = TRUE;
942 SIGRETURN;
943}
944#endif
945
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000946#if (defined(HAVE_SETJMP_H) \
947 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
948 || defined(FEAT_LIBCALL))) \
949 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950/*
951 * A simplistic version of setjmp() that only allows one level of using.
952 * Don't call twice before calling mch_endjmp()!.
953 * Usage:
954 * mch_startjmp();
955 * if (SETJMP(lc_jump_env) != 0)
956 * {
957 * mch_didjmp();
958 * EMSG("crash!");
959 * }
960 * else
961 * {
962 * do_the_work;
963 * mch_endjmp();
964 * }
965 * Note: Can't move SETJMP() here, because a function calling setjmp() must
966 * not return before the saved environment is used.
967 * Returns OK for normal return, FAIL when the protected code caused a
968 * problem and LONGJMP() was used.
969 */
970 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100971mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972{
973#ifdef SIGHASARG
974 lc_signal = 0;
975#endif
976 lc_active = TRUE;
977}
978
979 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100980mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981{
982 lc_active = FALSE;
983}
984
985 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100986mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987{
988# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
989 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
990 * otherwise catching the signal only works once. */
991 init_signal_stack();
992# endif
993}
994#endif
995
996/*
997 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200998 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001000 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
1001 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 */
1003 static RETSIGTYPE
1004deathtrap SIGDEFARG(sigarg)
1005{
1006 static int entered = 0; /* count the number of times we got here.
1007 Note: when memory has been corrupted
1008 this may get an arbitrary value! */
1009#ifdef SIGHASARG
1010 int i;
1011#endif
1012
1013#if defined(HAVE_SETJMP_H)
1014 /*
1015 * Catch a crash in protected code.
1016 * Restores the environment saved in lc_jump_env, which looks like
1017 * SETJMP() returns 1.
1018 */
1019 if (lc_active)
1020 {
1021# if defined(SIGHASARG)
1022 lc_signal = sigarg;
1023# endif
1024 lc_active = FALSE; /* don't jump again */
1025 LONGJMP(lc_jump_env, 1);
1026 /* NOTREACHED */
1027 }
1028#endif
1029
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001030#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001031# ifdef SIGQUIT
1032 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1033 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1034 * pressing CTRL-\, but we don't want Vim to exit then. */
1035 if (in_mch_delay && sigarg == SIGQUIT)
1036 SIGRETURN;
1037# endif
1038
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001039 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1040 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1041 * free(). Calling free() again may then cause a crash. */
1042 if (entered == 0
1043 && (0
1044# ifdef SIGHUP
1045 || sigarg == SIGHUP
1046# endif
1047# ifdef SIGQUIT
1048 || sigarg == SIGQUIT
1049# endif
1050# ifdef SIGTERM
1051 || sigarg == SIGTERM
1052# endif
1053# ifdef SIGPWR
1054 || sigarg == SIGPWR
1055# endif
1056# ifdef SIGUSR1
1057 || sigarg == SIGUSR1
1058# endif
1059# ifdef SIGUSR2
1060 || sigarg == SIGUSR2
1061# endif
1062 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001063 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001064 SIGRETURN;
1065#endif
1066
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 /* Remember how often we have been called. */
1068 ++entered;
1069
Bram Moolenaare429e702016-06-10 19:49:14 +02001070#ifdef FEAT_AUTOCMD
1071 /* Executing autocommands is likely to use more stack space than we have
1072 * available in the signal stack. */
1073 block_autocmds();
1074#endif
1075
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076#ifdef FEAT_EVAL
1077 /* Set the v:dying variable. */
1078 set_vim_var_nr(VV_DYING, (long)entered);
1079#endif
1080
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001081#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001082 /* Since we are now using the signal stack, need to reset the stack
1083 * limit. Otherwise using a regexp will fail. */
1084 get_stack_limit();
1085#endif
1086
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001087#if 0
1088 /* This is for opening gdb the moment Vim crashes.
1089 * You need to manually adjust the file name and Vim executable name.
1090 * Suggested by SungHyun Nam. */
1091 {
1092# define VI_GDB_FILE "/tmp/vimgdb"
1093# define VIM_NAME "/usr/bin/vim"
1094 FILE *fp = fopen(VI_GDB_FILE, "w");
1095 if (fp)
1096 {
1097 fprintf(fp,
1098 "file %s\n"
1099 "attach %d\n"
1100 "set height 1000\n"
1101 "bt full\n"
1102 , VIM_NAME, getpid());
1103 fclose(fp);
1104 system("xterm -e gdb -x "VI_GDB_FILE);
1105 unlink(VI_GDB_FILE);
1106 }
1107 }
1108#endif
1109
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110#ifdef SIGHASARG
1111 /* try to find the name of this signal */
1112 for (i = 0; signal_info[i].sig != -1; i++)
1113 if (sigarg == signal_info[i].sig)
1114 break;
1115 deadly_signal = sigarg;
1116#endif
1117
1118 full_screen = FALSE; /* don't write message to the GUI, it might be
1119 * part of the problem... */
1120 /*
1121 * If something goes wrong after entering here, we may get here again.
1122 * When this happens, give a message and try to exit nicely (resetting the
1123 * terminal mode, etc.)
1124 * When this happens twice, just exit, don't even try to give a message,
1125 * stack may be corrupt or something weird.
1126 * When this still happens again (or memory was corrupted in such a way
1127 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1128 */
1129 if (entered >= 3)
1130 {
1131 reset_signals(); /* don't catch any signals anymore */
1132 may_core_dump();
1133 if (entered >= 4)
1134 _exit(8);
1135 exit(7);
1136 }
1137 if (entered == 2)
1138 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001139 /* No translation, it may call malloc(). */
1140 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141 out_flush();
1142 getout(1);
1143 }
1144
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001145 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001147 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 signal_info[i].name);
1149#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001150 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001152
1153 /* Preserve files and exit. This sets the really_exiting flag to prevent
1154 * calling free(). */
1155 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156
Bram Moolenaare429e702016-06-10 19:49:14 +02001157 /* NOTREACHED */
1158
Bram Moolenaar009b2592004-10-24 19:18:58 +00001159#ifdef NBDEBUG
1160 reset_signals();
1161 may_core_dump();
1162 abort();
1163#endif
1164
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 SIGRETURN;
1166}
1167
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001168#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169/*
1170 * On Solaris with multi-threading, suspending might not work immediately.
1171 * Catch the SIGCONT signal, which will be used as an indication whether the
1172 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001173 *
1174 * On Linux, signal is not always handled immediately either.
1175 * See https://bugs.launchpad.net/bugs/291373
1176 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001177 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001179static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001180static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181
1182/*
1183 * signal handler for SIGCONT
1184 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 static RETSIGTYPE
1186sigcont_handler SIGDEFARG(sigarg)
1187{
1188 sigcont_received = TRUE;
1189 SIGRETURN;
1190}
1191#endif
1192
Bram Moolenaar62b42182010-09-21 22:09:37 +02001193# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001194static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001195# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001196static void save_clipboard(void);
1197static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001198
1199static void *clip_star_save = NULL;
1200static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001201# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001202
1203/*
1204 * Called when Vim is going to sleep or execute a shell command.
1205 * We can't respond to requests for the X selections. Lose them, otherwise
1206 * other applications will hang. But first copy the text to cut buffer 0.
1207 */
1208 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001209loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001210{
1211 if (clip_star.owned || clip_plus.owned)
1212 {
1213 x11_export_final_selection();
1214 if (clip_star.owned)
1215 clip_lose_selection(&clip_star);
1216 if (clip_plus.owned)
1217 clip_lose_selection(&clip_plus);
1218 if (x11_display != NULL)
1219 XFlush(x11_display);
1220 }
1221}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001222
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001223# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001224/*
1225 * Save clipboard text to restore later.
1226 */
1227 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001228save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001229{
1230 if (clip_star.owned)
1231 clip_star_save = get_register('*', TRUE);
1232 if (clip_plus.owned)
1233 clip_plus_save = get_register('+', TRUE);
1234}
1235
1236/*
1237 * Restore clipboard text if no one own the X selection.
1238 */
1239 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001240restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001241{
1242 if (clip_star_save != NULL)
1243 {
1244 if (!clip_gen_owner_exists(&clip_star))
1245 put_register('*', clip_star_save);
1246 else
1247 free_register(clip_star_save);
1248 clip_star_save = NULL;
1249 }
1250 if (clip_plus_save != NULL)
1251 {
1252 if (!clip_gen_owner_exists(&clip_plus))
1253 put_register('+', clip_plus_save);
1254 else
1255 free_register(clip_plus_save);
1256 clip_plus_save = NULL;
1257 }
1258}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001259# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001260#endif
1261
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262/*
1263 * If the machine has job control, use it to suspend the program,
1264 * otherwise fake it by starting a new shell.
1265 */
1266 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001267mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268{
1269 /* BeOS does have SIGTSTP, but it doesn't work. */
1270#if defined(SIGTSTP) && !defined(__BEOS__)
1271 out_flush(); /* needed to make cursor visible on some systems */
1272 settmode(TMODE_COOK);
1273 out_flush(); /* needed to disable mouse on some systems */
1274
1275# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001276 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277# endif
1278
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001279# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280 sigcont_received = FALSE;
1281# endif
1282 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001283# if defined(_REENTRANT) && defined(SIGCONT)
1284 /*
1285 * Wait for the SIGCONT signal to be handled. It generally happens
1286 * immediately, but somehow not all the time. Do not call pause()
1287 * because there would be race condition which would hang Vim if
1288 * signal happened in between the test of sigcont_received and the
1289 * call to pause(). If signal is not yet received, call sleep(0)
1290 * to just yield CPU. Signal should then be received. If somehow
1291 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1292 * further if signal is not received after 1+2+3+4 ms (not expected
1293 * to happen).
1294 */
1295 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001296 long wait_time;
1297 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001298 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001299 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001300 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301# endif
1302
1303# ifdef FEAT_TITLE
1304 /*
1305 * Set oldtitle to NULL, so the current title is obtained again.
1306 */
1307 vim_free(oldtitle);
1308 oldtitle = NULL;
1309# endif
1310 settmode(TMODE_RAW);
1311 need_check_timestamps = TRUE;
1312 did_check_timestamps = FALSE;
1313#else
1314 suspend_shell();
1315#endif
1316}
1317
1318 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001319mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320{
1321 Columns = 80;
1322 Rows = 24;
1323
1324 out_flush();
1325 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001326
Bram Moolenaar56718732006-03-15 22:53:57 +00001327#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001328 mac_conv_init();
1329#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001330#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1331 win_clip_init();
1332#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001333}
1334
1335 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001336set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337{
1338#if defined(SIGWINCH)
1339 /*
1340 * WINDOW CHANGE signal is handled with sig_winch().
1341 */
1342 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1343#endif
1344
1345 /*
1346 * We want the STOP signal to work, to make mch_suspend() work.
1347 * For "rvim" the STOP signal is ignored.
1348 */
1349#ifdef SIGTSTP
1350 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1351#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001352#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 signal(SIGCONT, sigcont_handler);
1354#endif
1355
1356 /*
1357 * We want to ignore breaking of PIPEs.
1358 */
1359#ifdef SIGPIPE
1360 signal(SIGPIPE, SIG_IGN);
1361#endif
1362
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001364 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365#endif
1366
1367 /*
1368 * Ignore alarm signals (Perl's alarm() generates it).
1369 */
1370#ifdef SIGALRM
1371 signal(SIGALRM, SIG_IGN);
1372#endif
1373
1374 /*
1375 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1376 * work will be lost.
1377 */
1378#ifdef SIGPWR
1379 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1380#endif
1381
1382 /*
1383 * Arrange for other signals to gracefully shutdown Vim.
1384 */
1385 catch_signals(deathtrap, SIG_ERR);
1386
1387#if defined(FEAT_GUI) && defined(SIGHUP)
1388 /*
1389 * When the GUI is running, ignore the hangup signal.
1390 */
1391 if (gui.in_use)
1392 signal(SIGHUP, SIG_IGN);
1393#endif
1394}
1395
Bram Moolenaardf177f62005-02-22 08:39:57 +00001396#if defined(SIGINT) || defined(PROTO)
1397/*
1398 * Catch CTRL-C (only works while in Cooked mode).
1399 */
1400 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001401catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001402{
1403 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1404}
1405#endif
1406
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001408reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409{
1410 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001411#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412 /* SIGCONT isn't in the list, because its default action is ignore */
1413 signal(SIGCONT, SIG_DFL);
1414#endif
1415}
1416
1417 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001418catch_signals(
1419 RETSIGTYPE (*func_deadly)(),
1420 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421{
1422 int i;
1423
1424 for (i = 0; signal_info[i].sig != -1; i++)
1425 if (signal_info[i].deadly)
1426 {
1427#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1428 struct sigaction sa;
1429
1430 /* Setup to use the alternate stack for the signal function. */
1431 sa.sa_handler = func_deadly;
1432 sigemptyset(&sa.sa_mask);
1433# if defined(__linux__) && defined(_REENTRANT)
1434 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1435 * thread handling in combination with using the alternate stack:
1436 * pthread library functions try to use the stack pointer to
1437 * identify the current thread, causing a SEGV signal, which
1438 * recursively calls deathtrap() and hangs. */
1439 sa.sa_flags = 0;
1440# else
1441 sa.sa_flags = SA_ONSTACK;
1442# endif
1443 sigaction(signal_info[i].sig, &sa, NULL);
1444#else
1445# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1446 struct sigvec sv;
1447
1448 /* Setup to use the alternate stack for the signal function. */
1449 sv.sv_handler = func_deadly;
1450 sv.sv_mask = 0;
1451 sv.sv_flags = SV_ONSTACK;
1452 sigvec(signal_info[i].sig, &sv, NULL);
1453# else
1454 signal(signal_info[i].sig, func_deadly);
1455# endif
1456#endif
1457 }
1458 else if (func_other != SIG_ERR)
1459 signal(signal_info[i].sig, func_other);
1460}
1461
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001462#ifdef HAVE_SIGPROCMASK
1463 static void
1464block_signals(sigset_t *set)
1465{
1466 sigset_t newset;
1467 int i;
1468
1469 sigemptyset(&newset);
1470
1471 for (i = 0; signal_info[i].sig != -1; i++)
1472 sigaddset(&newset, signal_info[i].sig);
1473
1474# if defined(_REENTRANT) && defined(SIGCONT)
1475 /* SIGCONT isn't in the list, because its default action is ignore */
1476 sigaddset(&newset, SIGCONT);
1477# endif
1478
1479 sigprocmask(SIG_BLOCK, &newset, set);
1480}
1481
1482 static void
1483unblock_signals(sigset_t *set)
1484{
1485 sigprocmask(SIG_SETMASK, set, NULL);
1486}
1487#endif
1488
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001490 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001491 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1492 * return TRUE
1493 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1494 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001495 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001496 * Returns TRUE when Vim should exit.
1497 */
1498 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001499vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001500{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001501 static int got_signal = 0;
1502 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001503
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001504 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001505 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001506 case SIGNAL_BLOCK: blocked = TRUE;
1507 break;
1508
1509 case SIGNAL_UNBLOCK: blocked = FALSE;
1510 if (got_signal != 0)
1511 {
1512 kill(getpid(), got_signal);
1513 got_signal = 0;
1514 }
1515 break;
1516
1517 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001518 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001519 got_signal = sig;
1520#ifdef SIGPWR
1521 if (sig != SIGPWR)
1522#endif
1523 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001524 break;
1525 }
1526 return FALSE;
1527}
1528
1529/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 * Check_win checks whether we have an interactive stdout.
1531 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001533mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535 if (isatty(1))
1536 return OK;
1537 return FAIL;
1538}
1539
1540/*
1541 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1542 */
1543 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001544mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545{
1546 if (isatty(read_cmd_fd))
1547 return TRUE;
1548 return FALSE;
1549}
1550
1551#ifdef FEAT_X11
1552
1553# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1554 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1555
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001556static void xopen_message(struct timeval *start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557
1558/*
1559 * Give a message about the elapsed time for opening the X window.
1560 */
1561 static void
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001562xopen_message(struct timeval *start_tv)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563{
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001564 smsg((char_u *)_("Opening the X display took %ld msec"), elapsed(start_tv));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565}
1566# endif
1567#endif
1568
1569#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1570/*
1571 * A few functions shared by X11 title and clipboard code.
1572 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001573static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1574static int x_error_check(Display *dpy, XErrorEvent *error_event);
1575static int x_connect_to_server(void);
1576static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577
1578static int got_x_error = FALSE;
1579
1580/*
1581 * X Error handler, otherwise X just exits! (very rude) -- webb
1582 */
1583 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001584x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001586 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 STRCAT(IObuff, _("\nVim: Got X error\n"));
1588
1589 /* We cannot print a message and continue, because no X calls are allowed
1590 * here (causes my system to hang). Silently continuing might be an
1591 * alternative... */
1592 preserve_exit(); /* preserve files and exit */
1593
1594 return 0; /* NOTREACHED */
1595}
1596
1597/*
1598 * Another X Error handler, just used to check for errors.
1599 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001601x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602{
1603 got_x_error = TRUE;
1604 return 0;
1605}
1606
1607#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1608# if defined(HAVE_SETJMP_H)
1609/*
1610 * An X IO Error handler, used to catch error while opening the display.
1611 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001612static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001615x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616{
1617 /* This function should not return, it causes exit(). Longjump instead. */
1618 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001619# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001620 return 0; /* avoid the compiler complains about missing return value */
1621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622}
1623# endif
1624
1625/*
1626 * An X IO Error handler, used to catch terminal errors.
1627 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001628static int x_IOerror_handler(Display *dpy);
1629static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001630static int xterm_dpy_was_reset = FALSE;
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_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634{
1635 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001636 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 x11_window = 0;
1638 x11_display = NULL;
1639 xterm_Shell = (Widget)0;
1640
1641 /* This function should not return, it causes exit(). Longjump instead. */
1642 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001643# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001644 return 0; /* avoid the compiler complains about missing return value */
1645# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001647
1648/*
1649 * If the X11 connection was lost try to restore it.
1650 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001651 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001652 */
1653 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001654may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001655{
1656 if (xterm_dpy_was_reset)
1657 {
1658 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001659
1660# ifndef LESSTIF_VERSION
1661 /* This has been reported to avoid Vim getting stuck. */
1662 if (app_context != (XtAppContext)NULL)
1663 {
1664 XtDestroyApplicationContext(app_context);
1665 app_context = (XtAppContext)NULL;
1666 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1667 }
1668# endif
1669
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001670 setup_term_clip();
1671 get_x11_title(FALSE);
1672 }
1673}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674#endif
1675
1676/*
1677 * Return TRUE when connection to the X server is desired.
1678 */
1679 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001680x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682#if defined(FEAT_CLIENTSERVER)
1683 if (x_force_connect)
1684 return TRUE;
1685#endif
1686 if (x_no_connect)
1687 return FALSE;
1688
1689 /* Check for a match with "exclude:" from 'clipboard'. */
1690 if (clip_exclude_prog != NULL)
1691 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001692 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 return FALSE;
1694 }
1695 return TRUE;
1696}
1697
1698/*
1699 * Test if "dpy" and x11_window are valid by getting the window title.
1700 * I don't actually want it yet, so there may be a simpler call to use, but
1701 * this will cause the error handler x_error_check() to be called if anything
1702 * is wrong, such as the window pointer being invalid (as can happen when the
1703 * user changes his DISPLAY, but not his WINDOWID) -- webb
1704 */
1705 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001706test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707{
1708 int (*old_handler)();
1709 XTextProperty text_prop;
1710
1711 old_handler = XSetErrorHandler(x_error_check);
1712 got_x_error = FALSE;
1713 if (XGetWMName(dpy, x11_window, &text_prop))
1714 XFree((void *)text_prop.value);
1715 XSync(dpy, False);
1716 (void)XSetErrorHandler(old_handler);
1717
1718 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001719 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720
1721 return (got_x_error ? FAIL : OK);
1722}
1723#endif
1724
1725#ifdef FEAT_TITLE
1726
1727#ifdef FEAT_X11
1728
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001729static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730
1731/*
1732 * try to get x11 window and display
1733 *
1734 * return FAIL for failure, OK otherwise
1735 */
1736 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001737get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738{
1739 char *winid;
1740 static int result = -1;
1741#define XD_NONE 0 /* x11_display not set here */
1742#define XD_HERE 1 /* x11_display opened here */
1743#define XD_GUI 2 /* x11_display used from gui.dpy */
1744#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1745 static int x11_display_from = XD_NONE;
1746 static int did_set_error_handler = FALSE;
1747
1748 if (!did_set_error_handler)
1749 {
1750 /* X just exits if it finds an error otherwise! */
1751 (void)XSetErrorHandler(x_error_handler);
1752 did_set_error_handler = TRUE;
1753 }
1754
Bram Moolenaar9372a112005-12-06 19:59:18 +00001755#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 if (gui.in_use)
1757 {
1758 /*
1759 * If the X11 display was opened here before, for the window where Vim
1760 * was started, close that one now to avoid a memory leak.
1761 */
1762 if (x11_display_from == XD_HERE && x11_display != NULL)
1763 {
1764 XCloseDisplay(x11_display);
1765 x11_display_from = XD_NONE;
1766 }
1767 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1768 {
1769 x11_display_from = XD_GUI;
1770 return OK;
1771 }
1772 x11_display = NULL;
1773 return FAIL;
1774 }
1775 else if (x11_display_from == XD_GUI)
1776 {
1777 /* GUI must have stopped somehow, clear x11_display */
1778 x11_window = 0;
1779 x11_display = NULL;
1780 x11_display_from = XD_NONE;
1781 }
1782#endif
1783
1784 /* When started with the "-X" argument, don't try connecting. */
1785 if (!x_connect_to_server())
1786 return FAIL;
1787
1788 /*
1789 * If WINDOWID not set, should try another method to find out
1790 * what the current window number is. The only code I know for
1791 * this is very complicated.
1792 * We assume that zero is invalid for WINDOWID.
1793 */
1794 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1795 x11_window = (Window)atol(winid);
1796
1797#ifdef FEAT_XCLIPBOARD
1798 if (xterm_dpy != NULL && x11_window != 0)
1799 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001800 /* We may have checked it already, but Gnome terminal can move us to
1801 * another window, so we need to check every time. */
1802 if (x11_display_from != XD_XTERM)
1803 {
1804 /*
1805 * If the X11 display was opened here before, for the window where
1806 * Vim was started, close that one now to avoid a memory leak.
1807 */
1808 if (x11_display_from == XD_HERE && x11_display != NULL)
1809 XCloseDisplay(x11_display);
1810 x11_display = xterm_dpy;
1811 x11_display_from = XD_XTERM;
1812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 if (test_x11_window(x11_display) == FAIL)
1814 {
1815 /* probably bad $WINDOWID */
1816 x11_window = 0;
1817 x11_display = NULL;
1818 x11_display_from = XD_NONE;
1819 return FAIL;
1820 }
1821 return OK;
1822 }
1823#endif
1824
1825 if (x11_window == 0 || x11_display == NULL)
1826 result = -1;
1827
1828 if (result != -1) /* Have already been here and set this */
1829 return result; /* Don't do all these X calls again */
1830
1831 if (x11_window != 0 && x11_display == NULL)
1832 {
1833#ifdef SET_SIG_ALARM
1834 RETSIGTYPE (*sig_save)();
1835#endif
1836#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1837 struct timeval start_tv;
1838
1839 if (p_verbose > 0)
1840 gettimeofday(&start_tv, NULL);
1841#endif
1842
1843#ifdef SET_SIG_ALARM
1844 /*
1845 * Opening the Display may hang if the DISPLAY setting is wrong, or
1846 * the network connection is bad. Set an alarm timer to get out.
1847 */
1848 sig_alarm_called = FALSE;
1849 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1850 (RETSIGTYPE (*)())sig_alarm);
1851 alarm(2);
1852#endif
1853 x11_display = XOpenDisplay(NULL);
1854
1855#ifdef SET_SIG_ALARM
1856 alarm(0);
1857 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1858 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001859 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860#endif
1861 if (x11_display != NULL)
1862 {
1863# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1864 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001865 {
1866 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001868 verbose_leave();
1869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870# endif
1871 if (test_x11_window(x11_display) == FAIL)
1872 {
1873 /* Maybe window id is bad */
1874 x11_window = 0;
1875 XCloseDisplay(x11_display);
1876 x11_display = NULL;
1877 }
1878 else
1879 x11_display_from = XD_HERE;
1880 }
1881 }
1882 if (x11_window == 0 || x11_display == NULL)
1883 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001884
1885# ifdef FEAT_EVAL
1886 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1887# endif
1888
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 return (result = OK);
1890}
1891
1892/*
1893 * Determine original x11 Window Title
1894 */
1895 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001896get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001898 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899}
1900
1901/*
1902 * Determine original x11 Window icon
1903 */
1904 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001905get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906{
1907 int retval = FALSE;
1908
1909 retval = get_x11_thing(FALSE, test_only);
1910
1911 /* could not get old icon, use terminal name */
1912 if (oldicon == NULL && !test_only)
1913 {
1914 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001915 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001917 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 }
1919
1920 return retval;
1921}
1922
1923 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001924get_x11_thing(
1925 int get_title, /* get title string */
1926 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927{
1928 XTextProperty text_prop;
1929 int retval = FALSE;
1930 Status status;
1931
1932 if (get_x11_windis() == OK)
1933 {
1934 /* Get window/icon name if any */
1935 if (get_title)
1936 status = XGetWMName(x11_display, x11_window, &text_prop);
1937 else
1938 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1939
1940 /*
1941 * If terminal is xterm, then x11_window may be a child window of the
1942 * outer xterm window that actually contains the window/icon name, so
1943 * keep traversing up the tree until a window with a title/icon is
1944 * found.
1945 */
1946 /* Previously this was only done for xterm and alikes. I don't see a
1947 * reason why it would fail for other terminal emulators.
1948 * if (term_is_xterm) */
1949 {
1950 Window root;
1951 Window parent;
1952 Window win = x11_window;
1953 Window *children;
1954 unsigned int num_children;
1955
1956 while (!status || text_prop.value == NULL)
1957 {
1958 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1959 &num_children))
1960 break;
1961 if (children)
1962 XFree((void *)children);
1963 if (parent == root || parent == 0)
1964 break;
1965
1966 win = parent;
1967 if (get_title)
1968 status = XGetWMName(x11_display, win, &text_prop);
1969 else
1970 status = XGetWMIconName(x11_display, win, &text_prop);
1971 }
1972 }
1973 if (status && text_prop.value != NULL)
1974 {
1975 retval = TRUE;
1976 if (!test_only)
1977 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001978#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1979 if (text_prop.encoding == XA_STRING
1980# ifdef FEAT_MBYTE
1981 && !has_mbyte
1982# endif
1983 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 {
1985#endif
1986 if (get_title)
1987 oldtitle = vim_strsave((char_u *)text_prop.value);
1988 else
1989 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001990#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 }
1992 else
1993 {
1994 char **cl;
1995 Status transform_status;
1996 int n = 0;
1997
1998 transform_status = XmbTextPropertyToTextList(x11_display,
1999 &text_prop,
2000 &cl, &n);
2001 if (transform_status >= Success && n > 0 && cl[0])
2002 {
2003 if (get_title)
2004 oldtitle = vim_strsave((char_u *) cl[0]);
2005 else
2006 oldicon = vim_strsave((char_u *) cl[0]);
2007 XFreeStringList(cl);
2008 }
2009 else
2010 {
2011 if (get_title)
2012 oldtitle = vim_strsave((char_u *)text_prop.value);
2013 else
2014 oldicon = vim_strsave((char_u *)text_prop.value);
2015 }
2016 }
2017#endif
2018 }
2019 XFree((void *)text_prop.value);
2020 }
2021 }
2022 return retval;
2023}
2024
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002025/* Xutf8 functions are not avaialble on older systems. Note that on some
2026 * systems X_HAVE_UTF8_STRING may be defined in a header file but
2027 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
2028 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002030# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031# define USE_UTF8_STRING
2032# endif
2033#endif
2034
2035/*
2036 * Set x11 Window Title
2037 *
2038 * get_x11_windis() must be called before this and have returned OK
2039 */
2040 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002041set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042{
2043 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2044 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2045 * supported everywhere and STRING doesn't work for multi-byte titles.
2046 */
2047#ifdef USE_UTF8_STRING
2048 if (enc_utf8)
2049 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2050 NULL, NULL, 0, NULL, NULL, NULL);
2051 else
2052#endif
2053 {
2054#if XtSpecificationRelease >= 4
2055# ifdef FEAT_XFONTSET
2056 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2057 NULL, NULL, 0, NULL, NULL, NULL);
2058# else
2059 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002060 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061
2062 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002063 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 XSetWMProperties(x11_display, x11_window, &text_prop,
2065 NULL, NULL, 0, NULL, NULL, NULL);
2066# endif
2067#else
2068 XStoreName(x11_display, x11_window, (char *)title);
2069#endif
2070 }
2071 XFlush(x11_display);
2072}
2073
2074/*
2075 * Set x11 Window icon
2076 *
2077 * get_x11_windis() must be called before this and have returned OK
2078 */
2079 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002080set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081{
2082 /* See above for comments about using X*SetWMProperties(). */
2083#ifdef USE_UTF8_STRING
2084 if (enc_utf8)
2085 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2086 NULL, 0, NULL, NULL, NULL);
2087 else
2088#endif
2089 {
2090#if XtSpecificationRelease >= 4
2091# ifdef FEAT_XFONTSET
2092 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2093 NULL, 0, NULL, NULL, NULL);
2094# else
2095 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002096 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002098 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2100 NULL, 0, NULL, NULL, NULL);
2101# endif
2102#else
2103 XSetIconName(x11_display, x11_window, (char *)icon);
2104#endif
2105 }
2106 XFlush(x11_display);
2107}
2108
2109#else /* FEAT_X11 */
2110
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002112get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113{
2114 return FALSE;
2115}
2116
2117 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002118get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119{
2120 if (!test_only)
2121 {
2122 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002123 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002125 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 }
2127 return FALSE;
2128}
2129
2130#endif /* FEAT_X11 */
2131
2132 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002133mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002134{
2135 return get_x11_title(TRUE);
2136}
2137
2138 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002139mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140{
2141 return get_x11_icon(TRUE);
2142}
2143
2144/*
2145 * Set the window title and icon.
2146 */
2147 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002148mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149{
2150 int type = 0;
2151 static int recursive = 0;
2152
2153 if (T_NAME == NULL) /* no terminal name (yet) */
2154 return;
2155 if (title == NULL && icon == NULL) /* nothing to do */
2156 return;
2157
2158 /* When one of the X11 functions causes a deadly signal, we get here again
2159 * recursively. Avoid hanging then (something is probably locked). */
2160 if (recursive)
2161 return;
2162 ++recursive;
2163
2164 /*
2165 * if the window ID and the display is known, we may use X11 calls
2166 */
2167#ifdef FEAT_X11
2168 if (get_x11_windis() == OK)
2169 type = 1;
2170#else
2171# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2172 if (gui.in_use)
2173 type = 1;
2174# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175#endif
2176
2177 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002178 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 * than x11 calls, because the x11 calls don't always work
2180 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181 if ((type || *T_TS != NUL) && title != NULL)
2182 {
2183 if (oldtitle == NULL
2184#ifdef FEAT_GUI
2185 && !gui.in_use
2186#endif
2187 ) /* first call but not in GUI, save title */
2188 (void)get_x11_title(FALSE);
2189
2190 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2191 term_settitle(title);
2192#ifdef FEAT_X11
2193 else
2194# ifdef FEAT_GUI_GTK
2195 if (!gui.in_use) /* don't do this if GTK+ is running */
2196# endif
2197 set_x11_title(title); /* x11 */
2198#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002199#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2201 else
2202 gui_mch_settitle(title, icon);
2203#endif
2204 did_set_title = TRUE;
2205 }
2206
2207 if ((type || *T_CIS != NUL) && icon != NULL)
2208 {
2209 if (oldicon == NULL
2210#ifdef FEAT_GUI
2211 && !gui.in_use
2212#endif
2213 ) /* first call, save icon */
2214 get_x11_icon(FALSE);
2215
2216 if (*T_CIS != NUL)
2217 {
2218 out_str(T_CIS); /* set icon start */
2219 out_str_nf(icon);
2220 out_str(T_CIE); /* set icon end */
2221 out_flush();
2222 }
2223#ifdef FEAT_X11
2224 else
2225# ifdef FEAT_GUI_GTK
2226 if (!gui.in_use) /* don't do this if GTK+ is running */
2227# endif
2228 set_x11_icon(icon); /* x11 */
2229#endif
2230 did_set_icon = TRUE;
2231 }
2232 --recursive;
2233}
2234
2235/*
2236 * Restore the window/icon title.
2237 * "which" is one of:
2238 * 1 only restore title
2239 * 2 only restore icon
2240 * 3 restore title and icon
2241 */
2242 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002243mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244{
2245 /* only restore the title or icon when it has been set */
2246 mch_settitle(((which & 1) && did_set_title) ?
2247 (oldtitle ? oldtitle : p_titleold) : NULL,
2248 ((which & 2) && did_set_icon) ? oldicon : NULL);
2249}
2250
2251#endif /* FEAT_TITLE */
2252
2253/*
2254 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002255 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 */
2257 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002258vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259{
2260 if (name == NULL)
2261 return FALSE;
2262 return (STRNICMP(name, "xterm", 5) == 0
2263 || STRNICMP(name, "nxterm", 6) == 0
2264 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002265 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 || STRNICMP(name, "rxvt", 4) == 0
2267 || STRCMP(name, "builtin_xterm") == 0);
2268}
2269
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002270#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2271/*
2272 * Return TRUE if "name" appears to be that of a terminal
2273 * known to support the xterm-style mouse protocol.
2274 * Relies on term_is_xterm having been set to its correct value.
2275 */
2276 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002277use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002278{
2279 return (name != NULL
Bram Moolenaare56132b2016-08-14 18:23:21 +02002280 && (term_is_xterm
2281 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002282 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaare56132b2016-08-14 18:23:21 +02002283 || STRICMP(name, "st") == 0
2284 || STRNICMP(name, "st-", 3) == 0
2285 || STRNICMP(name, "stterm", 6) == 0));
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002286}
2287#endif
2288
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2290/*
2291 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2292 * Return 1 for "xterm".
2293 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002294 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002295 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 */
2297 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002298use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002300 if (ttym_flags == TTYM_SGR)
2301 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002302 if (ttym_flags == TTYM_URXVT)
2303 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (ttym_flags == TTYM_XTERM2)
2305 return 2;
2306 if (ttym_flags == TTYM_XTERM)
2307 return 1;
2308 return 0;
2309}
2310#endif
2311
2312 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002313vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314{
2315 if (name == NULL)
2316 return FALSE;
2317 return (STRNICMP(name, "iris-ansi", 9) == 0
2318 || STRCMP(name, "builtin_iris-ansi") == 0);
2319}
2320
2321 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002322vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323{
2324 if (name == NULL)
2325 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002326 /* catch VT100 - VT5xx */
2327 return ((STRNICMP(name, "vt", 2) == 0
2328 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 || STRCMP(name, "builtin_vt320") == 0);
2330}
2331
2332/*
2333 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2334 * This should include all windowed terminal emulators.
2335 */
2336 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002337vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338{
2339 if (name == NULL)
2340 return FALSE;
2341 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2342 return TRUE;
2343 return ( STRNICMP(name, "hpterm", 6) == 0
2344 || STRNICMP(name, "sun-cmd", 7) == 0
2345 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002346 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 || STRNICMP(name, "dtterm", 6) == 0);
2348}
2349
2350/*
2351 * Insert user name in s[len].
2352 * Return OK if a name found.
2353 */
2354 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002355mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356{
2357#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002358 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 return OK;
2360#else
2361 return mch_get_uname(getuid(), s, len);
2362#endif
2363}
2364
2365/*
2366 * Insert user name for "uid" in s[len].
2367 * Return OK if a name found.
2368 */
2369 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002370mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371{
2372#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2373 struct passwd *pw;
2374
2375 if ((pw = getpwuid(uid)) != NULL
2376 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2377 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002378 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 return OK;
2380 }
2381#endif
2382 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2383 return FAIL; /* a number is not a name */
2384}
2385
2386/*
2387 * Insert host name is s[len].
2388 */
2389
2390#ifdef HAVE_SYS_UTSNAME_H
2391 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002392mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393{
2394 struct utsname vutsname;
2395
2396 if (uname(&vutsname) < 0)
2397 *s = NUL;
2398 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002399 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400}
2401#else /* HAVE_SYS_UTSNAME_H */
2402
2403# ifdef HAVE_SYS_SYSTEMINFO_H
2404# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2405# endif
2406
2407 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002408mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409{
2410# ifdef VAXC
2411 vaxc$gethostname((char *)s, len);
2412# else
2413 gethostname((char *)s, len);
2414# endif
2415 s[len - 1] = NUL; /* make sure it's terminated */
2416}
2417#endif /* HAVE_SYS_UTSNAME_H */
2418
2419/*
2420 * return process ID
2421 */
2422 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002423mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424{
2425 return (long)getpid();
2426}
2427
2428#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002429static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430
2431 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002432strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433{
2434 extern int sys_nerr;
2435 extern char *sys_errlist[];
2436 static char er[20];
2437
2438 if (err > 0 && err < sys_nerr)
2439 return (sys_errlist[err]);
2440 sprintf(er, "Error %d", err);
2441 return er;
2442}
2443#endif
2444
2445/*
2446 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2447 * Return OK for success, FAIL for failure.
2448 */
2449 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002450mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451{
2452#if defined(USE_GETCWD)
2453 if (getcwd((char *)buf, len) == NULL)
2454 {
2455 STRCPY(buf, strerror(errno));
2456 return FAIL;
2457 }
2458 return OK;
2459#else
2460 return (getwd((char *)buf) != NULL ? OK : FAIL);
2461#endif
2462}
2463
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002465 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 *
2467 * return FAIL for failure, OK for success
2468 */
2469 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002470mch_FullName(
2471 char_u *fname,
2472 char_u *buf,
2473 int len,
2474 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475{
2476 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002477#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 int fd = -1;
2479 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002480#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 char_u olddir[MAXPATHL];
2482 char_u *p;
2483 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002484#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002485 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2486 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002487#endif
2488
Bram Moolenaar38323e42007-03-06 19:22:53 +00002489#ifdef VMS
2490 fname = vms_fixfilename(fname);
2491#endif
2492
Bram Moolenaara2442432007-04-26 14:26:37 +00002493#ifdef __CYGWIN__
2494 /*
2495 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2496 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002497# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002498 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2499 * a forward slash. */
2500 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2501 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002502# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002503 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002504# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002505 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002506#endif
2507
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002508 /* Expand it if forced or not an absolute path.
2509 * Do not do it for "/file", the result is always "/". */
2510 if ((force || !mch_isFullName(fname))
2511 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 {
2513 /*
2514 * If the file name has a path, change to that directory for a moment,
2515 * and then do the getwd() (and get back to where we were).
2516 * This will get the correct path name with "../" things.
2517 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002518 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002520#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 /*
2522 * Use fchdir() if possible, it's said to be faster and more
2523 * reliable. But on SunOS 4 it might not work. Check this by
2524 * doing a fchdir() right now.
2525 */
2526 if (!dont_fchdir)
2527 {
2528 fd = open(".", O_RDONLY | O_EXTRA, 0);
2529 if (fd >= 0 && fchdir(fd) < 0)
2530 {
2531 close(fd);
2532 fd = -1;
2533 dont_fchdir = TRUE; /* don't try again */
2534 }
2535 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002536#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537
2538 /* Only change directory when we are sure we can return to where
2539 * we are now. After doing "su" chdir(".") might not work. */
2540 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002541#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 (mch_dirname(olddir, MAXPATHL) == FAIL
2545 || mch_chdir((char *)olddir) != 0))
2546 {
2547 p = NULL; /* can't get current dir: don't chdir */
2548 retval = FAIL;
2549 }
2550 else
2551 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 /* The directory is copied into buf[], to be able to remove
2553 * the file name without changing it (could be a string in
2554 * read-only memory) */
2555 if (p - fname >= len)
2556 retval = FAIL;
2557 else
2558 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002559 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 if (mch_chdir((char *)buf))
2561 retval = FAIL;
2562 else
2563 fname = p + 1;
2564 *buf = NUL;
2565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 }
2567 }
2568 if (mch_dirname(buf, len) == FAIL)
2569 {
2570 retval = FAIL;
2571 *buf = NUL;
2572 }
2573 if (p != NULL)
2574 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002575#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 if (fd >= 0)
2577 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002578 if (p_verbose >= 5)
2579 {
2580 verbose_enter();
2581 MSG("fchdir() to previous dir");
2582 verbose_leave();
2583 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 l = fchdir(fd);
2585 close(fd);
2586 }
2587 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002588#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 l = mch_chdir((char *)olddir);
2590 if (l != 0)
2591 EMSG(_(e_prev_dir));
2592 }
2593
2594 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002595 if (l >= len - 1)
2596 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002597#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002598 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002600 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002601#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002603
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002605 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 return FAIL;
2607
2608 /* Do not append ".", "/dir/." is equal to "/dir". */
2609 if (STRCMP(fname, ".") != 0)
2610 STRCAT(buf, fname);
2611
2612 return OK;
2613}
2614
2615/*
2616 * Return TRUE if "fname" does not depend on the current directory.
2617 */
2618 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002619mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620{
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002621#ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 return ( fname[0] == '/' || fname[0] == '.' ||
2623 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2624 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2625 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002626#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627 return (*fname == '/' || *fname == '~');
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628#endif
2629}
2630
Bram Moolenaar24552be2005-12-10 20:17:30 +00002631#if defined(USE_FNAME_CASE) || defined(PROTO)
2632/*
2633 * Set the case of the file name, if it already exists. This will cause the
2634 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002635 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002636 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002637 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002638fname_case(
2639 char_u *name,
2640 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002641{
2642 struct stat st;
2643 char_u *slash, *tail;
2644 DIR *dirp;
2645 struct dirent *dp;
2646
2647 if (lstat((char *)name, &st) >= 0)
2648 {
2649 /* Open the directory where the file is located. */
2650 slash = vim_strrchr(name, '/');
2651 if (slash == NULL)
2652 {
2653 dirp = opendir(".");
2654 tail = name;
2655 }
2656 else
2657 {
2658 *slash = NUL;
2659 dirp = opendir((char *)name);
2660 *slash = '/';
2661 tail = slash + 1;
2662 }
2663
2664 if (dirp != NULL)
2665 {
2666 while ((dp = readdir(dirp)) != NULL)
2667 {
2668 /* Only accept names that differ in case and are the same byte
2669 * length. TODO: accept different length name. */
2670 if (STRICMP(tail, dp->d_name) == 0
2671 && STRLEN(tail) == STRLEN(dp->d_name))
2672 {
2673 char_u newname[MAXPATHL + 1];
2674 struct stat st2;
2675
2676 /* Verify the inode is equal. */
2677 vim_strncpy(newname, name, MAXPATHL);
2678 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2679 MAXPATHL - (tail - name));
2680 if (lstat((char *)newname, &st2) >= 0
2681 && st.st_ino == st2.st_ino
2682 && st.st_dev == st2.st_dev)
2683 {
2684 STRCPY(tail, dp->d_name);
2685 break;
2686 }
2687 }
2688 }
2689
2690 closedir(dirp);
2691 }
2692 }
2693}
2694#endif
2695
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696/*
2697 * Get file permissions for 'name'.
2698 * Returns -1 when it doesn't exist.
2699 */
2700 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002701mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702{
2703 struct stat statb;
2704
2705 /* Keep the #ifdef outside of stat(), it may be a macro. */
2706#ifdef VMS
2707 if (stat((char *)vms_fixfilename(name), &statb))
2708#else
2709 if (stat((char *)name, &statb))
2710#endif
2711 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002712#ifdef __INTERIX
2713 /* The top bit makes the value negative, which means the file doesn't
2714 * exist. Remove the bit, we don't use it. */
2715 return statb.st_mode & ~S_ADDACE;
2716#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002718#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719}
2720
2721/*
2722 * set file permission for 'name' to 'perm'
2723 *
2724 * return FAIL for failure, OK otherwise
2725 */
2726 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002727mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728{
2729 return (chmod((char *)
2730#ifdef VMS
2731 vms_fixfilename(name),
2732#else
2733 name,
2734#endif
2735 (mode_t)perm) == 0 ? OK : FAIL);
2736}
2737
2738#if defined(HAVE_ACL) || defined(PROTO)
2739# ifdef HAVE_SYS_ACL_H
2740# include <sys/acl.h>
2741# endif
2742# ifdef HAVE_SYS_ACCESS_H
2743# include <sys/access.h>
2744# endif
2745
2746# ifdef HAVE_SOLARIS_ACL
2747typedef struct vim_acl_solaris_T {
2748 int acl_cnt;
2749 aclent_t *acl_entry;
2750} vim_acl_solaris_T;
2751# endif
2752
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002753#if defined(HAVE_SELINUX) || defined(PROTO)
2754/*
2755 * Copy security info from "from_file" to "to_file".
2756 */
2757 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002758mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002759{
2760 if (from_file == NULL)
2761 return;
2762
2763 if (selinux_enabled == -1)
2764 selinux_enabled = is_selinux_enabled();
2765
2766 if (selinux_enabled > 0)
2767 {
2768 security_context_t from_context = NULL;
2769 security_context_t to_context = NULL;
2770
2771 if (getfilecon((char *)from_file, &from_context) < 0)
2772 {
2773 /* If the filesystem doesn't support extended attributes,
2774 the original had no special security context and the
2775 target cannot have one either. */
2776 if (errno == EOPNOTSUPP)
2777 return;
2778
2779 MSG_PUTS(_("\nCould not get security context for "));
2780 msg_outtrans(from_file);
2781 msg_putchar('\n');
2782 return;
2783 }
2784 if (getfilecon((char *)to_file, &to_context) < 0)
2785 {
2786 MSG_PUTS(_("\nCould not get security context for "));
2787 msg_outtrans(to_file);
2788 msg_putchar('\n');
2789 freecon (from_context);
2790 return ;
2791 }
2792 if (strcmp(from_context, to_context) != 0)
2793 {
2794 if (setfilecon((char *)to_file, from_context) < 0)
2795 {
2796 MSG_PUTS(_("\nCould not set security context for "));
2797 msg_outtrans(to_file);
2798 msg_putchar('\n');
2799 }
2800 }
2801 freecon(to_context);
2802 freecon(from_context);
2803 }
2804}
2805#endif /* HAVE_SELINUX */
2806
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002807#if defined(HAVE_SMACK) && !defined(PROTO)
2808/*
2809 * Copy security info from "from_file" to "to_file".
2810 */
2811 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002812mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002813{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002814 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002815 {
2816 XATTR_NAME_SMACK,
2817 XATTR_NAME_SMACKEXEC,
2818 XATTR_NAME_SMACKMMAP
2819 };
2820
2821 char buffer[SMACK_LABEL_LEN];
2822 const char *name;
2823 int index;
2824 int ret;
2825 ssize_t size;
2826
2827 if (from_file == NULL)
2828 return;
2829
2830 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2831 / sizeof(smack_copied_attributes)[0]) ; index++)
2832 {
2833 /* get the name of the attribute to copy */
2834 name = smack_copied_attributes[index];
2835
2836 /* get the value of the attribute in buffer */
2837 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2838 if (size >= 0)
2839 {
2840 /* copy the attribute value of buffer */
2841 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2842 if (ret < 0)
2843 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002844 vim_snprintf((char *)IObuff, IOSIZE,
2845 _("Could not set security context %s for %s"),
2846 name, to_file);
2847 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002848 msg_putchar('\n');
2849 }
2850 }
2851 else
2852 {
2853 /* what reason of not having the attribute value? */
2854 switch (errno)
2855 {
2856 case ENOTSUP:
2857 /* extended attributes aren't supported or enabled */
2858 /* should a message be echoed? not sure... */
2859 return; /* leave because it isn't usefull to continue */
2860
2861 case ERANGE:
2862 default:
2863 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002864 vim_snprintf((char *)IObuff, IOSIZE,
2865 _("Could not get security context %s for %s. Removing it!"),
2866 name, from_file);
2867 msg_puts(IObuff);
2868 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002869 /* FALLTHROUGH to remove the attribute */
2870
2871 case ENODATA:
2872 /* no attribute of this name */
2873 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002874 /* Silently ignore errors, apparently this happens when
2875 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002876 break;
2877 }
2878 }
2879 }
2880}
2881#endif /* HAVE_SMACK */
2882
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883/*
2884 * Return a pointer to the ACL of file "fname" in allocated memory.
2885 * Return NULL if the ACL is not available for whatever reason.
2886 */
2887 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002888mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
2890 vim_acl_T ret = NULL;
2891#ifdef HAVE_POSIX_ACL
2892 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2893#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002894#ifdef HAVE_SOLARIS_ZFS_ACL
2895 acl_t *aclent;
2896
2897 if (acl_get((char *)fname, 0, &aclent) < 0)
2898 return NULL;
2899 ret = (vim_acl_T)aclent;
2900#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901#ifdef HAVE_SOLARIS_ACL
2902 vim_acl_solaris_T *aclent;
2903
2904 aclent = malloc(sizeof(vim_acl_solaris_T));
2905 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2906 {
2907 free(aclent);
2908 return NULL;
2909 }
2910 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2911 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2912 {
2913 free(aclent->acl_entry);
2914 free(aclent);
2915 return NULL;
2916 }
2917 ret = (vim_acl_T)aclent;
2918#else
2919#if defined(HAVE_AIX_ACL)
2920 int aclsize;
2921 struct acl *aclent;
2922
2923 aclsize = sizeof(struct acl);
2924 aclent = malloc(aclsize);
2925 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2926 {
2927 if (errno == ENOSPC)
2928 {
2929 aclsize = aclent->acl_len;
2930 aclent = realloc(aclent, aclsize);
2931 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2932 {
2933 free(aclent);
2934 return NULL;
2935 }
2936 }
2937 else
2938 {
2939 free(aclent);
2940 return NULL;
2941 }
2942 }
2943 ret = (vim_acl_T)aclent;
2944#endif /* HAVE_AIX_ACL */
2945#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002946#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947#endif /* HAVE_POSIX_ACL */
2948 return ret;
2949}
2950
2951/*
2952 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2953 */
2954 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002955mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956{
2957 if (aclent == NULL)
2958 return;
2959#ifdef HAVE_POSIX_ACL
2960 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2961#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002962#ifdef HAVE_SOLARIS_ZFS_ACL
2963 acl_set((char *)fname, (acl_t *)aclent);
2964#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965#ifdef HAVE_SOLARIS_ACL
2966 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2967 ((vim_acl_solaris_T *)aclent)->acl_entry);
2968#else
2969#ifdef HAVE_AIX_ACL
2970 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2971#endif /* HAVE_AIX_ACL */
2972#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002973#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974#endif /* HAVE_POSIX_ACL */
2975}
2976
2977 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002978mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979{
2980 if (aclent == NULL)
2981 return;
2982#ifdef HAVE_POSIX_ACL
2983 acl_free((acl_t)aclent);
2984#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002985#ifdef HAVE_SOLARIS_ZFS_ACL
2986 acl_free((acl_t *)aclent);
2987#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988#ifdef HAVE_SOLARIS_ACL
2989 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2990 free(aclent);
2991#else
2992#ifdef HAVE_AIX_ACL
2993 free(aclent);
2994#endif /* HAVE_AIX_ACL */
2995#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002996#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997#endif /* HAVE_POSIX_ACL */
2998}
2999#endif
3000
3001/*
3002 * Set hidden flag for "name".
3003 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003005mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006{
3007 /* can't hide a file */
3008}
3009
3010/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003011 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 * return FALSE if "name" is not a directory
3013 * return FALSE for error
3014 */
3015 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003016mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017{
3018 struct stat statb;
3019
3020 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3021 return FALSE;
3022 if (stat((char *)name, &statb))
3023 return FALSE;
3024#ifdef _POSIX_SOURCE
3025 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3026#else
3027 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3028#endif
3029}
3030
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003031/*
3032 * return TRUE if "name" is a directory, NOT a symlink to a directory
3033 * return FALSE if "name" is not a directory
3034 * return FALSE for error
3035 */
3036 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003037mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003038{
3039 struct stat statb;
3040
3041 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3042 return FALSE;
3043 if (lstat((char *)name, &statb))
3044 return FALSE;
3045#ifdef _POSIX_SOURCE
3046 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3047#else
3048 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3049#endif
3050}
3051
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003052static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053
3054/*
3055 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3056 */
3057 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003058executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059{
3060 struct stat st;
3061
3062 if (stat((char *)name, &st))
3063 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003064#ifdef VMS
3065 /* Like on Unix system file can have executable rights but not necessarily
3066 * be an executable, but on Unix is not a default for an ordianry file to
3067 * have an executable flag - on VMS it is in most cases.
3068 * Therefore, this check does not have any sense - let keep us to the
3069 * conventions instead:
3070 * *.COM and *.EXE files are the executables - the rest are not. This is
3071 * not ideal but better then it was.
3072 */
3073 int vms_executable = 0;
3074 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3075 {
3076 if (strstr(vms_tolower((char*)name),".exe") != NULL
3077 || strstr(vms_tolower((char*)name),".com")!= NULL)
3078 vms_executable = 1;
3079 }
3080 return vms_executable;
3081#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084}
3085
3086/*
3087 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003088 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 * Return -1 if unknown.
3090 */
3091 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003092mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093{
3094 char_u *buf;
3095 char_u *p, *e;
3096 int retval;
3097
Bram Moolenaarb5971142015-03-21 17:32:19 +01003098 /* When "use_path" is false and if it's an absolute or relative path don't
3099 * need to use $PATH. */
3100 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3101 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003102 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003103 /* There must be a path separator, files in the current directory
3104 * can't be executed. */
3105 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003106 {
3107 if (path != NULL)
3108 {
3109 if (name[0] == '.')
3110 *path = FullName_save(name, TRUE);
3111 else
3112 *path = vim_strsave(name);
3113 }
3114 return TRUE;
3115 }
3116 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003117 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118
3119 p = (char_u *)getenv("PATH");
3120 if (p == NULL || *p == NUL)
3121 return -1;
3122 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3123 if (buf == NULL)
3124 return -1;
3125
3126 /*
3127 * Walk through all entries in $PATH to check if "name" exists there and
3128 * is an executable file.
3129 */
3130 for (;;)
3131 {
3132 e = (char_u *)strchr((char *)p, ':');
3133 if (e == NULL)
3134 e = p + STRLEN(p);
3135 if (e - p <= 1) /* empty entry means current dir */
3136 STRCPY(buf, "./");
3137 else
3138 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003139 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 add_pathsep(buf);
3141 }
3142 STRCAT(buf, name);
3143 retval = executable_file(buf);
3144 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003145 {
3146 if (path != NULL)
3147 {
3148 if (buf[0] == '.')
3149 *path = FullName_save(buf, TRUE);
3150 else
3151 *path = vim_strsave(buf);
3152 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003154 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155
3156 if (*e != ':')
3157 break;
3158 p = e + 1;
3159 }
3160
3161 vim_free(buf);
3162 return retval;
3163}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003164
3165/*
3166 * Check what "name" is:
3167 * NODE_NORMAL: file or directory (or doesn't exist)
3168 * NODE_WRITABLE: writable device, socket, fifo, etc.
3169 * NODE_OTHER: non-writable things
3170 */
3171 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003172mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173{
3174 struct stat st;
3175
3176 if (stat((char *)name, &st))
3177 return NODE_NORMAL;
3178 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3179 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3181 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 /* Everything else is writable? */
3183 return NODE_WRITABLE;
3184}
3185
3186 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003187mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188{
3189#ifdef HAVE_CHECK_STACK_GROWTH
3190 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192 check_stack_growth((char *)&i);
3193
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003194# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 get_stack_limit();
3196# endif
3197
3198#endif
3199
3200 /*
3201 * Setup an alternative stack for signals. Helps to catch signals when
3202 * running out of stack space.
3203 * Use of sigaltstack() is preferred, it's more portable.
3204 * Ignore any errors.
3205 */
3206#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003207 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 init_signal_stack();
3209#endif
3210}
3211
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003212#if defined(EXITFREE) || defined(PROTO)
3213 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003214mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003215{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003216# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3217 if (clip_star.owned)
3218 clip_lose_selection(&clip_star);
3219 if (clip_plus.owned)
3220 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003221# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003222# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003223 if (xterm_Shell != (Widget)0)
3224 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003225# ifndef LESSTIF_VERSION
3226 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003227 if (xterm_dpy != NULL)
3228 XtCloseDisplay(xterm_dpy);
3229 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003230 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003231 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003232# ifdef FEAT_X11
3233 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3234# endif
3235 }
3236# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003237# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003238# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003239 if (x11_display != NULL
3240# ifdef FEAT_XCLIPBOARD
3241 && x11_display != xterm_dpy
3242# endif
3243 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003244 XCloseDisplay(x11_display);
3245# endif
3246# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3247 vim_free(signal_stack);
3248 signal_stack = NULL;
3249# endif
3250# ifdef FEAT_TITLE
3251 vim_free(oldtitle);
3252 vim_free(oldicon);
3253# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003254}
3255#endif
3256
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003257static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258
3259/*
3260 * Output a newline when exiting.
3261 * Make sure the newline goes to the same stream as the text.
3262 */
3263 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003264exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003266 if (silent_mode)
3267 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268 if (newline_on_exit || msg_didout)
3269 {
3270 if (msg_use_printf())
3271 {
3272 if (info_message)
3273 mch_msg("\n");
3274 else
3275 mch_errmsg("\r\n");
3276 }
3277 else
3278 out_char('\n');
3279 }
3280 else
3281 {
3282 restore_cterm_colors(); /* get original colors back */
3283 msg_clr_eos_force(); /* clear the rest of the display */
3284 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3285 }
3286}
3287
3288 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003289mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290{
3291 exiting = TRUE;
3292
3293#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3294 x11_export_final_selection();
3295#endif
3296
3297#ifdef FEAT_GUI
3298 if (!gui.in_use)
3299#endif
3300 {
3301 settmode(TMODE_COOK);
3302#ifdef FEAT_TITLE
3303 mch_restore_title(3); /* restore xterm title and icon name */
3304#endif
3305 /*
3306 * When t_ti is not empty but it doesn't cause swapping terminal
3307 * pages, need to output a newline when msg_didout is set. But when
3308 * t_ti does swap pages it should not go to the shell page. Do this
3309 * before stoptermcap().
3310 */
3311 if (swapping_screen() && !newline_on_exit)
3312 exit_scroll();
3313
3314 /* Stop termcap: May need to check for T_CRV response, which
3315 * requires RAW mode. */
3316 stoptermcap();
3317
3318 /*
3319 * A newline is only required after a message in the alternate screen.
3320 * This is set to TRUE by wait_return().
3321 */
3322 if (!swapping_screen() || newline_on_exit)
3323 exit_scroll();
3324
3325 /* Cursor may have been switched off without calling starttermcap()
3326 * when doing "vim -u vimrc" and vimrc contains ":q". */
3327 if (full_screen)
3328 cursor_on();
3329 }
3330 out_flush();
3331 ml_close_all(TRUE); /* remove all memfiles */
3332 may_core_dump();
3333#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335 gui_exit(r);
3336#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003337
Bram Moolenaar56718732006-03-15 22:53:57 +00003338#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003339 mac_conv_cleanup();
3340#endif
3341
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342#ifdef __QNX__
3343 /* A core dump won't be created if the signal handler
3344 * doesn't return, so we can't call exit() */
3345 if (deadly_signal != 0)
3346 return;
3347#endif
3348
Bram Moolenaar009b2592004-10-24 19:18:58 +00003349#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003350 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003351#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003352
3353#ifdef EXITFREE
3354 free_all_mem();
3355#endif
3356
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 exit(r);
3358}
3359
3360 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003361may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362{
3363 if (deadly_signal != 0)
3364 {
3365 signal(deadly_signal, SIG_DFL);
3366 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3367 }
3368}
3369
3370#ifndef VMS
3371
3372 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003373mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374{
3375 static int first = TRUE;
3376
3377 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3378#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3379 /*
3380 * for "new" tty systems
3381 */
3382# ifdef HAVE_TERMIOS_H
3383 static struct termios told;
3384 struct termios tnew;
3385# else
3386 static struct termio told;
3387 struct termio tnew;
3388# endif
3389
3390 if (first)
3391 {
3392 first = FALSE;
3393# if defined(HAVE_TERMIOS_H)
3394 tcgetattr(read_cmd_fd, &told);
3395# else
3396 ioctl(read_cmd_fd, TCGETA, &told);
3397# endif
3398 }
3399
3400 tnew = told;
3401 if (tmode == TMODE_RAW)
3402 {
3403 /*
3404 * ~ICRNL enables typing ^V^M
3405 */
3406 tnew.c_iflag &= ~ICRNL;
3407 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3408# if defined(IEXTEN) && !defined(__MINT__)
3409 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3410 /* but it breaks function keys on MINT */
3411# endif
3412 );
3413# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3414 tnew.c_oflag &= ~ONLCR;
3415# endif
3416 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3417 tnew.c_cc[VTIME] = 0; /* don't wait */
3418 }
3419 else if (tmode == TMODE_SLEEP)
Bram Moolenaar40de4562016-07-01 15:03:46 +02003420 {
3421 /* Also reset ICANON here, otherwise on Solaris select() won't see
3422 * typeahead characters. */
3423 tnew.c_lflag &= ~(ICANON | ECHO);
3424 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3425 tnew.c_cc[VTIME] = 0; /* don't wait */
3426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427
3428# if defined(HAVE_TERMIOS_H)
3429 {
3430 int n = 10;
3431
3432 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3433 * few times. */
3434 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3435 && errno == EINTR && n > 0)
3436 --n;
3437 }
3438# else
3439 ioctl(read_cmd_fd, TCSETA, &tnew);
3440# endif
3441
3442#else
3443
3444 /*
3445 * for "old" tty systems
3446 */
3447# ifndef TIOCSETN
3448# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3449# endif
3450 static struct sgttyb ttybold;
3451 struct sgttyb ttybnew;
3452
3453 if (first)
3454 {
3455 first = FALSE;
3456 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3457 }
3458
3459 ttybnew = ttybold;
3460 if (tmode == TMODE_RAW)
3461 {
3462 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3463 ttybnew.sg_flags |= RAW;
3464 }
3465 else if (tmode == TMODE_SLEEP)
3466 ttybnew.sg_flags &= ~(ECHO);
3467 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3468#endif
3469 curr_tmode = tmode;
3470}
3471
3472/*
3473 * Try to get the code for "t_kb" from the stty setting
3474 *
3475 * Even if termcap claims a backspace key, the user's setting *should*
3476 * prevail. stty knows more about reality than termcap does, and if
3477 * somebody's usual erase key is DEL (which, for most BSD users, it will
3478 * be), they're going to get really annoyed if their erase key starts
3479 * doing forward deletes for no reason. (Eric Fischer)
3480 */
3481 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003482get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483{
3484 char_u buf[2];
3485 char_u *p;
3486
3487 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3488#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3489 /* for "new" tty systems */
3490# ifdef HAVE_TERMIOS_H
3491 struct termios keys;
3492# else
3493 struct termio keys;
3494# endif
3495
3496# if defined(HAVE_TERMIOS_H)
3497 if (tcgetattr(read_cmd_fd, &keys) != -1)
3498# else
3499 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3500# endif
3501 {
3502 buf[0] = keys.c_cc[VERASE];
3503 intr_char = keys.c_cc[VINTR];
3504#else
3505 /* for "old" tty systems */
3506 struct sgttyb keys;
3507
3508 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3509 {
3510 buf[0] = keys.sg_erase;
3511 intr_char = keys.sg_kill;
3512#endif
3513 buf[1] = NUL;
3514 add_termcode((char_u *)"kb", buf, FALSE);
3515
3516 /*
3517 * If <BS> and <DEL> are now the same, redefine <DEL>.
3518 */
3519 p = find_termcode((char_u *)"kD");
3520 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3521 do_fixdel(NULL);
3522 }
3523#if 0
3524 } /* to keep cindent happy */
3525#endif
3526}
3527
3528#endif /* VMS */
3529
3530#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3531/*
3532 * Set mouse clicks on or off.
3533 */
3534 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003535mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536{
3537 static int ison = FALSE;
3538 int xterm_mouse_vers;
3539
3540 if (on == ison) /* return quickly if nothing to do */
3541 return;
3542
3543 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003544
3545# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003546 if (ttym_flags == TTYM_URXVT)
3547 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003548 out_str_nf((char_u *)
3549 (on
3550 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3551 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3552 ison = on;
3553 }
3554# endif
3555
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003556# ifdef FEAT_MOUSE_SGR
3557 if (ttym_flags == TTYM_SGR)
3558 {
3559 out_str_nf((char_u *)
3560 (on
3561 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3562 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3563 ison = on;
3564 }
3565# endif
3566
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567 if (xterm_mouse_vers > 0)
3568 {
3569 if (on) /* enable mouse events, use mouse tracking if available */
3570 out_str_nf((char_u *)
3571 (xterm_mouse_vers > 1
3572 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3573 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3574 else /* disable mouse events, could probably always send the same */
3575 out_str_nf((char_u *)
3576 (xterm_mouse_vers > 1
3577 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3578 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3579 ison = on;
3580 }
3581
3582# ifdef FEAT_MOUSE_DEC
3583 else if (ttym_flags == TTYM_DEC)
3584 {
3585 if (on) /* enable mouse events */
3586 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3587 else /* disable mouse events */
3588 out_str_nf((char_u *)"\033['z");
3589 ison = on;
3590 }
3591# endif
3592
3593# ifdef FEAT_MOUSE_GPM
3594 else
3595 {
3596 if (on)
3597 {
3598 if (gpm_open())
3599 ison = TRUE;
3600 }
3601 else
3602 {
3603 gpm_close();
3604 ison = FALSE;
3605 }
3606 }
3607# endif
3608
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003609# ifdef FEAT_SYSMOUSE
3610 else
3611 {
3612 if (on)
3613 {
3614 if (sysmouse_open() == OK)
3615 ison = TRUE;
3616 }
3617 else
3618 {
3619 sysmouse_close();
3620 ison = FALSE;
3621 }
3622 }
3623# endif
3624
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625# ifdef FEAT_MOUSE_JSB
3626 else
3627 {
3628 if (on)
3629 {
3630 /* D - Enable Mouse up/down messages
3631 * L - Enable Left Button Reporting
3632 * M - Enable Middle Button Reporting
3633 * R - Enable Right Button Reporting
3634 * K - Enable SHIFT and CTRL key Reporting
3635 * + - Enable Advanced messaging of mouse moves and up/down messages
3636 * Q - Quiet No Ack
3637 * # - Numeric value of mouse pointer required
3638 * 0 = Multiview 2000 cursor, used as standard
3639 * 1 = Windows Arrow
3640 * 2 = Windows I Beam
3641 * 3 = Windows Hour Glass
3642 * 4 = Windows Cross Hair
3643 * 5 = Windows UP Arrow
3644 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003645# ifdef JSBTERM_MOUSE_NONADVANCED
3646 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3648 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003649# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3651 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003652# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653 ison = TRUE;
3654 }
3655 else
3656 {
3657 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3658 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3659 ison = FALSE;
3660 }
3661 }
3662# endif
3663# ifdef FEAT_MOUSE_PTERM
3664 else
3665 {
3666 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3667 if (on)
3668 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3669 else
3670 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3671 ison = on;
3672 }
3673# endif
3674}
3675
3676/*
3677 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3678 */
3679 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003680check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681{
3682# ifdef FEAT_MOUSE_XTERM
3683 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003684# ifdef FEAT_MOUSE_URXVT
3685 && use_xterm_mouse() != 3
3686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687# ifdef FEAT_GUI
3688 && !gui.in_use
3689# endif
3690 )
3691 {
3692 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003693 ? IF_EB("\233M", CSI_STR "M")
3694 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 if (*p_mouse != NUL)
3696 {
3697 /* force mouse off and maybe on to send possibly new mouse
3698 * activation sequence to the xterm, with(out) drag tracing. */
3699 mch_setmouse(FALSE);
3700 setmouse();
3701 }
3702 }
3703 else
3704 del_mouse_termcode(KS_MOUSE);
3705# endif
3706
3707# ifdef FEAT_MOUSE_GPM
3708 if (!use_xterm_mouse()
3709# ifdef FEAT_GUI
3710 && !gui.in_use
3711# endif
3712 )
3713 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3714# endif
3715
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003716# ifdef FEAT_SYSMOUSE
3717 if (!use_xterm_mouse()
3718# ifdef FEAT_GUI
3719 && !gui.in_use
3720# endif
3721 )
3722 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3723# endif
3724
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003726 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 if (!use_xterm_mouse()
3728# ifdef FEAT_GUI
3729 && !gui.in_use
3730# endif
3731 )
3732 set_mouse_termcode(KS_JSBTERM_MOUSE,
3733 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3734 else
3735 del_mouse_termcode(KS_JSBTERM_MOUSE);
3736# endif
3737
3738# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003739 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 * define it in the GUI or when using an xterm. */
3741 if (!use_xterm_mouse()
3742# ifdef FEAT_GUI
3743 && !gui.in_use
3744# endif
3745 )
3746 set_mouse_termcode(KS_NETTERM_MOUSE,
3747 (char_u *)IF_EB("\033}", ESC_STR "}"));
3748 else
3749 del_mouse_termcode(KS_NETTERM_MOUSE);
3750# endif
3751
3752# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003753 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003754 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755# ifdef FEAT_GUI
3756 && !gui.in_use
3757# endif
3758 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003759 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3760 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 else
3762 del_mouse_termcode(KS_DEC_MOUSE);
3763# endif
3764# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003765 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003766 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767# ifdef FEAT_GUI
3768 && !gui.in_use
3769# endif
3770 )
3771 set_mouse_termcode(KS_PTERM_MOUSE,
3772 (char_u *) IF_EB("\033[", ESC_STR "["));
3773 else
3774 del_mouse_termcode(KS_PTERM_MOUSE);
3775# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003776# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003777 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003778 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003779# ifdef FEAT_GUI
3780 && !gui.in_use
3781# endif
3782 )
3783 {
3784 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3785 ? IF_EB("\233", CSI_STR)
3786 : IF_EB("\033[", ESC_STR "[")));
3787
3788 if (*p_mouse != NUL)
3789 {
3790 mch_setmouse(FALSE);
3791 setmouse();
3792 }
3793 }
3794 else
3795 del_mouse_termcode(KS_URXVT_MOUSE);
3796# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003797# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003798 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003799 if (use_xterm_mouse() == 4
3800# ifdef FEAT_GUI
3801 && !gui.in_use
3802# endif
3803 )
3804 {
3805 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3806 ? IF_EB("\233<", CSI_STR "<")
3807 : IF_EB("\033[<", ESC_STR "[<")));
3808
3809 if (*p_mouse != NUL)
3810 {
3811 mch_setmouse(FALSE);
3812 setmouse();
3813 }
3814 }
3815 else
3816 del_mouse_termcode(KS_SGR_MOUSE);
3817# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818}
3819#endif
3820
3821/*
3822 * set screen mode, always fails.
3823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003825mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826{
3827 EMSG(_(e_screenmode));
3828 return FAIL;
3829}
3830
3831#ifndef VMS
3832
3833/*
3834 * Try to get the current window size:
3835 * 1. with an ioctl(), most accurate method
3836 * 2. from the environment variables LINES and COLUMNS
3837 * 3. from the termcap
3838 * 4. keep using the old values
3839 * Return OK when size could be determined, FAIL otherwise.
3840 */
3841 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003842mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843{
3844 long rows = 0;
3845 long columns = 0;
3846 char_u *p;
3847
3848 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849 * 1. try using an ioctl. It is the most accurate method.
3850 *
3851 * Try using TIOCGWINSZ first, some systems that have it also define
3852 * TIOCGSIZE but don't have a struct ttysize.
3853 */
3854# ifdef TIOCGWINSZ
3855 {
3856 struct winsize ws;
3857 int fd = 1;
3858
3859 /* When stdout is not a tty, use stdin for the ioctl(). */
3860 if (!isatty(fd) && isatty(read_cmd_fd))
3861 fd = read_cmd_fd;
3862 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3863 {
3864 columns = ws.ws_col;
3865 rows = ws.ws_row;
3866 }
3867 }
3868# else /* TIOCGWINSZ */
3869# ifdef TIOCGSIZE
3870 {
3871 struct ttysize ts;
3872 int fd = 1;
3873
3874 /* When stdout is not a tty, use stdin for the ioctl(). */
3875 if (!isatty(fd) && isatty(read_cmd_fd))
3876 fd = read_cmd_fd;
3877 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3878 {
3879 columns = ts.ts_cols;
3880 rows = ts.ts_lines;
3881 }
3882 }
3883# endif /* TIOCGSIZE */
3884# endif /* TIOCGWINSZ */
3885
3886 /*
3887 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003888 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3889 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003891 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 {
3893 if ((p = (char_u *)getenv("LINES")))
3894 rows = atoi((char *)p);
3895 if ((p = (char_u *)getenv("COLUMNS")))
3896 columns = atoi((char *)p);
3897 }
3898
3899#ifdef HAVE_TGETENT
3900 /*
3901 * 3. try reading "co" and "li" entries from termcap
3902 */
3903 if (columns == 0 || rows == 0)
3904 getlinecol(&columns, &rows);
3905#endif
3906
3907 /*
3908 * 4. If everything fails, use the old values
3909 */
3910 if (columns <= 0 || rows <= 0)
3911 return FAIL;
3912
3913 Rows = rows;
3914 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003915 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 return OK;
3917}
3918
3919/*
3920 * Try to set the window size to Rows and Columns.
3921 */
3922 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003923mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 if (*T_CWS)
3926 {
3927 /*
3928 * NOTE: if you get an error here that term_set_winsize() is
3929 * undefined, check the output of configure. It could probably not
3930 * find a ncurses, termcap or termlib library.
3931 */
3932 term_set_winsize((int)Rows, (int)Columns);
3933 out_flush();
3934 screen_start(); /* don't know where cursor is now */
3935 }
3936}
3937
3938#endif /* VMS */
3939
3940/*
3941 * Rows and/or Columns has changed.
3942 */
3943 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003944mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945{
3946 /* Nothing to do. */
3947}
3948
Bram Moolenaar205b8862011-09-07 15:04:31 +02003949/*
3950 * Wait for process "child" to end.
3951 * Return "child" if it exited properly, <= 0 on error.
3952 */
3953 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003954wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003955{
3956 pid_t wait_pid = 0;
Bram Moolenaar0abe0522016-08-28 16:53:12 +02003957 long delay_msec = 1;
Bram Moolenaar205b8862011-09-07 15:04:31 +02003958
3959 while (wait_pid != child)
3960 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003961 /* When compiled with Python threads are probably used, in which case
3962 * wait() sometimes hangs for no obvious reason. Use waitpid()
3963 * instead and loop (like the GUI). Also needed for other interfaces,
3964 * they might call system(). */
3965# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003966 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003967# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003968 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003969# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003970 if (wait_pid == 0)
3971 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02003972 /* Wait for 1 to 10 msec before trying again. */
3973 mch_delay(delay_msec, TRUE);
3974 if (++delay_msec > 10)
3975 delay_msec = 10;
Bram Moolenaar205b8862011-09-07 15:04:31 +02003976 continue;
3977 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003978 if (wait_pid <= 0
3979# ifdef ECHILD
3980 && errno == ECHILD
3981# endif
3982 )
3983 break;
3984 }
3985 return wait_pid;
3986}
3987
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003988#if defined(FEAT_JOB_CHANNEL) || !defined(USE_SYSTEM) || defined(PROTO)
Bram Moolenaar72801402016-02-09 11:37:50 +01003989/*
3990 * Parse "cmd" and put the white-separated parts in "argv".
3991 * "argv" is an allocated array with "argc" entries.
3992 * Returns FAIL when out of memory.
3993 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01003994 int
3995mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
3996{
3997 int i;
3998 char_u *p;
3999 int inquote;
4000
4001 /*
4002 * Do this loop twice:
4003 * 1: find number of arguments
4004 * 2: separate them and build argv[]
4005 */
4006 for (i = 0; i < 2; ++i)
4007 {
Bram Moolenaar6231cb82016-04-26 19:42:42 +02004008 p = skipwhite(cmd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01004009 inquote = FALSE;
4010 *argc = 0;
4011 for (;;)
4012 {
4013 if (i == 1)
4014 (*argv)[*argc] = (char *)p;
4015 ++*argc;
4016 while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
4017 {
4018 if (*p == '"')
4019 inquote = !inquote;
4020 ++p;
4021 }
4022 if (*p == NUL)
4023 break;
4024 if (i == 1)
4025 *p++ = NUL;
4026 p = skipwhite(p);
4027 }
4028 if (*argv == NULL)
4029 {
4030 if (use_shcf)
4031 {
4032 /* Account for possible multiple args in p_shcf. */
4033 p = p_shcf;
4034 for (;;)
4035 {
4036 p = skiptowhite(p);
4037 if (*p == NUL)
4038 break;
4039 ++*argc;
4040 p = skipwhite(p);
4041 }
4042 }
4043
4044 *argv = (char **)alloc((unsigned)((*argc + 4) * sizeof(char *)));
4045 if (*argv == NULL) /* out of memory */
4046 return FAIL;
4047 }
4048 }
4049 return OK;
4050}
4051#endif
4052
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004053#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004054 static void
4055set_child_environment(void)
4056{
4057# ifdef HAVE_SETENV
4058 char envbuf[50];
4059# else
4060 static char envbuf_Rows[20];
4061 static char envbuf_Columns[20];
4062# endif
4063
4064 /* Simulate to have a dumb terminal (for now) */
4065# ifdef HAVE_SETENV
4066 setenv("TERM", "dumb", 1);
4067 sprintf((char *)envbuf, "%ld", Rows);
4068 setenv("ROWS", (char *)envbuf, 1);
4069 sprintf((char *)envbuf, "%ld", Rows);
4070 setenv("LINES", (char *)envbuf, 1);
4071 sprintf((char *)envbuf, "%ld", Columns);
4072 setenv("COLUMNS", (char *)envbuf, 1);
4073# else
4074 /*
4075 * Putenv does not copy the string, it has to remain valid.
4076 * Use a static array to avoid losing allocated memory.
4077 */
4078 putenv("TERM=dumb");
4079 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4080 putenv(envbuf_Rows);
4081 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4082 putenv(envbuf_Rows);
4083 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4084 putenv(envbuf_Columns);
4085# endif
4086}
4087#endif
4088
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004090mch_call_shell(
4091 char_u *cmd,
4092 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093{
4094#ifdef VMS
4095 char *ifn = NULL;
4096 char *ofn = NULL;
4097#endif
4098 int tmode = cur_tmode;
4099#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
Bram Moolenaarb2b050a2016-07-16 21:52:46 +02004100 char_u *newcmd; /* only needed for unix */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101
4102 out_flush();
4103
4104 if (options & SHELL_COOKED)
4105 settmode(TMODE_COOK); /* set to normal mode */
4106
Bram Moolenaar62b42182010-09-21 22:09:37 +02004107# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004108 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004109 loose_clipboard();
4110# endif
4111
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112 if (cmd == NULL)
4113 x = system((char *)p_sh);
4114 else
4115 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004116# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 if (ofn = strchr((char *)cmd, '>'))
4118 *ofn++ = '\0';
4119 if (ifn = strchr((char *)cmd, '<'))
4120 {
4121 char *p;
4122
4123 *ifn++ = '\0';
4124 p = strchr(ifn,' '); /* chop off any trailing spaces */
4125 if (p)
4126 *p = '\0';
4127 }
4128 if (ofn)
4129 x = vms_sys((char *)cmd, ofn, ifn);
4130 else
4131 x = system((char *)cmd);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004132# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 newcmd = lalloc(STRLEN(p_sh)
4134 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4135 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4136 if (newcmd == NULL)
4137 x = 0;
4138 else
4139 {
4140 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4141 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4142 (char *)p_shcf,
4143 (char *)cmd);
4144 x = system((char *)newcmd);
4145 vim_free(newcmd);
4146 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004147# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 }
4149# ifdef VMS
4150 x = vms_sys_status(x);
4151# endif
4152 if (emsg_silent)
4153 ;
4154 else if (x == 127)
4155 MSG_PUTS(_("\nCannot execute shell sh\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 else if (x && !(options & SHELL_SILENT))
4157 {
4158 MSG_PUTS(_("\nshell returned "));
4159 msg_outnum((long)x);
4160 msg_putchar('\n');
4161 }
4162
4163 if (tmode == TMODE_RAW)
4164 settmode(TMODE_RAW); /* set to raw mode */
4165# ifdef FEAT_TITLE
4166 resettitle();
4167# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004168# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4169 restore_clipboard();
4170# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 return x;
4172
4173#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4174
Bram Moolenaardf177f62005-02-22 08:39:57 +00004175# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4176 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177
Bram Moolenaar835dc632016-02-07 14:27:38 +01004178 char_u *newcmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004180 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 pid_t wait_pid = 0;
4182# ifdef HAVE_UNION_WAIT
4183 union wait status;
4184# else
4185 int status = -1;
4186# endif
4187 int retval = -1;
4188 char **argv = NULL;
4189 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004190 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 int i;
4192 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004194# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 int pty_slave_fd = -1;
4196 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004197# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004198 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 int fd_fromshell[2];
4200 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004201 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202
Bram Moolenaar62b42182010-09-21 22:09:37 +02004203 newcmd = vim_strsave(p_sh);
4204 if (newcmd == NULL) /* out of memory */
4205 goto error;
4206
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 out_flush();
4208 if (options & SHELL_COOKED)
4209 settmode(TMODE_COOK); /* set to normal mode */
4210
Bram Moolenaar835dc632016-02-07 14:27:38 +01004211 if (mch_parse_cmd(newcmd, TRUE, &argv, &argc) == FAIL)
4212 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004213
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 if (cmd != NULL)
4215 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004216 char_u *s;
4217
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218 if (extra_shell_arg != NULL)
4219 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004220
4221 /* Break 'shellcmdflag' into white separated parts. This doesn't
4222 * handle quoted strings, they are very unlikely to appear. */
4223 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4224 if (p_shcf_copy == NULL) /* out of memory */
4225 goto error;
4226 s = p_shcf_copy;
4227 p = p_shcf;
4228 while (*p != NUL)
4229 {
4230 argv[argc++] = (char *)s;
4231 while (*p && *p != ' ' && *p != TAB)
4232 *s++ = *p++;
4233 *s++ = NUL;
4234 p = skipwhite(p);
4235 }
4236
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 argv[argc++] = (char *)cmd;
4238 }
4239 argv[argc] = NULL;
4240
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004242 * For the GUI, when writing the output into the buffer and when reading
4243 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4244 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004246 if ((options & (SHELL_READ|SHELL_WRITE))
4247# ifdef FEAT_GUI
4248 || (gui.in_use && show_shell_mess)
4249# endif
4250 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004252# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 /*
4254 * Try to open a master pty.
4255 * If this works, open the slave pty.
4256 * If the slave can't be opened, close the master pty.
4257 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004258 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 {
4260 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004261 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004263 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4264 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4265 * adding O_NOCTTY always works when defined. */
4266#ifdef O_NOCTTY
4267 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4268#else
4269 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4270#endif
4271 if (pty_slave_fd < 0)
4272 {
4273 close(pty_master_fd);
4274 pty_master_fd = -1;
4275 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 }
4277 }
4278 /*
4279 * If not opening a pty or it didn't work, try using pipes.
4280 */
4281 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004282# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 {
4284 pipe_error = (pipe(fd_toshell) < 0);
4285 if (!pipe_error) /* pipe create OK */
4286 {
4287 pipe_error = (pipe(fd_fromshell) < 0);
4288 if (pipe_error) /* pipe create failed */
4289 {
4290 close(fd_toshell[0]);
4291 close(fd_toshell[1]);
4292 }
4293 }
4294 if (pipe_error)
4295 {
4296 MSG_PUTS(_("\nCannot create pipes\n"));
4297 out_flush();
4298 }
4299 }
4300 }
4301
4302 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004304 SIGSET_DECL(curset)
4305
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306# ifdef __BEOS__
4307 beos_cleanup_read_thread();
4308# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004309
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004310 BLOCK_SIGNALS(&curset);
4311 pid = fork(); /* maybe we should use vfork() */
4312 if (pid == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004314 UNBLOCK_SIGNALS(&curset);
4315
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004317 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004319 || (gui.in_use && show_shell_mess)
4320# endif
4321 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004323# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 if (pty_master_fd >= 0) /* close the pseudo tty */
4325 {
4326 close(pty_master_fd);
4327 close(pty_slave_fd);
4328 }
4329 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004330# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 {
4332 close(fd_toshell[0]);
4333 close(fd_toshell[1]);
4334 close(fd_fromshell[0]);
4335 close(fd_fromshell[1]);
4336 }
4337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338 }
4339 else if (pid == 0) /* child */
4340 {
4341 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004342 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343
4344 if (!show_shell_mess || (options & SHELL_EXPAND))
4345 {
4346 int fd;
4347
4348 /*
4349 * Don't want to show any message from the shell. Can't just
4350 * close stdout and stderr though, because some systems will
4351 * break if you try to write to them after that, so we must
4352 * use dup() to replace them with something else -- webb
4353 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4354 * waiting for input.
4355 */
4356 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4357 fclose(stdin);
4358 fclose(stdout);
4359 fclose(stderr);
4360
4361 /*
4362 * If any of these open()'s and dup()'s fail, we just continue
4363 * anyway. It's not fatal, and on most systems it will make
4364 * no difference at all. On a few it will cause the execvp()
4365 * to exit with a non-zero status even when the completion
4366 * could be done, which is nothing too serious. If the open()
4367 * or dup() failed we'd just do the same thing ourselves
4368 * anyway -- webb
4369 */
4370 if (fd >= 0)
4371 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004372 ignored = dup(fd); /* To replace stdin (fd 0) */
4373 ignored = dup(fd); /* To replace stdout (fd 1) */
4374 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375
4376 /* Don't need this now that we've duplicated it */
4377 close(fd);
4378 }
4379 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004380 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004382 || gui.in_use
4383# endif
4384 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004385 {
4386
Bram Moolenaardf177f62005-02-22 08:39:57 +00004387# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004388 /* Create our own process group, so that the child and all its
4389 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004390 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004391 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004392 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004393 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004394# if defined(SIGHUP)
4395 /* When doing "!xterm&" and 'shell' is bash: the shell
4396 * will exit and send SIGHUP to all processes in its
4397 * group, killing the just started process. Ignore SIGHUP
4398 * to avoid that. (suggested by Simon Schubert)
4399 */
4400 signal(SIGHUP, SIG_IGN);
4401# endif
4402 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004403# endif
4404# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004405 if (pty_slave_fd >= 0)
4406 {
4407 /* push stream discipline modules */
4408 if (options & SHELL_COOKED)
4409 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004411 /* Try to become controlling tty (probably doesn't work,
4412 * unless run by root) */
4413 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004415 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004416# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004417 set_child_environment();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418
Bram Moolenaara5792f52005-11-23 21:25:05 +00004419 /*
4420 * stderr is only redirected when using the GUI, so that a
4421 * program like gpg can still access the terminal to get a
4422 * passphrase using stderr.
4423 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004424# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004425 if (pty_master_fd >= 0)
4426 {
4427 close(pty_master_fd); /* close master side of pty */
4428
4429 /* set up stdin/stdout/stderr for the child */
4430 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004431 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004433 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004434 if (gui.in_use)
4435 {
4436 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004437 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439
4440 close(pty_slave_fd); /* has been dupped, close it now */
4441 }
4442 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004443# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 {
4445 /* set up stdin for the child */
4446 close(fd_toshell[1]);
4447 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004448 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 close(fd_toshell[0]);
4450
4451 /* set up stdout for the child */
4452 close(fd_fromshell[0]);
4453 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004454 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455 close(fd_fromshell[1]);
4456
Bram Moolenaara5792f52005-11-23 21:25:05 +00004457# ifdef FEAT_GUI
4458 if (gui.in_use)
4459 {
4460 /* set up stderr for the child */
4461 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004462 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004463 }
4464# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465 }
4466 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004467
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 /*
4469 * There is no type cast for the argv, because the type may be
4470 * different on different machines. This may cause a warning
4471 * message with strict compilers, don't worry about it.
4472 * Call _exit() instead of exit() to avoid closing the connection
4473 * to the X server (esp. with GTK, which uses atexit()).
4474 */
4475 execvp(argv[0], argv);
4476 _exit(EXEC_FAILED); /* exec failed, return failure code */
4477 }
4478 else /* parent */
4479 {
4480 /*
4481 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004482 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 */
4484 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004485 catch_int_signal();
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004486 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
4488 /*
4489 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004490 * This is also used to pipe stdin/stdout to/from the external
4491 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004493 if ((options & (SHELL_READ|SHELL_WRITE))
4494# ifdef FEAT_GUI
4495 || (gui.in_use && show_shell_mess)
4496# endif
4497 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004499# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004501# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4505 int ta_len = 0; /* valid bytes in ta_buf[] */
4506 int len;
4507 int p_more_save;
4508 int old_State;
4509 int c;
4510 int toshell_fd;
4511 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004512 garray_T ga;
4513 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004514# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4515 struct timeval start_tv;
4516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517
Bram Moolenaardf177f62005-02-22 08:39:57 +00004518# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 if (pty_master_fd >= 0)
4520 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 fromshell_fd = pty_master_fd;
4522 toshell_fd = dup(pty_master_fd);
4523 }
4524 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004525# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 {
4527 close(fd_toshell[0]);
4528 close(fd_fromshell[1]);
4529 toshell_fd = fd_toshell[1];
4530 fromshell_fd = fd_fromshell[0];
4531 }
4532
4533 /*
4534 * Write to the child if there are typed characters.
4535 * Read from the child if there are characters available.
4536 * Repeat the reading a few times if more characters are
4537 * available. Need to check for typed keys now and then, but
4538 * not too often (delays when no chars are available).
4539 * This loop is quit if no characters can be read from the pty
4540 * (WaitForChar detected special condition), or there are no
4541 * characters available and the child has exited.
4542 * Only check if the child has exited when there is no more
4543 * output. The child may exit before all the output has
4544 * been printed.
4545 *
4546 * Currently this busy loops!
4547 * This can probably dead-lock when the write blocks!
4548 */
4549 p_more_save = p_more;
4550 p_more = FALSE;
4551 old_State = State;
4552 State = EXTERNCMD; /* don't redraw at window resize */
4553
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004554 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004555 {
4556 /* Fork a process that will write the lines to the
4557 * external program. */
4558 if ((wpid = fork()) == -1)
4559 {
4560 MSG_PUTS(_("\nCannot fork\n"));
4561 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004562 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004563 {
4564 linenr_T lnum = curbuf->b_op_start.lnum;
4565 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004566 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004567 size_t l;
4568
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004569 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004570 for (;;)
4571 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004572 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004573 if (l == 0)
4574 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004575 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004576 /* NL -> NUL translation */
4577 len = write(toshell_fd, "", (size_t)1);
4578 else
4579 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004580 char_u *s = vim_strchr(lp + written, NL);
4581
Bram Moolenaar89d40322006-08-29 15:30:07 +00004582 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004583 s == NULL ? l
4584 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004585 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004586 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004587 {
4588 /* Finished a line, add a NL, unless this line
4589 * should not have one. */
4590 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004591 || (!curbuf->b_p_bin
4592 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004593 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004594 && (lnum !=
4595 curbuf->b_ml.ml_line_count
4596 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004597 ignored = write(toshell_fd, "\n",
4598 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004599 ++lnum;
4600 if (lnum > curbuf->b_op_end.lnum)
4601 {
4602 /* finished all the lines, close pipe */
4603 close(toshell_fd);
4604 toshell_fd = -1;
4605 break;
4606 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004607 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004608 written = 0;
4609 }
4610 else if (len > 0)
4611 written += len;
4612 }
4613 _exit(0);
4614 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004615 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004616 {
4617 close(toshell_fd);
4618 toshell_fd = -1;
4619 }
4620 }
4621
4622 if (options & SHELL_READ)
4623 ga_init2(&ga, 1, BUFLEN);
4624
4625 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004626# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4627 gettimeofday(&start_tv, NULL);
4628# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 for (;;)
4630 {
4631 /*
4632 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004633 * if there are any.
4634 * Don't do this if we are expanding wild cards (would eat
4635 * typeahead).
4636 * Don't do this when filtering and terminal is in cooked
4637 * mode, the shell command will handle the I/O. Avoids
4638 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004639 * Don't get characters when the child has already
4640 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004641 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004642 * while (noread_cnt > 4), avoids that ":r !ls" eats
4643 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004644 */
4645 len = 0;
4646 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004647 && ((options &
4648 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4649 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004650# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004651 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004652# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004653 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004654 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004655 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004657 if (ta_len == 0)
4658 {
4659 /* Get extra characters when we don't have any.
4660 * Reset the counter and timer. */
4661 noread_cnt = 0;
4662# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4663 gettimeofday(&start_tv, NULL);
4664# endif
4665 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4666 }
4667 if (ta_len > 0 || len > 0)
4668 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669 /*
4670 * For pipes:
4671 * Check for CTRL-C: send interrupt signal to child.
4672 * Check for CTRL-D: EOF, close pipe to child.
4673 */
4674 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4675 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004676# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 /*
4678 * Send SIGINT to the child's group or all
4679 * processes in our group.
4680 */
4681 if (ta_buf[ta_len] == Ctrl_C
4682 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004683 {
4684# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004686# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004689 if (wpid > 0)
4690 kill(wpid, SIGINT);
4691 }
4692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693 if (pty_master_fd < 0 && toshell_fd >= 0
4694 && ta_buf[ta_len] == Ctrl_D)
4695 {
4696 close(toshell_fd);
4697 toshell_fd = -1;
4698 }
4699 }
4700
4701 /* replace K_BS by <BS> and K_DEL by <DEL> */
4702 for (i = ta_len; i < ta_len + len; ++i)
4703 {
4704 if (ta_buf[i] == CSI && len - i > 2)
4705 {
4706 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4707 if (c == K_DEL || c == K_KDEL || c == K_BS)
4708 {
4709 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4710 (size_t)(len - i - 2));
4711 if (c == K_DEL || c == K_KDEL)
4712 ta_buf[i] = DEL;
4713 else
4714 ta_buf[i] = Ctrl_H;
4715 len -= 2;
4716 }
4717 }
4718 else if (ta_buf[i] == '\r')
4719 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004720# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004722 i += (*mb_ptr2len_len)(ta_buf + i,
4723 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725 }
4726
4727 /*
4728 * For pipes: echo the typed characters.
4729 * For a pty this does not seem to work.
4730 */
4731 if (pty_master_fd < 0)
4732 {
4733 for (i = ta_len; i < ta_len + len; ++i)
4734 {
4735 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4736 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004737# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738 else if (has_mbyte)
4739 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004740 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741
4742 msg_outtrans_len(ta_buf + i, l);
4743 i += l - 1;
4744 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746 else
4747 msg_outtrans_len(ta_buf + i, 1);
4748 }
4749 windgoto(msg_row, msg_col);
4750 out_flush();
4751 }
4752
4753 ta_len += len;
4754
4755 /*
4756 * Write the characters to the child, unless EOF has
4757 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004758 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004759 * When writing buffer lines, drop the typed
4760 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004762 if (options & SHELL_WRITE)
4763 ta_len = 0;
4764 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 {
4766 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4767 if (len > 0)
4768 {
4769 ta_len -= len;
4770 mch_memmove(ta_buf, ta_buf + len, ta_len);
4771 }
4772 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 }
4775
Bram Moolenaardf177f62005-02-22 08:39:57 +00004776 if (got_int)
4777 {
4778 /* CTRL-C sends a signal to the child, we ignore it
4779 * ourselves */
4780# ifdef HAVE_SETSID
4781 kill(-pid, SIGINT);
4782# else
4783 kill(0, SIGINT);
4784# endif
4785 if (wpid > 0)
4786 kill(wpid, SIGINT);
4787 got_int = FALSE;
4788 }
4789
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 /*
4791 * Check if the child has any characters to be printed.
4792 * Read them and write them to our window. Repeat this as
4793 * long as there is something to do, avoid the 10ms wait
4794 * for mch_inchar(), or sending typeahead characters to
4795 * the external process.
4796 * TODO: This should handle escape sequences, compatible
4797 * to some terminal (vt52?).
4798 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004799 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01004800 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004802 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004803# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004805# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004807# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 );
4809 if (len <= 0) /* end of file or error */
4810 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004811
4812 noread_cnt = 0;
4813 if (options & SHELL_READ)
4814 {
4815 /* Do NUL -> NL translation, append NL separated
4816 * lines to the current buffer. */
4817 for (i = 0; i < len; ++i)
4818 {
4819 if (buffer[i] == NL)
4820 append_ga_line(&ga);
4821 else if (buffer[i] == NUL)
4822 ga_append(&ga, NL);
4823 else
4824 ga_append(&ga, buffer[i]);
4825 }
4826 }
4827# ifdef FEAT_MBYTE
4828 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829 {
4830 int l;
4831
Bram Moolenaardf177f62005-02-22 08:39:57 +00004832 len += buffer_off;
4833 buffer[len] = NUL;
4834
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 /* Check if the last character in buffer[] is
4836 * incomplete, keep these bytes for the next
4837 * round. */
4838 for (p = buffer; p < buffer + len; p += l)
4839 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004840 l = MB_CPTR2LEN(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 if (l == 0)
4842 l = 1; /* NUL byte? */
4843 else if (MB_BYTE2LEN(*p) != l)
4844 break;
4845 }
4846 if (p == buffer) /* no complete character */
4847 {
4848 /* avoid getting stuck at an illegal byte */
4849 if (len >= 12)
4850 ++p;
4851 else
4852 {
4853 buffer_off = len;
4854 continue;
4855 }
4856 }
4857 c = *p;
4858 *p = NUL;
4859 msg_puts(buffer);
4860 if (p < buffer + len)
4861 {
4862 *p = c;
4863 buffer_off = (buffer + len) - p;
4864 mch_memmove(buffer, p, buffer_off);
4865 continue;
4866 }
4867 buffer_off = 0;
4868 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004869# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 {
4872 buffer[len] = NUL;
4873 msg_puts(buffer);
4874 }
4875
4876 windgoto(msg_row, msg_col);
4877 cursor_on();
4878 out_flush();
4879 if (got_int)
4880 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004881
4882# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004883 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004884 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +02004885 long msec = elapsed(&start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004886
4887 /* Avoid that we keep looping here without
4888 * checking for a CTRL-C for a long time. Don't
4889 * break out too often to avoid losing typeahead. */
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004890 if (msec > 2000)
4891 {
4892 noread_cnt = 5;
4893 break;
4894 }
4895 }
4896# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 }
4898
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004899 /* If we already detected the child has finished, continue
4900 * reading output for a short while. Some text may be
4901 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004902 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004903 {
4904 if (noread_cnt < 5)
4905 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004906 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004907 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004908
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 /*
4910 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004911 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004913# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004914 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004915# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004917# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4919 || (wait_pid == pid && WIFEXITED(status)))
4920 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004921 /* Don't break the loop yet, try reading more
4922 * characters from "fromshell_fd" first. When using
4923 * pipes there might still be something to read and
4924 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004927 else
4928 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004929
Bram Moolenaar95a51352013-03-21 22:53:50 +01004930# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004931 /* Handle any X events, e.g. serving the clipboard. */
4932 clip_update();
4933# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934 }
4935finished:
4936 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004937 if (options & SHELL_READ)
4938 {
4939 if (ga.ga_len > 0)
4940 {
4941 append_ga_line(&ga);
4942 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004943 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004944 }
4945 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004946 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004947 ga_clear(&ga);
4948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 /*
4951 * Give all typeahead that wasn't used back to ui_inchar().
4952 */
4953 if (ta_len)
4954 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955 State = old_State;
4956 if (toshell_fd >= 0)
4957 close(toshell_fd);
4958 close(fromshell_fd);
4959 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004960# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004961 else
4962 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004963 long delay_msec = 1;
4964
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004965 /*
4966 * Similar to the loop above, but only handle X events, no
4967 * I/O.
4968 */
4969 for (;;)
4970 {
4971 if (got_int)
4972 {
4973 /* CTRL-C sends a signal to the child, we ignore it
4974 * ourselves */
4975# ifdef HAVE_SETSID
4976 kill(-pid, SIGINT);
4977# else
4978 kill(0, SIGINT);
4979# endif
4980 got_int = FALSE;
4981 }
4982# ifdef __NeXT__
4983 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4984# else
4985 wait_pid = waitpid(pid, &status, WNOHANG);
4986# endif
4987 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4988 || (wait_pid == pid && WIFEXITED(status)))
4989 {
4990 wait_pid = pid;
4991 break;
4992 }
4993
4994 /* Handle any X events, e.g. serving the clipboard. */
4995 clip_update();
4996
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004997 /* Wait for 1 to 10 msec. 1 is faster but gives the child
4998 * less time. */
4999 mch_delay(delay_msec, TRUE);
5000 if (++delay_msec > 10)
5001 delay_msec = 10;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005002 }
5003 }
5004# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005
5006 /*
5007 * Wait until our child has exited.
5008 * Ignore wait() returning pids of other children and returning
5009 * because of some signal like SIGWINCH.
5010 * Don't wait if wait_pid was already set above, indicating the
5011 * child already exited.
5012 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005013 if (wait_pid != pid)
5014 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005015
Bram Moolenaar624891f2010-10-13 16:22:09 +02005016# ifdef FEAT_GUI
5017 /* Close slave side of pty. Only do this after the child has
5018 * exited, otherwise the child may hang when it tries to write on
5019 * the pty. */
5020 if (pty_master_fd >= 0)
5021 close(pty_slave_fd);
5022# endif
5023
Bram Moolenaardf177f62005-02-22 08:39:57 +00005024 /* Make sure the child that writes to the external program is
5025 * dead. */
5026 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005027 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005028 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005029 wait4pid(wpid, NULL);
5030 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005031
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 /*
5033 * Set to raw mode right now, otherwise a CTRL-C after
5034 * catch_signals() will kill Vim.
5035 */
5036 if (tmode == TMODE_RAW)
5037 settmode(TMODE_RAW);
5038 did_settmode = TRUE;
5039 set_signals();
5040
5041 if (WIFEXITED(status))
5042 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005043 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005045 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 {
5047 if (retval == EXEC_FAILED)
5048 {
5049 MSG_PUTS(_("\nCannot execute shell "));
5050 msg_outtrans(p_sh);
5051 msg_putchar('\n');
5052 }
5053 else if (!(options & SHELL_SILENT))
5054 {
5055 MSG_PUTS(_("\nshell returned "));
5056 msg_outnum((long)retval);
5057 msg_putchar('\n');
5058 }
5059 }
5060 }
5061 else
5062 MSG_PUTS(_("\nCommand terminated\n"));
5063 }
5064 }
5065 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005066 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067
5068error:
5069 if (!did_settmode)
5070 if (tmode == TMODE_RAW)
5071 settmode(TMODE_RAW); /* set to raw mode */
5072# ifdef FEAT_TITLE
5073 resettitle();
5074# endif
5075 vim_free(newcmd);
5076
5077 return retval;
5078
5079#endif /* USE_SYSTEM */
5080}
5081
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005082#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005083 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005084mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005085{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005086 pid_t pid;
5087 int fd_in[2]; /* for stdin */
5088 int fd_out[2]; /* for stdout */
5089 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005090 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005091 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5092 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5093 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005094 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005095 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5096 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005097 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005098 SIGSET_DECL(curset)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005099
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005100 if (use_out_for_err && use_null_for_out)
5101 use_null_for_err = TRUE;
5102
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005103 /* default is to fail */
5104 job->jv_status = JOB_FAILED;
5105 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005106 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005107 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005108 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005109 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005110 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005111
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005112 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005113 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005114 if (use_file_for_in)
5115 {
5116 char_u *fname = options->jo_io_name[PART_IN];
5117
5118 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5119 if (fd_in[0] < 0)
5120 {
5121 EMSG2(_(e_notopen), fname);
5122 goto failed;
5123 }
5124 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005125 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005126 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005127
5128 if (use_file_for_out)
5129 {
5130 char_u *fname = options->jo_io_name[PART_OUT];
5131
5132 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5133 if (fd_out[1] < 0)
5134 {
5135 EMSG2(_(e_notopen), fname);
5136 goto failed;
5137 }
5138 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005139 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005140 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005141
5142 if (use_file_for_err)
5143 {
5144 char_u *fname = options->jo_io_name[PART_ERR];
5145
5146 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5147 if (fd_err[1] < 0)
5148 {
5149 EMSG2(_(e_notopen), fname);
5150 goto failed;
5151 }
5152 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005153 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005154 goto failed;
5155
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005156 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5157 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005158 if (options->jo_set & JO_CHANNEL)
5159 {
5160 channel = options->jo_channel;
5161 if (channel != NULL)
5162 ++channel->ch_refcount;
5163 }
5164 else
5165 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005166 if (channel == NULL)
5167 goto failed;
5168 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005169
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005170 BLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005171 pid = fork(); /* maybe we should use vfork() */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005172 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005173 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005174 /* failed to fork */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005175 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005176 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005177 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005178 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005179 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005180 int null_fd = -1;
5181 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005182
Bram Moolenaar835dc632016-02-07 14:27:38 +01005183 /* child */
5184 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005185 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005186
5187# ifdef HAVE_SETSID
5188 /* Create our own process group, so that the child and all its
5189 * children can be kill()ed. Don't do this when using pipes,
5190 * because stdin is not a tty, we would lose /dev/tty. */
5191 (void)setsid();
5192# endif
5193
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005194 set_child_environment();
5195
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005196 if (use_null_for_in || use_null_for_out || use_null_for_err)
5197 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5198
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005199 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005200 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005201 {
5202 close(0);
5203 ignored = dup(null_fd);
5204 }
5205 else
5206 {
5207 if (!use_file_for_in)
5208 close(fd_in[1]);
5209 close(0);
5210 ignored = dup(fd_in[0]);
5211 close(fd_in[0]);
5212 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005213
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005214 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005215 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005216 {
5217 close(2);
5218 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005219 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005220 }
5221 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005222 {
5223 close(2);
5224 ignored = dup(fd_out[1]);
5225 }
5226 else
5227 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005228 if (!use_file_for_err)
5229 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005230 close(2);
5231 ignored = dup(fd_err[1]);
5232 close(fd_err[1]);
5233 }
5234
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005235 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005236 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005237 {
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005238 close(1);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005239 ignored = dup(null_fd);
5240 }
5241 else
5242 {
5243 if (!use_file_for_out)
5244 close(fd_out[0]);
5245 close(1);
5246 ignored = dup(fd_out[1]);
5247 close(fd_out[1]);
5248 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005249
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005250 if (null_fd >= 0)
5251 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005252
Bram Moolenaar835dc632016-02-07 14:27:38 +01005253 /* See above for type of argv. */
5254 execvp(argv[0], argv);
5255
Bram Moolenaar4694a172016-04-21 14:05:23 +02005256 if (stderr_works)
5257 perror("executing job failed");
Bram Moolenaarcda77642016-06-04 13:32:35 +02005258#ifdef EXITFREE
5259 /* calling free_all_mem() here causes problems. Ignore valgrind
5260 * reporting possibly leaked memory. */
5261#endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005262 _exit(EXEC_FAILED); /* exec failed, return failure code */
5263 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005264
5265 /* parent */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005266 UNBLOCK_SIGNALS(&curset);
5267
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005268 job->jv_pid = pid;
5269 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005270 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005271
5272 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005273 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005274 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005275 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005276 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005277 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005278 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005279 if (channel != NULL)
5280 {
5281 channel_set_pipes(channel,
5282 use_file_for_in || use_null_for_in
5283 ? INVALID_FD : fd_in[1],
5284 use_file_for_out || use_null_for_out
5285 ? INVALID_FD : fd_out[0],
5286 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005287 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005288 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005289 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005290
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005291 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005292 return;
5293
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005294failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005295 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005296 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005297 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005298 if (fd_in[1] >= 0)
5299 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005300 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005301 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005302 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005303 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005304 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005305 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005306 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005307 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005308}
5309
5310 char *
5311mch_job_status(job_T *job)
5312{
5313# ifdef HAVE_UNION_WAIT
5314 union wait status;
5315# else
5316 int status = -1;
5317# endif
5318 pid_t wait_pid = 0;
5319
5320# ifdef __NeXT__
5321 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5322# else
5323 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5324# endif
5325 if (wait_pid == -1)
5326 {
5327 /* process must have exited */
Bram Moolenaar97792de2016-10-15 18:36:49 +02005328 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005329 }
5330 if (wait_pid == 0)
5331 return "run";
5332 if (WIFEXITED(status))
5333 {
5334 /* LINTED avoid "bitwise operation on signed value" */
5335 job->jv_exitval = WEXITSTATUS(status);
Bram Moolenaar97792de2016-10-15 18:36:49 +02005336 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005337 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005338 if (WIFSIGNALED(status))
5339 {
5340 job->jv_exitval = -1;
Bram Moolenaar97792de2016-10-15 18:36:49 +02005341 goto return_dead;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005342 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005343 return "run";
Bram Moolenaar97792de2016-10-15 18:36:49 +02005344
5345return_dead:
5346 if (job->jv_status != JOB_ENDED)
5347 {
5348 ch_log(job->jv_channel, "Job ended");
5349 job->jv_status = JOB_ENDED;
5350 }
5351 return "dead";
5352}
5353
5354 job_T *
5355mch_detect_ended_job(job_T *job_list)
5356{
5357# ifdef HAVE_UNION_WAIT
5358 union wait status;
5359# else
5360 int status = -1;
5361# endif
5362 pid_t wait_pid = 0;
5363 job_T *job;
5364
5365# ifdef __NeXT__
5366 wait_pid = wait4(-1, &status, WNOHANG, (struct rusage *)0);
5367# else
5368 wait_pid = waitpid(-1, &status, WNOHANG);
5369# endif
5370 if (wait_pid <= 0)
5371 /* no process ended */
5372 return NULL;
5373 for (job = job_list; job != NULL; job = job->jv_next)
5374 {
5375 if (job->jv_pid == wait_pid)
5376 {
5377 if (WIFEXITED(status))
5378 /* LINTED avoid "bitwise operation on signed value" */
5379 job->jv_exitval = WEXITSTATUS(status);
5380 else if (WIFSIGNALED(status))
5381 job->jv_exitval = -1;
5382 if (job->jv_status != JOB_ENDED)
5383 {
5384 ch_log(job->jv_channel, "Job ended");
5385 job->jv_status = JOB_ENDED;
5386 }
5387 return job;
5388 }
5389 }
5390 return NULL;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005391}
5392
Bram Moolenaar3a117e12016-10-30 21:57:52 +01005393/*
5394 * Send a (deadly) signal to "job".
5395 * Return FAIL if "how" is not a valid name.
5396 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01005397 int
5398mch_stop_job(job_T *job, char_u *how)
5399{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005400 int sig = -1;
5401 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005402
Bram Moolenaar923d9262016-02-25 20:56:01 +01005403 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005404 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005405 else if (STRCMP(how, "hup") == 0)
5406 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005407 else if (STRCMP(how, "quit") == 0)
5408 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005409 else if (STRCMP(how, "int") == 0)
5410 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005411 else if (STRCMP(how, "kill") == 0)
5412 sig = SIGKILL;
5413 else if (isdigit(*how))
5414 sig = atoi((char *)how);
5415 else
5416 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005417
Bram Moolenaar72801402016-02-09 11:37:50 +01005418 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005419 job_pid = job->jv_pid;
5420 if (job_pid == getpgid(job_pid))
5421 job_pid = -job_pid;
5422
5423 kill(job_pid, sig);
5424
Bram Moolenaar835dc632016-02-07 14:27:38 +01005425 return OK;
5426}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005427
5428/*
5429 * Clear the data related to "job".
5430 */
5431 void
5432mch_clear_job(job_T *job)
5433{
5434 /* call waitpid because child process may become zombie */
5435# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005436 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005437# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005438 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005439# endif
5440}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005441#endif
5442
Bram Moolenaar071d4272004-06-13 20:20:40 +00005443/*
5444 * Check for CTRL-C typed by reading all available characters.
5445 * In cooked mode we should get SIGINT, no need to check.
5446 */
5447 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005448mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005449{
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005450 if ((curr_tmode == TMODE_RAW || force)
5451 && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452 fill_input_buf(FALSE);
5453}
5454
5455/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005456 * Wait "msec" msec until a character is available from the mouse, keyboard,
5457 * from inbuf[].
5458 * "msec" == -1 will block forever.
5459 * Invokes timer callbacks when needed.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005460 * "interrupted" (if not NULL) is set to TRUE when no character is available
5461 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005462 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005463 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464 */
5465 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005466WaitForChar(long msec, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005468#ifdef FEAT_TIMERS
5469 long due_time;
5470 long remaining = msec;
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005471 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005472
5473 /* When waiting very briefly don't trigger timers. */
5474 if (msec >= 0 && msec < 10L)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005475 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005476
5477 while (msec < 0 || remaining > 0)
5478 {
5479 /* Trigger timers and then get the time in msec until the next one is
5480 * due. Wait up to that time. */
5481 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005482 if (typebuf.tb_change_cnt != tb_change_cnt)
5483 {
5484 /* timer may have used feedkeys() */
5485 return FALSE;
5486 }
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005487 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5488 due_time = remaining;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005489 if (WaitForCharOrMouse(due_time, interrupted))
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005490 return TRUE;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005491 if (interrupted != NULL && *interrupted)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005492 /* Nothing available, but need to return so that side effects get
5493 * handled, such as handling a message on a channel. */
5494 return FALSE;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005495 if (msec > 0)
5496 remaining -= due_time;
5497 }
5498 return FALSE;
5499#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005500 return WaitForCharOrMouse(msec, interrupted);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005501#endif
5502}
5503
5504/*
5505 * Wait "msec" msec until a character is available from the mouse or keyboard
5506 * or from inbuf[].
5507 * "msec" == -1 will block forever.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005508 * "interrupted" (if not NULL) is set to TRUE when no character is available
5509 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005510 * When a GUI is being used, this will never get called -- webb
5511 */
5512 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005513WaitForCharOrMouse(long msec, int *interrupted)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005514{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515#ifdef FEAT_MOUSE_GPM
5516 int gpm_process_wanted;
5517#endif
5518#ifdef FEAT_XCLIPBOARD
5519 int rest;
5520#endif
5521 int avail;
5522
5523 if (input_available()) /* something in inbuf[] */
5524 return 1;
5525
5526#if defined(FEAT_MOUSE_DEC)
5527 /* May need to query the mouse position. */
5528 if (WantQueryMouse)
5529 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005530 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5532 }
5533#endif
5534
5535 /*
5536 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5537 * events. This is a bit complicated, because they might both be defined.
5538 */
5539#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5540# ifdef FEAT_XCLIPBOARD
5541 rest = 0;
5542 if (do_xterm_trace())
5543 rest = msec;
5544# endif
5545 do
5546 {
5547# ifdef FEAT_XCLIPBOARD
5548 if (rest != 0)
5549 {
5550 msec = XT_TRACE_DELAY;
5551 if (rest >= 0 && rest < XT_TRACE_DELAY)
5552 msec = rest;
5553 if (rest >= 0)
5554 rest -= msec;
5555 }
5556# endif
5557# ifdef FEAT_MOUSE_GPM
5558 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005559 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02005560 &gpm_process_wanted, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005562 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563# endif
5564 if (!avail)
5565 {
5566 if (input_available())
5567 return 1;
5568# ifdef FEAT_XCLIPBOARD
5569 if (rest == 0 || !do_xterm_trace())
5570# endif
5571 break;
5572 }
5573 }
5574 while (FALSE
5575# ifdef FEAT_MOUSE_GPM
5576 || (gpm_process_wanted && mch_gpm_process() == 0)
5577# endif
5578# ifdef FEAT_XCLIPBOARD
5579 || (!avail && rest != 0)
5580# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005581 )
5582 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583
5584#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005585 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586#endif
5587 return avail;
5588}
5589
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005590#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591/*
5592 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005593 * "msec" == 0 will check for characters once.
5594 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005597 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005598 * "interrupted" (if not NULL) is set to TRUE when no character is available
5599 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601#if defined(__BEOS__)
5602 int
5603#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005604 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005606RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607{
5608 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005609 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005610#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611 static int busy = FALSE;
5612
5613 /* May retry getting characters after an event was handled. */
5614# define MAY_LOOP
5615
5616# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5617 /* Remember at what time we started, so that we know how much longer we
5618 * should wait after being interrupted. */
5619# define USE_START_TV
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005620 long start_msec = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 struct timeval start_tv;
5622
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005623 if (msec > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 gettimeofday(&start_tv, NULL);
5625# endif
5626
5627 /* Handle being called recursively. This may happen for the session
5628 * manager stuff, it may save the file, which does a breakcheck. */
5629 if (busy)
5630 return 0;
5631#endif
5632
5633#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005634 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635#endif
5636 {
5637#ifdef MAY_LOOP
5638 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005639# ifdef FEAT_MZSCHEME
5640 int mzquantum_used = FALSE;
5641# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642#endif
5643#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005644 /* each channel may use in, out and err */
5645 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 int nfd;
5647# ifdef FEAT_XCLIPBOARD
5648 int xterm_idx = -1;
5649# endif
5650# ifdef FEAT_MOUSE_GPM
5651 int gpm_idx = -1;
5652# endif
5653# ifdef USE_XSMP
5654 int xsmp_idx = -1;
5655# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005656 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005658# ifdef FEAT_MZSCHEME
5659 mzvim_check_threads();
5660 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5661 {
5662 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5663 mzquantum_used = TRUE;
5664 }
5665# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 fds[0].fd = fd;
5667 fds[0].events = POLLIN;
5668 nfd = 1;
5669
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005671 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 if (xterm_Shell != (Widget)0)
5673 {
5674 xterm_idx = nfd;
5675 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5676 fds[nfd].events = POLLIN;
5677 nfd++;
5678 }
5679# endif
5680# ifdef FEAT_MOUSE_GPM
5681 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5682 {
5683 gpm_idx = nfd;
5684 fds[nfd].fd = gpm_fd;
5685 fds[nfd].events = POLLIN;
5686 nfd++;
5687 }
5688# endif
5689# ifdef USE_XSMP
5690 if (xsmp_icefd != -1)
5691 {
5692 xsmp_idx = nfd;
5693 fds[nfd].fd = xsmp_icefd;
5694 fds[nfd].events = POLLIN;
5695 nfd++;
5696 }
5697# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005698#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005699 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005700#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005701 if (interrupted != NULL)
5702 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005704 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005705
5706 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02005707 if (result == 0 && interrupted != NULL && ret > 0)
5708 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005709
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005710# ifdef FEAT_MZSCHEME
5711 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005712 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005713 finished = FALSE;
5714# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716# ifdef FEAT_XCLIPBOARD
5717 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5718 {
5719 xterm_update(); /* Maybe we should hand out clipboard */
5720 if (--ret == 0 && !input_available())
5721 /* Try again */
5722 finished = FALSE;
5723 }
5724# endif
5725# ifdef FEAT_MOUSE_GPM
5726 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5727 {
5728 *check_for_gpm = 1;
5729 }
5730# endif
5731# ifdef USE_XSMP
5732 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5733 {
5734 if (fds[xsmp_idx].revents & POLLIN)
5735 {
5736 busy = TRUE;
5737 xsmp_handle_requests();
5738 busy = FALSE;
5739 }
5740 else if (fds[xsmp_idx].revents & POLLHUP)
5741 {
5742 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005743 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 xsmp_close();
5745 }
5746 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005747 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 }
5749# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005750#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005751 if (ret > 0)
5752 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005753#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755#else /* HAVE_SELECT */
5756
5757 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005758 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005759 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005761 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005763# ifdef FEAT_MZSCHEME
5764 mzvim_check_threads();
5765 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5766 {
5767 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5768 mzquantum_used = TRUE;
5769 }
5770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005772 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005774 tv.tv_sec = towait / 1000;
5775 tv.tv_usec = (towait % 1000) * (1000000/1000);
5776 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005778 else
5779 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780
5781 /*
5782 * Select on ready for reading and exceptional condition (end of file).
5783 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005784select_eintr:
5785 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005786 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 FD_ZERO(&efds);
5788 FD_SET(fd, &rfds);
5789# if !defined(__QNX__) && !defined(__CYGWIN32__)
5790 /* For QNX select() always returns 1 if this is set. Why? */
5791 FD_SET(fd, &efds);
5792# endif
5793 maxfd = fd;
5794
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005796 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 if (xterm_Shell != (Widget)0)
5798 {
5799 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5800 if (maxfd < ConnectionNumber(xterm_dpy))
5801 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005802
5803 /* An event may have already been read but not handled. In
5804 * particulary, XFlush may cause this. */
5805 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 }
5807# endif
5808# ifdef FEAT_MOUSE_GPM
5809 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5810 {
5811 FD_SET(gpm_fd, &rfds);
5812 FD_SET(gpm_fd, &efds);
5813 if (maxfd < gpm_fd)
5814 maxfd = gpm_fd;
5815 }
5816# endif
5817# ifdef USE_XSMP
5818 if (xsmp_icefd != -1)
5819 {
5820 FD_SET(xsmp_icefd, &rfds);
5821 FD_SET(xsmp_icefd, &efds);
5822 if (maxfd < xsmp_icefd)
5823 maxfd = xsmp_icefd;
5824 }
5825# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005826# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005827 maxfd = channel_select_setup(maxfd, &rfds, &wfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005828# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005829 if (interrupted != NULL)
5830 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005832 ret = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005833 result = ret > 0 && FD_ISSET(fd, &rfds);
5834 if (result)
5835 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005836 else if (interrupted != NULL && ret > 0)
5837 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005838
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005839# ifdef EINTR
5840 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005841 {
5842 /* Check whether window has been resized, EINTR may be caused by
5843 * SIGWINCH. */
5844 if (do_resize)
5845 handle_resize();
5846
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005847 /* Interrupted by a signal, need to try again. We ignore msec
5848 * here, because we do want to check even after a timeout if
5849 * characters are available. Needed for reading output of an
5850 * external command after the process has finished. */
5851 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005852 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005853# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005854# ifdef __TANDEM
5855 if (ret == -1 && errno == ENOTSUP)
5856 {
5857 FD_ZERO(&rfds);
5858 FD_ZERO(&efds);
5859 ret = 0;
5860 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005861# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005862# ifdef FEAT_MZSCHEME
5863 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005864 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005865 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866# endif
5867
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868# ifdef FEAT_XCLIPBOARD
5869 if (ret > 0 && xterm_Shell != (Widget)0
5870 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5871 {
5872 xterm_update(); /* Maybe we should hand out clipboard */
5873 /* continue looping when we only got the X event and the input
5874 * buffer is empty */
5875 if (--ret == 0 && !input_available())
5876 {
5877 /* Try again */
5878 finished = FALSE;
5879 }
5880 }
5881# endif
5882# ifdef FEAT_MOUSE_GPM
5883 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5884 {
5885 if (FD_ISSET(gpm_fd, &efds))
5886 gpm_close();
5887 else if (FD_ISSET(gpm_fd, &rfds))
5888 *check_for_gpm = 1;
5889 }
5890# endif
5891# ifdef USE_XSMP
5892 if (ret > 0 && xsmp_icefd != -1)
5893 {
5894 if (FD_ISSET(xsmp_icefd, &efds))
5895 {
5896 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005897 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 xsmp_close();
5899 if (--ret == 0)
5900 finished = FALSE; /* keep going if event was only one */
5901 }
5902 else if (FD_ISSET(xsmp_icefd, &rfds))
5903 {
5904 busy = TRUE;
5905 xsmp_handle_requests();
5906 busy = FALSE;
5907 if (--ret == 0)
5908 finished = FALSE; /* keep going if event was only one */
5909 }
5910 }
5911# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005912#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005913 if (ret > 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005914 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005915#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916
5917#endif /* HAVE_SELECT */
5918
5919#ifdef MAY_LOOP
5920 if (finished || msec == 0)
5921 break;
5922
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005923# ifdef FEAT_CLIENTSERVER
5924 if (server_waiting())
5925 break;
5926# endif
5927
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 /* We're going to loop around again, find out for how long */
5929 if (msec > 0)
5930 {
5931# ifdef USE_START_TV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 /* Compute remaining wait time. */
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02005933 msec = start_msec - elapsed(&start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934# else
5935 /* Guess we got interrupted halfway. */
5936 msec = msec / 2;
5937# endif
5938 if (msec <= 0)
5939 break; /* waited long enough */
5940 }
5941#endif
5942 }
5943
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005944 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945}
5946
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005949 * Expand a path into all matching files and/or directories. Handles "*",
5950 * "?", "[a-z]", "**", etc.
5951 * "path" has backslashes before chars that are not to be expanded.
5952 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953 */
5954 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005955mch_expandpath(
5956 garray_T *gap,
5957 char_u *path,
5958 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959{
Bram Moolenaar02743632005-07-25 20:42:36 +00005960 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961}
5962#endif
5963
5964/*
5965 * mch_expand_wildcards() - this code does wild-card pattern matching using
5966 * the shell
5967 *
5968 * return OK for success, FAIL for error (you may lose some memory) and put
5969 * an error message in *file.
5970 *
5971 * num_pat is number of input patterns
5972 * pat is array of pointers to input patterns
5973 * num_file is pointer to number of matched file names
5974 * file is pointer to array of pointers to matched file names
5975 */
5976
5977#ifndef SEEK_SET
5978# define SEEK_SET 0
5979#endif
5980#ifndef SEEK_END
5981# define SEEK_END 2
5982#endif
5983
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005984#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005985
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005987mch_expand_wildcards(
5988 int num_pat,
5989 char_u **pat,
5990 int *num_file,
5991 char_u ***file,
5992 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993{
5994 int i;
5995 size_t len;
5996 char_u *p;
5997 int dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998
Bram Moolenaarc7247912008-01-13 12:54:11 +00005999 /*
6000 * This is the non-OS/2 implementation (really Unix).
6001 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002 int j;
6003 char_u *tempname;
6004 char_u *command;
6005 FILE *fd;
6006 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006007#define STYLE_ECHO 0 /* use "echo", the default */
6008#define STYLE_GLOB 1 /* use "glob", for csh */
6009#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6010#define STYLE_PRINT 3 /* use "print -N", for zsh */
6011#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6012 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013 int shell_style = STYLE_ECHO;
6014 int check_spaces;
6015 static int did_find_nul = FALSE;
6016 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006017 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006018 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019
6020 *num_file = 0; /* default: no files found */
6021 *file = NULL;
6022
6023 /*
6024 * If there are no wildcards, just copy the names to allocated memory.
6025 * Saves a lot of time, because we don't have to start a new shell.
6026 */
6027 if (!have_wildcard(num_pat, pat))
6028 return save_patterns(num_pat, pat, num_file, file);
6029
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006030# ifdef HAVE_SANDBOX
6031 /* Don't allow any shell command in the sandbox. */
6032 if (sandbox != 0 && check_secure())
6033 return FAIL;
6034# endif
6035
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036 /*
6037 * Don't allow the use of backticks in secure and restricted mode.
6038 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006039 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 for (i = 0; i < num_pat; ++i)
6041 if (vim_strchr(pat[i], '`') != NULL
6042 && (check_restricted() || check_secure()))
6043 return FAIL;
6044
6045 /*
6046 * get a name for the temp file
6047 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006048 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 {
6050 EMSG(_(e_notmp));
6051 return FAIL;
6052 }
6053
6054 /*
6055 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006056 * file.
6057 * STYLE_BT: NL separated
6058 * If expanding `cmd` execute it directly.
6059 * STYLE_GLOB: NUL separated
6060 * If we use *csh, "glob" will work better than "echo".
6061 * STYLE_PRINT: NL or NUL separated
6062 * If we use *zsh, "print -N" will work better than "glob".
6063 * STYLE_VIMGLOB: NL separated
6064 * If we use *sh*, we define "vimglob()".
6065 * STYLE_ECHO: space separated.
6066 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 */
6068 if (num_pat == 1 && *pat[0] == '`'
6069 && (len = STRLEN(pat[0])) > 2
6070 && *(pat[0] + len - 1) == '`')
6071 shell_style = STYLE_BT;
6072 else if ((len = STRLEN(p_sh)) >= 3)
6073 {
6074 if (STRCMP(p_sh + len - 3, "csh") == 0)
6075 shell_style = STYLE_GLOB;
6076 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6077 shell_style = STYLE_PRINT;
6078 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006079 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6080 "sh") != NULL)
6081 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082
Bram Moolenaarc7247912008-01-13 12:54:11 +00006083 /* Compute the length of the command. We need 2 extra bytes: for the
6084 * optional '&' and for the NUL.
6085 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006087 if (shell_style == STYLE_VIMGLOB)
6088 len += STRLEN(sh_vimglob_func);
6089
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006090 for (i = 0; i < num_pat; ++i)
6091 {
6092 /* Count the length of the patterns in the same way as they are put in
6093 * "command" below. */
6094#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006096#else
6097 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006098 for (j = 0; pat[i][j] != NUL; ++j)
6099 {
6100 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6101 ++len; /* may add a backslash */
6102 ++len;
6103 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006104#endif
6105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 command = alloc(len);
6107 if (command == NULL)
6108 {
6109 /* out of memory */
6110 vim_free(tempname);
6111 return FAIL;
6112 }
6113
6114 /*
6115 * Build the shell command:
6116 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6117 * recognizes this).
6118 * - Add the shell command to print the expanded names.
6119 * - Add the temp file name.
6120 * - Add the file name patterns.
6121 */
6122 if (shell_style == STYLE_BT)
6123 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006124 /* change `command; command& ` to (command; command ) */
6125 STRCPY(command, "(");
6126 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006128 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 while (p > command && vim_iswhite(*p))
6130 --p;
6131 if (*p == '&') /* remove trailing '&' */
6132 {
6133 ampersent = TRUE;
6134 *p = ' ';
6135 }
6136 STRCAT(command, ">");
6137 }
6138 else
6139 {
6140 if (flags & EW_NOTFOUND)
6141 STRCPY(command, "set nonomatch; ");
6142 else
6143 STRCPY(command, "unset nonomatch; ");
6144 if (shell_style == STYLE_GLOB)
6145 STRCAT(command, "glob >");
6146 else if (shell_style == STYLE_PRINT)
6147 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006148 else if (shell_style == STYLE_VIMGLOB)
6149 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 else
6151 STRCAT(command, "echo >");
6152 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006153
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006155
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 if (shell_style != STYLE_BT)
6157 for (i = 0; i < num_pat; ++i)
6158 {
6159 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006160 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006161 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162#ifdef USE_SYSTEM
6163 STRCAT(command, " \"");
6164 STRCAT(command, pat[i]);
6165 STRCAT(command, "\"");
6166#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006167 int intick = FALSE;
6168
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 p = command + STRLEN(command);
6170 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006171 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006172 {
6173 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006174 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006175 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6176 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006177 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006178 * backslash inside backticks, before a special character
6179 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006180 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006181 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6182 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006183 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006184 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006185 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006186 else if (!intick
6187 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6188 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006189 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006190 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6191 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006192 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006193
6194 /* Copy one character. */
6195 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 *p = NUL;
6198#endif
6199 }
6200 if (flags & EW_SILENT)
6201 show_shell_mess = FALSE;
6202 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006203 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204
6205 /*
6206 * Using zsh -G: If a pattern has no matches, it is just deleted from
6207 * the argument list, otherwise zsh gives an error message and doesn't
6208 * expand any other pattern.
6209 */
6210 if (shell_style == STYLE_PRINT)
6211 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6212
6213 /*
6214 * If we use -f then shell variables set in .cshrc won't get expanded.
6215 * vi can do it, so we will too, but it is only necessary if there is a "$"
6216 * in one of the patterns, otherwise we can still use the fast option.
6217 */
6218 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6219 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6220
6221 /*
6222 * execute the shell command
6223 */
6224 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6225
6226 /* When running in the background, give it some time to create the temp
6227 * file, but don't wait for it to finish. */
6228 if (ampersent)
6229 mch_delay(10L, TRUE);
6230
6231 extra_shell_arg = NULL; /* cleanup */
6232 show_shell_mess = TRUE;
6233 vim_free(command);
6234
Bram Moolenaarc7247912008-01-13 12:54:11 +00006235 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 {
6237 mch_remove(tempname);
6238 vim_free(tempname);
6239 /*
6240 * With interactive completion, the error message is not printed.
6241 * However with USE_SYSTEM, I don't know how to turn off error messages
6242 * from the shell, so screen may still get messed up -- webb.
6243 */
6244#ifndef USE_SYSTEM
6245 if (!(flags & EW_SILENT))
6246#endif
6247 {
6248 redraw_later_clear(); /* probably messed up screen */
6249 msg_putchar('\n'); /* clear bottom line quickly */
6250 cmdline_row = Rows - 1; /* continue on last line */
6251#ifdef USE_SYSTEM
6252 if (!(flags & EW_SILENT))
6253#endif
6254 {
6255 MSG(_(e_wildexpand));
6256 msg_start(); /* don't overwrite this message */
6257 }
6258 }
6259 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6260 * EW_NOTFOUND is given */
6261 if (shell_style == STYLE_BT)
6262 return FAIL;
6263 goto notfound;
6264 }
6265
6266 /*
6267 * read the names from the file into memory
6268 */
6269 fd = fopen((char *)tempname, READBIN);
6270 if (fd == NULL)
6271 {
6272 /* Something went wrong, perhaps a file name with a special char. */
6273 if (!(flags & EW_SILENT))
6274 {
6275 MSG(_(e_wildexpand));
6276 msg_start(); /* don't overwrite this message */
6277 }
6278 vim_free(tempname);
6279 goto notfound;
6280 }
6281 fseek(fd, 0L, SEEK_END);
6282 len = ftell(fd); /* get size of temp file */
6283 fseek(fd, 0L, SEEK_SET);
6284 buffer = alloc(len + 1);
6285 if (buffer == NULL)
6286 {
6287 /* out of memory */
6288 mch_remove(tempname);
6289 vim_free(tempname);
6290 fclose(fd);
6291 return FAIL;
6292 }
6293 i = fread((char *)buffer, 1, len, fd);
6294 fclose(fd);
6295 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006296 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 {
6298 /* unexpected read error */
6299 EMSG2(_(e_notread), tempname);
6300 vim_free(tempname);
6301 vim_free(buffer);
6302 return FAIL;
6303 }
6304 vim_free(tempname);
6305
Bram Moolenaarc7247912008-01-13 12:54:11 +00006306# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6308 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006309 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6311 *p++ = buffer[i];
6312 len = p - buffer;
6313# endif
6314
6315
6316 /* file names are separated with Space */
6317 if (shell_style == STYLE_ECHO)
6318 {
6319 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6320 p = buffer;
6321 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6322 {
6323 while (*p != ' ' && *p != '\n')
6324 ++p;
6325 p = skipwhite(p); /* skip to next entry */
6326 }
6327 }
6328 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006329 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 {
6331 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6332 p = buffer;
6333 for (i = 0; *p != NUL; ++i) /* count number of entries */
6334 {
6335 while (*p != '\n' && *p != NUL)
6336 ++p;
6337 if (*p != NUL)
6338 ++p;
6339 p = skipwhite(p); /* skip leading white space */
6340 }
6341 }
6342 /* file names are separated with NUL */
6343 else
6344 {
6345 /*
6346 * Some versions of zsh use spaces instead of NULs to separate
6347 * results. Only do this when there is no NUL before the end of the
6348 * buffer, otherwise we would never be able to use file names with
6349 * embedded spaces when zsh does use NULs.
6350 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6351 * don't check for spaces again.
6352 */
6353 check_spaces = FALSE;
6354 if (shell_style == STYLE_PRINT && !did_find_nul)
6355 {
6356 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006357 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006358 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 did_find_nul = TRUE;
6360 else
6361 check_spaces = TRUE;
6362 }
6363
6364 /*
6365 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6366 * already is one, for STYLE_GLOB it needs to be added.
6367 */
6368 if (len && buffer[len - 1] == NUL)
6369 --len;
6370 else
6371 buffer[len] = NUL;
6372 i = 0;
6373 for (p = buffer; p < buffer + len; ++p)
6374 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6375 {
6376 ++i;
6377 *p = NUL;
6378 }
6379 if (len)
6380 ++i; /* count last entry */
6381 }
6382 if (i == 0)
6383 {
6384 /*
6385 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6386 * /bin/sh will happily expand it to nothing rather than returning an
6387 * error; and hey, it's good to check anyway -- webb.
6388 */
6389 vim_free(buffer);
6390 goto notfound;
6391 }
6392 *num_file = i;
6393 *file = (char_u **)alloc(sizeof(char_u *) * i);
6394 if (*file == NULL)
6395 {
6396 /* out of memory */
6397 vim_free(buffer);
6398 return FAIL;
6399 }
6400
6401 /*
6402 * Isolate the individual file names.
6403 */
6404 p = buffer;
6405 for (i = 0; i < *num_file; ++i)
6406 {
6407 (*file)[i] = p;
6408 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006409 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6410 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006412 while (!(shell_style == STYLE_ECHO && *p == ' ')
6413 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414 ++p;
6415 if (p == buffer + len) /* last entry */
6416 *p = NUL;
6417 else
6418 {
6419 *p++ = NUL;
6420 p = skipwhite(p); /* skip to next entry */
6421 }
6422 }
6423 else /* NUL separates */
6424 {
6425 while (*p && p < buffer + len) /* skip entry */
6426 ++p;
6427 ++p; /* skip NUL */
6428 }
6429 }
6430
6431 /*
6432 * Move the file names to allocated memory.
6433 */
6434 for (j = 0, i = 0; i < *num_file; ++i)
6435 {
6436 /* Require the files to exist. Helps when using /bin/sh */
6437 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6438 continue;
6439
6440 /* check if this entry should be included */
6441 dir = (mch_isdir((*file)[i]));
6442 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6443 continue;
6444
Bram Moolenaara2031822006-03-07 22:29:51 +00006445 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006446 if (!dir && (flags & EW_EXEC)
6447 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006448 continue;
6449
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6451 if (p)
6452 {
6453 STRCPY(p, (*file)[i]);
6454 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006455 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 (*file)[j++] = p;
6457 }
6458 }
6459 vim_free(buffer);
6460 *num_file = j;
6461
6462 if (*num_file == 0) /* rejected all entries */
6463 {
6464 vim_free(*file);
6465 *file = NULL;
6466 goto notfound;
6467 }
6468
6469 return OK;
6470
6471notfound:
6472 if (flags & EW_NOTFOUND)
6473 return save_patterns(num_pat, pat, num_file, file);
6474 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475}
6476
6477#endif /* VMS */
6478
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006480save_patterns(
6481 int num_pat,
6482 char_u **pat,
6483 int *num_file,
6484 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485{
6486 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006487 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488
6489 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6490 if (*file == NULL)
6491 return FAIL;
6492 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006493 {
6494 s = vim_strsave(pat[i]);
6495 if (s != NULL)
6496 /* Be compatible with expand_filename(): halve the number of
6497 * backslashes. */
6498 backslash_halve(s);
6499 (*file)[i] = s;
6500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 *num_file = num_pat;
6502 return OK;
6503}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505/*
6506 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6507 * expand.
6508 */
6509 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006510mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006512 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 if (*p == '\\' && p[1] != NUL)
6515 ++p;
6516 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 if (vim_strchr((char_u *)
6518#ifdef VMS
6519 "*?%"
6520#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522#endif
6523 , *p) != NULL)
6524 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 }
6526 return FALSE;
6527}
6528
6529/*
6530 * Return TRUE if the string "p" contains a wildcard.
6531 * Don't recognize '~' at the end as a wildcard.
6532 */
6533 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006534mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006536 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 if (*p == '\\' && p[1] != NUL)
6539 ++p;
6540 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 if (vim_strchr((char_u *)
6542#ifdef VMS
6543 "*?%$"
6544#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546#endif
6547 , *p) != NULL
6548 || (*p == '~' && p[1] != NUL))
6549 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 }
6551 return FALSE;
6552}
6553
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006555have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556{
6557 int i;
6558
6559 for (i = 0; i < num; i++)
6560 if (mch_has_wildcard(file[i]))
6561 return 1;
6562 return 0;
6563}
6564
6565 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006566have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567{
6568 int i;
6569
6570 for (i = 0; i < num; i++)
6571 if (vim_strchr(file[i], '$') != NULL)
6572 return TRUE;
6573 return FALSE;
6574}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006576#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577/*
6578 * Scaled-down version of rename(), which is missing in Xenix.
6579 * This version can only move regular files and will fail if the
6580 * destination exists.
6581 */
6582 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006583mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584{
6585 struct stat st;
6586
6587 if (stat(dest, &st) >= 0) /* fail if destination exists */
6588 return -1;
6589 if (link(src, dest) != 0) /* link file to new name */
6590 return -1;
6591 if (mch_remove(src) == 0) /* delete link to old name */
6592 return 0;
6593 return -1;
6594}
6595#endif /* !HAVE_RENAME */
6596
6597#ifdef FEAT_MOUSE_GPM
6598/*
6599 * Initializes connection with gpm (if it isn't already opened)
6600 * Return 1 if succeeded (or connection already opened), 0 if failed
6601 */
6602 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006603gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604{
6605 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6606
6607 if (!gpm_flag)
6608 {
6609 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6610 gpm_connect.defaultMask = ~GPM_HARD;
6611 /* Default handling for mouse move*/
6612 gpm_connect.minMod = 0; /* Handle any modifier keys */
6613 gpm_connect.maxMod = 0xffff;
6614 if (Gpm_Open(&gpm_connect, 0) > 0)
6615 {
6616 /* gpm library tries to handling TSTP causes
6617 * problems. Anyways, we close connection to Gpm whenever
6618 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006619 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006621# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006623# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 return 1; /* succeed */
6625 }
6626 if (gpm_fd == -2)
6627 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6628 return 0;
6629 }
6630 return 1; /* already open */
6631}
6632
6633/*
6634 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006635 */
6636 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006637gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638{
6639 if (gpm_flag && gpm_fd >= 0) /* if Open */
6640 Gpm_Close();
6641}
6642
6643/* Reads gpm event and adds special keys to input buf. Returns length of
6644 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006645 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 */
6647 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006648mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649{
6650 int button;
6651 static Gpm_Event gpm_event;
6652 char_u string[6];
6653 int_u vim_modifiers;
6654 int row,col;
6655 unsigned char buttons_mask;
6656 unsigned char gpm_modifiers;
6657 static unsigned char old_buttons = 0;
6658
6659 Gpm_GetEvent(&gpm_event);
6660
6661#ifdef FEAT_GUI
6662 /* Don't put events in the input queue now. */
6663 if (hold_gui_events)
6664 return 0;
6665#endif
6666
6667 row = gpm_event.y - 1;
6668 col = gpm_event.x - 1;
6669
6670 string[0] = ESC; /* Our termcode */
6671 string[1] = 'M';
6672 string[2] = 'G';
6673 switch (GPM_BARE_EVENTS(gpm_event.type))
6674 {
6675 case GPM_DRAG:
6676 string[3] = MOUSE_DRAG;
6677 break;
6678 case GPM_DOWN:
6679 buttons_mask = gpm_event.buttons & ~old_buttons;
6680 old_buttons = gpm_event.buttons;
6681 switch (buttons_mask)
6682 {
6683 case GPM_B_LEFT:
6684 button = MOUSE_LEFT;
6685 break;
6686 case GPM_B_MIDDLE:
6687 button = MOUSE_MIDDLE;
6688 break;
6689 case GPM_B_RIGHT:
6690 button = MOUSE_RIGHT;
6691 break;
6692 default:
6693 return 0;
6694 /*Don't know what to do. Can more than one button be
6695 * reported in one event? */
6696 }
6697 string[3] = (char_u)(button | 0x20);
6698 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6699 break;
6700 case GPM_UP:
6701 string[3] = MOUSE_RELEASE;
6702 old_buttons &= ~gpm_event.buttons;
6703 break;
6704 default:
6705 return 0;
6706 }
6707 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6708 gpm_modifiers = gpm_event.modifiers;
6709 vim_modifiers = 0x0;
6710 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6711 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6712 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6713 */
6714 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6715 vim_modifiers |= MOUSE_SHIFT;
6716
6717 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6718 vim_modifiers |= MOUSE_CTRL;
6719 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6720 vim_modifiers |= MOUSE_ALT;
6721 string[3] |= vim_modifiers;
6722 string[4] = (char_u)(col + ' ' + 1);
6723 string[5] = (char_u)(row + ' ' + 1);
6724 add_to_input_buf(string, 6);
6725 return 6;
6726}
6727#endif /* FEAT_MOUSE_GPM */
6728
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006729#ifdef FEAT_SYSMOUSE
6730/*
6731 * Initialize connection with sysmouse.
6732 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6733 * output, any sysmouse output than will be processed via sig_sysmouse().
6734 * Return OK if succeeded, FAIL if failed.
6735 */
6736 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006737sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006738{
6739 struct mouse_info mouse;
6740
6741 mouse.operation = MOUSE_MODE;
6742 mouse.u.mode.mode = 0;
6743 mouse.u.mode.signal = SIGUSR2;
6744 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6745 {
6746 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6747 mouse.operation = MOUSE_SHOW;
6748 ioctl(1, CONS_MOUSECTL, &mouse);
6749 return OK;
6750 }
6751 return FAIL;
6752}
6753
6754/*
6755 * Stop processing SIGUSR2 signals, and also make sure that
6756 * virtual console do not send us any sysmouse related signal.
6757 */
6758 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006759sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006760{
6761 struct mouse_info mouse;
6762
6763 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6764 mouse.operation = MOUSE_MODE;
6765 mouse.u.mode.mode = 0;
6766 mouse.u.mode.signal = 0;
6767 ioctl(1, CONS_MOUSECTL, &mouse);
6768}
6769
6770/*
6771 * Gets info from sysmouse and adds special keys to input buf.
6772 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006773 static RETSIGTYPE
6774sig_sysmouse SIGDEFARG(sigarg)
6775{
6776 struct mouse_info mouse;
6777 struct video_info video;
6778 char_u string[6];
6779 int row, col;
6780 int button;
6781 int buttons;
6782 static int oldbuttons = 0;
6783
6784#ifdef FEAT_GUI
6785 /* Don't put events in the input queue now. */
6786 if (hold_gui_events)
6787 return;
6788#endif
6789
6790 mouse.operation = MOUSE_GETINFO;
6791 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6792 && ioctl(1, FBIO_MODEINFO, &video) != -1
6793 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6794 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6795 {
6796 row = mouse.u.data.y / video.vi_cheight;
6797 col = mouse.u.data.x / video.vi_cwidth;
6798 buttons = mouse.u.data.buttons;
6799 string[0] = ESC; /* Our termcode */
6800 string[1] = 'M';
6801 string[2] = 'S';
6802 if (oldbuttons == buttons && buttons != 0)
6803 {
6804 button = MOUSE_DRAG;
6805 }
6806 else
6807 {
6808 switch (buttons)
6809 {
6810 case 0:
6811 button = MOUSE_RELEASE;
6812 break;
6813 case 1:
6814 button = MOUSE_LEFT;
6815 break;
6816 case 2:
6817 button = MOUSE_MIDDLE;
6818 break;
6819 case 4:
6820 button = MOUSE_RIGHT;
6821 break;
6822 default:
6823 return;
6824 }
6825 oldbuttons = buttons;
6826 }
6827 string[3] = (char_u)(button);
6828 string[4] = (char_u)(col + ' ' + 1);
6829 string[5] = (char_u)(row + ' ' + 1);
6830 add_to_input_buf(string, 6);
6831 }
6832 return;
6833}
6834#endif /* FEAT_SYSMOUSE */
6835
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006837typedef char_u * (*STRPROCSTR)(char_u *);
6838typedef char_u * (*INTPROCSTR)(int);
6839typedef int (*STRPROCINT)(char_u *);
6840typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841
6842/*
6843 * Call a DLL routine which takes either a string or int param
6844 * and returns an allocated string.
6845 */
6846 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006847mch_libcall(
6848 char_u *libname,
6849 char_u *funcname,
6850 char_u *argstring, /* NULL when using a argint */
6851 int argint,
6852 char_u **string_result,/* NULL when using number_result */
6853 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854{
6855# if defined(USE_DLOPEN)
6856 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006857 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858# else
6859 shl_t hinstLib;
6860# endif
6861 STRPROCSTR ProcAdd;
6862 INTPROCSTR ProcAddI;
6863 char_u *retval_str = NULL;
6864 int retval_int = 0;
6865 int success = FALSE;
6866
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006867 /*
6868 * Get a handle to the DLL module.
6869 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006871 /* First clear any error, it's not cleared by the dlopen() call. */
6872 (void)dlerror();
6873
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 hinstLib = dlopen((char *)libname, RTLD_LAZY
6875# ifdef RTLD_LOCAL
6876 | RTLD_LOCAL
6877# endif
6878 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006879 if (hinstLib == NULL)
6880 {
6881 /* "dlerr" must be used before dlclose() */
6882 dlerr = (char *)dlerror();
6883 if (dlerr != NULL)
6884 EMSG2(_("dlerror = \"%s\""), dlerr);
6885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886# else
6887 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6888# endif
6889
6890 /* If the handle is valid, try to get the function address. */
6891 if (hinstLib != NULL)
6892 {
6893# ifdef HAVE_SETJMP_H
6894 /*
6895 * Catch a crash when calling the library function. For example when
6896 * using a number where a string pointer is expected.
6897 */
6898 mch_startjmp();
6899 if (SETJMP(lc_jump_env) != 0)
6900 {
6901 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006902# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006903 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006904# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 mch_didjmp();
6906 }
6907 else
6908# endif
6909 {
6910 retval_str = NULL;
6911 retval_int = 0;
6912
6913 if (argstring != NULL)
6914 {
6915# if defined(USE_DLOPEN)
6916 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006917 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918# else
6919 if (shl_findsym(&hinstLib, (const char *)funcname,
6920 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6921 ProcAdd = NULL;
6922# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006923 if ((success = (ProcAdd != NULL
6924# if defined(USE_DLOPEN)
6925 && dlerr == NULL
6926# endif
6927 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 {
6929 if (string_result == NULL)
6930 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6931 else
6932 retval_str = (ProcAdd)(argstring);
6933 }
6934 }
6935 else
6936 {
6937# if defined(USE_DLOPEN)
6938 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006939 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940# else
6941 if (shl_findsym(&hinstLib, (const char *)funcname,
6942 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6943 ProcAddI = NULL;
6944# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006945 if ((success = (ProcAddI != NULL
6946# if defined(USE_DLOPEN)
6947 && dlerr == NULL
6948# endif
6949 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 {
6951 if (string_result == NULL)
6952 retval_int = ((INTPROCINT)ProcAddI)(argint);
6953 else
6954 retval_str = (ProcAddI)(argint);
6955 }
6956 }
6957
6958 /* Save the string before we free the library. */
6959 /* Assume that a "1" or "-1" result is an illegal pointer. */
6960 if (string_result == NULL)
6961 *number_result = retval_int;
6962 else if (retval_str != NULL
6963 && retval_str != (char_u *)1
6964 && retval_str != (char_u *)-1)
6965 *string_result = vim_strsave(retval_str);
6966 }
6967
6968# ifdef HAVE_SETJMP_H
6969 mch_endjmp();
6970# ifdef SIGHASARG
6971 if (lc_signal != 0)
6972 {
6973 int i;
6974
6975 /* try to find the name of this signal */
6976 for (i = 0; signal_info[i].sig != -1; i++)
6977 if (lc_signal == signal_info[i].sig)
6978 break;
6979 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6980 }
6981# endif
6982# endif
6983
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006985 /* "dlerr" must be used before dlclose() */
6986 if (dlerr != NULL)
6987 EMSG2(_("dlerror = \"%s\""), dlerr);
6988
6989 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 (void)dlclose(hinstLib);
6991# else
6992 (void)shl_unload(hinstLib);
6993# endif
6994 }
6995
6996 if (!success)
6997 {
6998 EMSG2(_(e_libcall), funcname);
6999 return FAIL;
7000 }
7001
7002 return OK;
7003}
7004#endif
7005
7006#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7007static int xterm_trace = -1; /* default: disabled */
7008static int xterm_button;
7009
7010/*
7011 * Setup a dummy window for X selections in a terminal.
7012 */
7013 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007014setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015{
7016 int z = 0;
7017 char *strp = "";
7018 Widget AppShell;
7019
7020 if (!x_connect_to_server())
7021 return;
7022
7023 open_app_context();
7024 if (app_context != NULL && xterm_Shell == (Widget)0)
7025 {
7026 int (*oldhandler)();
7027#if defined(HAVE_SETJMP_H)
7028 int (*oldIOhandler)();
7029#endif
7030# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7031 struct timeval start_tv;
7032
7033 if (p_verbose > 0)
7034 gettimeofday(&start_tv, NULL);
7035# endif
7036
7037 /* Ignore X errors while opening the display */
7038 oldhandler = XSetErrorHandler(x_error_check);
7039
7040#if defined(HAVE_SETJMP_H)
7041 /* Ignore X IO errors while opening the display */
7042 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7043 mch_startjmp();
7044 if (SETJMP(lc_jump_env) != 0)
7045 {
7046 mch_didjmp();
7047 xterm_dpy = NULL;
7048 }
7049 else
7050#endif
7051 {
7052 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7053 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7054#if defined(HAVE_SETJMP_H)
7055 mch_endjmp();
7056#endif
7057 }
7058
7059#if defined(HAVE_SETJMP_H)
7060 /* Now handle X IO errors normally. */
7061 (void)XSetIOErrorHandler(oldIOhandler);
7062#endif
7063 /* Now handle X errors normally. */
7064 (void)XSetErrorHandler(oldhandler);
7065
7066 if (xterm_dpy == NULL)
7067 {
7068 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007069 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 return;
7071 }
7072
7073 /* Catch terminating error of the X server connection. */
7074 (void)XSetIOErrorHandler(x_IOerror_handler);
7075
7076# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7077 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007078 {
7079 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007081 verbose_leave();
7082 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083# endif
7084
7085 /* Create a Shell to make converters work. */
7086 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7087 applicationShellWidgetClass, xterm_dpy,
7088 NULL);
7089 if (AppShell == (Widget)0)
7090 return;
7091 xterm_Shell = XtVaCreatePopupShell("VIM",
7092 topLevelShellWidgetClass, AppShell,
7093 XtNmappedWhenManaged, 0,
7094 XtNwidth, 1,
7095 XtNheight, 1,
7096 NULL);
7097 if (xterm_Shell == (Widget)0)
7098 return;
7099
7100 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007101 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102 if (x11_display == NULL)
7103 x11_display = xterm_dpy;
7104
7105 XtRealizeWidget(xterm_Shell);
7106 XSync(xterm_dpy, False);
7107 xterm_update();
7108 }
7109 if (xterm_Shell != (Widget)0)
7110 {
7111 clip_init(TRUE);
7112 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7113 x11_window = (Window)atol(strp);
7114 /* Check if $WINDOWID is valid. */
7115 if (test_x11_window(xterm_dpy) == FAIL)
7116 x11_window = 0;
7117 if (x11_window != 0)
7118 xterm_trace = 0;
7119 }
7120}
7121
7122 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007123start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124{
7125 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7126 return;
7127 xterm_trace = 1;
7128 xterm_button = button;
7129 do_xterm_trace();
7130}
7131
7132
7133 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007134stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135{
7136 if (xterm_trace < 0)
7137 return;
7138 xterm_trace = 0;
7139}
7140
7141/*
7142 * Query the xterm pointer and generate mouse termcodes if necessary
7143 * return TRUE if dragging is active, else FALSE
7144 */
7145 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007146do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147{
7148 Window root, child;
7149 int root_x, root_y;
7150 int win_x, win_y;
7151 int row, col;
7152 int_u mask_return;
7153 char_u buf[50];
7154 char_u *strp;
7155 long got_hints;
7156 static char_u *mouse_code;
7157 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7158 static int prev_row = 0, prev_col = 0;
7159 static XSizeHints xterm_hints;
7160
7161 if (xterm_trace <= 0)
7162 return FALSE;
7163
7164 if (xterm_trace == 1)
7165 {
7166 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007167 * have changed recently. */
7168 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7169 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 || xterm_hints.width_inc <= 1
7171 || xterm_hints.height_inc <= 1)
7172 {
7173 xterm_trace = -1; /* Not enough data -- disable tracing */
7174 return FALSE;
7175 }
7176
7177 /* Rely on the same mouse code for the duration of this */
7178 mouse_code = find_termcode(mouse_name);
7179 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007180 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 xterm_trace = 2;
7182
7183 /* Find the offset of the chars, there might be a scrollbar on the
7184 * left of the window and/or a menu on the top (eterm etc.) */
7185 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7186 &win_x, &win_y, &mask_return);
7187 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7188 - (xterm_hints.height_inc / 2);
7189 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7190 xterm_hints.y = 2;
7191 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7192 - (xterm_hints.width_inc / 2);
7193 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7194 xterm_hints.x = 2;
7195 return TRUE;
7196 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007197 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007198 {
7199 xterm_trace = 0;
7200 return FALSE;
7201 }
7202
7203 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7204 &win_x, &win_y, &mask_return);
7205
7206 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7207 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7208 if (row == prev_row && col == prev_col)
7209 return TRUE;
7210
7211 STRCPY(buf, mouse_code);
7212 strp = buf + STRLEN(buf);
7213 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7214 *strp++ = (char_u)(col + ' ' + 1);
7215 *strp++ = (char_u)(row + ' ' + 1);
7216 *strp = 0;
7217 add_to_input_buf(buf, STRLEN(buf));
7218
7219 prev_row = row;
7220 prev_col = col;
7221 return TRUE;
7222}
7223
7224# if defined(FEAT_GUI) || defined(PROTO)
7225/*
7226 * Destroy the display, window and app_context. Required for GTK.
7227 */
7228 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007229clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230{
7231 if (xterm_Shell != (Widget)0)
7232 {
7233 XtDestroyWidget(xterm_Shell);
7234 xterm_Shell = (Widget)0;
7235 }
7236 if (xterm_dpy != NULL)
7237 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007238# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 /* Lesstif and Solaris crash here, lose some memory */
7240 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007241# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 if (x11_display == xterm_dpy)
7243 x11_display = NULL;
7244 xterm_dpy = NULL;
7245 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007246# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 if (app_context != (XtAppContext)NULL)
7248 {
7249 /* Lesstif and Solaris crash here, lose some memory */
7250 XtDestroyApplicationContext(app_context);
7251 app_context = (XtAppContext)NULL;
7252 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007253# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254}
7255# endif
7256
7257/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007258 * Catch up with GUI or X events.
7259 */
7260 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007261clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007262{
7263# ifdef FEAT_GUI
7264 if (gui.in_use)
7265 gui_mch_update();
7266 else
7267# endif
7268 if (xterm_Shell != (Widget)0)
7269 xterm_update();
7270}
7271
7272/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 * Catch up with any queued X events. This may put keyboard input into the
7274 * input buffer, call resize call-backs, trigger timers etc. If there is
7275 * nothing in the X event queue (& no timers pending), then we return
7276 * immediately.
7277 */
7278 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007279xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280{
7281 XEvent event;
7282
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007283 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007285 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007287 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007288 break;
7289
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007290 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007291 {
7292 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007293 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007294#ifdef FEAT_CLIENTSERVER
7295 {
7296 XPropertyEvent *e = (XPropertyEvent *)&event;
7297
7298 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007300 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007301 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007303 XtDispatchEvent(&event);
7304 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007305 else
7306 {
7307 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007308 XtAppProcessEvent(app_context, mask);
7309 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 }
7311}
7312
7313 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007314clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315{
7316 if (xterm_Shell != (Widget)0)
7317 return clip_x11_own_selection(xterm_Shell, cbd);
7318 return FAIL;
7319}
7320
7321 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007322clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323{
7324 if (xterm_Shell != (Widget)0)
7325 clip_x11_lose_selection(xterm_Shell, cbd);
7326}
7327
7328 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007329clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330{
7331 if (xterm_Shell != (Widget)0)
7332 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7333}
7334
7335 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007336clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337{
7338 clip_x11_set_selection(cbd);
7339}
7340#endif
7341
7342
7343#if defined(USE_XSMP) || defined(PROTO)
7344/*
7345 * Code for X Session Management Protocol.
7346 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007347static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7348static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7349static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7350static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7351static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352
7353
7354# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007355static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356
7357/*
7358 * This is our chance to ask the user if they want to save,
7359 * or abort the logout
7360 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007362xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363{
7364 cmdmod_T save_cmdmod;
7365 int cancel_shutdown = False;
7366
7367 save_cmdmod = cmdmod;
7368 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007369 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370 /* Mustn't logout */
7371 cancel_shutdown = True;
7372 cmdmod = save_cmdmod;
7373 setcursor(); /* position cursor */
7374 out_flush();
7375
7376 /* Done interaction */
7377 SmcInteractDone(smc_conn, cancel_shutdown);
7378
7379 /* Finish off
7380 * Only end save-yourself here if we're not cancelling shutdown;
7381 * we'll get a cancelled callback later in which we'll end it.
7382 * Hopefully get around glitchy SMs (like GNOME-1)
7383 */
7384 if (!cancel_shutdown)
7385 {
7386 xsmp.save_yourself = False;
7387 SmcSaveYourselfDone(smc_conn, True);
7388 }
7389}
7390# endif
7391
7392/*
7393 * Callback that starts save-yourself.
7394 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007396xsmp_handle_save_yourself(
7397 SmcConn smc_conn,
7398 SmPointer client_data UNUSED,
7399 int save_type UNUSED,
7400 Bool shutdown,
7401 int interact_style UNUSED,
7402 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403{
7404 /* Handle already being in saveyourself */
7405 if (xsmp.save_yourself)
7406 SmcSaveYourselfDone(smc_conn, True);
7407 xsmp.save_yourself = True;
7408 xsmp.shutdown = shutdown;
7409
7410 /* First up, preserve all files */
7411 out_flush();
7412 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7413
7414 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007415 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416
7417# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7418 /* Now see if we can ask about unsaved files */
7419 if (shutdown && !fast && gui.in_use)
7420 /* Need to interact with user, but need SM's permission */
7421 SmcInteractRequest(smc_conn, SmDialogError,
7422 xsmp_handle_interaction, client_data);
7423 else
7424# endif
7425 {
7426 /* Can stop the cycle here */
7427 SmcSaveYourselfDone(smc_conn, True);
7428 xsmp.save_yourself = False;
7429 }
7430}
7431
7432
7433/*
7434 * Callback to warn us of imminent death.
7435 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007437xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438{
7439 xsmp_close();
7440
7441 /* quit quickly leaving swapfiles for modified buffers behind */
7442 getout_preserve_modified(0);
7443}
7444
7445
7446/*
7447 * Callback to tell us that save-yourself has completed.
7448 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007450xsmp_save_complete(
7451 SmcConn smc_conn UNUSED,
7452 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453{
7454 xsmp.save_yourself = False;
7455}
7456
7457
7458/*
7459 * Callback to tell us that an instigated shutdown was cancelled
7460 * (maybe even by us)
7461 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007463xsmp_shutdown_cancelled(
7464 SmcConn smc_conn,
7465 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466{
7467 if (xsmp.save_yourself)
7468 SmcSaveYourselfDone(smc_conn, True);
7469 xsmp.save_yourself = False;
7470 xsmp.shutdown = False;
7471}
7472
7473
7474/*
7475 * Callback to tell us that a new ICE connection has been established.
7476 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007478xsmp_ice_connection(
7479 IceConn iceConn,
7480 IcePointer clientData UNUSED,
7481 Bool opening,
7482 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483{
7484 /* Intercept creation of ICE connection fd */
7485 if (opening)
7486 {
7487 xsmp_icefd = IceConnectionNumber(iceConn);
7488 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7489 }
7490}
7491
7492
7493/* Handle any ICE processing that's required; return FAIL if SM lost */
7494 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007495xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496{
7497 Bool rep;
7498
7499 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7500 == IceProcessMessagesIOError)
7501 {
7502 /* Lost ICE */
7503 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007504 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505 xsmp_close();
7506 return FAIL;
7507 }
7508 else
7509 return OK;
7510}
7511
7512static int dummy;
7513
7514/* Set up X Session Management Protocol */
7515 void
7516xsmp_init(void)
7517{
7518 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 SmcCallbacks smcallbacks;
7520#if 0
7521 SmPropValue smname;
7522 SmProp smnameprop;
7523 SmProp *smprops[1];
7524#endif
7525
7526 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007527 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528
7529 xsmp.save_yourself = xsmp.shutdown = False;
7530
7531 /* Set up SM callbacks - must have all, even if they're not used */
7532 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7533 smcallbacks.save_yourself.client_data = NULL;
7534 smcallbacks.die.callback = xsmp_die;
7535 smcallbacks.die.client_data = NULL;
7536 smcallbacks.save_complete.callback = xsmp_save_complete;
7537 smcallbacks.save_complete.client_data = NULL;
7538 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7539 smcallbacks.shutdown_cancelled.client_data = NULL;
7540
7541 /* Set up a watch on ICE connection creations. The "dummy" argument is
7542 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7543 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7544 {
7545 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007546 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 return;
7548 }
7549
7550 /* Create an SM connection */
7551 xsmp.smcconn = SmcOpenConnection(
7552 NULL,
7553 NULL,
7554 SmProtoMajor,
7555 SmProtoMinor,
7556 SmcSaveYourselfProcMask | SmcDieProcMask
7557 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7558 &smcallbacks,
7559 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007560 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 sizeof(errorstring),
7562 errorstring);
7563 if (xsmp.smcconn == NULL)
7564 {
7565 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007566
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007568 {
7569 vim_snprintf(errorreport, sizeof(errorreport),
7570 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7571 verb_msg((char_u *)errorreport);
7572 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 return;
7574 }
7575 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7576
7577#if 0
7578 /* ID ourselves */
7579 smname.value = "vim";
7580 smname.length = 3;
7581 smnameprop.name = "SmProgram";
7582 smnameprop.type = "SmARRAY8";
7583 smnameprop.num_vals = 1;
7584 smnameprop.vals = &smname;
7585
7586 smprops[0] = &smnameprop;
7587 SmcSetProperties(xsmp.smcconn, 1, smprops);
7588#endif
7589}
7590
7591
7592/* Shut down XSMP comms. */
7593 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007594xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595{
7596 if (xsmp_icefd != -1)
7597 {
7598 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007599 if (xsmp.clientid != NULL)
7600 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007601 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 xsmp_icefd = -1;
7603 }
7604}
7605#endif /* USE_XSMP */
7606
7607
7608#ifdef EBCDIC
7609/* Translate character to its CTRL- value */
7610char CtrlTable[] =
7611{
7612/* 00 - 5E */
7613 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7614 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7615 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7616 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7617 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7618 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7619/* ^ */ 0x1E,
7620/* - */ 0x1F,
7621/* 61 - 6C */
7622 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7623/* _ */ 0x1F,
7624/* 6E - 80 */
7625 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7626/* a */ 0x01,
7627/* b */ 0x02,
7628/* c */ 0x03,
7629/* d */ 0x37,
7630/* e */ 0x2D,
7631/* f */ 0x2E,
7632/* g */ 0x2F,
7633/* h */ 0x16,
7634/* i */ 0x05,
7635/* 8A - 90 */
7636 0, 0, 0, 0, 0, 0, 0,
7637/* j */ 0x15,
7638/* k */ 0x0B,
7639/* l */ 0x0C,
7640/* m */ 0x0D,
7641/* n */ 0x0E,
7642/* o */ 0x0F,
7643/* p */ 0x10,
7644/* q */ 0x11,
7645/* r */ 0x12,
7646/* 9A - A1 */
7647 0, 0, 0, 0, 0, 0, 0, 0,
7648/* s */ 0x13,
7649/* t */ 0x3C,
7650/* u */ 0x3D,
7651/* v */ 0x32,
7652/* w */ 0x26,
7653/* x */ 0x18,
7654/* y */ 0x19,
7655/* z */ 0x3F,
7656/* AA - AC */
7657 0, 0, 0,
7658/* [ */ 0x27,
7659/* AE - BC */
7660 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7661/* ] */ 0x1D,
7662/* BE - C0 */ 0, 0, 0,
7663/* A */ 0x01,
7664/* B */ 0x02,
7665/* C */ 0x03,
7666/* D */ 0x37,
7667/* E */ 0x2D,
7668/* F */ 0x2E,
7669/* G */ 0x2F,
7670/* H */ 0x16,
7671/* I */ 0x05,
7672/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7673/* J */ 0x15,
7674/* K */ 0x0B,
7675/* L */ 0x0C,
7676/* M */ 0x0D,
7677/* N */ 0x0E,
7678/* O */ 0x0F,
7679/* P */ 0x10,
7680/* Q */ 0x11,
7681/* R */ 0x12,
7682/* DA - DF */ 0, 0, 0, 0, 0, 0,
7683/* \ */ 0x1C,
7684/* E1 */ 0,
7685/* S */ 0x13,
7686/* T */ 0x3C,
7687/* U */ 0x3D,
7688/* V */ 0x32,
7689/* W */ 0x26,
7690/* X */ 0x18,
7691/* Y */ 0x19,
7692/* Z */ 0x3F,
7693/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7694 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7695};
7696
7697char MetaCharTable[]=
7698{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7699 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7700 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7701 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7702 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7703};
7704
7705
7706/* TODO: Use characters NOT numbers!!! */
7707char CtrlCharTable[]=
7708{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7709 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7710 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7711 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7712 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7713};
7714
7715
7716#endif