blob: 5c30a43584ebd884556af96b462f1bb05b7ffe9b [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
6 *
7 * Do ":help uganda" in Vim to read copying and usage conditions.
8 * Do ":help credits" in Vim to see a list of people who contributed.
9 * See README.txt for an overview of the Vim source code.
10 */
11
12/*
13 * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
14 * Also for OS/2, using the excellent EMX package!!!
15 * Also for BeOS and Atari MiNT.
16 *
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
19 */
20
21/*
22 * Some systems have a prototype for select() that has (int *) instead of
23 * (fd_set *), which is wrong. This define removes that prototype. We define
24 * our own prototype below.
25 * Don't use it for the Mac, it causes a warning for precompiled headers.
26 * TODO: use a configure check for precompiled headers?
27 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000028#if !defined(__APPLE__) && !defined(__TANDEM)
Bram Moolenaar071d4272004-06-13 20:20:40 +000029# define select select_declared_wrong
30#endif
31
32#include "vim.h"
33
Bram Moolenaar325b7a22004-07-05 15:58:32 +000034#ifdef FEAT_MZSCHEME
35# include "if_mzsch.h"
36#endif
37
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#include "os_unixx.h" /* unix includes for os_unix.c only */
39
40#ifdef USE_XSMP
41# include <X11/SM/SMlib.h>
42#endif
43
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000044#ifdef HAVE_SELINUX
45# include <selinux/selinux.h>
46static int selinux_enabled = -1;
47#endif
48
Bram Moolenaar5bd32f42014-04-02 14:05:38 +020049#ifdef HAVE_SMACK
50# include <attr/xattr.h>
51# include <linux/xattr.h>
52# ifndef SMACK_LABEL_LEN
53# define SMACK_LABEL_LEN 1024
54# endif
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057/*
58 * Use this prototype for select, some include files have a wrong prototype
59 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000060#ifndef __TANDEM
61# undef select
62# ifdef __BEOS__
63# define select beos_select
64# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#endif
66
Bram Moolenaara2442432007-04-26 14:26:37 +000067#ifdef __CYGWIN__
68# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000069# include <cygwin/version.h>
70# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
71 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010072# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
73# define WIN32_LEAN_AND_MEAN
74# include <windows.h>
75# include "winclip.pro"
76# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000077# endif
78#endif
79
Bram Moolenaar071d4272004-06-13 20:20:40 +000080#if defined(HAVE_SELECT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +010081extern int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
Bram Moolenaar071d4272004-06-13 20:20:40 +000082#endif
83
84#ifdef FEAT_MOUSE_GPM
85# include <gpm.h>
86/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
87 * I just copied relevant defines here. A cleaner solution would be to put gpm
88 * code into separate file and include there linux/keyboard.h
89 */
90/* #include <linux/keyboard.h> */
91# define KG_SHIFT 0
92# define KG_CTRL 2
93# define KG_ALT 3
94# define KG_ALTGR 1
95# define KG_SHIFTL 4
96# define KG_SHIFTR 5
97# define KG_CTRLL 6
98# define KG_CTRLR 7
99# define KG_CAPSSHIFT 8
100
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100101static void gpm_close(void);
102static int gpm_open(void);
103static int mch_gpm_process(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104#endif
105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000106#ifdef FEAT_SYSMOUSE
107# include <sys/consio.h>
108# include <sys/fbio.h>
109
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100110static int sysmouse_open(void);
111static void sysmouse_close(void);
Bram Moolenaard99df422016-01-29 23:20:40 +0100112static RETSIGTYPE sig_sysmouse SIGPROTOARG;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000113#endif
114
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115/*
116 * end of autoconf section. To be extended...
117 */
118
119/* Are the following #ifdefs still required? And why? Is that for X11? */
120
121#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
122# ifdef SIGWINCH
123# undef SIGWINCH
124# endif
125# ifdef TIOCGWINSZ
126# undef TIOCGWINSZ
127# endif
128#endif
129
130#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
131# define SIGWINCH SIGWINDOW
132#endif
133
134#ifdef FEAT_X11
135# include <X11/Xlib.h>
136# include <X11/Xutil.h>
137# include <X11/Xatom.h>
138# ifdef FEAT_XCLIPBOARD
139# include <X11/Intrinsic.h>
140# include <X11/Shell.h>
141# include <X11/StringDefs.h>
142static Widget xterm_Shell = (Widget)0;
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100143static void clip_update(void);
144static void xterm_update(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145# endif
146
147# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
148Window x11_window = 0;
149# endif
150Display *x11_display = NULL;
151
152# ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100153static int get_x11_windis(void);
154static void set_x11_title(char_u *);
155static void set_x11_icon(char_u *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156# endif
157#endif
158
159#ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100160static int get_x11_title(int);
161static int get_x11_icon(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162
163static char_u *oldtitle = NULL;
164static int did_set_title = FALSE;
165static char_u *oldicon = NULL;
166static int did_set_icon = FALSE;
167#endif
168
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100169static void may_core_dump(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000170
Bram Moolenaar205b8862011-09-07 15:04:31 +0200171#ifdef HAVE_UNION_WAIT
172typedef union wait waitstatus;
173#else
174typedef int waitstatus;
175#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100176static pid_t wait4pid(pid_t, waitstatus *);
Bram Moolenaar205b8862011-09-07 15:04:31 +0200177
Bram 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 Moolenaar071d4272004-06-13 20:20:40 +0000214#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100215static int have_wildcard(int, char_u **);
216static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217#endif
218
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100220static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221#endif
222
223#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000224# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225#endif
226
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000227/* volatile because it is used in signal handler sig_winch(). */
228static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229#ifndef __EMX__
230static char_u *extra_shell_arg = NULL;
231static int show_shell_mess = TRUE;
232#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000233/* volatile because it is used in signal handler deathtrap(). */
234static volatile int deadly_signal = 0; /* The signal we caught */
235/* volatile because it is used in signal handler deathtrap(). */
236static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237
238static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
239
240#ifdef USE_XSMP
241typedef struct
242{
243 SmcConn smcconn; /* The SM connection ID */
244 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200245 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 Bool save_yourself; /* If we're in the middle of a save_yourself */
247 Bool shutdown; /* If we're in shutdown mode */
248} xsmp_config_T;
249
250static xsmp_config_T xsmp;
251#endif
252
253#ifdef SYS_SIGLIST_DECLARED
254/*
255 * I have seen
256 * extern char *_sys_siglist[NSIG];
257 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
258 * that describe the signals. That is nearly what we want here. But
259 * autoconf does only check for sys_siglist (without the underscore), I
260 * do not want to change everything today.... jw.
261 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
262 */
263#endif
264
265static struct signalinfo
266{
267 int sig; /* Signal number, eg. SIGSEGV etc */
268 char *name; /* Signal name (not char_u!). */
269 char deadly; /* Catch as a deadly signal? */
270} signal_info[] =
271{
272#ifdef SIGHUP
273 {SIGHUP, "HUP", TRUE},
274#endif
275#ifdef SIGQUIT
276 {SIGQUIT, "QUIT", TRUE},
277#endif
278#ifdef SIGILL
279 {SIGILL, "ILL", TRUE},
280#endif
281#ifdef SIGTRAP
282 {SIGTRAP, "TRAP", TRUE},
283#endif
284#ifdef SIGABRT
285 {SIGABRT, "ABRT", TRUE},
286#endif
287#ifdef SIGEMT
288 {SIGEMT, "EMT", TRUE},
289#endif
290#ifdef SIGFPE
291 {SIGFPE, "FPE", TRUE},
292#endif
293#ifdef SIGBUS
294 {SIGBUS, "BUS", TRUE},
295#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100296#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
297 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 {SIGSEGV, "SEGV", TRUE},
299#endif
300#ifdef SIGSYS
301 {SIGSYS, "SYS", TRUE},
302#endif
303#ifdef SIGALRM
304 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
305#endif
306#ifdef SIGTERM
307 {SIGTERM, "TERM", TRUE},
308#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100309#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000310 {SIGVTALRM, "VTALRM", TRUE},
311#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000312#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
313 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
314 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 {SIGPROF, "PROF", TRUE},
316#endif
317#ifdef SIGXCPU
318 {SIGXCPU, "XCPU", TRUE},
319#endif
320#ifdef SIGXFSZ
321 {SIGXFSZ, "XFSZ", TRUE},
322#endif
323#ifdef SIGUSR1
324 {SIGUSR1, "USR1", TRUE},
325#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000326#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
327 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 {SIGUSR2, "USR2", TRUE},
329#endif
330#ifdef SIGINT
331 {SIGINT, "INT", FALSE},
332#endif
333#ifdef SIGWINCH
334 {SIGWINCH, "WINCH", FALSE},
335#endif
336#ifdef SIGTSTP
337 {SIGTSTP, "TSTP", FALSE},
338#endif
339#ifdef SIGPIPE
340 {SIGPIPE, "PIPE", FALSE},
341#endif
342 {-1, "Unknown!", FALSE}
343};
344
Bram Moolenaar25724922009-07-14 15:38:41 +0000345 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100346mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000347{
348 if (p_verbose >= 5)
349 {
350 verbose_enter();
351 smsg((char_u *)"chdir(%s)", path);
352 verbose_leave();
353 }
354# ifdef VMS
355 return chdir(vms_fixfilename(path));
356# else
357 return chdir(path);
358# endif
359}
360
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000361/*
362 * Write s[len] to the screen.
363 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100365mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000367 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368 if (p_wd) /* Unix is too fast, slow down a bit more */
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100369 RealWaitForChar(read_cmd_fd, p_wd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370}
371
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200372#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
373/*
374 * Return time in msec since "start_tv".
375 */
376 static long
377elapsed(struct timeval *start_tv)
378{
379 struct timeval now_tv;
380
381 gettimeofday(&now_tv, NULL);
382 return (now_tv.tv_sec - start_tv->tv_sec) * 1000L
383 + (now_tv.tv_usec - start_tv->tv_usec) / 1000L;
384}
385#endif
386
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000388 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 * Get a characters from the keyboard.
390 * Return the number of characters that are available.
391 * If wtime == 0 do not wait for characters.
392 * If wtime == n wait a short time for characters.
393 * If wtime == -1 wait forever for characters.
394 */
395 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100396mch_inchar(
397 char_u *buf,
398 int maxlen,
399 long wtime, /* don't use "time", MIPS cannot handle it */
400 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401{
402 int len;
Bram Moolenaarcda77642016-06-04 13:32:35 +0200403 int interrupted = FALSE;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200404 long wait_time;
405#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
406 struct timeval start_tv;
407
408 gettimeofday(&start_tv, NULL);
409#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200411#ifdef MESSAGE_QUEUE
412 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200413#endif
414
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 /* Check if window changed size while we were busy, perhaps the ":set
416 * columns=99" command was used. */
417 while (do_resize)
418 handle_resize();
419
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200420 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200422 if (wtime >= 0)
423 wait_time = wtime;
424 else
425 wait_time = p_ut;
426#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
427 wait_time -= elapsed(&start_tv);
428 if (wait_time >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200430#endif
431 if (WaitForChar(wait_time, &interrupted))
432 break;
433
Bram Moolenaarcda77642016-06-04 13:32:35 +0200434 /* no character available */
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100435 if (do_resize)
Bram Moolenaarcda77642016-06-04 13:32:35 +0200436 {
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100437 handle_resize();
Bram Moolenaarcda77642016-06-04 13:32:35 +0200438 continue;
439 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100440#ifdef FEAT_CLIENTSERVER
Bram Moolenaarcda77642016-06-04 13:32:35 +0200441 if (server_waiting())
442 {
443 parse_queued_messages();
444 continue;
445 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100446#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200447#ifdef MESSAGE_QUEUE
Bram Moolenaarcda77642016-06-04 13:32:35 +0200448 if (interrupted)
449 {
450 parse_queued_messages();
451 continue;
452 }
Bram Moolenaar67c53842010-05-22 18:28:27 +0200453#endif
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200454#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 }
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200456#endif
457 if (wtime >= 0)
458 /* no character available within "wtime" */
459 return 0;
460
461 /* wtime == -1: no character available within 'updatetime' */
462#ifdef FEAT_AUTOCMD
463 if (trigger_cursorhold() && maxlen >= 3
464 && !typebuf_changed(tb_change_cnt))
465 {
466 buf[0] = K_SPECIAL;
467 buf[1] = KS_EXTRA;
468 buf[2] = (int)KE_CURSORHOLD;
469 return 3;
470 }
471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472 /*
473 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000474 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 * Also done when interrupted by SIGWINCH.
476 */
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200477 before_blocking();
478 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 }
480
Bram Moolenaarcda77642016-06-04 13:32:35 +0200481 /* repeat until we got a character */
482 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 {
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200484 long wtime_now = -1L;
485
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 while (do_resize) /* window changed size */
487 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200488
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200489#ifdef MESSAGE_QUEUE
490 parse_queued_messages();
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200491
492# ifdef FEAT_JOB_CHANNEL
493 if (has_pending_job())
494 {
495 /* Don't wait longer than a few seconds, checking for a finished
496 * job requires polling. */
497 if (p_ut > 9000L)
498 wtime_now = 1000L;
499 else
500 wtime_now = 10000L - p_ut;
501 }
502# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200503#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200505 * We want to be interrupted by the winch signal
506 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200508 if (!WaitForChar(wtime_now, &interrupted))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200509 {
510 if (do_resize) /* interrupted by SIGWINCH signal */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200511 continue;
512#ifdef MESSAGE_QUEUE
513 if (interrupted || wtime_now > 0)
514 {
515 parse_queued_messages();
516 continue;
517 }
518#endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200519 return 0;
520 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521
522 /* If input was put directly in typeahead buffer bail out here. */
523 if (typebuf_changed(tb_change_cnt))
524 return 0;
525
526 /*
527 * For some terminals we only get one character at a time.
528 * We want the get all available characters, so we could keep on
529 * trying until none is available
530 * For some other terminals this is quite slow, that's why we don't do
531 * it.
532 */
533 len = read_from_input_buf(buf, (long)maxlen);
534 if (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 return len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 }
537}
538
539 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100540handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541{
542 do_resize = FALSE;
543 shell_resized();
544}
545
546/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200547 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548 */
549 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100550mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551{
Bram Moolenaarcda77642016-06-04 13:32:35 +0200552 return WaitForChar(0L, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553}
554
555#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
556# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000557# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558# endif
559# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
560# include <sys/sysctl.h>
561# endif
562# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
563# include <sys/sysinfo.h>
564# endif
565
566/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000567 * Return total amount of memory available in Kbyte.
568 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100571mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572{
573# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000574 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000575# else
576 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000577 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578
579# ifdef HAVE_SYSCTL
580 int mib[2], physmem;
581 size_t len;
582
583 /* BSD way of getting the amount of RAM available. */
584 mib[0] = CTL_HW;
585 mib[1] = HW_USERMEM;
586 len = sizeof(physmem);
587 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
588 mem = (long_u)physmem;
589# endif
590
591# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
592 if (mem == 0)
593 {
594 struct sysinfo sinfo;
595
596 /* Linux way of getting amount of RAM available */
597 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000598 {
599# ifdef HAVE_SYSINFO_MEM_UNIT
600 /* avoid overflow as much as possible */
601 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
602 {
603 sinfo.mem_unit = sinfo.mem_unit >> 1;
604 --shiftright;
605 }
606 mem = sinfo.totalram * sinfo.mem_unit;
607# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000609# endif
610 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 }
612# endif
613
614# ifdef HAVE_SYSCONF
615 if (mem == 0)
616 {
617 long pagesize, pagecount;
618
619 /* Solaris way of getting amount of RAM available */
620 pagesize = sysconf(_SC_PAGESIZE);
621 pagecount = sysconf(_SC_PHYS_PAGES);
622 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000623 {
624 /* avoid overflow as much as possible */
625 while (shiftright > 0 && (pagesize & 1) == 0)
626 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000627 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000628 --shiftright;
629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 }
633# endif
634
635 /* Return the minimum of the physical memory and the user limit, because
636 * using more than the user limit may cause Vim to be terminated. */
637# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
638 {
639 struct rlimit rlp;
640
641 if (getrlimit(RLIMIT_DATA, &rlp) == 0
642 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
643# ifdef RLIM_INFINITY
644 && rlp.rlim_cur != RLIM_INFINITY
645# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000646 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000648 {
649 mem = (long_u)rlp.rlim_cur;
650 shiftright = 10;
651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 }
653# endif
654
655 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000656 return mem >> shiftright;
657 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658# endif
659}
660#endif
661
662 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100663mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664{
665 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000666#ifdef FEAT_MZSCHEME
667 long total = msec; /* remember original value */
668#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000669
670 if (ignoreinput)
671 {
672 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000673 * here. But we don't want QUIT to kill us (CTRL-\ used in a
674 * shell may produce SIGQUIT). */
675 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676 old_tmode = curr_tmode;
677 if (curr_tmode == TMODE_RAW)
678 settmode(TMODE_SLEEP);
679
680 /*
681 * Everybody sleeps in a different way...
682 * Prefer nanosleep(), some versions of usleep() can only sleep up to
683 * one second.
684 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000685#ifdef FEAT_MZSCHEME
686 do
687 {
688 /* if total is large enough, wait by portions in p_mzq */
689 if (total > p_mzq)
690 msec = p_mzq;
691 else
692 msec = total;
693 total -= msec;
694#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695#ifdef HAVE_NANOSLEEP
696 {
697 struct timespec ts;
698
699 ts.tv_sec = msec / 1000;
700 ts.tv_nsec = (msec % 1000) * 1000000;
701 (void)nanosleep(&ts, NULL);
702 }
703#else
704# ifdef HAVE_USLEEP
705 while (msec >= 1000)
706 {
707 usleep((unsigned int)(999 * 1000));
708 msec -= 999;
709 }
710 usleep((unsigned int)(msec * 1000));
711# else
712# ifndef HAVE_SELECT
713 poll(NULL, 0, (int)msec);
714# else
715# ifdef __EMX__
716 _sleep2(msec);
717# else
718 {
719 struct timeval tv;
720
721 tv.tv_sec = msec / 1000;
722 tv.tv_usec = (msec % 1000) * 1000;
723 /*
724 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
725 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
726 */
727 select(0, NULL, NULL, NULL, &tv);
728 }
729# endif /* __EMX__ */
730# endif /* HAVE_SELECT */
731# endif /* HAVE_NANOSLEEP */
732#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000733#ifdef FEAT_MZSCHEME
734 }
735 while (total > 0);
736#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737
738 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000739 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 }
741 else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200742 WaitForChar(msec, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743}
744
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000745#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
747# define HAVE_CHECK_STACK_GROWTH
748/*
749 * Support for checking for an almost-out-of-stack-space situation.
750 */
751
752/*
753 * Return a pointer to an item on the stack. Used to find out if the stack
754 * grows up or down.
755 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100756static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757static int stack_grows_downwards;
758
759/*
760 * Find out if the stack grows upwards or downwards.
761 * "p" points to a variable on the stack of the caller.
762 */
763 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100764check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765{
766 int i;
767
768 stack_grows_downwards = (p > (char *)&i);
769}
770#endif
771
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000772#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773static char *stack_limit = NULL;
774
775#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
776# include <pthread.h>
777# include <pthread_np.h>
778#endif
779
780/*
781 * Find out until how var the stack can grow without getting into trouble.
782 * Called when starting up and when switching to the signal stack in
783 * deathtrap().
784 */
785 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100786get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787{
788 struct rlimit rlp;
789 int i;
790 long lim;
791
792 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
793 * limit doesn't fit in a long (rlim_cur might be "long long"). */
794 if (getrlimit(RLIMIT_STACK, &rlp) == 0
795 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
796# ifdef RLIM_INFINITY
797 && rlp.rlim_cur != RLIM_INFINITY
798# endif
799 )
800 {
801 lim = (long)rlp.rlim_cur;
802#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
803 {
804 pthread_attr_t attr;
805 size_t size;
806
807 /* On FreeBSD the initial thread always has a fixed stack size, no
808 * matter what the limits are set to. Normally it's 1 Mbyte. */
809 pthread_attr_init(&attr);
810 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
811 {
812 pthread_attr_getstacksize(&attr, &size);
813 if (lim > (long)size)
814 lim = (long)size;
815 }
816 pthread_attr_destroy(&attr);
817 }
818#endif
819 if (stack_grows_downwards)
820 {
821 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
822 if (stack_limit >= (char *)&i)
823 /* overflow, set to 1/16 of current stack position */
824 stack_limit = (char *)((long)&i / 16L);
825 }
826 else
827 {
828 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
829 if (stack_limit <= (char *)&i)
830 stack_limit = NULL; /* overflow */
831 }
832 }
833}
834
835/*
836 * Return FAIL when running out of stack space.
837 * "p" must point to any variable local to the caller that's on the stack.
838 */
839 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100840mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841{
842 if (stack_limit != NULL)
843 {
844 if (stack_grows_downwards)
845 {
846 if (p < stack_limit)
847 return FAIL;
848 }
849 else if (p > stack_limit)
850 return FAIL;
851 }
852 return OK;
853}
854#endif
855
856#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
857/*
858 * Support for using the signal stack.
859 * This helps when we run out of stack space, which causes a SIGSEGV. The
860 * signal handler then must run on another stack, since the normal stack is
861 * completely full.
862 */
863
Bram Moolenaar39766a72013-11-03 00:41:00 +0100864#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100865# include <AvailabilityMacros.h>
866#endif
867
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868#ifndef SIGSTKSZ
869# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
870#endif
871
872# ifdef HAVE_SIGALTSTACK
873static stack_t sigstk; /* for sigaltstack() */
874# else
875static struct sigstack sigstk; /* for sigstack() */
876# endif
877
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100878static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879static char *signal_stack;
880
881 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100882init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883{
884 if (signal_stack != NULL)
885 {
886# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000887# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
888 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
890 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100891 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892# endif
893
894# ifdef HAVE_SS_BASE
895 sigstk.ss_base = signal_stack;
896# else
897 sigstk.ss_sp = signal_stack;
898# endif
899 sigstk.ss_size = SIGSTKSZ;
900 sigstk.ss_flags = 0;
901 (void)sigaltstack(&sigstk, NULL);
902# else
903 sigstk.ss_sp = signal_stack;
904 if (stack_grows_downwards)
905 sigstk.ss_sp += SIGSTKSZ - 1;
906 sigstk.ss_onstack = 0;
907 (void)sigstack(&sigstk, NULL);
908# endif
909 }
910}
911#endif
912
913/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000914 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 * will barf when the second argument to signal() is ``wrong''.
916 * Let me try it with a few tricky defines from my own osdef.h (jw).
917 */
918#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919 static RETSIGTYPE
920sig_winch SIGDEFARG(sigarg)
921{
922 /* this is not required on all systems, but it doesn't hurt anybody */
923 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
924 do_resize = TRUE;
925 SIGRETURN;
926}
927#endif
928
929#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930 static RETSIGTYPE
931catch_sigint SIGDEFARG(sigarg)
932{
933 /* this is not required on all systems, but it doesn't hurt anybody */
934 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
935 got_int = TRUE;
936 SIGRETURN;
937}
938#endif
939
940#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 static RETSIGTYPE
942catch_sigpwr SIGDEFARG(sigarg)
943{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000944 /* this is not required on all systems, but it doesn't hurt anybody */
945 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 /*
947 * I'm not sure we get the SIGPWR signal when the system is really going
948 * down or when the batteries are almost empty. Just preserve the swap
949 * files and don't exit, that can't do any harm.
950 */
951 ml_sync_all(FALSE, FALSE);
952 SIGRETURN;
953}
954#endif
955
956#ifdef SET_SIG_ALARM
957/*
958 * signal function for alarm().
959 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 static RETSIGTYPE
961sig_alarm SIGDEFARG(sigarg)
962{
963 /* doesn't do anything, just to break a system call */
964 sig_alarm_called = TRUE;
965 SIGRETURN;
966}
967#endif
968
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000969#if (defined(HAVE_SETJMP_H) \
970 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
971 || defined(FEAT_LIBCALL))) \
972 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973/*
974 * A simplistic version of setjmp() that only allows one level of using.
975 * Don't call twice before calling mch_endjmp()!.
976 * Usage:
977 * mch_startjmp();
978 * if (SETJMP(lc_jump_env) != 0)
979 * {
980 * mch_didjmp();
981 * EMSG("crash!");
982 * }
983 * else
984 * {
985 * do_the_work;
986 * mch_endjmp();
987 * }
988 * Note: Can't move SETJMP() here, because a function calling setjmp() must
989 * not return before the saved environment is used.
990 * Returns OK for normal return, FAIL when the protected code caused a
991 * problem and LONGJMP() was used.
992 */
993 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100994mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995{
996#ifdef SIGHASARG
997 lc_signal = 0;
998#endif
999 lc_active = TRUE;
1000}
1001
1002 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001003mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001004{
1005 lc_active = FALSE;
1006}
1007
1008 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001009mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010{
1011# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
1012 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
1013 * otherwise catching the signal only works once. */
1014 init_signal_stack();
1015# endif
1016}
1017#endif
1018
1019/*
1020 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001021 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001023 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
1024 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 */
1026 static RETSIGTYPE
1027deathtrap SIGDEFARG(sigarg)
1028{
1029 static int entered = 0; /* count the number of times we got here.
1030 Note: when memory has been corrupted
1031 this may get an arbitrary value! */
1032#ifdef SIGHASARG
1033 int i;
1034#endif
1035
1036#if defined(HAVE_SETJMP_H)
1037 /*
1038 * Catch a crash in protected code.
1039 * Restores the environment saved in lc_jump_env, which looks like
1040 * SETJMP() returns 1.
1041 */
1042 if (lc_active)
1043 {
1044# if defined(SIGHASARG)
1045 lc_signal = sigarg;
1046# endif
1047 lc_active = FALSE; /* don't jump again */
1048 LONGJMP(lc_jump_env, 1);
1049 /* NOTREACHED */
1050 }
1051#endif
1052
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001053#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001054# ifdef SIGQUIT
1055 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1056 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1057 * pressing CTRL-\, but we don't want Vim to exit then. */
1058 if (in_mch_delay && sigarg == SIGQUIT)
1059 SIGRETURN;
1060# endif
1061
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001062 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1063 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1064 * free(). Calling free() again may then cause a crash. */
1065 if (entered == 0
1066 && (0
1067# ifdef SIGHUP
1068 || sigarg == SIGHUP
1069# endif
1070# ifdef SIGQUIT
1071 || sigarg == SIGQUIT
1072# endif
1073# ifdef SIGTERM
1074 || sigarg == SIGTERM
1075# endif
1076# ifdef SIGPWR
1077 || sigarg == SIGPWR
1078# endif
1079# ifdef SIGUSR1
1080 || sigarg == SIGUSR1
1081# endif
1082# ifdef SIGUSR2
1083 || sigarg == SIGUSR2
1084# endif
1085 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001086 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001087 SIGRETURN;
1088#endif
1089
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 /* Remember how often we have been called. */
1091 ++entered;
1092
1093#ifdef FEAT_EVAL
1094 /* Set the v:dying variable. */
1095 set_vim_var_nr(VV_DYING, (long)entered);
1096#endif
1097
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001098#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 /* Since we are now using the signal stack, need to reset the stack
1100 * limit. Otherwise using a regexp will fail. */
1101 get_stack_limit();
1102#endif
1103
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001104#if 0
1105 /* This is for opening gdb the moment Vim crashes.
1106 * You need to manually adjust the file name and Vim executable name.
1107 * Suggested by SungHyun Nam. */
1108 {
1109# define VI_GDB_FILE "/tmp/vimgdb"
1110# define VIM_NAME "/usr/bin/vim"
1111 FILE *fp = fopen(VI_GDB_FILE, "w");
1112 if (fp)
1113 {
1114 fprintf(fp,
1115 "file %s\n"
1116 "attach %d\n"
1117 "set height 1000\n"
1118 "bt full\n"
1119 , VIM_NAME, getpid());
1120 fclose(fp);
1121 system("xterm -e gdb -x "VI_GDB_FILE);
1122 unlink(VI_GDB_FILE);
1123 }
1124 }
1125#endif
1126
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127#ifdef SIGHASARG
1128 /* try to find the name of this signal */
1129 for (i = 0; signal_info[i].sig != -1; i++)
1130 if (sigarg == signal_info[i].sig)
1131 break;
1132 deadly_signal = sigarg;
1133#endif
1134
1135 full_screen = FALSE; /* don't write message to the GUI, it might be
1136 * part of the problem... */
1137 /*
1138 * If something goes wrong after entering here, we may get here again.
1139 * When this happens, give a message and try to exit nicely (resetting the
1140 * terminal mode, etc.)
1141 * When this happens twice, just exit, don't even try to give a message,
1142 * stack may be corrupt or something weird.
1143 * When this still happens again (or memory was corrupted in such a way
1144 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1145 */
1146 if (entered >= 3)
1147 {
1148 reset_signals(); /* don't catch any signals anymore */
1149 may_core_dump();
1150 if (entered >= 4)
1151 _exit(8);
1152 exit(7);
1153 }
1154 if (entered == 2)
1155 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001156 /* No translation, it may call malloc(). */
1157 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158 out_flush();
1159 getout(1);
1160 }
1161
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001162 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001164 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 signal_info[i].name);
1166#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001167 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001169
1170 /* Preserve files and exit. This sets the really_exiting flag to prevent
1171 * calling free(). */
1172 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173
Bram Moolenaar009b2592004-10-24 19:18:58 +00001174#ifdef NBDEBUG
1175 reset_signals();
1176 may_core_dump();
1177 abort();
1178#endif
1179
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 SIGRETURN;
1181}
1182
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001183#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184/*
1185 * On Solaris with multi-threading, suspending might not work immediately.
1186 * Catch the SIGCONT signal, which will be used as an indication whether the
1187 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001188 *
1189 * On Linux, signal is not always handled immediately either.
1190 * See https://bugs.launchpad.net/bugs/291373
1191 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001192 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001194static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001195static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196
1197/*
1198 * signal handler for SIGCONT
1199 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 static RETSIGTYPE
1201sigcont_handler SIGDEFARG(sigarg)
1202{
1203 sigcont_received = TRUE;
1204 SIGRETURN;
1205}
1206#endif
1207
Bram Moolenaar62b42182010-09-21 22:09:37 +02001208# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001209static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001210# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001211static void save_clipboard(void);
1212static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001213
1214static void *clip_star_save = NULL;
1215static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001216# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001217
1218/*
1219 * Called when Vim is going to sleep or execute a shell command.
1220 * We can't respond to requests for the X selections. Lose them, otherwise
1221 * other applications will hang. But first copy the text to cut buffer 0.
1222 */
1223 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001224loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001225{
1226 if (clip_star.owned || clip_plus.owned)
1227 {
1228 x11_export_final_selection();
1229 if (clip_star.owned)
1230 clip_lose_selection(&clip_star);
1231 if (clip_plus.owned)
1232 clip_lose_selection(&clip_plus);
1233 if (x11_display != NULL)
1234 XFlush(x11_display);
1235 }
1236}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001237
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001238# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001239/*
1240 * Save clipboard text to restore later.
1241 */
1242 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001243save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001244{
1245 if (clip_star.owned)
1246 clip_star_save = get_register('*', TRUE);
1247 if (clip_plus.owned)
1248 clip_plus_save = get_register('+', TRUE);
1249}
1250
1251/*
1252 * Restore clipboard text if no one own the X selection.
1253 */
1254 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001255restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001256{
1257 if (clip_star_save != NULL)
1258 {
1259 if (!clip_gen_owner_exists(&clip_star))
1260 put_register('*', clip_star_save);
1261 else
1262 free_register(clip_star_save);
1263 clip_star_save = NULL;
1264 }
1265 if (clip_plus_save != NULL)
1266 {
1267 if (!clip_gen_owner_exists(&clip_plus))
1268 put_register('+', clip_plus_save);
1269 else
1270 free_register(clip_plus_save);
1271 clip_plus_save = NULL;
1272 }
1273}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001274# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001275#endif
1276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277/*
1278 * If the machine has job control, use it to suspend the program,
1279 * otherwise fake it by starting a new shell.
1280 */
1281 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001282mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283{
1284 /* BeOS does have SIGTSTP, but it doesn't work. */
1285#if defined(SIGTSTP) && !defined(__BEOS__)
1286 out_flush(); /* needed to make cursor visible on some systems */
1287 settmode(TMODE_COOK);
1288 out_flush(); /* needed to disable mouse on some systems */
1289
1290# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001291 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292# endif
1293
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001294# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001295 sigcont_received = FALSE;
1296# endif
1297 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001298# if defined(_REENTRANT) && defined(SIGCONT)
1299 /*
1300 * Wait for the SIGCONT signal to be handled. It generally happens
1301 * immediately, but somehow not all the time. Do not call pause()
1302 * because there would be race condition which would hang Vim if
1303 * signal happened in between the test of sigcont_received and the
1304 * call to pause(). If signal is not yet received, call sleep(0)
1305 * to just yield CPU. Signal should then be received. If somehow
1306 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1307 * further if signal is not received after 1+2+3+4 ms (not expected
1308 * to happen).
1309 */
1310 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001311 long wait_time;
1312 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001313 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001314 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316# endif
1317
1318# ifdef FEAT_TITLE
1319 /*
1320 * Set oldtitle to NULL, so the current title is obtained again.
1321 */
1322 vim_free(oldtitle);
1323 oldtitle = NULL;
1324# endif
1325 settmode(TMODE_RAW);
1326 need_check_timestamps = TRUE;
1327 did_check_timestamps = FALSE;
1328#else
1329 suspend_shell();
1330#endif
1331}
1332
1333 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001334mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335{
1336 Columns = 80;
1337 Rows = 24;
1338
1339 out_flush();
1340 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001341
Bram Moolenaar56718732006-03-15 22:53:57 +00001342#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001343 mac_conv_init();
1344#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001345#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1346 win_clip_init();
1347#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001348}
1349
1350 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001351set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352{
1353#if defined(SIGWINCH)
1354 /*
1355 * WINDOW CHANGE signal is handled with sig_winch().
1356 */
1357 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1358#endif
1359
1360 /*
1361 * We want the STOP signal to work, to make mch_suspend() work.
1362 * For "rvim" the STOP signal is ignored.
1363 */
1364#ifdef SIGTSTP
1365 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1366#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001367#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 signal(SIGCONT, sigcont_handler);
1369#endif
1370
1371 /*
1372 * We want to ignore breaking of PIPEs.
1373 */
1374#ifdef SIGPIPE
1375 signal(SIGPIPE, SIG_IGN);
1376#endif
1377
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001379 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380#endif
1381
1382 /*
1383 * Ignore alarm signals (Perl's alarm() generates it).
1384 */
1385#ifdef SIGALRM
1386 signal(SIGALRM, SIG_IGN);
1387#endif
1388
1389 /*
1390 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1391 * work will be lost.
1392 */
1393#ifdef SIGPWR
1394 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1395#endif
1396
1397 /*
1398 * Arrange for other signals to gracefully shutdown Vim.
1399 */
1400 catch_signals(deathtrap, SIG_ERR);
1401
1402#if defined(FEAT_GUI) && defined(SIGHUP)
1403 /*
1404 * When the GUI is running, ignore the hangup signal.
1405 */
1406 if (gui.in_use)
1407 signal(SIGHUP, SIG_IGN);
1408#endif
1409}
1410
Bram Moolenaardf177f62005-02-22 08:39:57 +00001411#if defined(SIGINT) || defined(PROTO)
1412/*
1413 * Catch CTRL-C (only works while in Cooked mode).
1414 */
1415 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001416catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001417{
1418 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1419}
1420#endif
1421
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001423reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424{
1425 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001426#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 /* SIGCONT isn't in the list, because its default action is ignore */
1428 signal(SIGCONT, SIG_DFL);
1429#endif
1430}
1431
1432 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001433catch_signals(
1434 RETSIGTYPE (*func_deadly)(),
1435 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436{
1437 int i;
1438
1439 for (i = 0; signal_info[i].sig != -1; i++)
1440 if (signal_info[i].deadly)
1441 {
1442#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1443 struct sigaction sa;
1444
1445 /* Setup to use the alternate stack for the signal function. */
1446 sa.sa_handler = func_deadly;
1447 sigemptyset(&sa.sa_mask);
1448# if defined(__linux__) && defined(_REENTRANT)
1449 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1450 * thread handling in combination with using the alternate stack:
1451 * pthread library functions try to use the stack pointer to
1452 * identify the current thread, causing a SEGV signal, which
1453 * recursively calls deathtrap() and hangs. */
1454 sa.sa_flags = 0;
1455# else
1456 sa.sa_flags = SA_ONSTACK;
1457# endif
1458 sigaction(signal_info[i].sig, &sa, NULL);
1459#else
1460# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1461 struct sigvec sv;
1462
1463 /* Setup to use the alternate stack for the signal function. */
1464 sv.sv_handler = func_deadly;
1465 sv.sv_mask = 0;
1466 sv.sv_flags = SV_ONSTACK;
1467 sigvec(signal_info[i].sig, &sv, NULL);
1468# else
1469 signal(signal_info[i].sig, func_deadly);
1470# endif
1471#endif
1472 }
1473 else if (func_other != SIG_ERR)
1474 signal(signal_info[i].sig, func_other);
1475}
1476
1477/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001478 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001479 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1480 * return TRUE
1481 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1482 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001483 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001484 * Returns TRUE when Vim should exit.
1485 */
1486 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001487vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001488{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001489 static int got_signal = 0;
1490 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001491
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001492 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001493 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001494 case SIGNAL_BLOCK: blocked = TRUE;
1495 break;
1496
1497 case SIGNAL_UNBLOCK: blocked = FALSE;
1498 if (got_signal != 0)
1499 {
1500 kill(getpid(), got_signal);
1501 got_signal = 0;
1502 }
1503 break;
1504
1505 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001506 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001507 got_signal = sig;
1508#ifdef SIGPWR
1509 if (sig != SIGPWR)
1510#endif
1511 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001512 break;
1513 }
1514 return FALSE;
1515}
1516
1517/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 * Check_win checks whether we have an interactive stdout.
1519 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001521mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 if (isatty(1))
1524 return OK;
1525 return FAIL;
1526}
1527
1528/*
1529 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1530 */
1531 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001532mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533{
1534 if (isatty(read_cmd_fd))
1535 return TRUE;
1536 return FALSE;
1537}
1538
1539#ifdef FEAT_X11
1540
1541# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1542 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1543
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001544static void xopen_message(struct timeval *start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545
1546/*
1547 * Give a message about the elapsed time for opening the X window.
1548 */
1549 static void
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001550xopen_message(struct timeval *start_tv)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551{
Bram Moolenaare30a3d02016-06-04 14:11:20 +02001552 smsg((char_u *)_("Opening the X display took %ld msec"), elapsed(start_tv));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553}
1554# endif
1555#endif
1556
1557#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1558/*
1559 * A few functions shared by X11 title and clipboard code.
1560 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001561static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1562static int x_error_check(Display *dpy, XErrorEvent *error_event);
1563static int x_connect_to_server(void);
1564static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565
1566static int got_x_error = FALSE;
1567
1568/*
1569 * X Error handler, otherwise X just exits! (very rude) -- webb
1570 */
1571 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001572x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001574 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 STRCAT(IObuff, _("\nVim: Got X error\n"));
1576
1577 /* We cannot print a message and continue, because no X calls are allowed
1578 * here (causes my system to hang). Silently continuing might be an
1579 * alternative... */
1580 preserve_exit(); /* preserve files and exit */
1581
1582 return 0; /* NOTREACHED */
1583}
1584
1585/*
1586 * Another X Error handler, just used to check for errors.
1587 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001589x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590{
1591 got_x_error = TRUE;
1592 return 0;
1593}
1594
1595#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1596# if defined(HAVE_SETJMP_H)
1597/*
1598 * An X IO Error handler, used to catch error while opening the display.
1599 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001600static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001603x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604{
1605 /* This function should not return, it causes exit(). Longjump instead. */
1606 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001607# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001608 return 0; /* avoid the compiler complains about missing return value */
1609# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610}
1611# endif
1612
1613/*
1614 * An X IO Error handler, used to catch terminal errors.
1615 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001616static int x_IOerror_handler(Display *dpy);
1617static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001618static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001621x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622{
1623 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001624 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 x11_window = 0;
1626 x11_display = NULL;
1627 xterm_Shell = (Widget)0;
1628
1629 /* This function should not return, it causes exit(). Longjump instead. */
1630 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001631# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001632 return 0; /* avoid the compiler complains about missing return value */
1633# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001635
1636/*
1637 * If the X11 connection was lost try to restore it.
1638 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001639 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001640 */
1641 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001642may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001643{
1644 if (xterm_dpy_was_reset)
1645 {
1646 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001647
1648# ifndef LESSTIF_VERSION
1649 /* This has been reported to avoid Vim getting stuck. */
1650 if (app_context != (XtAppContext)NULL)
1651 {
1652 XtDestroyApplicationContext(app_context);
1653 app_context = (XtAppContext)NULL;
1654 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1655 }
1656# endif
1657
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001658 setup_term_clip();
1659 get_x11_title(FALSE);
1660 }
1661}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662#endif
1663
1664/*
1665 * Return TRUE when connection to the X server is desired.
1666 */
1667 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001668x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670#if defined(FEAT_CLIENTSERVER)
1671 if (x_force_connect)
1672 return TRUE;
1673#endif
1674 if (x_no_connect)
1675 return FALSE;
1676
1677 /* Check for a match with "exclude:" from 'clipboard'. */
1678 if (clip_exclude_prog != NULL)
1679 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001680 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 return FALSE;
1682 }
1683 return TRUE;
1684}
1685
1686/*
1687 * Test if "dpy" and x11_window are valid by getting the window title.
1688 * I don't actually want it yet, so there may be a simpler call to use, but
1689 * this will cause the error handler x_error_check() to be called if anything
1690 * is wrong, such as the window pointer being invalid (as can happen when the
1691 * user changes his DISPLAY, but not his WINDOWID) -- webb
1692 */
1693 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001694test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695{
1696 int (*old_handler)();
1697 XTextProperty text_prop;
1698
1699 old_handler = XSetErrorHandler(x_error_check);
1700 got_x_error = FALSE;
1701 if (XGetWMName(dpy, x11_window, &text_prop))
1702 XFree((void *)text_prop.value);
1703 XSync(dpy, False);
1704 (void)XSetErrorHandler(old_handler);
1705
1706 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001707 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708
1709 return (got_x_error ? FAIL : OK);
1710}
1711#endif
1712
1713#ifdef FEAT_TITLE
1714
1715#ifdef FEAT_X11
1716
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001717static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718
1719/*
1720 * try to get x11 window and display
1721 *
1722 * return FAIL for failure, OK otherwise
1723 */
1724 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001725get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726{
1727 char *winid;
1728 static int result = -1;
1729#define XD_NONE 0 /* x11_display not set here */
1730#define XD_HERE 1 /* x11_display opened here */
1731#define XD_GUI 2 /* x11_display used from gui.dpy */
1732#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1733 static int x11_display_from = XD_NONE;
1734 static int did_set_error_handler = FALSE;
1735
1736 if (!did_set_error_handler)
1737 {
1738 /* X just exits if it finds an error otherwise! */
1739 (void)XSetErrorHandler(x_error_handler);
1740 did_set_error_handler = TRUE;
1741 }
1742
Bram Moolenaar9372a112005-12-06 19:59:18 +00001743#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 if (gui.in_use)
1745 {
1746 /*
1747 * If the X11 display was opened here before, for the window where Vim
1748 * was started, close that one now to avoid a memory leak.
1749 */
1750 if (x11_display_from == XD_HERE && x11_display != NULL)
1751 {
1752 XCloseDisplay(x11_display);
1753 x11_display_from = XD_NONE;
1754 }
1755 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1756 {
1757 x11_display_from = XD_GUI;
1758 return OK;
1759 }
1760 x11_display = NULL;
1761 return FAIL;
1762 }
1763 else if (x11_display_from == XD_GUI)
1764 {
1765 /* GUI must have stopped somehow, clear x11_display */
1766 x11_window = 0;
1767 x11_display = NULL;
1768 x11_display_from = XD_NONE;
1769 }
1770#endif
1771
1772 /* When started with the "-X" argument, don't try connecting. */
1773 if (!x_connect_to_server())
1774 return FAIL;
1775
1776 /*
1777 * If WINDOWID not set, should try another method to find out
1778 * what the current window number is. The only code I know for
1779 * this is very complicated.
1780 * We assume that zero is invalid for WINDOWID.
1781 */
1782 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1783 x11_window = (Window)atol(winid);
1784
1785#ifdef FEAT_XCLIPBOARD
1786 if (xterm_dpy != NULL && x11_window != 0)
1787 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001788 /* We may have checked it already, but Gnome terminal can move us to
1789 * another window, so we need to check every time. */
1790 if (x11_display_from != XD_XTERM)
1791 {
1792 /*
1793 * If the X11 display was opened here before, for the window where
1794 * Vim was started, close that one now to avoid a memory leak.
1795 */
1796 if (x11_display_from == XD_HERE && x11_display != NULL)
1797 XCloseDisplay(x11_display);
1798 x11_display = xterm_dpy;
1799 x11_display_from = XD_XTERM;
1800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 if (test_x11_window(x11_display) == FAIL)
1802 {
1803 /* probably bad $WINDOWID */
1804 x11_window = 0;
1805 x11_display = NULL;
1806 x11_display_from = XD_NONE;
1807 return FAIL;
1808 }
1809 return OK;
1810 }
1811#endif
1812
1813 if (x11_window == 0 || x11_display == NULL)
1814 result = -1;
1815
1816 if (result != -1) /* Have already been here and set this */
1817 return result; /* Don't do all these X calls again */
1818
1819 if (x11_window != 0 && x11_display == NULL)
1820 {
1821#ifdef SET_SIG_ALARM
1822 RETSIGTYPE (*sig_save)();
1823#endif
1824#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1825 struct timeval start_tv;
1826
1827 if (p_verbose > 0)
1828 gettimeofday(&start_tv, NULL);
1829#endif
1830
1831#ifdef SET_SIG_ALARM
1832 /*
1833 * Opening the Display may hang if the DISPLAY setting is wrong, or
1834 * the network connection is bad. Set an alarm timer to get out.
1835 */
1836 sig_alarm_called = FALSE;
1837 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1838 (RETSIGTYPE (*)())sig_alarm);
1839 alarm(2);
1840#endif
1841 x11_display = XOpenDisplay(NULL);
1842
1843#ifdef SET_SIG_ALARM
1844 alarm(0);
1845 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1846 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001847 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848#endif
1849 if (x11_display != NULL)
1850 {
1851# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1852 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001853 {
1854 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001856 verbose_leave();
1857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858# endif
1859 if (test_x11_window(x11_display) == FAIL)
1860 {
1861 /* Maybe window id is bad */
1862 x11_window = 0;
1863 XCloseDisplay(x11_display);
1864 x11_display = NULL;
1865 }
1866 else
1867 x11_display_from = XD_HERE;
1868 }
1869 }
1870 if (x11_window == 0 || x11_display == NULL)
1871 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001872
1873# ifdef FEAT_EVAL
1874 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1875# endif
1876
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 return (result = OK);
1878}
1879
1880/*
1881 * Determine original x11 Window Title
1882 */
1883 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001884get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001886 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887}
1888
1889/*
1890 * Determine original x11 Window icon
1891 */
1892 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001893get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894{
1895 int retval = FALSE;
1896
1897 retval = get_x11_thing(FALSE, test_only);
1898
1899 /* could not get old icon, use terminal name */
1900 if (oldicon == NULL && !test_only)
1901 {
1902 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001903 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001905 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 }
1907
1908 return retval;
1909}
1910
1911 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001912get_x11_thing(
1913 int get_title, /* get title string */
1914 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915{
1916 XTextProperty text_prop;
1917 int retval = FALSE;
1918 Status status;
1919
1920 if (get_x11_windis() == OK)
1921 {
1922 /* Get window/icon name if any */
1923 if (get_title)
1924 status = XGetWMName(x11_display, x11_window, &text_prop);
1925 else
1926 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1927
1928 /*
1929 * If terminal is xterm, then x11_window may be a child window of the
1930 * outer xterm window that actually contains the window/icon name, so
1931 * keep traversing up the tree until a window with a title/icon is
1932 * found.
1933 */
1934 /* Previously this was only done for xterm and alikes. I don't see a
1935 * reason why it would fail for other terminal emulators.
1936 * if (term_is_xterm) */
1937 {
1938 Window root;
1939 Window parent;
1940 Window win = x11_window;
1941 Window *children;
1942 unsigned int num_children;
1943
1944 while (!status || text_prop.value == NULL)
1945 {
1946 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1947 &num_children))
1948 break;
1949 if (children)
1950 XFree((void *)children);
1951 if (parent == root || parent == 0)
1952 break;
1953
1954 win = parent;
1955 if (get_title)
1956 status = XGetWMName(x11_display, win, &text_prop);
1957 else
1958 status = XGetWMIconName(x11_display, win, &text_prop);
1959 }
1960 }
1961 if (status && text_prop.value != NULL)
1962 {
1963 retval = TRUE;
1964 if (!test_only)
1965 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001966#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1967 if (text_prop.encoding == XA_STRING
1968# ifdef FEAT_MBYTE
1969 && !has_mbyte
1970# endif
1971 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 {
1973#endif
1974 if (get_title)
1975 oldtitle = vim_strsave((char_u *)text_prop.value);
1976 else
1977 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001978#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 }
1980 else
1981 {
1982 char **cl;
1983 Status transform_status;
1984 int n = 0;
1985
1986 transform_status = XmbTextPropertyToTextList(x11_display,
1987 &text_prop,
1988 &cl, &n);
1989 if (transform_status >= Success && n > 0 && cl[0])
1990 {
1991 if (get_title)
1992 oldtitle = vim_strsave((char_u *) cl[0]);
1993 else
1994 oldicon = vim_strsave((char_u *) cl[0]);
1995 XFreeStringList(cl);
1996 }
1997 else
1998 {
1999 if (get_title)
2000 oldtitle = vim_strsave((char_u *)text_prop.value);
2001 else
2002 oldicon = vim_strsave((char_u *)text_prop.value);
2003 }
2004 }
2005#endif
2006 }
2007 XFree((void *)text_prop.value);
2008 }
2009 }
2010 return retval;
2011}
2012
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002013/* Xutf8 functions are not avaialble on older systems. Note that on some
2014 * systems X_HAVE_UTF8_STRING may be defined in a header file but
2015 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
2016 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002018# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019# define USE_UTF8_STRING
2020# endif
2021#endif
2022
2023/*
2024 * Set x11 Window Title
2025 *
2026 * get_x11_windis() must be called before this and have returned OK
2027 */
2028 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002029set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030{
2031 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2032 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2033 * supported everywhere and STRING doesn't work for multi-byte titles.
2034 */
2035#ifdef USE_UTF8_STRING
2036 if (enc_utf8)
2037 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2038 NULL, NULL, 0, NULL, NULL, NULL);
2039 else
2040#endif
2041 {
2042#if XtSpecificationRelease >= 4
2043# ifdef FEAT_XFONTSET
2044 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2045 NULL, NULL, 0, NULL, NULL, NULL);
2046# else
2047 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002048 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049
2050 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002051 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 XSetWMProperties(x11_display, x11_window, &text_prop,
2053 NULL, NULL, 0, NULL, NULL, NULL);
2054# endif
2055#else
2056 XStoreName(x11_display, x11_window, (char *)title);
2057#endif
2058 }
2059 XFlush(x11_display);
2060}
2061
2062/*
2063 * Set x11 Window icon
2064 *
2065 * get_x11_windis() must be called before this and have returned OK
2066 */
2067 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002068set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069{
2070 /* See above for comments about using X*SetWMProperties(). */
2071#ifdef USE_UTF8_STRING
2072 if (enc_utf8)
2073 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2074 NULL, 0, NULL, NULL, NULL);
2075 else
2076#endif
2077 {
2078#if XtSpecificationRelease >= 4
2079# ifdef FEAT_XFONTSET
2080 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2081 NULL, 0, NULL, NULL, NULL);
2082# else
2083 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002084 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002086 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2088 NULL, 0, NULL, NULL, NULL);
2089# endif
2090#else
2091 XSetIconName(x11_display, x11_window, (char *)icon);
2092#endif
2093 }
2094 XFlush(x11_display);
2095}
2096
2097#else /* FEAT_X11 */
2098
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002100get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101{
2102 return FALSE;
2103}
2104
2105 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002106get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107{
2108 if (!test_only)
2109 {
2110 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002111 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002113 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 }
2115 return FALSE;
2116}
2117
2118#endif /* FEAT_X11 */
2119
2120 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002121mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122{
2123 return get_x11_title(TRUE);
2124}
2125
2126 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002127mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128{
2129 return get_x11_icon(TRUE);
2130}
2131
2132/*
2133 * Set the window title and icon.
2134 */
2135 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002136mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137{
2138 int type = 0;
2139 static int recursive = 0;
2140
2141 if (T_NAME == NULL) /* no terminal name (yet) */
2142 return;
2143 if (title == NULL && icon == NULL) /* nothing to do */
2144 return;
2145
2146 /* When one of the X11 functions causes a deadly signal, we get here again
2147 * recursively. Avoid hanging then (something is probably locked). */
2148 if (recursive)
2149 return;
2150 ++recursive;
2151
2152 /*
2153 * if the window ID and the display is known, we may use X11 calls
2154 */
2155#ifdef FEAT_X11
2156 if (get_x11_windis() == OK)
2157 type = 1;
2158#else
2159# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2160 if (gui.in_use)
2161 type = 1;
2162# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163#endif
2164
2165 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002166 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 * than x11 calls, because the x11 calls don't always work
2168 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 if ((type || *T_TS != NUL) && title != NULL)
2170 {
2171 if (oldtitle == NULL
2172#ifdef FEAT_GUI
2173 && !gui.in_use
2174#endif
2175 ) /* first call but not in GUI, save title */
2176 (void)get_x11_title(FALSE);
2177
2178 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2179 term_settitle(title);
2180#ifdef FEAT_X11
2181 else
2182# ifdef FEAT_GUI_GTK
2183 if (!gui.in_use) /* don't do this if GTK+ is running */
2184# endif
2185 set_x11_title(title); /* x11 */
2186#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002187#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2189 else
2190 gui_mch_settitle(title, icon);
2191#endif
2192 did_set_title = TRUE;
2193 }
2194
2195 if ((type || *T_CIS != NUL) && icon != NULL)
2196 {
2197 if (oldicon == NULL
2198#ifdef FEAT_GUI
2199 && !gui.in_use
2200#endif
2201 ) /* first call, save icon */
2202 get_x11_icon(FALSE);
2203
2204 if (*T_CIS != NUL)
2205 {
2206 out_str(T_CIS); /* set icon start */
2207 out_str_nf(icon);
2208 out_str(T_CIE); /* set icon end */
2209 out_flush();
2210 }
2211#ifdef FEAT_X11
2212 else
2213# ifdef FEAT_GUI_GTK
2214 if (!gui.in_use) /* don't do this if GTK+ is running */
2215# endif
2216 set_x11_icon(icon); /* x11 */
2217#endif
2218 did_set_icon = TRUE;
2219 }
2220 --recursive;
2221}
2222
2223/*
2224 * Restore the window/icon title.
2225 * "which" is one of:
2226 * 1 only restore title
2227 * 2 only restore icon
2228 * 3 restore title and icon
2229 */
2230 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002231mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232{
2233 /* only restore the title or icon when it has been set */
2234 mch_settitle(((which & 1) && did_set_title) ?
2235 (oldtitle ? oldtitle : p_titleold) : NULL,
2236 ((which & 2) && did_set_icon) ? oldicon : NULL);
2237}
2238
2239#endif /* FEAT_TITLE */
2240
2241/*
2242 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002243 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 */
2245 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002246vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247{
2248 if (name == NULL)
2249 return FALSE;
2250 return (STRNICMP(name, "xterm", 5) == 0
2251 || STRNICMP(name, "nxterm", 6) == 0
2252 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002253 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254 || STRNICMP(name, "rxvt", 4) == 0
2255 || STRCMP(name, "builtin_xterm") == 0);
2256}
2257
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002258#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2259/*
2260 * Return TRUE if "name" appears to be that of a terminal
2261 * known to support the xterm-style mouse protocol.
2262 * Relies on term_is_xterm having been set to its correct value.
2263 */
2264 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002265use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002266{
2267 return (name != NULL
2268 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2269}
2270#endif
2271
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2273/*
2274 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2275 * Return 1 for "xterm".
2276 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002277 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002278 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 */
2280 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002281use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002283 if (ttym_flags == TTYM_SGR)
2284 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002285 if (ttym_flags == TTYM_URXVT)
2286 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 if (ttym_flags == TTYM_XTERM2)
2288 return 2;
2289 if (ttym_flags == TTYM_XTERM)
2290 return 1;
2291 return 0;
2292}
2293#endif
2294
2295 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002296vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297{
2298 if (name == NULL)
2299 return FALSE;
2300 return (STRNICMP(name, "iris-ansi", 9) == 0
2301 || STRCMP(name, "builtin_iris-ansi") == 0);
2302}
2303
2304 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002305vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306{
2307 if (name == NULL)
2308 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002309 /* catch VT100 - VT5xx */
2310 return ((STRNICMP(name, "vt", 2) == 0
2311 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 || STRCMP(name, "builtin_vt320") == 0);
2313}
2314
2315/*
2316 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2317 * This should include all windowed terminal emulators.
2318 */
2319 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002320vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
2322 if (name == NULL)
2323 return FALSE;
2324 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2325 return TRUE;
2326 return ( STRNICMP(name, "hpterm", 6) == 0
2327 || STRNICMP(name, "sun-cmd", 7) == 0
2328 || STRNICMP(name, "screen", 6) == 0
2329 || STRNICMP(name, "dtterm", 6) == 0);
2330}
2331
2332/*
2333 * Insert user name in s[len].
2334 * Return OK if a name found.
2335 */
2336 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002337mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338{
2339#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002340 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 return OK;
2342#else
2343 return mch_get_uname(getuid(), s, len);
2344#endif
2345}
2346
2347/*
2348 * Insert user name for "uid" in s[len].
2349 * Return OK if a name found.
2350 */
2351 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002352mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353{
2354#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2355 struct passwd *pw;
2356
2357 if ((pw = getpwuid(uid)) != NULL
2358 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2359 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002360 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361 return OK;
2362 }
2363#endif
2364 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2365 return FAIL; /* a number is not a name */
2366}
2367
2368/*
2369 * Insert host name is s[len].
2370 */
2371
2372#ifdef HAVE_SYS_UTSNAME_H
2373 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002374mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375{
2376 struct utsname vutsname;
2377
2378 if (uname(&vutsname) < 0)
2379 *s = NUL;
2380 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002381 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382}
2383#else /* HAVE_SYS_UTSNAME_H */
2384
2385# ifdef HAVE_SYS_SYSTEMINFO_H
2386# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2387# endif
2388
2389 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002390mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391{
2392# ifdef VAXC
2393 vaxc$gethostname((char *)s, len);
2394# else
2395 gethostname((char *)s, len);
2396# endif
2397 s[len - 1] = NUL; /* make sure it's terminated */
2398}
2399#endif /* HAVE_SYS_UTSNAME_H */
2400
2401/*
2402 * return process ID
2403 */
2404 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002405mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406{
2407 return (long)getpid();
2408}
2409
2410#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002411static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412
2413 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002414strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415{
2416 extern int sys_nerr;
2417 extern char *sys_errlist[];
2418 static char er[20];
2419
2420 if (err > 0 && err < sys_nerr)
2421 return (sys_errlist[err]);
2422 sprintf(er, "Error %d", err);
2423 return er;
2424}
2425#endif
2426
2427/*
2428 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2429 * Return OK for success, FAIL for failure.
2430 */
2431 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002432mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433{
2434#if defined(USE_GETCWD)
2435 if (getcwd((char *)buf, len) == NULL)
2436 {
2437 STRCPY(buf, strerror(errno));
2438 return FAIL;
2439 }
2440 return OK;
2441#else
2442 return (getwd((char *)buf) != NULL ? OK : FAIL);
2443#endif
2444}
2445
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002447 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 *
2449 * return FAIL for failure, OK for success
2450 */
2451 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002452mch_FullName(
2453 char_u *fname,
2454 char_u *buf,
2455 int len,
2456 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457{
2458 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002459#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002460 int fd = -1;
2461 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002462#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463 char_u olddir[MAXPATHL];
2464 char_u *p;
2465 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002466#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002467 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2468 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002469#endif
2470
Bram Moolenaar38323e42007-03-06 19:22:53 +00002471#ifdef VMS
2472 fname = vms_fixfilename(fname);
2473#endif
2474
Bram Moolenaara2442432007-04-26 14:26:37 +00002475#ifdef __CYGWIN__
2476 /*
2477 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2478 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002479# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002480 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2481 * a forward slash. */
2482 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2483 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002484# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002485 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002486# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002487 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002488#endif
2489
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002490 /* Expand it if forced or not an absolute path.
2491 * Do not do it for "/file", the result is always "/". */
2492 if ((force || !mch_isFullName(fname))
2493 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 {
2495 /*
2496 * If the file name has a path, change to that directory for a moment,
2497 * and then do the getwd() (and get back to where we were).
2498 * This will get the correct path name with "../" things.
2499 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002500 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002501 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002502#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 /*
2504 * Use fchdir() if possible, it's said to be faster and more
2505 * reliable. But on SunOS 4 it might not work. Check this by
2506 * doing a fchdir() right now.
2507 */
2508 if (!dont_fchdir)
2509 {
2510 fd = open(".", O_RDONLY | O_EXTRA, 0);
2511 if (fd >= 0 && fchdir(fd) < 0)
2512 {
2513 close(fd);
2514 fd = -1;
2515 dont_fchdir = TRUE; /* don't try again */
2516 }
2517 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519
2520 /* Only change directory when we are sure we can return to where
2521 * we are now. After doing "su" chdir(".") might not work. */
2522 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002523#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002525#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 (mch_dirname(olddir, MAXPATHL) == FAIL
2527 || mch_chdir((char *)olddir) != 0))
2528 {
2529 p = NULL; /* can't get current dir: don't chdir */
2530 retval = FAIL;
2531 }
2532 else
2533 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 /* The directory is copied into buf[], to be able to remove
2535 * the file name without changing it (could be a string in
2536 * read-only memory) */
2537 if (p - fname >= len)
2538 retval = FAIL;
2539 else
2540 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002541 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (mch_chdir((char *)buf))
2543 retval = FAIL;
2544 else
2545 fname = p + 1;
2546 *buf = NUL;
2547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 }
2549 }
2550 if (mch_dirname(buf, len) == FAIL)
2551 {
2552 retval = FAIL;
2553 *buf = NUL;
2554 }
2555 if (p != NULL)
2556 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002557#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 if (fd >= 0)
2559 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002560 if (p_verbose >= 5)
2561 {
2562 verbose_enter();
2563 MSG("fchdir() to previous dir");
2564 verbose_leave();
2565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 l = fchdir(fd);
2567 close(fd);
2568 }
2569 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 l = mch_chdir((char *)olddir);
2572 if (l != 0)
2573 EMSG(_(e_prev_dir));
2574 }
2575
2576 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002577 if (l >= len - 1)
2578 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002579#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002580 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002582 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002583#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002585
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002587 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 return FAIL;
2589
2590 /* Do not append ".", "/dir/." is equal to "/dir". */
2591 if (STRCMP(fname, ".") != 0)
2592 STRCAT(buf, fname);
2593
2594 return OK;
2595}
2596
2597/*
2598 * Return TRUE if "fname" does not depend on the current directory.
2599 */
2600 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002601mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602{
2603#ifdef __EMX__
2604 return _fnisabs(fname);
2605#else
2606# ifdef VMS
2607 return ( fname[0] == '/' || fname[0] == '.' ||
2608 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2609 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2610 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2611# else
2612 return (*fname == '/' || *fname == '~');
2613# endif
2614#endif
2615}
2616
Bram Moolenaar24552be2005-12-10 20:17:30 +00002617#if defined(USE_FNAME_CASE) || defined(PROTO)
2618/*
2619 * Set the case of the file name, if it already exists. This will cause the
2620 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002621 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002622 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002623 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002624fname_case(
2625 char_u *name,
2626 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002627{
2628 struct stat st;
2629 char_u *slash, *tail;
2630 DIR *dirp;
2631 struct dirent *dp;
2632
2633 if (lstat((char *)name, &st) >= 0)
2634 {
2635 /* Open the directory where the file is located. */
2636 slash = vim_strrchr(name, '/');
2637 if (slash == NULL)
2638 {
2639 dirp = opendir(".");
2640 tail = name;
2641 }
2642 else
2643 {
2644 *slash = NUL;
2645 dirp = opendir((char *)name);
2646 *slash = '/';
2647 tail = slash + 1;
2648 }
2649
2650 if (dirp != NULL)
2651 {
2652 while ((dp = readdir(dirp)) != NULL)
2653 {
2654 /* Only accept names that differ in case and are the same byte
2655 * length. TODO: accept different length name. */
2656 if (STRICMP(tail, dp->d_name) == 0
2657 && STRLEN(tail) == STRLEN(dp->d_name))
2658 {
2659 char_u newname[MAXPATHL + 1];
2660 struct stat st2;
2661
2662 /* Verify the inode is equal. */
2663 vim_strncpy(newname, name, MAXPATHL);
2664 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2665 MAXPATHL - (tail - name));
2666 if (lstat((char *)newname, &st2) >= 0
2667 && st.st_ino == st2.st_ino
2668 && st.st_dev == st2.st_dev)
2669 {
2670 STRCPY(tail, dp->d_name);
2671 break;
2672 }
2673 }
2674 }
2675
2676 closedir(dirp);
2677 }
2678 }
2679}
2680#endif
2681
Bram Moolenaar071d4272004-06-13 20:20:40 +00002682/*
2683 * Get file permissions for 'name'.
2684 * Returns -1 when it doesn't exist.
2685 */
2686 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002687mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688{
2689 struct stat statb;
2690
2691 /* Keep the #ifdef outside of stat(), it may be a macro. */
2692#ifdef VMS
2693 if (stat((char *)vms_fixfilename(name), &statb))
2694#else
2695 if (stat((char *)name, &statb))
2696#endif
2697 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002698#ifdef __INTERIX
2699 /* The top bit makes the value negative, which means the file doesn't
2700 * exist. Remove the bit, we don't use it. */
2701 return statb.st_mode & ~S_ADDACE;
2702#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002704#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705}
2706
2707/*
2708 * set file permission for 'name' to 'perm'
2709 *
2710 * return FAIL for failure, OK otherwise
2711 */
2712 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002713mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714{
2715 return (chmod((char *)
2716#ifdef VMS
2717 vms_fixfilename(name),
2718#else
2719 name,
2720#endif
2721 (mode_t)perm) == 0 ? OK : FAIL);
2722}
2723
2724#if defined(HAVE_ACL) || defined(PROTO)
2725# ifdef HAVE_SYS_ACL_H
2726# include <sys/acl.h>
2727# endif
2728# ifdef HAVE_SYS_ACCESS_H
2729# include <sys/access.h>
2730# endif
2731
2732# ifdef HAVE_SOLARIS_ACL
2733typedef struct vim_acl_solaris_T {
2734 int acl_cnt;
2735 aclent_t *acl_entry;
2736} vim_acl_solaris_T;
2737# endif
2738
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002739#if defined(HAVE_SELINUX) || defined(PROTO)
2740/*
2741 * Copy security info from "from_file" to "to_file".
2742 */
2743 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002744mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002745{
2746 if (from_file == NULL)
2747 return;
2748
2749 if (selinux_enabled == -1)
2750 selinux_enabled = is_selinux_enabled();
2751
2752 if (selinux_enabled > 0)
2753 {
2754 security_context_t from_context = NULL;
2755 security_context_t to_context = NULL;
2756
2757 if (getfilecon((char *)from_file, &from_context) < 0)
2758 {
2759 /* If the filesystem doesn't support extended attributes,
2760 the original had no special security context and the
2761 target cannot have one either. */
2762 if (errno == EOPNOTSUPP)
2763 return;
2764
2765 MSG_PUTS(_("\nCould not get security context for "));
2766 msg_outtrans(from_file);
2767 msg_putchar('\n');
2768 return;
2769 }
2770 if (getfilecon((char *)to_file, &to_context) < 0)
2771 {
2772 MSG_PUTS(_("\nCould not get security context for "));
2773 msg_outtrans(to_file);
2774 msg_putchar('\n');
2775 freecon (from_context);
2776 return ;
2777 }
2778 if (strcmp(from_context, to_context) != 0)
2779 {
2780 if (setfilecon((char *)to_file, from_context) < 0)
2781 {
2782 MSG_PUTS(_("\nCould not set security context for "));
2783 msg_outtrans(to_file);
2784 msg_putchar('\n');
2785 }
2786 }
2787 freecon(to_context);
2788 freecon(from_context);
2789 }
2790}
2791#endif /* HAVE_SELINUX */
2792
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002793#if defined(HAVE_SMACK) && !defined(PROTO)
2794/*
2795 * Copy security info from "from_file" to "to_file".
2796 */
2797 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002798mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002799{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002800 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002801 {
2802 XATTR_NAME_SMACK,
2803 XATTR_NAME_SMACKEXEC,
2804 XATTR_NAME_SMACKMMAP
2805 };
2806
2807 char buffer[SMACK_LABEL_LEN];
2808 const char *name;
2809 int index;
2810 int ret;
2811 ssize_t size;
2812
2813 if (from_file == NULL)
2814 return;
2815
2816 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2817 / sizeof(smack_copied_attributes)[0]) ; index++)
2818 {
2819 /* get the name of the attribute to copy */
2820 name = smack_copied_attributes[index];
2821
2822 /* get the value of the attribute in buffer */
2823 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2824 if (size >= 0)
2825 {
2826 /* copy the attribute value of buffer */
2827 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2828 if (ret < 0)
2829 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002830 vim_snprintf((char *)IObuff, IOSIZE,
2831 _("Could not set security context %s for %s"),
2832 name, to_file);
2833 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002834 msg_putchar('\n');
2835 }
2836 }
2837 else
2838 {
2839 /* what reason of not having the attribute value? */
2840 switch (errno)
2841 {
2842 case ENOTSUP:
2843 /* extended attributes aren't supported or enabled */
2844 /* should a message be echoed? not sure... */
2845 return; /* leave because it isn't usefull to continue */
2846
2847 case ERANGE:
2848 default:
2849 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002850 vim_snprintf((char *)IObuff, IOSIZE,
2851 _("Could not get security context %s for %s. Removing it!"),
2852 name, from_file);
2853 msg_puts(IObuff);
2854 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002855 /* FALLTHROUGH to remove the attribute */
2856
2857 case ENODATA:
2858 /* no attribute of this name */
2859 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002860 /* Silently ignore errors, apparently this happens when
2861 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002862 break;
2863 }
2864 }
2865 }
2866}
2867#endif /* HAVE_SMACK */
2868
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869/*
2870 * Return a pointer to the ACL of file "fname" in allocated memory.
2871 * Return NULL if the ACL is not available for whatever reason.
2872 */
2873 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002874mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875{
2876 vim_acl_T ret = NULL;
2877#ifdef HAVE_POSIX_ACL
2878 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2879#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002880#ifdef HAVE_SOLARIS_ZFS_ACL
2881 acl_t *aclent;
2882
2883 if (acl_get((char *)fname, 0, &aclent) < 0)
2884 return NULL;
2885 ret = (vim_acl_T)aclent;
2886#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887#ifdef HAVE_SOLARIS_ACL
2888 vim_acl_solaris_T *aclent;
2889
2890 aclent = malloc(sizeof(vim_acl_solaris_T));
2891 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2892 {
2893 free(aclent);
2894 return NULL;
2895 }
2896 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2897 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2898 {
2899 free(aclent->acl_entry);
2900 free(aclent);
2901 return NULL;
2902 }
2903 ret = (vim_acl_T)aclent;
2904#else
2905#if defined(HAVE_AIX_ACL)
2906 int aclsize;
2907 struct acl *aclent;
2908
2909 aclsize = sizeof(struct acl);
2910 aclent = malloc(aclsize);
2911 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2912 {
2913 if (errno == ENOSPC)
2914 {
2915 aclsize = aclent->acl_len;
2916 aclent = realloc(aclent, aclsize);
2917 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2918 {
2919 free(aclent);
2920 return NULL;
2921 }
2922 }
2923 else
2924 {
2925 free(aclent);
2926 return NULL;
2927 }
2928 }
2929 ret = (vim_acl_T)aclent;
2930#endif /* HAVE_AIX_ACL */
2931#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002932#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933#endif /* HAVE_POSIX_ACL */
2934 return ret;
2935}
2936
2937/*
2938 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2939 */
2940 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002941mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942{
2943 if (aclent == NULL)
2944 return;
2945#ifdef HAVE_POSIX_ACL
2946 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2947#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002948#ifdef HAVE_SOLARIS_ZFS_ACL
2949 acl_set((char *)fname, (acl_t *)aclent);
2950#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951#ifdef HAVE_SOLARIS_ACL
2952 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2953 ((vim_acl_solaris_T *)aclent)->acl_entry);
2954#else
2955#ifdef HAVE_AIX_ACL
2956 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2957#endif /* HAVE_AIX_ACL */
2958#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002959#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960#endif /* HAVE_POSIX_ACL */
2961}
2962
2963 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002964mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965{
2966 if (aclent == NULL)
2967 return;
2968#ifdef HAVE_POSIX_ACL
2969 acl_free((acl_t)aclent);
2970#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002971#ifdef HAVE_SOLARIS_ZFS_ACL
2972 acl_free((acl_t *)aclent);
2973#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974#ifdef HAVE_SOLARIS_ACL
2975 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2976 free(aclent);
2977#else
2978#ifdef HAVE_AIX_ACL
2979 free(aclent);
2980#endif /* HAVE_AIX_ACL */
2981#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002982#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983#endif /* HAVE_POSIX_ACL */
2984}
2985#endif
2986
2987/*
2988 * Set hidden flag for "name".
2989 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002991mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992{
2993 /* can't hide a file */
2994}
2995
2996/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002997 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998 * return FALSE if "name" is not a directory
2999 * return FALSE for error
3000 */
3001 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003002mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003{
3004 struct stat statb;
3005
3006 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3007 return FALSE;
3008 if (stat((char *)name, &statb))
3009 return FALSE;
3010#ifdef _POSIX_SOURCE
3011 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3012#else
3013 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3014#endif
3015}
3016
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003017/*
3018 * return TRUE if "name" is a directory, NOT a symlink to a directory
3019 * return FALSE if "name" is not a directory
3020 * return FALSE for error
3021 */
3022 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003023mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003024{
3025 struct stat statb;
3026
3027 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3028 return FALSE;
3029 if (lstat((char *)name, &statb))
3030 return FALSE;
3031#ifdef _POSIX_SOURCE
3032 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3033#else
3034 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3035#endif
3036}
3037
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003038static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039
3040/*
3041 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3042 */
3043 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003044executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045{
3046 struct stat st;
3047
3048 if (stat((char *)name, &st))
3049 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003050#ifdef VMS
3051 /* Like on Unix system file can have executable rights but not necessarily
3052 * be an executable, but on Unix is not a default for an ordianry file to
3053 * have an executable flag - on VMS it is in most cases.
3054 * Therefore, this check does not have any sense - let keep us to the
3055 * conventions instead:
3056 * *.COM and *.EXE files are the executables - the rest are not. This is
3057 * not ideal but better then it was.
3058 */
3059 int vms_executable = 0;
3060 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3061 {
3062 if (strstr(vms_tolower((char*)name),".exe") != NULL
3063 || strstr(vms_tolower((char*)name),".com")!= NULL)
3064 vms_executable = 1;
3065 }
3066 return vms_executable;
3067#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003069#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070}
3071
3072/*
3073 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003074 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 * Return -1 if unknown.
3076 */
3077 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003078mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079{
3080 char_u *buf;
3081 char_u *p, *e;
3082 int retval;
3083
Bram Moolenaarb5971142015-03-21 17:32:19 +01003084 /* When "use_path" is false and if it's an absolute or relative path don't
3085 * need to use $PATH. */
3086 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3087 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003088 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003089 /* There must be a path separator, files in the current directory
3090 * can't be executed. */
3091 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003092 {
3093 if (path != NULL)
3094 {
3095 if (name[0] == '.')
3096 *path = FullName_save(name, TRUE);
3097 else
3098 *path = vim_strsave(name);
3099 }
3100 return TRUE;
3101 }
3102 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003103 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
3105 p = (char_u *)getenv("PATH");
3106 if (p == NULL || *p == NUL)
3107 return -1;
3108 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3109 if (buf == NULL)
3110 return -1;
3111
3112 /*
3113 * Walk through all entries in $PATH to check if "name" exists there and
3114 * is an executable file.
3115 */
3116 for (;;)
3117 {
3118 e = (char_u *)strchr((char *)p, ':');
3119 if (e == NULL)
3120 e = p + STRLEN(p);
3121 if (e - p <= 1) /* empty entry means current dir */
3122 STRCPY(buf, "./");
3123 else
3124 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003125 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 add_pathsep(buf);
3127 }
3128 STRCAT(buf, name);
3129 retval = executable_file(buf);
3130 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003131 {
3132 if (path != NULL)
3133 {
3134 if (buf[0] == '.')
3135 *path = FullName_save(buf, TRUE);
3136 else
3137 *path = vim_strsave(buf);
3138 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141
3142 if (*e != ':')
3143 break;
3144 p = e + 1;
3145 }
3146
3147 vim_free(buf);
3148 return retval;
3149}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150
3151/*
3152 * Check what "name" is:
3153 * NODE_NORMAL: file or directory (or doesn't exist)
3154 * NODE_WRITABLE: writable device, socket, fifo, etc.
3155 * NODE_OTHER: non-writable things
3156 */
3157 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003158mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159{
3160 struct stat st;
3161
3162 if (stat((char *)name, &st))
3163 return NODE_NORMAL;
3164 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3165 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3167 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 /* Everything else is writable? */
3169 return NODE_WRITABLE;
3170}
3171
3172 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003173mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174{
3175#ifdef HAVE_CHECK_STACK_GROWTH
3176 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 check_stack_growth((char *)&i);
3179
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003180# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 get_stack_limit();
3182# endif
3183
3184#endif
3185
3186 /*
3187 * Setup an alternative stack for signals. Helps to catch signals when
3188 * running out of stack space.
3189 * Use of sigaltstack() is preferred, it's more portable.
3190 * Ignore any errors.
3191 */
3192#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003193 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 init_signal_stack();
3195#endif
3196}
3197
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003198#if defined(EXITFREE) || defined(PROTO)
3199 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003200mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003201{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003202# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3203 if (clip_star.owned)
3204 clip_lose_selection(&clip_star);
3205 if (clip_plus.owned)
3206 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003207# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003208# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003209 if (xterm_Shell != (Widget)0)
3210 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003211# ifndef LESSTIF_VERSION
3212 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003213 if (xterm_dpy != NULL)
3214 XtCloseDisplay(xterm_dpy);
3215 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003216 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003217 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003218# ifdef FEAT_X11
3219 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3220# endif
3221 }
3222# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003223# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003224# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003225 if (x11_display != NULL
3226# ifdef FEAT_XCLIPBOARD
3227 && x11_display != xterm_dpy
3228# endif
3229 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003230 XCloseDisplay(x11_display);
3231# endif
3232# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3233 vim_free(signal_stack);
3234 signal_stack = NULL;
3235# endif
3236# ifdef FEAT_TITLE
3237 vim_free(oldtitle);
3238 vim_free(oldicon);
3239# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003240}
3241#endif
3242
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003243static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
3245/*
3246 * Output a newline when exiting.
3247 * Make sure the newline goes to the same stream as the text.
3248 */
3249 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003250exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003252 if (silent_mode)
3253 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 if (newline_on_exit || msg_didout)
3255 {
3256 if (msg_use_printf())
3257 {
3258 if (info_message)
3259 mch_msg("\n");
3260 else
3261 mch_errmsg("\r\n");
3262 }
3263 else
3264 out_char('\n');
3265 }
3266 else
3267 {
3268 restore_cterm_colors(); /* get original colors back */
3269 msg_clr_eos_force(); /* clear the rest of the display */
3270 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3271 }
3272}
3273
3274 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003275mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276{
3277 exiting = TRUE;
3278
3279#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3280 x11_export_final_selection();
3281#endif
3282
3283#ifdef FEAT_GUI
3284 if (!gui.in_use)
3285#endif
3286 {
3287 settmode(TMODE_COOK);
3288#ifdef FEAT_TITLE
3289 mch_restore_title(3); /* restore xterm title and icon name */
3290#endif
3291 /*
3292 * When t_ti is not empty but it doesn't cause swapping terminal
3293 * pages, need to output a newline when msg_didout is set. But when
3294 * t_ti does swap pages it should not go to the shell page. Do this
3295 * before stoptermcap().
3296 */
3297 if (swapping_screen() && !newline_on_exit)
3298 exit_scroll();
3299
3300 /* Stop termcap: May need to check for T_CRV response, which
3301 * requires RAW mode. */
3302 stoptermcap();
3303
3304 /*
3305 * A newline is only required after a message in the alternate screen.
3306 * This is set to TRUE by wait_return().
3307 */
3308 if (!swapping_screen() || newline_on_exit)
3309 exit_scroll();
3310
3311 /* Cursor may have been switched off without calling starttermcap()
3312 * when doing "vim -u vimrc" and vimrc contains ":q". */
3313 if (full_screen)
3314 cursor_on();
3315 }
3316 out_flush();
3317 ml_close_all(TRUE); /* remove all memfiles */
3318 may_core_dump();
3319#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 gui_exit(r);
3322#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003323
Bram Moolenaar56718732006-03-15 22:53:57 +00003324#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003325 mac_conv_cleanup();
3326#endif
3327
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328#ifdef __QNX__
3329 /* A core dump won't be created if the signal handler
3330 * doesn't return, so we can't call exit() */
3331 if (deadly_signal != 0)
3332 return;
3333#endif
3334
Bram Moolenaar009b2592004-10-24 19:18:58 +00003335#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003336 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003337#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003338
3339#ifdef EXITFREE
3340 free_all_mem();
3341#endif
3342
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 exit(r);
3344}
3345
3346 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003347may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348{
3349 if (deadly_signal != 0)
3350 {
3351 signal(deadly_signal, SIG_DFL);
3352 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3353 }
3354}
3355
3356#ifndef VMS
3357
3358 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003359mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360{
3361 static int first = TRUE;
3362
3363 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3364#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3365 /*
3366 * for "new" tty systems
3367 */
3368# ifdef HAVE_TERMIOS_H
3369 static struct termios told;
3370 struct termios tnew;
3371# else
3372 static struct termio told;
3373 struct termio tnew;
3374# endif
3375
3376 if (first)
3377 {
3378 first = FALSE;
3379# if defined(HAVE_TERMIOS_H)
3380 tcgetattr(read_cmd_fd, &told);
3381# else
3382 ioctl(read_cmd_fd, TCGETA, &told);
3383# endif
3384 }
3385
3386 tnew = told;
3387 if (tmode == TMODE_RAW)
3388 {
3389 /*
3390 * ~ICRNL enables typing ^V^M
3391 */
3392 tnew.c_iflag &= ~ICRNL;
3393 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3394# if defined(IEXTEN) && !defined(__MINT__)
3395 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3396 /* but it breaks function keys on MINT */
3397# endif
3398 );
3399# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3400 tnew.c_oflag &= ~ONLCR;
3401# endif
3402 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3403 tnew.c_cc[VTIME] = 0; /* don't wait */
3404 }
3405 else if (tmode == TMODE_SLEEP)
3406 tnew.c_lflag &= ~(ECHO);
3407
3408# if defined(HAVE_TERMIOS_H)
3409 {
3410 int n = 10;
3411
3412 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3413 * few times. */
3414 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3415 && errno == EINTR && n > 0)
3416 --n;
3417 }
3418# else
3419 ioctl(read_cmd_fd, TCSETA, &tnew);
3420# endif
3421
3422#else
3423
3424 /*
3425 * for "old" tty systems
3426 */
3427# ifndef TIOCSETN
3428# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3429# endif
3430 static struct sgttyb ttybold;
3431 struct sgttyb ttybnew;
3432
3433 if (first)
3434 {
3435 first = FALSE;
3436 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3437 }
3438
3439 ttybnew = ttybold;
3440 if (tmode == TMODE_RAW)
3441 {
3442 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3443 ttybnew.sg_flags |= RAW;
3444 }
3445 else if (tmode == TMODE_SLEEP)
3446 ttybnew.sg_flags &= ~(ECHO);
3447 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3448#endif
3449 curr_tmode = tmode;
3450}
3451
3452/*
3453 * Try to get the code for "t_kb" from the stty setting
3454 *
3455 * Even if termcap claims a backspace key, the user's setting *should*
3456 * prevail. stty knows more about reality than termcap does, and if
3457 * somebody's usual erase key is DEL (which, for most BSD users, it will
3458 * be), they're going to get really annoyed if their erase key starts
3459 * doing forward deletes for no reason. (Eric Fischer)
3460 */
3461 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003462get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463{
3464 char_u buf[2];
3465 char_u *p;
3466
3467 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3468#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3469 /* for "new" tty systems */
3470# ifdef HAVE_TERMIOS_H
3471 struct termios keys;
3472# else
3473 struct termio keys;
3474# endif
3475
3476# if defined(HAVE_TERMIOS_H)
3477 if (tcgetattr(read_cmd_fd, &keys) != -1)
3478# else
3479 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3480# endif
3481 {
3482 buf[0] = keys.c_cc[VERASE];
3483 intr_char = keys.c_cc[VINTR];
3484#else
3485 /* for "old" tty systems */
3486 struct sgttyb keys;
3487
3488 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3489 {
3490 buf[0] = keys.sg_erase;
3491 intr_char = keys.sg_kill;
3492#endif
3493 buf[1] = NUL;
3494 add_termcode((char_u *)"kb", buf, FALSE);
3495
3496 /*
3497 * If <BS> and <DEL> are now the same, redefine <DEL>.
3498 */
3499 p = find_termcode((char_u *)"kD");
3500 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3501 do_fixdel(NULL);
3502 }
3503#if 0
3504 } /* to keep cindent happy */
3505#endif
3506}
3507
3508#endif /* VMS */
3509
3510#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3511/*
3512 * Set mouse clicks on or off.
3513 */
3514 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003515mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516{
3517 static int ison = FALSE;
3518 int xterm_mouse_vers;
3519
3520 if (on == ison) /* return quickly if nothing to do */
3521 return;
3522
3523 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003524
3525# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003526 if (ttym_flags == TTYM_URXVT)
3527 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003528 out_str_nf((char_u *)
3529 (on
3530 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3531 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3532 ison = on;
3533 }
3534# endif
3535
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003536# ifdef FEAT_MOUSE_SGR
3537 if (ttym_flags == TTYM_SGR)
3538 {
3539 out_str_nf((char_u *)
3540 (on
3541 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3542 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3543 ison = on;
3544 }
3545# endif
3546
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 if (xterm_mouse_vers > 0)
3548 {
3549 if (on) /* enable mouse events, use mouse tracking if available */
3550 out_str_nf((char_u *)
3551 (xterm_mouse_vers > 1
3552 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3553 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3554 else /* disable mouse events, could probably always send the same */
3555 out_str_nf((char_u *)
3556 (xterm_mouse_vers > 1
3557 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3558 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3559 ison = on;
3560 }
3561
3562# ifdef FEAT_MOUSE_DEC
3563 else if (ttym_flags == TTYM_DEC)
3564 {
3565 if (on) /* enable mouse events */
3566 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3567 else /* disable mouse events */
3568 out_str_nf((char_u *)"\033['z");
3569 ison = on;
3570 }
3571# endif
3572
3573# ifdef FEAT_MOUSE_GPM
3574 else
3575 {
3576 if (on)
3577 {
3578 if (gpm_open())
3579 ison = TRUE;
3580 }
3581 else
3582 {
3583 gpm_close();
3584 ison = FALSE;
3585 }
3586 }
3587# endif
3588
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003589# ifdef FEAT_SYSMOUSE
3590 else
3591 {
3592 if (on)
3593 {
3594 if (sysmouse_open() == OK)
3595 ison = TRUE;
3596 }
3597 else
3598 {
3599 sysmouse_close();
3600 ison = FALSE;
3601 }
3602 }
3603# endif
3604
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605# ifdef FEAT_MOUSE_JSB
3606 else
3607 {
3608 if (on)
3609 {
3610 /* D - Enable Mouse up/down messages
3611 * L - Enable Left Button Reporting
3612 * M - Enable Middle Button Reporting
3613 * R - Enable Right Button Reporting
3614 * K - Enable SHIFT and CTRL key Reporting
3615 * + - Enable Advanced messaging of mouse moves and up/down messages
3616 * Q - Quiet No Ack
3617 * # - Numeric value of mouse pointer required
3618 * 0 = Multiview 2000 cursor, used as standard
3619 * 1 = Windows Arrow
3620 * 2 = Windows I Beam
3621 * 3 = Windows Hour Glass
3622 * 4 = Windows Cross Hair
3623 * 5 = Windows UP Arrow
3624 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003625# ifdef JSBTERM_MOUSE_NONADVANCED
3626 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3628 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003629# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3631 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 ison = TRUE;
3634 }
3635 else
3636 {
3637 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3638 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3639 ison = FALSE;
3640 }
3641 }
3642# endif
3643# ifdef FEAT_MOUSE_PTERM
3644 else
3645 {
3646 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3647 if (on)
3648 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3649 else
3650 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3651 ison = on;
3652 }
3653# endif
3654}
3655
3656/*
3657 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3658 */
3659 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003660check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661{
3662# ifdef FEAT_MOUSE_XTERM
3663 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003664# ifdef FEAT_MOUSE_URXVT
3665 && use_xterm_mouse() != 3
3666# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667# ifdef FEAT_GUI
3668 && !gui.in_use
3669# endif
3670 )
3671 {
3672 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003673 ? IF_EB("\233M", CSI_STR "M")
3674 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675 if (*p_mouse != NUL)
3676 {
3677 /* force mouse off and maybe on to send possibly new mouse
3678 * activation sequence to the xterm, with(out) drag tracing. */
3679 mch_setmouse(FALSE);
3680 setmouse();
3681 }
3682 }
3683 else
3684 del_mouse_termcode(KS_MOUSE);
3685# endif
3686
3687# ifdef FEAT_MOUSE_GPM
3688 if (!use_xterm_mouse()
3689# ifdef FEAT_GUI
3690 && !gui.in_use
3691# endif
3692 )
3693 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3694# endif
3695
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003696# ifdef FEAT_SYSMOUSE
3697 if (!use_xterm_mouse()
3698# ifdef FEAT_GUI
3699 && !gui.in_use
3700# endif
3701 )
3702 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3703# endif
3704
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003706 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 if (!use_xterm_mouse()
3708# ifdef FEAT_GUI
3709 && !gui.in_use
3710# endif
3711 )
3712 set_mouse_termcode(KS_JSBTERM_MOUSE,
3713 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3714 else
3715 del_mouse_termcode(KS_JSBTERM_MOUSE);
3716# endif
3717
3718# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003719 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720 * define it in the GUI or when using an xterm. */
3721 if (!use_xterm_mouse()
3722# ifdef FEAT_GUI
3723 && !gui.in_use
3724# endif
3725 )
3726 set_mouse_termcode(KS_NETTERM_MOUSE,
3727 (char_u *)IF_EB("\033}", ESC_STR "}"));
3728 else
3729 del_mouse_termcode(KS_NETTERM_MOUSE);
3730# endif
3731
3732# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003733 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003734 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735# ifdef FEAT_GUI
3736 && !gui.in_use
3737# endif
3738 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003739 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3740 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 else
3742 del_mouse_termcode(KS_DEC_MOUSE);
3743# endif
3744# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003745 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003746 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747# ifdef FEAT_GUI
3748 && !gui.in_use
3749# endif
3750 )
3751 set_mouse_termcode(KS_PTERM_MOUSE,
3752 (char_u *) IF_EB("\033[", ESC_STR "["));
3753 else
3754 del_mouse_termcode(KS_PTERM_MOUSE);
3755# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003756# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003757 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003758 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003759# ifdef FEAT_GUI
3760 && !gui.in_use
3761# endif
3762 )
3763 {
3764 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3765 ? IF_EB("\233", CSI_STR)
3766 : IF_EB("\033[", ESC_STR "[")));
3767
3768 if (*p_mouse != NUL)
3769 {
3770 mch_setmouse(FALSE);
3771 setmouse();
3772 }
3773 }
3774 else
3775 del_mouse_termcode(KS_URXVT_MOUSE);
3776# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003777# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003778 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003779 if (use_xterm_mouse() == 4
3780# ifdef FEAT_GUI
3781 && !gui.in_use
3782# endif
3783 )
3784 {
3785 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3786 ? IF_EB("\233<", CSI_STR "<")
3787 : IF_EB("\033[<", ESC_STR "[<")));
3788
3789 if (*p_mouse != NUL)
3790 {
3791 mch_setmouse(FALSE);
3792 setmouse();
3793 }
3794 }
3795 else
3796 del_mouse_termcode(KS_SGR_MOUSE);
3797# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798}
3799#endif
3800
3801/*
3802 * set screen mode, always fails.
3803 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003805mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806{
3807 EMSG(_(e_screenmode));
3808 return FAIL;
3809}
3810
3811#ifndef VMS
3812
3813/*
3814 * Try to get the current window size:
3815 * 1. with an ioctl(), most accurate method
3816 * 2. from the environment variables LINES and COLUMNS
3817 * 3. from the termcap
3818 * 4. keep using the old values
3819 * Return OK when size could be determined, FAIL otherwise.
3820 */
3821 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003822mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823{
3824 long rows = 0;
3825 long columns = 0;
3826 char_u *p;
3827
3828 /*
3829 * For OS/2 use _scrsize().
3830 */
3831# ifdef __EMX__
3832 {
3833 int s[2];
3834
3835 _scrsize(s);
3836 columns = s[0];
3837 rows = s[1];
3838 }
3839# endif
3840
3841 /*
3842 * 1. try using an ioctl. It is the most accurate method.
3843 *
3844 * Try using TIOCGWINSZ first, some systems that have it also define
3845 * TIOCGSIZE but don't have a struct ttysize.
3846 */
3847# ifdef TIOCGWINSZ
3848 {
3849 struct winsize ws;
3850 int fd = 1;
3851
3852 /* When stdout is not a tty, use stdin for the ioctl(). */
3853 if (!isatty(fd) && isatty(read_cmd_fd))
3854 fd = read_cmd_fd;
3855 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3856 {
3857 columns = ws.ws_col;
3858 rows = ws.ws_row;
3859 }
3860 }
3861# else /* TIOCGWINSZ */
3862# ifdef TIOCGSIZE
3863 {
3864 struct ttysize ts;
3865 int fd = 1;
3866
3867 /* When stdout is not a tty, use stdin for the ioctl(). */
3868 if (!isatty(fd) && isatty(read_cmd_fd))
3869 fd = read_cmd_fd;
3870 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3871 {
3872 columns = ts.ts_cols;
3873 rows = ts.ts_lines;
3874 }
3875 }
3876# endif /* TIOCGSIZE */
3877# endif /* TIOCGWINSZ */
3878
3879 /*
3880 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003881 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3882 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003884 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 {
3886 if ((p = (char_u *)getenv("LINES")))
3887 rows = atoi((char *)p);
3888 if ((p = (char_u *)getenv("COLUMNS")))
3889 columns = atoi((char *)p);
3890 }
3891
3892#ifdef HAVE_TGETENT
3893 /*
3894 * 3. try reading "co" and "li" entries from termcap
3895 */
3896 if (columns == 0 || rows == 0)
3897 getlinecol(&columns, &rows);
3898#endif
3899
3900 /*
3901 * 4. If everything fails, use the old values
3902 */
3903 if (columns <= 0 || rows <= 0)
3904 return FAIL;
3905
3906 Rows = rows;
3907 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003908 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 return OK;
3910}
3911
3912/*
3913 * Try to set the window size to Rows and Columns.
3914 */
3915 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003916mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917{
3918 if (*T_CWS)
3919 {
3920 /*
3921 * NOTE: if you get an error here that term_set_winsize() is
3922 * undefined, check the output of configure. It could probably not
3923 * find a ncurses, termcap or termlib library.
3924 */
3925 term_set_winsize((int)Rows, (int)Columns);
3926 out_flush();
3927 screen_start(); /* don't know where cursor is now */
3928 }
3929}
3930
3931#endif /* VMS */
3932
3933/*
3934 * Rows and/or Columns has changed.
3935 */
3936 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003937mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938{
3939 /* Nothing to do. */
3940}
3941
Bram Moolenaar205b8862011-09-07 15:04:31 +02003942/*
3943 * Wait for process "child" to end.
3944 * Return "child" if it exited properly, <= 0 on error.
3945 */
3946 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003947wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003948{
3949 pid_t wait_pid = 0;
3950
3951 while (wait_pid != child)
3952 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003953 /* When compiled with Python threads are probably used, in which case
3954 * wait() sometimes hangs for no obvious reason. Use waitpid()
3955 * instead and loop (like the GUI). Also needed for other interfaces,
3956 * they might call system(). */
3957# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003958 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003959# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003960 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003961# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003962 if (wait_pid == 0)
3963 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003964 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003965 mch_delay(10L, TRUE);
3966 continue;
3967 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003968 if (wait_pid <= 0
3969# ifdef ECHILD
3970 && errno == ECHILD
3971# endif
3972 )
3973 break;
3974 }
3975 return wait_pid;
3976}
3977
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003978#if defined(FEAT_JOB_CHANNEL) || !defined(USE_SYSTEM) || defined(PROTO)
Bram Moolenaar72801402016-02-09 11:37:50 +01003979/*
3980 * Parse "cmd" and put the white-separated parts in "argv".
3981 * "argv" is an allocated array with "argc" entries.
3982 * Returns FAIL when out of memory.
3983 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01003984 int
3985mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
3986{
3987 int i;
3988 char_u *p;
3989 int inquote;
3990
3991 /*
3992 * Do this loop twice:
3993 * 1: find number of arguments
3994 * 2: separate them and build argv[]
3995 */
3996 for (i = 0; i < 2; ++i)
3997 {
Bram Moolenaar6231cb82016-04-26 19:42:42 +02003998 p = skipwhite(cmd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01003999 inquote = FALSE;
4000 *argc = 0;
4001 for (;;)
4002 {
4003 if (i == 1)
4004 (*argv)[*argc] = (char *)p;
4005 ++*argc;
4006 while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
4007 {
4008 if (*p == '"')
4009 inquote = !inquote;
4010 ++p;
4011 }
4012 if (*p == NUL)
4013 break;
4014 if (i == 1)
4015 *p++ = NUL;
4016 p = skipwhite(p);
4017 }
4018 if (*argv == NULL)
4019 {
4020 if (use_shcf)
4021 {
4022 /* Account for possible multiple args in p_shcf. */
4023 p = p_shcf;
4024 for (;;)
4025 {
4026 p = skiptowhite(p);
4027 if (*p == NUL)
4028 break;
4029 ++*argc;
4030 p = skipwhite(p);
4031 }
4032 }
4033
4034 *argv = (char **)alloc((unsigned)((*argc + 4) * sizeof(char *)));
4035 if (*argv == NULL) /* out of memory */
4036 return FAIL;
4037 }
4038 }
4039 return OK;
4040}
4041#endif
4042
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004043#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004044 static void
4045set_child_environment(void)
4046{
4047# ifdef HAVE_SETENV
4048 char envbuf[50];
4049# else
4050 static char envbuf_Rows[20];
4051 static char envbuf_Columns[20];
4052# endif
4053
4054 /* Simulate to have a dumb terminal (for now) */
4055# ifdef HAVE_SETENV
4056 setenv("TERM", "dumb", 1);
4057 sprintf((char *)envbuf, "%ld", Rows);
4058 setenv("ROWS", (char *)envbuf, 1);
4059 sprintf((char *)envbuf, "%ld", Rows);
4060 setenv("LINES", (char *)envbuf, 1);
4061 sprintf((char *)envbuf, "%ld", Columns);
4062 setenv("COLUMNS", (char *)envbuf, 1);
4063# else
4064 /*
4065 * Putenv does not copy the string, it has to remain valid.
4066 * Use a static array to avoid losing allocated memory.
4067 */
4068 putenv("TERM=dumb");
4069 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4070 putenv(envbuf_Rows);
4071 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4072 putenv(envbuf_Rows);
4073 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4074 putenv(envbuf_Columns);
4075# endif
4076}
4077#endif
4078
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004080mch_call_shell(
4081 char_u *cmd,
4082 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083{
4084#ifdef VMS
4085 char *ifn = NULL;
4086 char *ofn = NULL;
4087#endif
4088 int tmode = cur_tmode;
4089#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
4090 int x;
4091# ifndef __EMX__
4092 char_u *newcmd; /* only needed for unix */
4093# else
4094 /*
4095 * Set the preferred shell in the EMXSHELL environment variable (but
4096 * only if it is different from what is already in the environment).
4097 * Emx then takes care of whether to use "/c" or "-c" in an
4098 * intelligent way. Simply pass the whole thing to emx's system() call.
4099 * Emx also starts an interactive shell if system() is passed an empty
4100 * string.
4101 */
4102 char_u *p, *old;
4103
4104 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4105 {
4106 /* should check HAVE_SETENV, but I know we don't have it. */
4107 p = alloc(10 + strlen(p_sh));
4108 if (p)
4109 {
4110 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4111 putenv((char *)p); /* don't free the pointer! */
4112 }
4113 }
4114# endif
4115
4116 out_flush();
4117
4118 if (options & SHELL_COOKED)
4119 settmode(TMODE_COOK); /* set to normal mode */
4120
Bram Moolenaar62b42182010-09-21 22:09:37 +02004121# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004122 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004123 loose_clipboard();
4124# endif
4125
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126# ifdef __EMX__
4127 if (cmd == NULL)
4128 x = system(""); /* this starts an interactive shell in emx */
4129 else
4130 x = system((char *)cmd);
4131 /* system() returns -1 when error occurs in starting shell */
4132 if (x == -1 && !emsg_silent)
4133 {
4134 MSG_PUTS(_("\nCannot execute shell "));
4135 msg_outtrans(p_sh);
4136 msg_putchar('\n');
4137 }
4138# else /* not __EMX__ */
4139 if (cmd == NULL)
4140 x = system((char *)p_sh);
4141 else
4142 {
4143# ifdef VMS
4144 if (ofn = strchr((char *)cmd, '>'))
4145 *ofn++ = '\0';
4146 if (ifn = strchr((char *)cmd, '<'))
4147 {
4148 char *p;
4149
4150 *ifn++ = '\0';
4151 p = strchr(ifn,' '); /* chop off any trailing spaces */
4152 if (p)
4153 *p = '\0';
4154 }
4155 if (ofn)
4156 x = vms_sys((char *)cmd, ofn, ifn);
4157 else
4158 x = system((char *)cmd);
4159# else
4160 newcmd = lalloc(STRLEN(p_sh)
4161 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4162 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4163 if (newcmd == NULL)
4164 x = 0;
4165 else
4166 {
4167 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4168 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4169 (char *)p_shcf,
4170 (char *)cmd);
4171 x = system((char *)newcmd);
4172 vim_free(newcmd);
4173 }
4174# endif
4175 }
4176# ifdef VMS
4177 x = vms_sys_status(x);
4178# endif
4179 if (emsg_silent)
4180 ;
4181 else if (x == 127)
4182 MSG_PUTS(_("\nCannot execute shell sh\n"));
4183# endif /* __EMX__ */
4184 else if (x && !(options & SHELL_SILENT))
4185 {
4186 MSG_PUTS(_("\nshell returned "));
4187 msg_outnum((long)x);
4188 msg_putchar('\n');
4189 }
4190
4191 if (tmode == TMODE_RAW)
4192 settmode(TMODE_RAW); /* set to raw mode */
4193# ifdef FEAT_TITLE
4194 resettitle();
4195# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004196# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4197 restore_clipboard();
4198# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 return x;
4200
4201#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4202
Bram Moolenaardf177f62005-02-22 08:39:57 +00004203# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4204 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205
Bram Moolenaar835dc632016-02-07 14:27:38 +01004206 char_u *newcmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004208 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 pid_t wait_pid = 0;
4210# ifdef HAVE_UNION_WAIT
4211 union wait status;
4212# else
4213 int status = -1;
4214# endif
4215 int retval = -1;
4216 char **argv = NULL;
4217 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004218 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219 int i;
4220 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004222# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 int pty_slave_fd = -1;
4224 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004225# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004226 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 int fd_fromshell[2];
4228 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004229 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230
Bram Moolenaar62b42182010-09-21 22:09:37 +02004231 newcmd = vim_strsave(p_sh);
4232 if (newcmd == NULL) /* out of memory */
4233 goto error;
4234
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 out_flush();
4236 if (options & SHELL_COOKED)
4237 settmode(TMODE_COOK); /* set to normal mode */
4238
Bram Moolenaar835dc632016-02-07 14:27:38 +01004239 if (mch_parse_cmd(newcmd, TRUE, &argv, &argc) == FAIL)
4240 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004241
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242 if (cmd != NULL)
4243 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004244 char_u *s;
4245
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246 if (extra_shell_arg != NULL)
4247 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004248
4249 /* Break 'shellcmdflag' into white separated parts. This doesn't
4250 * handle quoted strings, they are very unlikely to appear. */
4251 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4252 if (p_shcf_copy == NULL) /* out of memory */
4253 goto error;
4254 s = p_shcf_copy;
4255 p = p_shcf;
4256 while (*p != NUL)
4257 {
4258 argv[argc++] = (char *)s;
4259 while (*p && *p != ' ' && *p != TAB)
4260 *s++ = *p++;
4261 *s++ = NUL;
4262 p = skipwhite(p);
4263 }
4264
Bram Moolenaar071d4272004-06-13 20:20:40 +00004265 argv[argc++] = (char *)cmd;
4266 }
4267 argv[argc] = NULL;
4268
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004270 * For the GUI, when writing the output into the buffer and when reading
4271 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4272 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004274 if ((options & (SHELL_READ|SHELL_WRITE))
4275# ifdef FEAT_GUI
4276 || (gui.in_use && show_shell_mess)
4277# endif
4278 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004280# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 /*
4282 * Try to open a master pty.
4283 * If this works, open the slave pty.
4284 * If the slave can't be opened, close the master pty.
4285 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004286 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287 {
4288 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004289 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004291 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4292 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4293 * adding O_NOCTTY always works when defined. */
4294#ifdef O_NOCTTY
4295 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4296#else
4297 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4298#endif
4299 if (pty_slave_fd < 0)
4300 {
4301 close(pty_master_fd);
4302 pty_master_fd = -1;
4303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 }
4305 }
4306 /*
4307 * If not opening a pty or it didn't work, try using pipes.
4308 */
4309 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004310# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 {
4312 pipe_error = (pipe(fd_toshell) < 0);
4313 if (!pipe_error) /* pipe create OK */
4314 {
4315 pipe_error = (pipe(fd_fromshell) < 0);
4316 if (pipe_error) /* pipe create failed */
4317 {
4318 close(fd_toshell[0]);
4319 close(fd_toshell[1]);
4320 }
4321 }
4322 if (pipe_error)
4323 {
4324 MSG_PUTS(_("\nCannot create pipes\n"));
4325 out_flush();
4326 }
4327 }
4328 }
4329
4330 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 {
4332# ifdef __BEOS__
4333 beos_cleanup_read_thread();
4334# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004335
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4337 {
4338 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004339 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004341 || (gui.in_use && show_shell_mess)
4342# endif
4343 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004345# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004346 if (pty_master_fd >= 0) /* close the pseudo tty */
4347 {
4348 close(pty_master_fd);
4349 close(pty_slave_fd);
4350 }
4351 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004352# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 {
4354 close(fd_toshell[0]);
4355 close(fd_toshell[1]);
4356 close(fd_fromshell[0]);
4357 close(fd_fromshell[1]);
4358 }
4359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 }
4361 else if (pid == 0) /* child */
4362 {
4363 reset_signals(); /* handle signals normally */
4364
4365 if (!show_shell_mess || (options & SHELL_EXPAND))
4366 {
4367 int fd;
4368
4369 /*
4370 * Don't want to show any message from the shell. Can't just
4371 * close stdout and stderr though, because some systems will
4372 * break if you try to write to them after that, so we must
4373 * use dup() to replace them with something else -- webb
4374 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4375 * waiting for input.
4376 */
4377 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4378 fclose(stdin);
4379 fclose(stdout);
4380 fclose(stderr);
4381
4382 /*
4383 * If any of these open()'s and dup()'s fail, we just continue
4384 * anyway. It's not fatal, and on most systems it will make
4385 * no difference at all. On a few it will cause the execvp()
4386 * to exit with a non-zero status even when the completion
4387 * could be done, which is nothing too serious. If the open()
4388 * or dup() failed we'd just do the same thing ourselves
4389 * anyway -- webb
4390 */
4391 if (fd >= 0)
4392 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004393 ignored = dup(fd); /* To replace stdin (fd 0) */
4394 ignored = dup(fd); /* To replace stdout (fd 1) */
4395 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396
4397 /* Don't need this now that we've duplicated it */
4398 close(fd);
4399 }
4400 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004401 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004403 || gui.in_use
4404# endif
4405 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406 {
4407
Bram Moolenaardf177f62005-02-22 08:39:57 +00004408# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004409 /* Create our own process group, so that the child and all its
4410 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004411 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004412 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004413 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004414 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004415# if defined(SIGHUP)
4416 /* When doing "!xterm&" and 'shell' is bash: the shell
4417 * will exit and send SIGHUP to all processes in its
4418 * group, killing the just started process. Ignore SIGHUP
4419 * to avoid that. (suggested by Simon Schubert)
4420 */
4421 signal(SIGHUP, SIG_IGN);
4422# endif
4423 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004424# endif
4425# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004426 if (pty_slave_fd >= 0)
4427 {
4428 /* push stream discipline modules */
4429 if (options & SHELL_COOKED)
4430 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004432 /* Try to become controlling tty (probably doesn't work,
4433 * unless run by root) */
4434 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004436 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004437# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004438 set_child_environment();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439
Bram Moolenaara5792f52005-11-23 21:25:05 +00004440 /*
4441 * stderr is only redirected when using the GUI, so that a
4442 * program like gpg can still access the terminal to get a
4443 * passphrase using stderr.
4444 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004445# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 if (pty_master_fd >= 0)
4447 {
4448 close(pty_master_fd); /* close master side of pty */
4449
4450 /* set up stdin/stdout/stderr for the child */
4451 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004452 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004454 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004455 if (gui.in_use)
4456 {
4457 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004458 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460
4461 close(pty_slave_fd); /* has been dupped, close it now */
4462 }
4463 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004464# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465 {
4466 /* set up stdin for the child */
4467 close(fd_toshell[1]);
4468 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004469 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 close(fd_toshell[0]);
4471
4472 /* set up stdout for the child */
4473 close(fd_fromshell[0]);
4474 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004475 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 close(fd_fromshell[1]);
4477
Bram Moolenaara5792f52005-11-23 21:25:05 +00004478# ifdef FEAT_GUI
4479 if (gui.in_use)
4480 {
4481 /* set up stderr for the child */
4482 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004483 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004484 }
4485# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 }
4487 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004488
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 /*
4490 * There is no type cast for the argv, because the type may be
4491 * different on different machines. This may cause a warning
4492 * message with strict compilers, don't worry about it.
4493 * Call _exit() instead of exit() to avoid closing the connection
4494 * to the X server (esp. with GTK, which uses atexit()).
4495 */
4496 execvp(argv[0], argv);
4497 _exit(EXEC_FAILED); /* exec failed, return failure code */
4498 }
4499 else /* parent */
4500 {
4501 /*
4502 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004503 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 */
4505 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004506 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507
4508 /*
4509 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004510 * This is also used to pipe stdin/stdout to/from the external
4511 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004513 if ((options & (SHELL_READ|SHELL_WRITE))
4514# ifdef FEAT_GUI
4515 || (gui.in_use && show_shell_mess)
4516# endif
4517 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004519# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004521# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004523# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4525 int ta_len = 0; /* valid bytes in ta_buf[] */
4526 int len;
4527 int p_more_save;
4528 int old_State;
4529 int c;
4530 int toshell_fd;
4531 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004532 garray_T ga;
4533 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004534# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4535 struct timeval start_tv;
4536# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537
Bram Moolenaardf177f62005-02-22 08:39:57 +00004538# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 if (pty_master_fd >= 0)
4540 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 fromshell_fd = pty_master_fd;
4542 toshell_fd = dup(pty_master_fd);
4543 }
4544 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004545# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 {
4547 close(fd_toshell[0]);
4548 close(fd_fromshell[1]);
4549 toshell_fd = fd_toshell[1];
4550 fromshell_fd = fd_fromshell[0];
4551 }
4552
4553 /*
4554 * Write to the child if there are typed characters.
4555 * Read from the child if there are characters available.
4556 * Repeat the reading a few times if more characters are
4557 * available. Need to check for typed keys now and then, but
4558 * not too often (delays when no chars are available).
4559 * This loop is quit if no characters can be read from the pty
4560 * (WaitForChar detected special condition), or there are no
4561 * characters available and the child has exited.
4562 * Only check if the child has exited when there is no more
4563 * output. The child may exit before all the output has
4564 * been printed.
4565 *
4566 * Currently this busy loops!
4567 * This can probably dead-lock when the write blocks!
4568 */
4569 p_more_save = p_more;
4570 p_more = FALSE;
4571 old_State = State;
4572 State = EXTERNCMD; /* don't redraw at window resize */
4573
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004574 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004575 {
4576 /* Fork a process that will write the lines to the
4577 * external program. */
4578 if ((wpid = fork()) == -1)
4579 {
4580 MSG_PUTS(_("\nCannot fork\n"));
4581 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004582 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004583 {
4584 linenr_T lnum = curbuf->b_op_start.lnum;
4585 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004586 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004587 size_t l;
4588
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004589 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004590 for (;;)
4591 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004592 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004593 if (l == 0)
4594 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004595 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004596 /* NL -> NUL translation */
4597 len = write(toshell_fd, "", (size_t)1);
4598 else
4599 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004600 char_u *s = vim_strchr(lp + written, NL);
4601
Bram Moolenaar89d40322006-08-29 15:30:07 +00004602 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004603 s == NULL ? l
4604 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004605 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004606 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004607 {
4608 /* Finished a line, add a NL, unless this line
4609 * should not have one. */
4610 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004611 || (!curbuf->b_p_bin
4612 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004613 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004614 && (lnum !=
4615 curbuf->b_ml.ml_line_count
4616 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004617 ignored = write(toshell_fd, "\n",
4618 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004619 ++lnum;
4620 if (lnum > curbuf->b_op_end.lnum)
4621 {
4622 /* finished all the lines, close pipe */
4623 close(toshell_fd);
4624 toshell_fd = -1;
4625 break;
4626 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004627 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004628 written = 0;
4629 }
4630 else if (len > 0)
4631 written += len;
4632 }
4633 _exit(0);
4634 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004635 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004636 {
4637 close(toshell_fd);
4638 toshell_fd = -1;
4639 }
4640 }
4641
4642 if (options & SHELL_READ)
4643 ga_init2(&ga, 1, BUFLEN);
4644
4645 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004646# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4647 gettimeofday(&start_tv, NULL);
4648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 for (;;)
4650 {
4651 /*
4652 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004653 * if there are any.
4654 * Don't do this if we are expanding wild cards (would eat
4655 * typeahead).
4656 * Don't do this when filtering and terminal is in cooked
4657 * mode, the shell command will handle the I/O. Avoids
4658 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004659 * Don't get characters when the child has already
4660 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004661 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004662 * while (noread_cnt > 4), avoids that ":r !ls" eats
4663 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 */
4665 len = 0;
4666 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004667 && ((options &
4668 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4669 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004670# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004671 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004672# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004673 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004674 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004675 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004677 if (ta_len == 0)
4678 {
4679 /* Get extra characters when we don't have any.
4680 * Reset the counter and timer. */
4681 noread_cnt = 0;
4682# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4683 gettimeofday(&start_tv, NULL);
4684# endif
4685 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4686 }
4687 if (ta_len > 0 || len > 0)
4688 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 /*
4690 * For pipes:
4691 * Check for CTRL-C: send interrupt signal to child.
4692 * Check for CTRL-D: EOF, close pipe to child.
4693 */
4694 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4695 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004696# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 /*
4698 * Send SIGINT to the child's group or all
4699 * processes in our group.
4700 */
4701 if (ta_buf[ta_len] == Ctrl_C
4702 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004703 {
4704# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004706# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004709 if (wpid > 0)
4710 kill(wpid, SIGINT);
4711 }
4712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713 if (pty_master_fd < 0 && toshell_fd >= 0
4714 && ta_buf[ta_len] == Ctrl_D)
4715 {
4716 close(toshell_fd);
4717 toshell_fd = -1;
4718 }
4719 }
4720
4721 /* replace K_BS by <BS> and K_DEL by <DEL> */
4722 for (i = ta_len; i < ta_len + len; ++i)
4723 {
4724 if (ta_buf[i] == CSI && len - i > 2)
4725 {
4726 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4727 if (c == K_DEL || c == K_KDEL || c == K_BS)
4728 {
4729 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4730 (size_t)(len - i - 2));
4731 if (c == K_DEL || c == K_KDEL)
4732 ta_buf[i] = DEL;
4733 else
4734 ta_buf[i] = Ctrl_H;
4735 len -= 2;
4736 }
4737 }
4738 else if (ta_buf[i] == '\r')
4739 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004740# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004742 i += (*mb_ptr2len_len)(ta_buf + i,
4743 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004744# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 }
4746
4747 /*
4748 * For pipes: echo the typed characters.
4749 * For a pty this does not seem to work.
4750 */
4751 if (pty_master_fd < 0)
4752 {
4753 for (i = ta_len; i < ta_len + len; ++i)
4754 {
4755 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4756 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004757# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 else if (has_mbyte)
4759 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004760 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761
4762 msg_outtrans_len(ta_buf + i, l);
4763 i += l - 1;
4764 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004765# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 else
4767 msg_outtrans_len(ta_buf + i, 1);
4768 }
4769 windgoto(msg_row, msg_col);
4770 out_flush();
4771 }
4772
4773 ta_len += len;
4774
4775 /*
4776 * Write the characters to the child, unless EOF has
4777 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004778 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004779 * When writing buffer lines, drop the typed
4780 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004782 if (options & SHELL_WRITE)
4783 ta_len = 0;
4784 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 {
4786 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4787 if (len > 0)
4788 {
4789 ta_len -= len;
4790 mch_memmove(ta_buf, ta_buf + len, ta_len);
4791 }
4792 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 }
4795
Bram Moolenaardf177f62005-02-22 08:39:57 +00004796 if (got_int)
4797 {
4798 /* CTRL-C sends a signal to the child, we ignore it
4799 * ourselves */
4800# ifdef HAVE_SETSID
4801 kill(-pid, SIGINT);
4802# else
4803 kill(0, SIGINT);
4804# endif
4805 if (wpid > 0)
4806 kill(wpid, SIGINT);
4807 got_int = FALSE;
4808 }
4809
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 /*
4811 * Check if the child has any characters to be printed.
4812 * Read them and write them to our window. Repeat this as
4813 * long as there is something to do, avoid the 10ms wait
4814 * for mch_inchar(), or sending typeahead characters to
4815 * the external process.
4816 * TODO: This should handle escape sequences, compatible
4817 * to some terminal (vt52?).
4818 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004819 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01004820 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004822 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004823# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004825# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004827# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 );
4829 if (len <= 0) /* end of file or error */
4830 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004831
4832 noread_cnt = 0;
4833 if (options & SHELL_READ)
4834 {
4835 /* Do NUL -> NL translation, append NL separated
4836 * lines to the current buffer. */
4837 for (i = 0; i < len; ++i)
4838 {
4839 if (buffer[i] == NL)
4840 append_ga_line(&ga);
4841 else if (buffer[i] == NUL)
4842 ga_append(&ga, NL);
4843 else
4844 ga_append(&ga, buffer[i]);
4845 }
4846 }
4847# ifdef FEAT_MBYTE
4848 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 {
4850 int l;
4851
Bram Moolenaardf177f62005-02-22 08:39:57 +00004852 len += buffer_off;
4853 buffer[len] = NUL;
4854
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 /* Check if the last character in buffer[] is
4856 * incomplete, keep these bytes for the next
4857 * round. */
4858 for (p = buffer; p < buffer + len; p += l)
4859 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004860 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 if (l == 0)
4862 l = 1; /* NUL byte? */
4863 else if (MB_BYTE2LEN(*p) != l)
4864 break;
4865 }
4866 if (p == buffer) /* no complete character */
4867 {
4868 /* avoid getting stuck at an illegal byte */
4869 if (len >= 12)
4870 ++p;
4871 else
4872 {
4873 buffer_off = len;
4874 continue;
4875 }
4876 }
4877 c = *p;
4878 *p = NUL;
4879 msg_puts(buffer);
4880 if (p < buffer + len)
4881 {
4882 *p = c;
4883 buffer_off = (buffer + len) - p;
4884 mch_memmove(buffer, p, buffer_off);
4885 continue;
4886 }
4887 buffer_off = 0;
4888 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004889# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 {
4892 buffer[len] = NUL;
4893 msg_puts(buffer);
4894 }
4895
4896 windgoto(msg_row, msg_col);
4897 cursor_on();
4898 out_flush();
4899 if (got_int)
4900 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004901
4902# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004903 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004904 {
Bram Moolenaare30a3d02016-06-04 14:11:20 +02004905 long msec = elapsed(&start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004906
4907 /* Avoid that we keep looping here without
4908 * checking for a CTRL-C for a long time. Don't
4909 * break out too often to avoid losing typeahead. */
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004910 if (msec > 2000)
4911 {
4912 noread_cnt = 5;
4913 break;
4914 }
4915 }
4916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 }
4918
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004919 /* If we already detected the child has finished, continue
4920 * reading output for a short while. Some text may be
4921 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004922 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004923 {
4924 if (noread_cnt < 5)
4925 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004926 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004927 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004928
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929 /*
4930 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004931 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004933# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004934 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004935# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004937# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4939 || (wait_pid == pid && WIFEXITED(status)))
4940 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004941 /* Don't break the loop yet, try reading more
4942 * characters from "fromshell_fd" first. When using
4943 * pipes there might still be something to read and
4944 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004947 else
4948 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004949
Bram Moolenaar95a51352013-03-21 22:53:50 +01004950# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004951 /* Handle any X events, e.g. serving the clipboard. */
4952 clip_update();
4953# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 }
4955finished:
4956 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004957 if (options & SHELL_READ)
4958 {
4959 if (ga.ga_len > 0)
4960 {
4961 append_ga_line(&ga);
4962 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004963 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004964 }
4965 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004966 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004967 ga_clear(&ga);
4968 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970 /*
4971 * Give all typeahead that wasn't used back to ui_inchar().
4972 */
4973 if (ta_len)
4974 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 State = old_State;
4976 if (toshell_fd >= 0)
4977 close(toshell_fd);
4978 close(fromshell_fd);
4979 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004980# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004981 else
4982 {
4983 /*
4984 * Similar to the loop above, but only handle X events, no
4985 * I/O.
4986 */
4987 for (;;)
4988 {
4989 if (got_int)
4990 {
4991 /* CTRL-C sends a signal to the child, we ignore it
4992 * ourselves */
4993# ifdef HAVE_SETSID
4994 kill(-pid, SIGINT);
4995# else
4996 kill(0, SIGINT);
4997# endif
4998 got_int = FALSE;
4999 }
5000# ifdef __NeXT__
5001 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
5002# else
5003 wait_pid = waitpid(pid, &status, WNOHANG);
5004# endif
5005 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5006 || (wait_pid == pid && WIFEXITED(status)))
5007 {
5008 wait_pid = pid;
5009 break;
5010 }
5011
5012 /* Handle any X events, e.g. serving the clipboard. */
5013 clip_update();
5014
5015 mch_delay(10L, TRUE);
5016 }
5017 }
5018# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019
5020 /*
5021 * Wait until our child has exited.
5022 * Ignore wait() returning pids of other children and returning
5023 * because of some signal like SIGWINCH.
5024 * Don't wait if wait_pid was already set above, indicating the
5025 * child already exited.
5026 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005027 if (wait_pid != pid)
5028 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029
Bram Moolenaar624891f2010-10-13 16:22:09 +02005030# ifdef FEAT_GUI
5031 /* Close slave side of pty. Only do this after the child has
5032 * exited, otherwise the child may hang when it tries to write on
5033 * the pty. */
5034 if (pty_master_fd >= 0)
5035 close(pty_slave_fd);
5036# endif
5037
Bram Moolenaardf177f62005-02-22 08:39:57 +00005038 /* Make sure the child that writes to the external program is
5039 * dead. */
5040 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005041 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005042 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005043 wait4pid(wpid, NULL);
5044 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005045
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 /*
5047 * Set to raw mode right now, otherwise a CTRL-C after
5048 * catch_signals() will kill Vim.
5049 */
5050 if (tmode == TMODE_RAW)
5051 settmode(TMODE_RAW);
5052 did_settmode = TRUE;
5053 set_signals();
5054
5055 if (WIFEXITED(status))
5056 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005057 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005059 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 {
5061 if (retval == EXEC_FAILED)
5062 {
5063 MSG_PUTS(_("\nCannot execute shell "));
5064 msg_outtrans(p_sh);
5065 msg_putchar('\n');
5066 }
5067 else if (!(options & SHELL_SILENT))
5068 {
5069 MSG_PUTS(_("\nshell returned "));
5070 msg_outnum((long)retval);
5071 msg_putchar('\n');
5072 }
5073 }
5074 }
5075 else
5076 MSG_PUTS(_("\nCommand terminated\n"));
5077 }
5078 }
5079 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005080 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081
5082error:
5083 if (!did_settmode)
5084 if (tmode == TMODE_RAW)
5085 settmode(TMODE_RAW); /* set to raw mode */
5086# ifdef FEAT_TITLE
5087 resettitle();
5088# endif
5089 vim_free(newcmd);
5090
5091 return retval;
5092
5093#endif /* USE_SYSTEM */
5094}
5095
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005096#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005097 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005098mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005099{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005100 pid_t pid;
5101 int fd_in[2]; /* for stdin */
5102 int fd_out[2]; /* for stdout */
5103 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005104 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005105 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5106 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5107 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005108 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005109 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5110 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005111 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005112
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005113 if (use_out_for_err && use_null_for_out)
5114 use_null_for_err = TRUE;
5115
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005116 /* default is to fail */
5117 job->jv_status = JOB_FAILED;
5118 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005119 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005120 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005121 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005122 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005123 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005124
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005125 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005126 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005127 if (use_file_for_in)
5128 {
5129 char_u *fname = options->jo_io_name[PART_IN];
5130
5131 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5132 if (fd_in[0] < 0)
5133 {
5134 EMSG2(_(e_notopen), fname);
5135 goto failed;
5136 }
5137 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005138 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005139 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005140
5141 if (use_file_for_out)
5142 {
5143 char_u *fname = options->jo_io_name[PART_OUT];
5144
5145 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5146 if (fd_out[1] < 0)
5147 {
5148 EMSG2(_(e_notopen), fname);
5149 goto failed;
5150 }
5151 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005152 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005153 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005154
5155 if (use_file_for_err)
5156 {
5157 char_u *fname = options->jo_io_name[PART_ERR];
5158
5159 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5160 if (fd_err[1] < 0)
5161 {
5162 EMSG2(_(e_notopen), fname);
5163 goto failed;
5164 }
5165 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005166 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005167 goto failed;
5168
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005169 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5170 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005171 if (options->jo_set & JO_CHANNEL)
5172 {
5173 channel = options->jo_channel;
5174 if (channel != NULL)
5175 ++channel->ch_refcount;
5176 }
5177 else
5178 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005179 if (channel == NULL)
5180 goto failed;
5181 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005182
5183 pid = fork(); /* maybe we should use vfork() */
5184 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005185 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005186 /* failed to fork */
5187 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005188 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005189
5190 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005191 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005192 int null_fd = -1;
5193 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005194
Bram Moolenaar835dc632016-02-07 14:27:38 +01005195 /* child */
5196 reset_signals(); /* handle signals normally */
5197
5198# ifdef HAVE_SETSID
5199 /* Create our own process group, so that the child and all its
5200 * children can be kill()ed. Don't do this when using pipes,
5201 * because stdin is not a tty, we would lose /dev/tty. */
5202 (void)setsid();
5203# endif
5204
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005205 set_child_environment();
5206
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005207 if (use_null_for_in || use_null_for_out || use_null_for_err)
5208 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5209
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005210 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005211 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005212 {
5213 close(0);
5214 ignored = dup(null_fd);
5215 }
5216 else
5217 {
5218 if (!use_file_for_in)
5219 close(fd_in[1]);
5220 close(0);
5221 ignored = dup(fd_in[0]);
5222 close(fd_in[0]);
5223 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005224
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005225 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005226 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005227 {
5228 close(2);
5229 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005230 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005231 }
5232 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005233 {
5234 close(2);
5235 ignored = dup(fd_out[1]);
5236 }
5237 else
5238 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005239 if (!use_file_for_err)
5240 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005241 close(2);
5242 ignored = dup(fd_err[1]);
5243 close(fd_err[1]);
5244 }
5245
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005246 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005247 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005248 {
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005249 close(1);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005250 ignored = dup(null_fd);
5251 }
5252 else
5253 {
5254 if (!use_file_for_out)
5255 close(fd_out[0]);
5256 close(1);
5257 ignored = dup(fd_out[1]);
5258 close(fd_out[1]);
5259 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005260
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005261 if (null_fd >= 0)
5262 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005263
Bram Moolenaar835dc632016-02-07 14:27:38 +01005264 /* See above for type of argv. */
5265 execvp(argv[0], argv);
5266
Bram Moolenaar4694a172016-04-21 14:05:23 +02005267 if (stderr_works)
5268 perror("executing job failed");
Bram Moolenaarcda77642016-06-04 13:32:35 +02005269#ifdef EXITFREE
5270 /* calling free_all_mem() here causes problems. Ignore valgrind
5271 * reporting possibly leaked memory. */
5272#endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005273 _exit(EXEC_FAILED); /* exec failed, return failure code */
5274 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005275
5276 /* parent */
5277 job->jv_pid = pid;
5278 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005279 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005280
5281 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005282 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005283 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005284 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005285 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005286 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005287 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005288 if (channel != NULL)
5289 {
5290 channel_set_pipes(channel,
5291 use_file_for_in || use_null_for_in
5292 ? INVALID_FD : fd_in[1],
5293 use_file_for_out || use_null_for_out
5294 ? INVALID_FD : fd_out[0],
5295 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005296 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005297 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005298 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005299
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005300 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005301 return;
5302
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005303failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005304 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005305 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005306 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005307 if (fd_in[1] >= 0)
5308 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005309 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005310 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005311 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005312 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005313 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005314 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005315 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005316 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005317}
5318
5319 char *
5320mch_job_status(job_T *job)
5321{
5322# ifdef HAVE_UNION_WAIT
5323 union wait status;
5324# else
5325 int status = -1;
5326# endif
5327 pid_t wait_pid = 0;
5328
5329# ifdef __NeXT__
5330 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5331# else
5332 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5333# endif
5334 if (wait_pid == -1)
5335 {
5336 /* process must have exited */
5337 job->jv_status = JOB_ENDED;
5338 return "dead";
5339 }
5340 if (wait_pid == 0)
5341 return "run";
5342 if (WIFEXITED(status))
5343 {
5344 /* LINTED avoid "bitwise operation on signed value" */
5345 job->jv_exitval = WEXITSTATUS(status);
5346 job->jv_status = JOB_ENDED;
5347 return "dead";
5348 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005349 if (WIFSIGNALED(status))
5350 {
5351 job->jv_exitval = -1;
5352 job->jv_status = JOB_ENDED;
5353 return "dead";
5354 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005355 return "run";
5356}
5357
5358 int
5359mch_stop_job(job_T *job, char_u *how)
5360{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005361 int sig = -1;
5362 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005363
Bram Moolenaar923d9262016-02-25 20:56:01 +01005364 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005365 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005366 else if (STRCMP(how, "hup") == 0)
5367 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005368 else if (STRCMP(how, "quit") == 0)
5369 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005370 else if (STRCMP(how, "int") == 0)
5371 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005372 else if (STRCMP(how, "kill") == 0)
5373 sig = SIGKILL;
5374 else if (isdigit(*how))
5375 sig = atoi((char *)how);
5376 else
5377 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005378
Bram Moolenaar72801402016-02-09 11:37:50 +01005379 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005380 job_pid = job->jv_pid;
5381 if (job_pid == getpgid(job_pid))
5382 job_pid = -job_pid;
5383
5384 kill(job_pid, sig);
5385
Bram Moolenaar835dc632016-02-07 14:27:38 +01005386 return OK;
5387}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005388
5389/*
5390 * Clear the data related to "job".
5391 */
5392 void
5393mch_clear_job(job_T *job)
5394{
5395 /* call waitpid because child process may become zombie */
5396# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005397 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005398# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005399 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005400# endif
5401}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005402#endif
5403
Bram Moolenaar071d4272004-06-13 20:20:40 +00005404/*
5405 * Check for CTRL-C typed by reading all available characters.
5406 * In cooked mode we should get SIGINT, no need to check.
5407 */
5408 void
Bram Moolenaar05540972016-01-30 20:31:25 +01005409mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005410{
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005411 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005412 fill_input_buf(FALSE);
5413}
5414
5415/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005416 * Wait "msec" msec until a character is available from the mouse, keyboard,
5417 * from inbuf[].
5418 * "msec" == -1 will block forever.
5419 * Invokes timer callbacks when needed.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005420 * "interrupted" (if not NULL) is set to TRUE when no character is available
5421 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005422 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005423 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005424 */
5425 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005426WaitForChar(long msec, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005427{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005428#ifdef FEAT_TIMERS
5429 long due_time;
5430 long remaining = msec;
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005431 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005432
5433 /* When waiting very briefly don't trigger timers. */
5434 if (msec >= 0 && msec < 10L)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005435 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005436
5437 while (msec < 0 || remaining > 0)
5438 {
5439 /* Trigger timers and then get the time in msec until the next one is
5440 * due. Wait up to that time. */
5441 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005442 if (typebuf.tb_change_cnt != tb_change_cnt)
5443 {
5444 /* timer may have used feedkeys() */
5445 return FALSE;
5446 }
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005447 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5448 due_time = remaining;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005449 if (WaitForCharOrMouse(due_time, interrupted))
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005450 return TRUE;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005451 if (interrupted != NULL && *interrupted)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005452 /* Nothing available, but need to return so that side effects get
5453 * handled, such as handling a message on a channel. */
5454 return FALSE;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005455 if (msec > 0)
5456 remaining -= due_time;
5457 }
5458 return FALSE;
5459#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005460 return WaitForCharOrMouse(msec, interrupted);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005461#endif
5462}
5463
5464/*
5465 * Wait "msec" msec until a character is available from the mouse or keyboard
5466 * or from inbuf[].
5467 * "msec" == -1 will block forever.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005468 * "interrupted" (if not NULL) is set to TRUE when no character is available
5469 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005470 * When a GUI is being used, this will never get called -- webb
5471 */
5472 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005473WaitForCharOrMouse(long msec, int *interrupted)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005474{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475#ifdef FEAT_MOUSE_GPM
5476 int gpm_process_wanted;
5477#endif
5478#ifdef FEAT_XCLIPBOARD
5479 int rest;
5480#endif
5481 int avail;
5482
5483 if (input_available()) /* something in inbuf[] */
5484 return 1;
5485
5486#if defined(FEAT_MOUSE_DEC)
5487 /* May need to query the mouse position. */
5488 if (WantQueryMouse)
5489 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005490 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5492 }
5493#endif
5494
5495 /*
5496 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5497 * events. This is a bit complicated, because they might both be defined.
5498 */
5499#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5500# ifdef FEAT_XCLIPBOARD
5501 rest = 0;
5502 if (do_xterm_trace())
5503 rest = msec;
5504# endif
5505 do
5506 {
5507# ifdef FEAT_XCLIPBOARD
5508 if (rest != 0)
5509 {
5510 msec = XT_TRACE_DELAY;
5511 if (rest >= 0 && rest < XT_TRACE_DELAY)
5512 msec = rest;
5513 if (rest >= 0)
5514 rest -= msec;
5515 }
5516# endif
5517# ifdef FEAT_MOUSE_GPM
5518 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005519 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02005520 &gpm_process_wanted, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005522 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523# endif
5524 if (!avail)
5525 {
5526 if (input_available())
5527 return 1;
5528# ifdef FEAT_XCLIPBOARD
5529 if (rest == 0 || !do_xterm_trace())
5530# endif
5531 break;
5532 }
5533 }
5534 while (FALSE
5535# ifdef FEAT_MOUSE_GPM
5536 || (gpm_process_wanted && mch_gpm_process() == 0)
5537# endif
5538# ifdef FEAT_XCLIPBOARD
5539 || (!avail && rest != 0)
5540# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005541 )
5542 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005545 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546#endif
5547 return avail;
5548}
5549
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005550#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551/*
5552 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005553 * "msec" == 0 will check for characters once.
5554 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005555 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005557 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005558 * "interrupted" (if not NULL) is set to TRUE when no character is available
5559 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561#if defined(__BEOS__)
5562 int
5563#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005564 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005566RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567{
5568 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005569 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005570#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 static int busy = FALSE;
5572
5573 /* May retry getting characters after an event was handled. */
5574# define MAY_LOOP
5575
5576# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5577 /* Remember at what time we started, so that we know how much longer we
5578 * should wait after being interrupted. */
5579# define USE_START_TV
5580 struct timeval start_tv;
5581
5582 if (msec > 0 && (
5583# ifdef FEAT_XCLIPBOARD
5584 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005585# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 ||
5587# endif
5588# endif
5589# ifdef USE_XSMP
5590 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005591# ifdef FEAT_MZSCHEME
5592 ||
5593# endif
5594# endif
5595# ifdef FEAT_MZSCHEME
5596 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597# endif
5598 ))
5599 gettimeofday(&start_tv, NULL);
5600# endif
5601
5602 /* Handle being called recursively. This may happen for the session
5603 * manager stuff, it may save the file, which does a breakcheck. */
5604 if (busy)
5605 return 0;
5606#endif
5607
5608#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005609 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610#endif
5611 {
5612#ifdef MAY_LOOP
5613 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005614# ifdef FEAT_MZSCHEME
5615 int mzquantum_used = FALSE;
5616# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617#endif
5618#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005619 /* each channel may use in, out and err */
5620 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 int nfd;
5622# ifdef FEAT_XCLIPBOARD
5623 int xterm_idx = -1;
5624# endif
5625# ifdef FEAT_MOUSE_GPM
5626 int gpm_idx = -1;
5627# endif
5628# ifdef USE_XSMP
5629 int xsmp_idx = -1;
5630# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005631 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005633# ifdef FEAT_MZSCHEME
5634 mzvim_check_threads();
5635 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5636 {
5637 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5638 mzquantum_used = TRUE;
5639 }
5640# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 fds[0].fd = fd;
5642 fds[0].events = POLLIN;
5643 nfd = 1;
5644
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005646 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 if (xterm_Shell != (Widget)0)
5648 {
5649 xterm_idx = nfd;
5650 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5651 fds[nfd].events = POLLIN;
5652 nfd++;
5653 }
5654# endif
5655# ifdef FEAT_MOUSE_GPM
5656 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5657 {
5658 gpm_idx = nfd;
5659 fds[nfd].fd = gpm_fd;
5660 fds[nfd].events = POLLIN;
5661 nfd++;
5662 }
5663# endif
5664# ifdef USE_XSMP
5665 if (xsmp_icefd != -1)
5666 {
5667 xsmp_idx = nfd;
5668 fds[nfd].fd = xsmp_icefd;
5669 fds[nfd].events = POLLIN;
5670 nfd++;
5671 }
5672# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005673#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005674 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005675#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005676 if (interrupted != NULL)
5677 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005679 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005680
5681 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02005682 if (result == 0 && interrupted != NULL && ret > 0)
5683 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005684
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005685# ifdef FEAT_MZSCHEME
5686 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005687 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005688 finished = FALSE;
5689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691# ifdef FEAT_XCLIPBOARD
5692 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5693 {
5694 xterm_update(); /* Maybe we should hand out clipboard */
5695 if (--ret == 0 && !input_available())
5696 /* Try again */
5697 finished = FALSE;
5698 }
5699# endif
5700# ifdef FEAT_MOUSE_GPM
5701 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5702 {
5703 *check_for_gpm = 1;
5704 }
5705# endif
5706# ifdef USE_XSMP
5707 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5708 {
5709 if (fds[xsmp_idx].revents & POLLIN)
5710 {
5711 busy = TRUE;
5712 xsmp_handle_requests();
5713 busy = FALSE;
5714 }
5715 else if (fds[xsmp_idx].revents & POLLHUP)
5716 {
5717 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005718 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 xsmp_close();
5720 }
5721 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005722 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723 }
5724# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005725#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005726 if (ret > 0)
5727 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005728#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730#else /* HAVE_SELECT */
5731
5732 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005733 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005734 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005736 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005738# ifdef FEAT_MZSCHEME
5739 mzvim_check_threads();
5740 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5741 {
5742 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5743 mzquantum_used = TRUE;
5744 }
5745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746# ifdef __EMX__
5747 /* don't check for incoming chars if not in raw mode, because select()
5748 * always returns TRUE then (in some version of emx.dll) */
5749 if (curr_tmode != TMODE_RAW)
5750 return 0;
5751# endif
5752
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005753 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005755 tv.tv_sec = towait / 1000;
5756 tv.tv_usec = (towait % 1000) * (1000000/1000);
5757 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005759 else
5760 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761
5762 /*
5763 * Select on ready for reading and exceptional condition (end of file).
5764 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005765select_eintr:
5766 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005767 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 FD_ZERO(&efds);
5769 FD_SET(fd, &rfds);
5770# if !defined(__QNX__) && !defined(__CYGWIN32__)
5771 /* For QNX select() always returns 1 if this is set. Why? */
5772 FD_SET(fd, &efds);
5773# endif
5774 maxfd = fd;
5775
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005777 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778 if (xterm_Shell != (Widget)0)
5779 {
5780 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5781 if (maxfd < ConnectionNumber(xterm_dpy))
5782 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005783
5784 /* An event may have already been read but not handled. In
5785 * particulary, XFlush may cause this. */
5786 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 }
5788# endif
5789# ifdef FEAT_MOUSE_GPM
5790 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5791 {
5792 FD_SET(gpm_fd, &rfds);
5793 FD_SET(gpm_fd, &efds);
5794 if (maxfd < gpm_fd)
5795 maxfd = gpm_fd;
5796 }
5797# endif
5798# ifdef USE_XSMP
5799 if (xsmp_icefd != -1)
5800 {
5801 FD_SET(xsmp_icefd, &rfds);
5802 FD_SET(xsmp_icefd, &efds);
5803 if (maxfd < xsmp_icefd)
5804 maxfd = xsmp_icefd;
5805 }
5806# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005807# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005808 maxfd = channel_select_setup(maxfd, &rfds, &wfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005809# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005810 if (interrupted != NULL)
5811 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005813 ret = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005814 result = ret > 0 && FD_ISSET(fd, &rfds);
5815 if (result)
5816 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005817 else if (interrupted != NULL && ret > 0)
5818 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005819
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005820# ifdef EINTR
5821 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005822 {
5823 /* Check whether window has been resized, EINTR may be caused by
5824 * SIGWINCH. */
5825 if (do_resize)
5826 handle_resize();
5827
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005828 /* Interrupted by a signal, need to try again. We ignore msec
5829 * here, because we do want to check even after a timeout if
5830 * characters are available. Needed for reading output of an
5831 * external command after the process has finished. */
5832 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005833 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005834# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005835# ifdef __TANDEM
5836 if (ret == -1 && errno == ENOTSUP)
5837 {
5838 FD_ZERO(&rfds);
5839 FD_ZERO(&efds);
5840 ret = 0;
5841 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005842# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005843# ifdef FEAT_MZSCHEME
5844 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005845 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005846 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847# endif
5848
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849# ifdef FEAT_XCLIPBOARD
5850 if (ret > 0 && xterm_Shell != (Widget)0
5851 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5852 {
5853 xterm_update(); /* Maybe we should hand out clipboard */
5854 /* continue looping when we only got the X event and the input
5855 * buffer is empty */
5856 if (--ret == 0 && !input_available())
5857 {
5858 /* Try again */
5859 finished = FALSE;
5860 }
5861 }
5862# endif
5863# ifdef FEAT_MOUSE_GPM
5864 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5865 {
5866 if (FD_ISSET(gpm_fd, &efds))
5867 gpm_close();
5868 else if (FD_ISSET(gpm_fd, &rfds))
5869 *check_for_gpm = 1;
5870 }
5871# endif
5872# ifdef USE_XSMP
5873 if (ret > 0 && xsmp_icefd != -1)
5874 {
5875 if (FD_ISSET(xsmp_icefd, &efds))
5876 {
5877 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005878 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 xsmp_close();
5880 if (--ret == 0)
5881 finished = FALSE; /* keep going if event was only one */
5882 }
5883 else if (FD_ISSET(xsmp_icefd, &rfds))
5884 {
5885 busy = TRUE;
5886 xsmp_handle_requests();
5887 busy = FALSE;
5888 if (--ret == 0)
5889 finished = FALSE; /* keep going if event was only one */
5890 }
5891 }
5892# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005893#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005894 if (ret > 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005895 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005897
5898#endif /* HAVE_SELECT */
5899
5900#ifdef MAY_LOOP
5901 if (finished || msec == 0)
5902 break;
5903
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005904# ifdef FEAT_CLIENTSERVER
5905 if (server_waiting())
5906 break;
5907# endif
5908
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 /* We're going to loop around again, find out for how long */
5910 if (msec > 0)
5911 {
5912# ifdef USE_START_TV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913 /* Compute remaining wait time. */
Bram Moolenaare30a3d02016-06-04 14:11:20 +02005914 msec -= elapsed(&start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915# else
5916 /* Guess we got interrupted halfway. */
5917 msec = msec / 2;
5918# endif
5919 if (msec <= 0)
5920 break; /* waited long enough */
5921 }
5922#endif
5923 }
5924
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005925 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926}
5927
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005930 * Expand a path into all matching files and/or directories. Handles "*",
5931 * "?", "[a-z]", "**", etc.
5932 * "path" has backslashes before chars that are not to be expanded.
5933 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 */
5935 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005936mch_expandpath(
5937 garray_T *gap,
5938 char_u *path,
5939 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005940{
Bram Moolenaar02743632005-07-25 20:42:36 +00005941 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942}
5943#endif
5944
5945/*
5946 * mch_expand_wildcards() - this code does wild-card pattern matching using
5947 * the shell
5948 *
5949 * return OK for success, FAIL for error (you may lose some memory) and put
5950 * an error message in *file.
5951 *
5952 * num_pat is number of input patterns
5953 * pat is array of pointers to input patterns
5954 * num_file is pointer to number of matched file names
5955 * file is pointer to array of pointers to matched file names
5956 */
5957
5958#ifndef SEEK_SET
5959# define SEEK_SET 0
5960#endif
5961#ifndef SEEK_END
5962# define SEEK_END 2
5963#endif
5964
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005965#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005966
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005968mch_expand_wildcards(
5969 int num_pat,
5970 char_u **pat,
5971 int *num_file,
5972 char_u ***file,
5973 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974{
5975 int i;
5976 size_t len;
5977 char_u *p;
5978 int dir;
5979#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005980 /*
5981 * This is the OS/2 implementation.
5982 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983# define EXPL_ALLOC_INC 16
5984 char_u **expl_files;
5985 size_t files_alloced, files_free;
5986 char_u *buf;
5987 int has_wildcard;
5988
5989 *num_file = 0; /* default: no files found */
5990 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5991 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5992 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5993 if (*file == NULL)
5994 return FAIL;
5995
5996 for (; num_pat > 0; num_pat--, pat++)
5997 {
5998 expl_files = NULL;
5999 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
6000 /* expand environment var or home dir */
6001 buf = expand_env_save(*pat);
6002 else
6003 buf = vim_strsave(*pat);
6004 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006005 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 if (has_wildcard) /* yes, so expand them */
6007 expl_files = (char_u **)_fnexplode(buf);
6008
6009 /*
6010 * return value of buf if no wildcards left,
6011 * OR if no match AND EW_NOTFOUND is set.
6012 */
6013 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
6014 || (expl_files == NULL && (flags & EW_NOTFOUND)))
6015 { /* simply save the current contents of *buf */
6016 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
6017 if (expl_files != NULL)
6018 {
6019 expl_files[0] = vim_strsave(buf);
6020 expl_files[1] = NULL;
6021 }
6022 }
6023 vim_free(buf);
6024
6025 /*
6026 * Count number of names resulting from expansion,
6027 * At the same time add a backslash to the end of names that happen to
6028 * be directories, and replace slashes with backslashes.
6029 */
6030 if (expl_files)
6031 {
6032 for (i = 0; (p = expl_files[i]) != NULL; i++)
6033 {
6034 dir = mch_isdir(p);
6035 /* If we don't want dirs and this is one, skip it */
6036 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6037 continue;
6038
Bram Moolenaara2031822006-03-07 22:29:51 +00006039 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006040 if (!dir && (flags & EW_EXEC)
6041 && !mch_can_exe(p, NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006042 continue;
6043
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 if (--files_free == 0)
6045 {
6046 /* need more room in table of pointers */
6047 files_alloced += EXPL_ALLOC_INC;
6048 *file = (char_u **)vim_realloc(*file,
6049 sizeof(char_u **) * files_alloced);
6050 if (*file == NULL)
6051 {
6052 EMSG(_(e_outofmem));
6053 *num_file = 0;
6054 return FAIL;
6055 }
6056 files_free = EXPL_ALLOC_INC;
6057 }
6058 slash_adjust(p);
6059 if (dir)
6060 {
6061 /* For a directory we add a '/', unless it's already
6062 * there. */
6063 len = STRLEN(p);
6064 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
6065 {
6066 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00006067 if (!after_pathsep((*file)[*num_file],
6068 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069 {
6070 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006071 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072 }
6073 }
6074 }
6075 else
6076 {
6077 (*file)[*num_file] = vim_strsave(p);
6078 }
6079
6080 /*
6081 * Error message already given by either alloc or vim_strsave.
6082 * Should return FAIL, but returning OK works also.
6083 */
6084 if ((*file)[*num_file] == NULL)
6085 break;
6086 (*num_file)++;
6087 }
6088 _fnexplodefree((char **)expl_files);
6089 }
6090 }
6091 return OK;
6092
6093#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006094 /*
6095 * This is the non-OS/2 implementation (really Unix).
6096 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097 int j;
6098 char_u *tempname;
6099 char_u *command;
6100 FILE *fd;
6101 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006102#define STYLE_ECHO 0 /* use "echo", the default */
6103#define STYLE_GLOB 1 /* use "glob", for csh */
6104#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6105#define STYLE_PRINT 3 /* use "print -N", for zsh */
6106#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6107 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108 int shell_style = STYLE_ECHO;
6109 int check_spaces;
6110 static int did_find_nul = FALSE;
6111 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006112 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006113 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
6115 *num_file = 0; /* default: no files found */
6116 *file = NULL;
6117
6118 /*
6119 * If there are no wildcards, just copy the names to allocated memory.
6120 * Saves a lot of time, because we don't have to start a new shell.
6121 */
6122 if (!have_wildcard(num_pat, pat))
6123 return save_patterns(num_pat, pat, num_file, file);
6124
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006125# ifdef HAVE_SANDBOX
6126 /* Don't allow any shell command in the sandbox. */
6127 if (sandbox != 0 && check_secure())
6128 return FAIL;
6129# endif
6130
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 /*
6132 * Don't allow the use of backticks in secure and restricted mode.
6133 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006134 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 for (i = 0; i < num_pat; ++i)
6136 if (vim_strchr(pat[i], '`') != NULL
6137 && (check_restricted() || check_secure()))
6138 return FAIL;
6139
6140 /*
6141 * get a name for the temp file
6142 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006143 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 {
6145 EMSG(_(e_notmp));
6146 return FAIL;
6147 }
6148
6149 /*
6150 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006151 * file.
6152 * STYLE_BT: NL separated
6153 * If expanding `cmd` execute it directly.
6154 * STYLE_GLOB: NUL separated
6155 * If we use *csh, "glob" will work better than "echo".
6156 * STYLE_PRINT: NL or NUL separated
6157 * If we use *zsh, "print -N" will work better than "glob".
6158 * STYLE_VIMGLOB: NL separated
6159 * If we use *sh*, we define "vimglob()".
6160 * STYLE_ECHO: space separated.
6161 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 */
6163 if (num_pat == 1 && *pat[0] == '`'
6164 && (len = STRLEN(pat[0])) > 2
6165 && *(pat[0] + len - 1) == '`')
6166 shell_style = STYLE_BT;
6167 else if ((len = STRLEN(p_sh)) >= 3)
6168 {
6169 if (STRCMP(p_sh + len - 3, "csh") == 0)
6170 shell_style = STYLE_GLOB;
6171 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6172 shell_style = STYLE_PRINT;
6173 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006174 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6175 "sh") != NULL)
6176 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177
Bram Moolenaarc7247912008-01-13 12:54:11 +00006178 /* Compute the length of the command. We need 2 extra bytes: for the
6179 * optional '&' and for the NUL.
6180 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006182 if (shell_style == STYLE_VIMGLOB)
6183 len += STRLEN(sh_vimglob_func);
6184
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006185 for (i = 0; i < num_pat; ++i)
6186 {
6187 /* Count the length of the patterns in the same way as they are put in
6188 * "command" below. */
6189#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006191#else
6192 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006193 for (j = 0; pat[i][j] != NUL; ++j)
6194 {
6195 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6196 ++len; /* may add a backslash */
6197 ++len;
6198 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006199#endif
6200 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201 command = alloc(len);
6202 if (command == NULL)
6203 {
6204 /* out of memory */
6205 vim_free(tempname);
6206 return FAIL;
6207 }
6208
6209 /*
6210 * Build the shell command:
6211 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6212 * recognizes this).
6213 * - Add the shell command to print the expanded names.
6214 * - Add the temp file name.
6215 * - Add the file name patterns.
6216 */
6217 if (shell_style == STYLE_BT)
6218 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006219 /* change `command; command& ` to (command; command ) */
6220 STRCPY(command, "(");
6221 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006223 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 while (p > command && vim_iswhite(*p))
6225 --p;
6226 if (*p == '&') /* remove trailing '&' */
6227 {
6228 ampersent = TRUE;
6229 *p = ' ';
6230 }
6231 STRCAT(command, ">");
6232 }
6233 else
6234 {
6235 if (flags & EW_NOTFOUND)
6236 STRCPY(command, "set nonomatch; ");
6237 else
6238 STRCPY(command, "unset nonomatch; ");
6239 if (shell_style == STYLE_GLOB)
6240 STRCAT(command, "glob >");
6241 else if (shell_style == STYLE_PRINT)
6242 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006243 else if (shell_style == STYLE_VIMGLOB)
6244 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 else
6246 STRCAT(command, "echo >");
6247 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006248
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006250
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 if (shell_style != STYLE_BT)
6252 for (i = 0; i < num_pat; ++i)
6253 {
6254 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006255 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006256 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257#ifdef USE_SYSTEM
6258 STRCAT(command, " \"");
6259 STRCAT(command, pat[i]);
6260 STRCAT(command, "\"");
6261#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006262 int intick = FALSE;
6263
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 p = command + STRLEN(command);
6265 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006266 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006267 {
6268 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006269 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006270 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6271 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006272 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006273 * backslash inside backticks, before a special character
6274 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006275 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006276 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6277 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006278 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006279 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006280 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006281 else if (!intick
6282 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6283 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006284 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006285 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6286 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006287 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006288
6289 /* Copy one character. */
6290 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006291 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 *p = NUL;
6293#endif
6294 }
6295 if (flags & EW_SILENT)
6296 show_shell_mess = FALSE;
6297 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006298 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299
6300 /*
6301 * Using zsh -G: If a pattern has no matches, it is just deleted from
6302 * the argument list, otherwise zsh gives an error message and doesn't
6303 * expand any other pattern.
6304 */
6305 if (shell_style == STYLE_PRINT)
6306 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6307
6308 /*
6309 * If we use -f then shell variables set in .cshrc won't get expanded.
6310 * vi can do it, so we will too, but it is only necessary if there is a "$"
6311 * in one of the patterns, otherwise we can still use the fast option.
6312 */
6313 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6314 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6315
6316 /*
6317 * execute the shell command
6318 */
6319 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6320
6321 /* When running in the background, give it some time to create the temp
6322 * file, but don't wait for it to finish. */
6323 if (ampersent)
6324 mch_delay(10L, TRUE);
6325
6326 extra_shell_arg = NULL; /* cleanup */
6327 show_shell_mess = TRUE;
6328 vim_free(command);
6329
Bram Moolenaarc7247912008-01-13 12:54:11 +00006330 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 {
6332 mch_remove(tempname);
6333 vim_free(tempname);
6334 /*
6335 * With interactive completion, the error message is not printed.
6336 * However with USE_SYSTEM, I don't know how to turn off error messages
6337 * from the shell, so screen may still get messed up -- webb.
6338 */
6339#ifndef USE_SYSTEM
6340 if (!(flags & EW_SILENT))
6341#endif
6342 {
6343 redraw_later_clear(); /* probably messed up screen */
6344 msg_putchar('\n'); /* clear bottom line quickly */
6345 cmdline_row = Rows - 1; /* continue on last line */
6346#ifdef USE_SYSTEM
6347 if (!(flags & EW_SILENT))
6348#endif
6349 {
6350 MSG(_(e_wildexpand));
6351 msg_start(); /* don't overwrite this message */
6352 }
6353 }
6354 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6355 * EW_NOTFOUND is given */
6356 if (shell_style == STYLE_BT)
6357 return FAIL;
6358 goto notfound;
6359 }
6360
6361 /*
6362 * read the names from the file into memory
6363 */
6364 fd = fopen((char *)tempname, READBIN);
6365 if (fd == NULL)
6366 {
6367 /* Something went wrong, perhaps a file name with a special char. */
6368 if (!(flags & EW_SILENT))
6369 {
6370 MSG(_(e_wildexpand));
6371 msg_start(); /* don't overwrite this message */
6372 }
6373 vim_free(tempname);
6374 goto notfound;
6375 }
6376 fseek(fd, 0L, SEEK_END);
6377 len = ftell(fd); /* get size of temp file */
6378 fseek(fd, 0L, SEEK_SET);
6379 buffer = alloc(len + 1);
6380 if (buffer == NULL)
6381 {
6382 /* out of memory */
6383 mch_remove(tempname);
6384 vim_free(tempname);
6385 fclose(fd);
6386 return FAIL;
6387 }
6388 i = fread((char *)buffer, 1, len, fd);
6389 fclose(fd);
6390 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006391 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 {
6393 /* unexpected read error */
6394 EMSG2(_(e_notread), tempname);
6395 vim_free(tempname);
6396 vim_free(buffer);
6397 return FAIL;
6398 }
6399 vim_free(tempname);
6400
Bram Moolenaarc7247912008-01-13 12:54:11 +00006401# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6403 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006404 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6406 *p++ = buffer[i];
6407 len = p - buffer;
6408# endif
6409
6410
6411 /* file names are separated with Space */
6412 if (shell_style == STYLE_ECHO)
6413 {
6414 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6415 p = buffer;
6416 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6417 {
6418 while (*p != ' ' && *p != '\n')
6419 ++p;
6420 p = skipwhite(p); /* skip to next entry */
6421 }
6422 }
6423 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006424 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 {
6426 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6427 p = buffer;
6428 for (i = 0; *p != NUL; ++i) /* count number of entries */
6429 {
6430 while (*p != '\n' && *p != NUL)
6431 ++p;
6432 if (*p != NUL)
6433 ++p;
6434 p = skipwhite(p); /* skip leading white space */
6435 }
6436 }
6437 /* file names are separated with NUL */
6438 else
6439 {
6440 /*
6441 * Some versions of zsh use spaces instead of NULs to separate
6442 * results. Only do this when there is no NUL before the end of the
6443 * buffer, otherwise we would never be able to use file names with
6444 * embedded spaces when zsh does use NULs.
6445 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6446 * don't check for spaces again.
6447 */
6448 check_spaces = FALSE;
6449 if (shell_style == STYLE_PRINT && !did_find_nul)
6450 {
6451 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006452 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006453 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454 did_find_nul = TRUE;
6455 else
6456 check_spaces = TRUE;
6457 }
6458
6459 /*
6460 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6461 * already is one, for STYLE_GLOB it needs to be added.
6462 */
6463 if (len && buffer[len - 1] == NUL)
6464 --len;
6465 else
6466 buffer[len] = NUL;
6467 i = 0;
6468 for (p = buffer; p < buffer + len; ++p)
6469 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6470 {
6471 ++i;
6472 *p = NUL;
6473 }
6474 if (len)
6475 ++i; /* count last entry */
6476 }
6477 if (i == 0)
6478 {
6479 /*
6480 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6481 * /bin/sh will happily expand it to nothing rather than returning an
6482 * error; and hey, it's good to check anyway -- webb.
6483 */
6484 vim_free(buffer);
6485 goto notfound;
6486 }
6487 *num_file = i;
6488 *file = (char_u **)alloc(sizeof(char_u *) * i);
6489 if (*file == NULL)
6490 {
6491 /* out of memory */
6492 vim_free(buffer);
6493 return FAIL;
6494 }
6495
6496 /*
6497 * Isolate the individual file names.
6498 */
6499 p = buffer;
6500 for (i = 0; i < *num_file; ++i)
6501 {
6502 (*file)[i] = p;
6503 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006504 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6505 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006507 while (!(shell_style == STYLE_ECHO && *p == ' ')
6508 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 ++p;
6510 if (p == buffer + len) /* last entry */
6511 *p = NUL;
6512 else
6513 {
6514 *p++ = NUL;
6515 p = skipwhite(p); /* skip to next entry */
6516 }
6517 }
6518 else /* NUL separates */
6519 {
6520 while (*p && p < buffer + len) /* skip entry */
6521 ++p;
6522 ++p; /* skip NUL */
6523 }
6524 }
6525
6526 /*
6527 * Move the file names to allocated memory.
6528 */
6529 for (j = 0, i = 0; i < *num_file; ++i)
6530 {
6531 /* Require the files to exist. Helps when using /bin/sh */
6532 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6533 continue;
6534
6535 /* check if this entry should be included */
6536 dir = (mch_isdir((*file)[i]));
6537 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6538 continue;
6539
Bram Moolenaara2031822006-03-07 22:29:51 +00006540 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006541 if (!dir && (flags & EW_EXEC)
6542 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006543 continue;
6544
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6546 if (p)
6547 {
6548 STRCPY(p, (*file)[i]);
6549 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006550 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 (*file)[j++] = p;
6552 }
6553 }
6554 vim_free(buffer);
6555 *num_file = j;
6556
6557 if (*num_file == 0) /* rejected all entries */
6558 {
6559 vim_free(*file);
6560 *file = NULL;
6561 goto notfound;
6562 }
6563
6564 return OK;
6565
6566notfound:
6567 if (flags & EW_NOTFOUND)
6568 return save_patterns(num_pat, pat, num_file, file);
6569 return FAIL;
6570
6571#endif /* __EMX__ */
6572}
6573
6574#endif /* VMS */
6575
6576#ifndef __EMX__
6577 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006578save_patterns(
6579 int num_pat,
6580 char_u **pat,
6581 int *num_file,
6582 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583{
6584 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006585 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586
6587 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6588 if (*file == NULL)
6589 return FAIL;
6590 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006591 {
6592 s = vim_strsave(pat[i]);
6593 if (s != NULL)
6594 /* Be compatible with expand_filename(): halve the number of
6595 * backslashes. */
6596 backslash_halve(s);
6597 (*file)[i] = s;
6598 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 *num_file = num_pat;
6600 return OK;
6601}
6602#endif
6603
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604/*
6605 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6606 * expand.
6607 */
6608 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006609mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006611 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 if (*p == '\\' && p[1] != NUL)
6614 ++p;
6615 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 if (vim_strchr((char_u *)
6617#ifdef VMS
6618 "*?%"
6619#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621#endif
6622 , *p) != NULL)
6623 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 }
6625 return FALSE;
6626}
6627
6628/*
6629 * Return TRUE if the string "p" contains a wildcard.
6630 * Don't recognize '~' at the end as a wildcard.
6631 */
6632 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006633mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006635 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (*p == '\\' && p[1] != NUL)
6638 ++p;
6639 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 if (vim_strchr((char_u *)
6641#ifdef VMS
6642 "*?%$"
6643#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645#endif
6646 , *p) != NULL
6647 || (*p == '~' && p[1] != NUL))
6648 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 }
6650 return FALSE;
6651}
6652
6653#ifndef __EMX__
6654 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006655have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656{
6657 int i;
6658
6659 for (i = 0; i < num; i++)
6660 if (mch_has_wildcard(file[i]))
6661 return 1;
6662 return 0;
6663}
6664
6665 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006666have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667{
6668 int i;
6669
6670 for (i = 0; i < num; i++)
6671 if (vim_strchr(file[i], '$') != NULL)
6672 return TRUE;
6673 return FALSE;
6674}
6675#endif /* ifndef __EMX__ */
6676
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006677#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678/*
6679 * Scaled-down version of rename(), which is missing in Xenix.
6680 * This version can only move regular files and will fail if the
6681 * destination exists.
6682 */
6683 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006684mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685{
6686 struct stat st;
6687
6688 if (stat(dest, &st) >= 0) /* fail if destination exists */
6689 return -1;
6690 if (link(src, dest) != 0) /* link file to new name */
6691 return -1;
6692 if (mch_remove(src) == 0) /* delete link to old name */
6693 return 0;
6694 return -1;
6695}
6696#endif /* !HAVE_RENAME */
6697
6698#ifdef FEAT_MOUSE_GPM
6699/*
6700 * Initializes connection with gpm (if it isn't already opened)
6701 * Return 1 if succeeded (or connection already opened), 0 if failed
6702 */
6703 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006704gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705{
6706 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6707
6708 if (!gpm_flag)
6709 {
6710 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6711 gpm_connect.defaultMask = ~GPM_HARD;
6712 /* Default handling for mouse move*/
6713 gpm_connect.minMod = 0; /* Handle any modifier keys */
6714 gpm_connect.maxMod = 0xffff;
6715 if (Gpm_Open(&gpm_connect, 0) > 0)
6716 {
6717 /* gpm library tries to handling TSTP causes
6718 * problems. Anyways, we close connection to Gpm whenever
6719 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006720 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006722# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 return 1; /* succeed */
6726 }
6727 if (gpm_fd == -2)
6728 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6729 return 0;
6730 }
6731 return 1; /* already open */
6732}
6733
6734/*
6735 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 */
6737 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006738gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739{
6740 if (gpm_flag && gpm_fd >= 0) /* if Open */
6741 Gpm_Close();
6742}
6743
6744/* Reads gpm event and adds special keys to input buf. Returns length of
6745 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006746 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 */
6748 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006749mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750{
6751 int button;
6752 static Gpm_Event gpm_event;
6753 char_u string[6];
6754 int_u vim_modifiers;
6755 int row,col;
6756 unsigned char buttons_mask;
6757 unsigned char gpm_modifiers;
6758 static unsigned char old_buttons = 0;
6759
6760 Gpm_GetEvent(&gpm_event);
6761
6762#ifdef FEAT_GUI
6763 /* Don't put events in the input queue now. */
6764 if (hold_gui_events)
6765 return 0;
6766#endif
6767
6768 row = gpm_event.y - 1;
6769 col = gpm_event.x - 1;
6770
6771 string[0] = ESC; /* Our termcode */
6772 string[1] = 'M';
6773 string[2] = 'G';
6774 switch (GPM_BARE_EVENTS(gpm_event.type))
6775 {
6776 case GPM_DRAG:
6777 string[3] = MOUSE_DRAG;
6778 break;
6779 case GPM_DOWN:
6780 buttons_mask = gpm_event.buttons & ~old_buttons;
6781 old_buttons = gpm_event.buttons;
6782 switch (buttons_mask)
6783 {
6784 case GPM_B_LEFT:
6785 button = MOUSE_LEFT;
6786 break;
6787 case GPM_B_MIDDLE:
6788 button = MOUSE_MIDDLE;
6789 break;
6790 case GPM_B_RIGHT:
6791 button = MOUSE_RIGHT;
6792 break;
6793 default:
6794 return 0;
6795 /*Don't know what to do. Can more than one button be
6796 * reported in one event? */
6797 }
6798 string[3] = (char_u)(button | 0x20);
6799 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6800 break;
6801 case GPM_UP:
6802 string[3] = MOUSE_RELEASE;
6803 old_buttons &= ~gpm_event.buttons;
6804 break;
6805 default:
6806 return 0;
6807 }
6808 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6809 gpm_modifiers = gpm_event.modifiers;
6810 vim_modifiers = 0x0;
6811 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6812 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6813 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6814 */
6815 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6816 vim_modifiers |= MOUSE_SHIFT;
6817
6818 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6819 vim_modifiers |= MOUSE_CTRL;
6820 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6821 vim_modifiers |= MOUSE_ALT;
6822 string[3] |= vim_modifiers;
6823 string[4] = (char_u)(col + ' ' + 1);
6824 string[5] = (char_u)(row + ' ' + 1);
6825 add_to_input_buf(string, 6);
6826 return 6;
6827}
6828#endif /* FEAT_MOUSE_GPM */
6829
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006830#ifdef FEAT_SYSMOUSE
6831/*
6832 * Initialize connection with sysmouse.
6833 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6834 * output, any sysmouse output than will be processed via sig_sysmouse().
6835 * Return OK if succeeded, FAIL if failed.
6836 */
6837 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006838sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006839{
6840 struct mouse_info mouse;
6841
6842 mouse.operation = MOUSE_MODE;
6843 mouse.u.mode.mode = 0;
6844 mouse.u.mode.signal = SIGUSR2;
6845 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6846 {
6847 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6848 mouse.operation = MOUSE_SHOW;
6849 ioctl(1, CONS_MOUSECTL, &mouse);
6850 return OK;
6851 }
6852 return FAIL;
6853}
6854
6855/*
6856 * Stop processing SIGUSR2 signals, and also make sure that
6857 * virtual console do not send us any sysmouse related signal.
6858 */
6859 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006860sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006861{
6862 struct mouse_info mouse;
6863
6864 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6865 mouse.operation = MOUSE_MODE;
6866 mouse.u.mode.mode = 0;
6867 mouse.u.mode.signal = 0;
6868 ioctl(1, CONS_MOUSECTL, &mouse);
6869}
6870
6871/*
6872 * Gets info from sysmouse and adds special keys to input buf.
6873 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006874 static RETSIGTYPE
6875sig_sysmouse SIGDEFARG(sigarg)
6876{
6877 struct mouse_info mouse;
6878 struct video_info video;
6879 char_u string[6];
6880 int row, col;
6881 int button;
6882 int buttons;
6883 static int oldbuttons = 0;
6884
6885#ifdef FEAT_GUI
6886 /* Don't put events in the input queue now. */
6887 if (hold_gui_events)
6888 return;
6889#endif
6890
6891 mouse.operation = MOUSE_GETINFO;
6892 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6893 && ioctl(1, FBIO_MODEINFO, &video) != -1
6894 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6895 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6896 {
6897 row = mouse.u.data.y / video.vi_cheight;
6898 col = mouse.u.data.x / video.vi_cwidth;
6899 buttons = mouse.u.data.buttons;
6900 string[0] = ESC; /* Our termcode */
6901 string[1] = 'M';
6902 string[2] = 'S';
6903 if (oldbuttons == buttons && buttons != 0)
6904 {
6905 button = MOUSE_DRAG;
6906 }
6907 else
6908 {
6909 switch (buttons)
6910 {
6911 case 0:
6912 button = MOUSE_RELEASE;
6913 break;
6914 case 1:
6915 button = MOUSE_LEFT;
6916 break;
6917 case 2:
6918 button = MOUSE_MIDDLE;
6919 break;
6920 case 4:
6921 button = MOUSE_RIGHT;
6922 break;
6923 default:
6924 return;
6925 }
6926 oldbuttons = buttons;
6927 }
6928 string[3] = (char_u)(button);
6929 string[4] = (char_u)(col + ' ' + 1);
6930 string[5] = (char_u)(row + ' ' + 1);
6931 add_to_input_buf(string, 6);
6932 }
6933 return;
6934}
6935#endif /* FEAT_SYSMOUSE */
6936
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006938typedef char_u * (*STRPROCSTR)(char_u *);
6939typedef char_u * (*INTPROCSTR)(int);
6940typedef int (*STRPROCINT)(char_u *);
6941typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942
6943/*
6944 * Call a DLL routine which takes either a string or int param
6945 * and returns an allocated string.
6946 */
6947 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006948mch_libcall(
6949 char_u *libname,
6950 char_u *funcname,
6951 char_u *argstring, /* NULL when using a argint */
6952 int argint,
6953 char_u **string_result,/* NULL when using number_result */
6954 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955{
6956# if defined(USE_DLOPEN)
6957 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006958 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959# else
6960 shl_t hinstLib;
6961# endif
6962 STRPROCSTR ProcAdd;
6963 INTPROCSTR ProcAddI;
6964 char_u *retval_str = NULL;
6965 int retval_int = 0;
6966 int success = FALSE;
6967
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006968 /*
6969 * Get a handle to the DLL module.
6970 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006972 /* First clear any error, it's not cleared by the dlopen() call. */
6973 (void)dlerror();
6974
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 hinstLib = dlopen((char *)libname, RTLD_LAZY
6976# ifdef RTLD_LOCAL
6977 | RTLD_LOCAL
6978# endif
6979 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006980 if (hinstLib == NULL)
6981 {
6982 /* "dlerr" must be used before dlclose() */
6983 dlerr = (char *)dlerror();
6984 if (dlerr != NULL)
6985 EMSG2(_("dlerror = \"%s\""), dlerr);
6986 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987# else
6988 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6989# endif
6990
6991 /* If the handle is valid, try to get the function address. */
6992 if (hinstLib != NULL)
6993 {
6994# ifdef HAVE_SETJMP_H
6995 /*
6996 * Catch a crash when calling the library function. For example when
6997 * using a number where a string pointer is expected.
6998 */
6999 mch_startjmp();
7000 if (SETJMP(lc_jump_env) != 0)
7001 {
7002 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007003# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007004 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007005# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 mch_didjmp();
7007 }
7008 else
7009# endif
7010 {
7011 retval_str = NULL;
7012 retval_int = 0;
7013
7014 if (argstring != NULL)
7015 {
7016# if defined(USE_DLOPEN)
7017 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007018 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019# else
7020 if (shl_findsym(&hinstLib, (const char *)funcname,
7021 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
7022 ProcAdd = NULL;
7023# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007024 if ((success = (ProcAdd != NULL
7025# if defined(USE_DLOPEN)
7026 && dlerr == NULL
7027# endif
7028 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 {
7030 if (string_result == NULL)
7031 retval_int = ((STRPROCINT)ProcAdd)(argstring);
7032 else
7033 retval_str = (ProcAdd)(argstring);
7034 }
7035 }
7036 else
7037 {
7038# if defined(USE_DLOPEN)
7039 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007040 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041# else
7042 if (shl_findsym(&hinstLib, (const char *)funcname,
7043 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
7044 ProcAddI = NULL;
7045# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007046 if ((success = (ProcAddI != NULL
7047# if defined(USE_DLOPEN)
7048 && dlerr == NULL
7049# endif
7050 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 {
7052 if (string_result == NULL)
7053 retval_int = ((INTPROCINT)ProcAddI)(argint);
7054 else
7055 retval_str = (ProcAddI)(argint);
7056 }
7057 }
7058
7059 /* Save the string before we free the library. */
7060 /* Assume that a "1" or "-1" result is an illegal pointer. */
7061 if (string_result == NULL)
7062 *number_result = retval_int;
7063 else if (retval_str != NULL
7064 && retval_str != (char_u *)1
7065 && retval_str != (char_u *)-1)
7066 *string_result = vim_strsave(retval_str);
7067 }
7068
7069# ifdef HAVE_SETJMP_H
7070 mch_endjmp();
7071# ifdef SIGHASARG
7072 if (lc_signal != 0)
7073 {
7074 int i;
7075
7076 /* try to find the name of this signal */
7077 for (i = 0; signal_info[i].sig != -1; i++)
7078 if (lc_signal == signal_info[i].sig)
7079 break;
7080 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
7081 }
7082# endif
7083# endif
7084
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007086 /* "dlerr" must be used before dlclose() */
7087 if (dlerr != NULL)
7088 EMSG2(_("dlerror = \"%s\""), dlerr);
7089
7090 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 (void)dlclose(hinstLib);
7092# else
7093 (void)shl_unload(hinstLib);
7094# endif
7095 }
7096
7097 if (!success)
7098 {
7099 EMSG2(_(e_libcall), funcname);
7100 return FAIL;
7101 }
7102
7103 return OK;
7104}
7105#endif
7106
7107#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7108static int xterm_trace = -1; /* default: disabled */
7109static int xterm_button;
7110
7111/*
7112 * Setup a dummy window for X selections in a terminal.
7113 */
7114 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007115setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116{
7117 int z = 0;
7118 char *strp = "";
7119 Widget AppShell;
7120
7121 if (!x_connect_to_server())
7122 return;
7123
7124 open_app_context();
7125 if (app_context != NULL && xterm_Shell == (Widget)0)
7126 {
7127 int (*oldhandler)();
7128#if defined(HAVE_SETJMP_H)
7129 int (*oldIOhandler)();
7130#endif
7131# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7132 struct timeval start_tv;
7133
7134 if (p_verbose > 0)
7135 gettimeofday(&start_tv, NULL);
7136# endif
7137
7138 /* Ignore X errors while opening the display */
7139 oldhandler = XSetErrorHandler(x_error_check);
7140
7141#if defined(HAVE_SETJMP_H)
7142 /* Ignore X IO errors while opening the display */
7143 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7144 mch_startjmp();
7145 if (SETJMP(lc_jump_env) != 0)
7146 {
7147 mch_didjmp();
7148 xterm_dpy = NULL;
7149 }
7150 else
7151#endif
7152 {
7153 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7154 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7155#if defined(HAVE_SETJMP_H)
7156 mch_endjmp();
7157#endif
7158 }
7159
7160#if defined(HAVE_SETJMP_H)
7161 /* Now handle X IO errors normally. */
7162 (void)XSetIOErrorHandler(oldIOhandler);
7163#endif
7164 /* Now handle X errors normally. */
7165 (void)XSetErrorHandler(oldhandler);
7166
7167 if (xterm_dpy == NULL)
7168 {
7169 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007170 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 return;
7172 }
7173
7174 /* Catch terminating error of the X server connection. */
7175 (void)XSetIOErrorHandler(x_IOerror_handler);
7176
7177# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7178 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007179 {
7180 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007182 verbose_leave();
7183 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184# endif
7185
7186 /* Create a Shell to make converters work. */
7187 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7188 applicationShellWidgetClass, xterm_dpy,
7189 NULL);
7190 if (AppShell == (Widget)0)
7191 return;
7192 xterm_Shell = XtVaCreatePopupShell("VIM",
7193 topLevelShellWidgetClass, AppShell,
7194 XtNmappedWhenManaged, 0,
7195 XtNwidth, 1,
7196 XtNheight, 1,
7197 NULL);
7198 if (xterm_Shell == (Widget)0)
7199 return;
7200
7201 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007202 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 if (x11_display == NULL)
7204 x11_display = xterm_dpy;
7205
7206 XtRealizeWidget(xterm_Shell);
7207 XSync(xterm_dpy, False);
7208 xterm_update();
7209 }
7210 if (xterm_Shell != (Widget)0)
7211 {
7212 clip_init(TRUE);
7213 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7214 x11_window = (Window)atol(strp);
7215 /* Check if $WINDOWID is valid. */
7216 if (test_x11_window(xterm_dpy) == FAIL)
7217 x11_window = 0;
7218 if (x11_window != 0)
7219 xterm_trace = 0;
7220 }
7221}
7222
7223 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007224start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225{
7226 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7227 return;
7228 xterm_trace = 1;
7229 xterm_button = button;
7230 do_xterm_trace();
7231}
7232
7233
7234 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007235stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236{
7237 if (xterm_trace < 0)
7238 return;
7239 xterm_trace = 0;
7240}
7241
7242/*
7243 * Query the xterm pointer and generate mouse termcodes if necessary
7244 * return TRUE if dragging is active, else FALSE
7245 */
7246 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007247do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007248{
7249 Window root, child;
7250 int root_x, root_y;
7251 int win_x, win_y;
7252 int row, col;
7253 int_u mask_return;
7254 char_u buf[50];
7255 char_u *strp;
7256 long got_hints;
7257 static char_u *mouse_code;
7258 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7259 static int prev_row = 0, prev_col = 0;
7260 static XSizeHints xterm_hints;
7261
7262 if (xterm_trace <= 0)
7263 return FALSE;
7264
7265 if (xterm_trace == 1)
7266 {
7267 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007268 * have changed recently. */
7269 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7270 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 || xterm_hints.width_inc <= 1
7272 || xterm_hints.height_inc <= 1)
7273 {
7274 xterm_trace = -1; /* Not enough data -- disable tracing */
7275 return FALSE;
7276 }
7277
7278 /* Rely on the same mouse code for the duration of this */
7279 mouse_code = find_termcode(mouse_name);
7280 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007281 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007282 xterm_trace = 2;
7283
7284 /* Find the offset of the chars, there might be a scrollbar on the
7285 * left of the window and/or a menu on the top (eterm etc.) */
7286 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7287 &win_x, &win_y, &mask_return);
7288 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7289 - (xterm_hints.height_inc / 2);
7290 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7291 xterm_hints.y = 2;
7292 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7293 - (xterm_hints.width_inc / 2);
7294 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7295 xterm_hints.x = 2;
7296 return TRUE;
7297 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007298 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 {
7300 xterm_trace = 0;
7301 return FALSE;
7302 }
7303
7304 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7305 &win_x, &win_y, &mask_return);
7306
7307 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7308 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7309 if (row == prev_row && col == prev_col)
7310 return TRUE;
7311
7312 STRCPY(buf, mouse_code);
7313 strp = buf + STRLEN(buf);
7314 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7315 *strp++ = (char_u)(col + ' ' + 1);
7316 *strp++ = (char_u)(row + ' ' + 1);
7317 *strp = 0;
7318 add_to_input_buf(buf, STRLEN(buf));
7319
7320 prev_row = row;
7321 prev_col = col;
7322 return TRUE;
7323}
7324
7325# if defined(FEAT_GUI) || defined(PROTO)
7326/*
7327 * Destroy the display, window and app_context. Required for GTK.
7328 */
7329 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007330clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007331{
7332 if (xterm_Shell != (Widget)0)
7333 {
7334 XtDestroyWidget(xterm_Shell);
7335 xterm_Shell = (Widget)0;
7336 }
7337 if (xterm_dpy != NULL)
7338 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007339# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 /* Lesstif and Solaris crash here, lose some memory */
7341 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007342# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343 if (x11_display == xterm_dpy)
7344 x11_display = NULL;
7345 xterm_dpy = NULL;
7346 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007347# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 if (app_context != (XtAppContext)NULL)
7349 {
7350 /* Lesstif and Solaris crash here, lose some memory */
7351 XtDestroyApplicationContext(app_context);
7352 app_context = (XtAppContext)NULL;
7353 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007354# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355}
7356# endif
7357
7358/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007359 * Catch up with GUI or X events.
7360 */
7361 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007362clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007363{
7364# ifdef FEAT_GUI
7365 if (gui.in_use)
7366 gui_mch_update();
7367 else
7368# endif
7369 if (xterm_Shell != (Widget)0)
7370 xterm_update();
7371}
7372
7373/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 * Catch up with any queued X events. This may put keyboard input into the
7375 * input buffer, call resize call-backs, trigger timers etc. If there is
7376 * nothing in the X event queue (& no timers pending), then we return
7377 * immediately.
7378 */
7379 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007380xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381{
7382 XEvent event;
7383
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007384 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007386 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007388 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007389 break;
7390
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007391 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007392 {
7393 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007394 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007395#ifdef FEAT_CLIENTSERVER
7396 {
7397 XPropertyEvent *e = (XPropertyEvent *)&event;
7398
7399 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007401 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007402 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007404 XtDispatchEvent(&event);
7405 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007406 else
7407 {
7408 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007409 XtAppProcessEvent(app_context, mask);
7410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 }
7412}
7413
7414 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007415clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416{
7417 if (xterm_Shell != (Widget)0)
7418 return clip_x11_own_selection(xterm_Shell, cbd);
7419 return FAIL;
7420}
7421
7422 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007423clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
7425 if (xterm_Shell != (Widget)0)
7426 clip_x11_lose_selection(xterm_Shell, cbd);
7427}
7428
7429 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007430clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431{
7432 if (xterm_Shell != (Widget)0)
7433 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7434}
7435
7436 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007437clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438{
7439 clip_x11_set_selection(cbd);
7440}
7441#endif
7442
7443
7444#if defined(USE_XSMP) || defined(PROTO)
7445/*
7446 * Code for X Session Management Protocol.
7447 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007448static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7449static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7450static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7451static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7452static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453
7454
7455# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007456static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457
7458/*
7459 * This is our chance to ask the user if they want to save,
7460 * or abort the logout
7461 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007463xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464{
7465 cmdmod_T save_cmdmod;
7466 int cancel_shutdown = False;
7467
7468 save_cmdmod = cmdmod;
7469 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007470 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 /* Mustn't logout */
7472 cancel_shutdown = True;
7473 cmdmod = save_cmdmod;
7474 setcursor(); /* position cursor */
7475 out_flush();
7476
7477 /* Done interaction */
7478 SmcInteractDone(smc_conn, cancel_shutdown);
7479
7480 /* Finish off
7481 * Only end save-yourself here if we're not cancelling shutdown;
7482 * we'll get a cancelled callback later in which we'll end it.
7483 * Hopefully get around glitchy SMs (like GNOME-1)
7484 */
7485 if (!cancel_shutdown)
7486 {
7487 xsmp.save_yourself = False;
7488 SmcSaveYourselfDone(smc_conn, True);
7489 }
7490}
7491# endif
7492
7493/*
7494 * Callback that starts save-yourself.
7495 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007497xsmp_handle_save_yourself(
7498 SmcConn smc_conn,
7499 SmPointer client_data UNUSED,
7500 int save_type UNUSED,
7501 Bool shutdown,
7502 int interact_style UNUSED,
7503 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504{
7505 /* Handle already being in saveyourself */
7506 if (xsmp.save_yourself)
7507 SmcSaveYourselfDone(smc_conn, True);
7508 xsmp.save_yourself = True;
7509 xsmp.shutdown = shutdown;
7510
7511 /* First up, preserve all files */
7512 out_flush();
7513 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7514
7515 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007516 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517
7518# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7519 /* Now see if we can ask about unsaved files */
7520 if (shutdown && !fast && gui.in_use)
7521 /* Need to interact with user, but need SM's permission */
7522 SmcInteractRequest(smc_conn, SmDialogError,
7523 xsmp_handle_interaction, client_data);
7524 else
7525# endif
7526 {
7527 /* Can stop the cycle here */
7528 SmcSaveYourselfDone(smc_conn, True);
7529 xsmp.save_yourself = False;
7530 }
7531}
7532
7533
7534/*
7535 * Callback to warn us of imminent death.
7536 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007538xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539{
7540 xsmp_close();
7541
7542 /* quit quickly leaving swapfiles for modified buffers behind */
7543 getout_preserve_modified(0);
7544}
7545
7546
7547/*
7548 * Callback to tell us that save-yourself has completed.
7549 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007551xsmp_save_complete(
7552 SmcConn smc_conn UNUSED,
7553 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554{
7555 xsmp.save_yourself = False;
7556}
7557
7558
7559/*
7560 * Callback to tell us that an instigated shutdown was cancelled
7561 * (maybe even by us)
7562 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007564xsmp_shutdown_cancelled(
7565 SmcConn smc_conn,
7566 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567{
7568 if (xsmp.save_yourself)
7569 SmcSaveYourselfDone(smc_conn, True);
7570 xsmp.save_yourself = False;
7571 xsmp.shutdown = False;
7572}
7573
7574
7575/*
7576 * Callback to tell us that a new ICE connection has been established.
7577 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007579xsmp_ice_connection(
7580 IceConn iceConn,
7581 IcePointer clientData UNUSED,
7582 Bool opening,
7583 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007584{
7585 /* Intercept creation of ICE connection fd */
7586 if (opening)
7587 {
7588 xsmp_icefd = IceConnectionNumber(iceConn);
7589 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7590 }
7591}
7592
7593
7594/* Handle any ICE processing that's required; return FAIL if SM lost */
7595 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007596xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597{
7598 Bool rep;
7599
7600 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7601 == IceProcessMessagesIOError)
7602 {
7603 /* Lost ICE */
7604 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007605 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 xsmp_close();
7607 return FAIL;
7608 }
7609 else
7610 return OK;
7611}
7612
7613static int dummy;
7614
7615/* Set up X Session Management Protocol */
7616 void
7617xsmp_init(void)
7618{
7619 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620 SmcCallbacks smcallbacks;
7621#if 0
7622 SmPropValue smname;
7623 SmProp smnameprop;
7624 SmProp *smprops[1];
7625#endif
7626
7627 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007628 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629
7630 xsmp.save_yourself = xsmp.shutdown = False;
7631
7632 /* Set up SM callbacks - must have all, even if they're not used */
7633 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7634 smcallbacks.save_yourself.client_data = NULL;
7635 smcallbacks.die.callback = xsmp_die;
7636 smcallbacks.die.client_data = NULL;
7637 smcallbacks.save_complete.callback = xsmp_save_complete;
7638 smcallbacks.save_complete.client_data = NULL;
7639 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7640 smcallbacks.shutdown_cancelled.client_data = NULL;
7641
7642 /* Set up a watch on ICE connection creations. The "dummy" argument is
7643 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7644 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7645 {
7646 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007647 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648 return;
7649 }
7650
7651 /* Create an SM connection */
7652 xsmp.smcconn = SmcOpenConnection(
7653 NULL,
7654 NULL,
7655 SmProtoMajor,
7656 SmProtoMinor,
7657 SmcSaveYourselfProcMask | SmcDieProcMask
7658 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7659 &smcallbacks,
7660 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007661 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 sizeof(errorstring),
7663 errorstring);
7664 if (xsmp.smcconn == NULL)
7665 {
7666 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007667
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007669 {
7670 vim_snprintf(errorreport, sizeof(errorreport),
7671 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7672 verb_msg((char_u *)errorreport);
7673 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 return;
7675 }
7676 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7677
7678#if 0
7679 /* ID ourselves */
7680 smname.value = "vim";
7681 smname.length = 3;
7682 smnameprop.name = "SmProgram";
7683 smnameprop.type = "SmARRAY8";
7684 smnameprop.num_vals = 1;
7685 smnameprop.vals = &smname;
7686
7687 smprops[0] = &smnameprop;
7688 SmcSetProperties(xsmp.smcconn, 1, smprops);
7689#endif
7690}
7691
7692
7693/* Shut down XSMP comms. */
7694 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007695xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696{
7697 if (xsmp_icefd != -1)
7698 {
7699 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007700 if (xsmp.clientid != NULL)
7701 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007702 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 xsmp_icefd = -1;
7704 }
7705}
7706#endif /* USE_XSMP */
7707
7708
7709#ifdef EBCDIC
7710/* Translate character to its CTRL- value */
7711char CtrlTable[] =
7712{
7713/* 00 - 5E */
7714 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7715 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7716 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7717 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7718 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7719 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7720/* ^ */ 0x1E,
7721/* - */ 0x1F,
7722/* 61 - 6C */
7723 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7724/* _ */ 0x1F,
7725/* 6E - 80 */
7726 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7727/* a */ 0x01,
7728/* b */ 0x02,
7729/* c */ 0x03,
7730/* d */ 0x37,
7731/* e */ 0x2D,
7732/* f */ 0x2E,
7733/* g */ 0x2F,
7734/* h */ 0x16,
7735/* i */ 0x05,
7736/* 8A - 90 */
7737 0, 0, 0, 0, 0, 0, 0,
7738/* j */ 0x15,
7739/* k */ 0x0B,
7740/* l */ 0x0C,
7741/* m */ 0x0D,
7742/* n */ 0x0E,
7743/* o */ 0x0F,
7744/* p */ 0x10,
7745/* q */ 0x11,
7746/* r */ 0x12,
7747/* 9A - A1 */
7748 0, 0, 0, 0, 0, 0, 0, 0,
7749/* s */ 0x13,
7750/* t */ 0x3C,
7751/* u */ 0x3D,
7752/* v */ 0x32,
7753/* w */ 0x26,
7754/* x */ 0x18,
7755/* y */ 0x19,
7756/* z */ 0x3F,
7757/* AA - AC */
7758 0, 0, 0,
7759/* [ */ 0x27,
7760/* AE - BC */
7761 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7762/* ] */ 0x1D,
7763/* BE - C0 */ 0, 0, 0,
7764/* A */ 0x01,
7765/* B */ 0x02,
7766/* C */ 0x03,
7767/* D */ 0x37,
7768/* E */ 0x2D,
7769/* F */ 0x2E,
7770/* G */ 0x2F,
7771/* H */ 0x16,
7772/* I */ 0x05,
7773/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7774/* J */ 0x15,
7775/* K */ 0x0B,
7776/* L */ 0x0C,
7777/* M */ 0x0D,
7778/* N */ 0x0E,
7779/* O */ 0x0F,
7780/* P */ 0x10,
7781/* Q */ 0x11,
7782/* R */ 0x12,
7783/* DA - DF */ 0, 0, 0, 0, 0, 0,
7784/* \ */ 0x1C,
7785/* E1 */ 0,
7786/* S */ 0x13,
7787/* T */ 0x3C,
7788/* U */ 0x3D,
7789/* V */ 0x32,
7790/* W */ 0x26,
7791/* X */ 0x18,
7792/* Y */ 0x19,
7793/* Z */ 0x3F,
7794/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7795 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7796};
7797
7798char MetaCharTable[]=
7799{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7800 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7801 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7802 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7803 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7804};
7805
7806
7807/* TODO: Use characters NOT numbers!!! */
7808char CtrlCharTable[]=
7809{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7810 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7811 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7812 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7813 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7814};
7815
7816
7817#endif