blob: 12e229cd95f7dd6509ca0d800a50d8020fa84686 [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
372/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000373 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 * Get a characters from the keyboard.
375 * Return the number of characters that are available.
376 * If wtime == 0 do not wait for characters.
377 * If wtime == n wait a short time for characters.
378 * If wtime == -1 wait forever for characters.
379 */
380 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100381mch_inchar(
382 char_u *buf,
383 int maxlen,
384 long wtime, /* don't use "time", MIPS cannot handle it */
385 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386{
387 int len;
Bram Moolenaarcda77642016-06-04 13:32:35 +0200388 int interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200390#ifdef MESSAGE_QUEUE
391 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200392#endif
393
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 /* Check if window changed size while we were busy, perhaps the ":set
395 * columns=99" command was used. */
396 while (do_resize)
397 handle_resize();
398
399 if (wtime >= 0)
400 {
Bram Moolenaarcda77642016-06-04 13:32:35 +0200401 /* TODO: when looping reduce wtime by the elapsed time. */
402 while (!WaitForChar(wtime, &interrupted))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 {
Bram Moolenaarcda77642016-06-04 13:32:35 +0200404 /* no character available */
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100405 if (do_resize)
Bram Moolenaarcda77642016-06-04 13:32:35 +0200406 {
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100407 handle_resize();
Bram Moolenaarcda77642016-06-04 13:32:35 +0200408 continue;
409 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100410#ifdef FEAT_CLIENTSERVER
Bram Moolenaarcda77642016-06-04 13:32:35 +0200411 if (server_waiting())
412 {
413 parse_queued_messages();
414 continue;
415 }
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100416#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200417#ifdef MESSAGE_QUEUE
Bram Moolenaarcda77642016-06-04 13:32:35 +0200418 if (interrupted)
419 {
420 parse_queued_messages();
421 continue;
422 }
Bram Moolenaar67c53842010-05-22 18:28:27 +0200423#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +0200424 /* return if not interrupted by resize or server */
425 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 }
427 }
428 else /* wtime == -1 */
429 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 /*
431 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000432 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 * Also done when interrupted by SIGWINCH.
434 */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200435 if (!WaitForChar(p_ut, &interrupted))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 {
Bram Moolenaarcda77642016-06-04 13:32:35 +0200437 /* TODO: if interrupted is set loop to wait the remaining time. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000438#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000439 if (trigger_cursorhold() && maxlen >= 3
440 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000442 buf[0] = K_SPECIAL;
443 buf[1] = KS_EXTRA;
444 buf[2] = (int)KE_CURSORHOLD;
445 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000448 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 }
450 }
451
Bram Moolenaarcda77642016-06-04 13:32:35 +0200452 /* repeat until we got a character */
453 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454 {
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200455 long wtime_now = -1L;
456
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 while (do_resize) /* window changed size */
458 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200459
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200460#ifdef MESSAGE_QUEUE
461 parse_queued_messages();
Bram Moolenaarcf7c11a2016-06-02 20:05:26 +0200462
463# ifdef FEAT_JOB_CHANNEL
464 if (has_pending_job())
465 {
466 /* Don't wait longer than a few seconds, checking for a finished
467 * job requires polling. */
468 if (p_ut > 9000L)
469 wtime_now = 1000L;
470 else
471 wtime_now = 10000L - p_ut;
472 }
473# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200474#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200476 * We want to be interrupted by the winch signal
477 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200479 if (!WaitForChar(wtime_now, &interrupted))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200480 {
481 if (do_resize) /* interrupted by SIGWINCH signal */
Bram Moolenaarcda77642016-06-04 13:32:35 +0200482 continue;
483#ifdef MESSAGE_QUEUE
484 if (interrupted || wtime_now > 0)
485 {
486 parse_queued_messages();
487 continue;
488 }
489#endif
Bram Moolenaar67c53842010-05-22 18:28:27 +0200490 return 0;
491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492
493 /* If input was put directly in typeahead buffer bail out here. */
494 if (typebuf_changed(tb_change_cnt))
495 return 0;
496
497 /*
498 * For some terminals we only get one character at a time.
499 * We want the get all available characters, so we could keep on
500 * trying until none is available
501 * For some other terminals this is quite slow, that's why we don't do
502 * it.
503 */
504 len = read_from_input_buf(buf, (long)maxlen);
505 if (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 return len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 }
508}
509
510 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100511handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512{
513 do_resize = FALSE;
514 shell_resized();
515}
516
517/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200518 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 */
520 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100521mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522{
Bram Moolenaarcda77642016-06-04 13:32:35 +0200523 return WaitForChar(0L, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524}
525
526#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
527# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000528# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529# endif
530# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
531# include <sys/sysctl.h>
532# endif
533# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
534# include <sys/sysinfo.h>
535# endif
536
537/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000538 * Return total amount of memory available in Kbyte.
539 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100542mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543{
544# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000545 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546# else
547 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000548 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549
550# ifdef HAVE_SYSCTL
551 int mib[2], physmem;
552 size_t len;
553
554 /* BSD way of getting the amount of RAM available. */
555 mib[0] = CTL_HW;
556 mib[1] = HW_USERMEM;
557 len = sizeof(physmem);
558 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
559 mem = (long_u)physmem;
560# endif
561
562# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
563 if (mem == 0)
564 {
565 struct sysinfo sinfo;
566
567 /* Linux way of getting amount of RAM available */
568 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000569 {
570# ifdef HAVE_SYSINFO_MEM_UNIT
571 /* avoid overflow as much as possible */
572 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
573 {
574 sinfo.mem_unit = sinfo.mem_unit >> 1;
575 --shiftright;
576 }
577 mem = sinfo.totalram * sinfo.mem_unit;
578# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000580# endif
581 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582 }
583# endif
584
585# ifdef HAVE_SYSCONF
586 if (mem == 0)
587 {
588 long pagesize, pagecount;
589
590 /* Solaris way of getting amount of RAM available */
591 pagesize = sysconf(_SC_PAGESIZE);
592 pagecount = sysconf(_SC_PHYS_PAGES);
593 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000594 {
595 /* avoid overflow as much as possible */
596 while (shiftright > 0 && (pagesize & 1) == 0)
597 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000598 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000599 --shiftright;
600 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000602 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 }
604# endif
605
606 /* Return the minimum of the physical memory and the user limit, because
607 * using more than the user limit may cause Vim to be terminated. */
608# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
609 {
610 struct rlimit rlp;
611
612 if (getrlimit(RLIMIT_DATA, &rlp) == 0
613 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
614# ifdef RLIM_INFINITY
615 && rlp.rlim_cur != RLIM_INFINITY
616# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000617 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000619 {
620 mem = (long_u)rlp.rlim_cur;
621 shiftright = 10;
622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 }
624# endif
625
626 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000627 return mem >> shiftright;
628 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629# endif
630}
631#endif
632
633 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100634mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635{
636 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000637#ifdef FEAT_MZSCHEME
638 long total = msec; /* remember original value */
639#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640
641 if (ignoreinput)
642 {
643 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000644 * here. But we don't want QUIT to kill us (CTRL-\ used in a
645 * shell may produce SIGQUIT). */
646 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647 old_tmode = curr_tmode;
648 if (curr_tmode == TMODE_RAW)
649 settmode(TMODE_SLEEP);
650
651 /*
652 * Everybody sleeps in a different way...
653 * Prefer nanosleep(), some versions of usleep() can only sleep up to
654 * one second.
655 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000656#ifdef FEAT_MZSCHEME
657 do
658 {
659 /* if total is large enough, wait by portions in p_mzq */
660 if (total > p_mzq)
661 msec = p_mzq;
662 else
663 msec = total;
664 total -= msec;
665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000666#ifdef HAVE_NANOSLEEP
667 {
668 struct timespec ts;
669
670 ts.tv_sec = msec / 1000;
671 ts.tv_nsec = (msec % 1000) * 1000000;
672 (void)nanosleep(&ts, NULL);
673 }
674#else
675# ifdef HAVE_USLEEP
676 while (msec >= 1000)
677 {
678 usleep((unsigned int)(999 * 1000));
679 msec -= 999;
680 }
681 usleep((unsigned int)(msec * 1000));
682# else
683# ifndef HAVE_SELECT
684 poll(NULL, 0, (int)msec);
685# else
686# ifdef __EMX__
687 _sleep2(msec);
688# else
689 {
690 struct timeval tv;
691
692 tv.tv_sec = msec / 1000;
693 tv.tv_usec = (msec % 1000) * 1000;
694 /*
695 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
696 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
697 */
698 select(0, NULL, NULL, NULL, &tv);
699 }
700# endif /* __EMX__ */
701# endif /* HAVE_SELECT */
702# endif /* HAVE_NANOSLEEP */
703#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000704#ifdef FEAT_MZSCHEME
705 }
706 while (total > 0);
707#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708
709 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000710 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711 }
712 else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200713 WaitForChar(msec, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714}
715
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000716#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
718# define HAVE_CHECK_STACK_GROWTH
719/*
720 * Support for checking for an almost-out-of-stack-space situation.
721 */
722
723/*
724 * Return a pointer to an item on the stack. Used to find out if the stack
725 * grows up or down.
726 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100727static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728static int stack_grows_downwards;
729
730/*
731 * Find out if the stack grows upwards or downwards.
732 * "p" points to a variable on the stack of the caller.
733 */
734 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100735check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000736{
737 int i;
738
739 stack_grows_downwards = (p > (char *)&i);
740}
741#endif
742
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000743#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744static char *stack_limit = NULL;
745
746#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
747# include <pthread.h>
748# include <pthread_np.h>
749#endif
750
751/*
752 * Find out until how var the stack can grow without getting into trouble.
753 * Called when starting up and when switching to the signal stack in
754 * deathtrap().
755 */
756 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100757get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758{
759 struct rlimit rlp;
760 int i;
761 long lim;
762
763 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
764 * limit doesn't fit in a long (rlim_cur might be "long long"). */
765 if (getrlimit(RLIMIT_STACK, &rlp) == 0
766 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
767# ifdef RLIM_INFINITY
768 && rlp.rlim_cur != RLIM_INFINITY
769# endif
770 )
771 {
772 lim = (long)rlp.rlim_cur;
773#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
774 {
775 pthread_attr_t attr;
776 size_t size;
777
778 /* On FreeBSD the initial thread always has a fixed stack size, no
779 * matter what the limits are set to. Normally it's 1 Mbyte. */
780 pthread_attr_init(&attr);
781 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
782 {
783 pthread_attr_getstacksize(&attr, &size);
784 if (lim > (long)size)
785 lim = (long)size;
786 }
787 pthread_attr_destroy(&attr);
788 }
789#endif
790 if (stack_grows_downwards)
791 {
792 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
793 if (stack_limit >= (char *)&i)
794 /* overflow, set to 1/16 of current stack position */
795 stack_limit = (char *)((long)&i / 16L);
796 }
797 else
798 {
799 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
800 if (stack_limit <= (char *)&i)
801 stack_limit = NULL; /* overflow */
802 }
803 }
804}
805
806/*
807 * Return FAIL when running out of stack space.
808 * "p" must point to any variable local to the caller that's on the stack.
809 */
810 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100811mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812{
813 if (stack_limit != NULL)
814 {
815 if (stack_grows_downwards)
816 {
817 if (p < stack_limit)
818 return FAIL;
819 }
820 else if (p > stack_limit)
821 return FAIL;
822 }
823 return OK;
824}
825#endif
826
827#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
828/*
829 * Support for using the signal stack.
830 * This helps when we run out of stack space, which causes a SIGSEGV. The
831 * signal handler then must run on another stack, since the normal stack is
832 * completely full.
833 */
834
Bram Moolenaar39766a72013-11-03 00:41:00 +0100835#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100836# include <AvailabilityMacros.h>
837#endif
838
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839#ifndef SIGSTKSZ
840# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
841#endif
842
843# ifdef HAVE_SIGALTSTACK
844static stack_t sigstk; /* for sigaltstack() */
845# else
846static struct sigstack sigstk; /* for sigstack() */
847# endif
848
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100849static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850static char *signal_stack;
851
852 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100853init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854{
855 if (signal_stack != NULL)
856 {
857# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000858# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
859 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
861 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100862 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863# endif
864
865# ifdef HAVE_SS_BASE
866 sigstk.ss_base = signal_stack;
867# else
868 sigstk.ss_sp = signal_stack;
869# endif
870 sigstk.ss_size = SIGSTKSZ;
871 sigstk.ss_flags = 0;
872 (void)sigaltstack(&sigstk, NULL);
873# else
874 sigstk.ss_sp = signal_stack;
875 if (stack_grows_downwards)
876 sigstk.ss_sp += SIGSTKSZ - 1;
877 sigstk.ss_onstack = 0;
878 (void)sigstack(&sigstk, NULL);
879# endif
880 }
881}
882#endif
883
884/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000885 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886 * will barf when the second argument to signal() is ``wrong''.
887 * Let me try it with a few tricky defines from my own osdef.h (jw).
888 */
889#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 static RETSIGTYPE
891sig_winch SIGDEFARG(sigarg)
892{
893 /* this is not required on all systems, but it doesn't hurt anybody */
894 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
895 do_resize = TRUE;
896 SIGRETURN;
897}
898#endif
899
900#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 static RETSIGTYPE
902catch_sigint SIGDEFARG(sigarg)
903{
904 /* this is not required on all systems, but it doesn't hurt anybody */
905 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
906 got_int = TRUE;
907 SIGRETURN;
908}
909#endif
910
911#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912 static RETSIGTYPE
913catch_sigpwr SIGDEFARG(sigarg)
914{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000915 /* this is not required on all systems, but it doesn't hurt anybody */
916 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917 /*
918 * I'm not sure we get the SIGPWR signal when the system is really going
919 * down or when the batteries are almost empty. Just preserve the swap
920 * files and don't exit, that can't do any harm.
921 */
922 ml_sync_all(FALSE, FALSE);
923 SIGRETURN;
924}
925#endif
926
927#ifdef SET_SIG_ALARM
928/*
929 * signal function for alarm().
930 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931 static RETSIGTYPE
932sig_alarm SIGDEFARG(sigarg)
933{
934 /* doesn't do anything, just to break a system call */
935 sig_alarm_called = TRUE;
936 SIGRETURN;
937}
938#endif
939
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000940#if (defined(HAVE_SETJMP_H) \
941 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
942 || defined(FEAT_LIBCALL))) \
943 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944/*
945 * A simplistic version of setjmp() that only allows one level of using.
946 * Don't call twice before calling mch_endjmp()!.
947 * Usage:
948 * mch_startjmp();
949 * if (SETJMP(lc_jump_env) != 0)
950 * {
951 * mch_didjmp();
952 * EMSG("crash!");
953 * }
954 * else
955 * {
956 * do_the_work;
957 * mch_endjmp();
958 * }
959 * Note: Can't move SETJMP() here, because a function calling setjmp() must
960 * not return before the saved environment is used.
961 * Returns OK for normal return, FAIL when the protected code caused a
962 * problem and LONGJMP() was used.
963 */
964 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100965mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966{
967#ifdef SIGHASARG
968 lc_signal = 0;
969#endif
970 lc_active = TRUE;
971}
972
973 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100974mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975{
976 lc_active = FALSE;
977}
978
979 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100980mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981{
982# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
983 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
984 * otherwise catching the signal only works once. */
985 init_signal_stack();
986# endif
987}
988#endif
989
990/*
991 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200992 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200994 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
995 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 */
997 static RETSIGTYPE
998deathtrap SIGDEFARG(sigarg)
999{
1000 static int entered = 0; /* count the number of times we got here.
1001 Note: when memory has been corrupted
1002 this may get an arbitrary value! */
1003#ifdef SIGHASARG
1004 int i;
1005#endif
1006
1007#if defined(HAVE_SETJMP_H)
1008 /*
1009 * Catch a crash in protected code.
1010 * Restores the environment saved in lc_jump_env, which looks like
1011 * SETJMP() returns 1.
1012 */
1013 if (lc_active)
1014 {
1015# if defined(SIGHASARG)
1016 lc_signal = sigarg;
1017# endif
1018 lc_active = FALSE; /* don't jump again */
1019 LONGJMP(lc_jump_env, 1);
1020 /* NOTREACHED */
1021 }
1022#endif
1023
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001024#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001025# ifdef SIGQUIT
1026 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1027 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1028 * pressing CTRL-\, but we don't want Vim to exit then. */
1029 if (in_mch_delay && sigarg == SIGQUIT)
1030 SIGRETURN;
1031# endif
1032
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001033 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1034 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1035 * free(). Calling free() again may then cause a crash. */
1036 if (entered == 0
1037 && (0
1038# ifdef SIGHUP
1039 || sigarg == SIGHUP
1040# endif
1041# ifdef SIGQUIT
1042 || sigarg == SIGQUIT
1043# endif
1044# ifdef SIGTERM
1045 || sigarg == SIGTERM
1046# endif
1047# ifdef SIGPWR
1048 || sigarg == SIGPWR
1049# endif
1050# ifdef SIGUSR1
1051 || sigarg == SIGUSR1
1052# endif
1053# ifdef SIGUSR2
1054 || sigarg == SIGUSR2
1055# endif
1056 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001057 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001058 SIGRETURN;
1059#endif
1060
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 /* Remember how often we have been called. */
1062 ++entered;
1063
1064#ifdef FEAT_EVAL
1065 /* Set the v:dying variable. */
1066 set_vim_var_nr(VV_DYING, (long)entered);
1067#endif
1068
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001069#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070 /* Since we are now using the signal stack, need to reset the stack
1071 * limit. Otherwise using a regexp will fail. */
1072 get_stack_limit();
1073#endif
1074
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001075#if 0
1076 /* This is for opening gdb the moment Vim crashes.
1077 * You need to manually adjust the file name and Vim executable name.
1078 * Suggested by SungHyun Nam. */
1079 {
1080# define VI_GDB_FILE "/tmp/vimgdb"
1081# define VIM_NAME "/usr/bin/vim"
1082 FILE *fp = fopen(VI_GDB_FILE, "w");
1083 if (fp)
1084 {
1085 fprintf(fp,
1086 "file %s\n"
1087 "attach %d\n"
1088 "set height 1000\n"
1089 "bt full\n"
1090 , VIM_NAME, getpid());
1091 fclose(fp);
1092 system("xterm -e gdb -x "VI_GDB_FILE);
1093 unlink(VI_GDB_FILE);
1094 }
1095 }
1096#endif
1097
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098#ifdef SIGHASARG
1099 /* try to find the name of this signal */
1100 for (i = 0; signal_info[i].sig != -1; i++)
1101 if (sigarg == signal_info[i].sig)
1102 break;
1103 deadly_signal = sigarg;
1104#endif
1105
1106 full_screen = FALSE; /* don't write message to the GUI, it might be
1107 * part of the problem... */
1108 /*
1109 * If something goes wrong after entering here, we may get here again.
1110 * When this happens, give a message and try to exit nicely (resetting the
1111 * terminal mode, etc.)
1112 * When this happens twice, just exit, don't even try to give a message,
1113 * stack may be corrupt or something weird.
1114 * When this still happens again (or memory was corrupted in such a way
1115 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1116 */
1117 if (entered >= 3)
1118 {
1119 reset_signals(); /* don't catch any signals anymore */
1120 may_core_dump();
1121 if (entered >= 4)
1122 _exit(8);
1123 exit(7);
1124 }
1125 if (entered == 2)
1126 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001127 /* No translation, it may call malloc(). */
1128 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 out_flush();
1130 getout(1);
1131 }
1132
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001133 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001135 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136 signal_info[i].name);
1137#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001138 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001140
1141 /* Preserve files and exit. This sets the really_exiting flag to prevent
1142 * calling free(). */
1143 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144
Bram Moolenaar009b2592004-10-24 19:18:58 +00001145#ifdef NBDEBUG
1146 reset_signals();
1147 may_core_dump();
1148 abort();
1149#endif
1150
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 SIGRETURN;
1152}
1153
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001154#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155/*
1156 * On Solaris with multi-threading, suspending might not work immediately.
1157 * Catch the SIGCONT signal, which will be used as an indication whether the
1158 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001159 *
1160 * On Linux, signal is not always handled immediately either.
1161 * See https://bugs.launchpad.net/bugs/291373
1162 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001163 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001165static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001166static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168/*
1169 * signal handler for SIGCONT
1170 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 static RETSIGTYPE
1172sigcont_handler SIGDEFARG(sigarg)
1173{
1174 sigcont_received = TRUE;
1175 SIGRETURN;
1176}
1177#endif
1178
Bram Moolenaar62b42182010-09-21 22:09:37 +02001179# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001180static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001181# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001182static void save_clipboard(void);
1183static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001184
1185static void *clip_star_save = NULL;
1186static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001187# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001188
1189/*
1190 * Called when Vim is going to sleep or execute a shell command.
1191 * We can't respond to requests for the X selections. Lose them, otherwise
1192 * other applications will hang. But first copy the text to cut buffer 0.
1193 */
1194 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001195loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001196{
1197 if (clip_star.owned || clip_plus.owned)
1198 {
1199 x11_export_final_selection();
1200 if (clip_star.owned)
1201 clip_lose_selection(&clip_star);
1202 if (clip_plus.owned)
1203 clip_lose_selection(&clip_plus);
1204 if (x11_display != NULL)
1205 XFlush(x11_display);
1206 }
1207}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001208
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001209# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001210/*
1211 * Save clipboard text to restore later.
1212 */
1213 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001214save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001215{
1216 if (clip_star.owned)
1217 clip_star_save = get_register('*', TRUE);
1218 if (clip_plus.owned)
1219 clip_plus_save = get_register('+', TRUE);
1220}
1221
1222/*
1223 * Restore clipboard text if no one own the X selection.
1224 */
1225 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001226restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001227{
1228 if (clip_star_save != NULL)
1229 {
1230 if (!clip_gen_owner_exists(&clip_star))
1231 put_register('*', clip_star_save);
1232 else
1233 free_register(clip_star_save);
1234 clip_star_save = NULL;
1235 }
1236 if (clip_plus_save != NULL)
1237 {
1238 if (!clip_gen_owner_exists(&clip_plus))
1239 put_register('+', clip_plus_save);
1240 else
1241 free_register(clip_plus_save);
1242 clip_plus_save = NULL;
1243 }
1244}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001245# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001246#endif
1247
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248/*
1249 * If the machine has job control, use it to suspend the program,
1250 * otherwise fake it by starting a new shell.
1251 */
1252 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001253mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254{
1255 /* BeOS does have SIGTSTP, but it doesn't work. */
1256#if defined(SIGTSTP) && !defined(__BEOS__)
1257 out_flush(); /* needed to make cursor visible on some systems */
1258 settmode(TMODE_COOK);
1259 out_flush(); /* needed to disable mouse on some systems */
1260
1261# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001262 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263# endif
1264
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001265# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266 sigcont_received = FALSE;
1267# endif
1268 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001269# if defined(_REENTRANT) && defined(SIGCONT)
1270 /*
1271 * Wait for the SIGCONT signal to be handled. It generally happens
1272 * immediately, but somehow not all the time. Do not call pause()
1273 * because there would be race condition which would hang Vim if
1274 * signal happened in between the test of sigcont_received and the
1275 * call to pause(). If signal is not yet received, call sleep(0)
1276 * to just yield CPU. Signal should then be received. If somehow
1277 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1278 * further if signal is not received after 1+2+3+4 ms (not expected
1279 * to happen).
1280 */
1281 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001282 long wait_time;
1283 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001284 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001285 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287# endif
1288
1289# ifdef FEAT_TITLE
1290 /*
1291 * Set oldtitle to NULL, so the current title is obtained again.
1292 */
1293 vim_free(oldtitle);
1294 oldtitle = NULL;
1295# endif
1296 settmode(TMODE_RAW);
1297 need_check_timestamps = TRUE;
1298 did_check_timestamps = FALSE;
1299#else
1300 suspend_shell();
1301#endif
1302}
1303
1304 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001305mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306{
1307 Columns = 80;
1308 Rows = 24;
1309
1310 out_flush();
1311 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001312
Bram Moolenaar56718732006-03-15 22:53:57 +00001313#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001314 mac_conv_init();
1315#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001316#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1317 win_clip_init();
1318#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319}
1320
1321 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001322set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323{
1324#if defined(SIGWINCH)
1325 /*
1326 * WINDOW CHANGE signal is handled with sig_winch().
1327 */
1328 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1329#endif
1330
1331 /*
1332 * We want the STOP signal to work, to make mch_suspend() work.
1333 * For "rvim" the STOP signal is ignored.
1334 */
1335#ifdef SIGTSTP
1336 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1337#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001338#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339 signal(SIGCONT, sigcont_handler);
1340#endif
1341
1342 /*
1343 * We want to ignore breaking of PIPEs.
1344 */
1345#ifdef SIGPIPE
1346 signal(SIGPIPE, SIG_IGN);
1347#endif
1348
Bram Moolenaar071d4272004-06-13 20:20:40 +00001349#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001350 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351#endif
1352
1353 /*
1354 * Ignore alarm signals (Perl's alarm() generates it).
1355 */
1356#ifdef SIGALRM
1357 signal(SIGALRM, SIG_IGN);
1358#endif
1359
1360 /*
1361 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1362 * work will be lost.
1363 */
1364#ifdef SIGPWR
1365 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1366#endif
1367
1368 /*
1369 * Arrange for other signals to gracefully shutdown Vim.
1370 */
1371 catch_signals(deathtrap, SIG_ERR);
1372
1373#if defined(FEAT_GUI) && defined(SIGHUP)
1374 /*
1375 * When the GUI is running, ignore the hangup signal.
1376 */
1377 if (gui.in_use)
1378 signal(SIGHUP, SIG_IGN);
1379#endif
1380}
1381
Bram Moolenaardf177f62005-02-22 08:39:57 +00001382#if defined(SIGINT) || defined(PROTO)
1383/*
1384 * Catch CTRL-C (only works while in Cooked mode).
1385 */
1386 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001387catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001388{
1389 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1390}
1391#endif
1392
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001394reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395{
1396 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001397#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 /* SIGCONT isn't in the list, because its default action is ignore */
1399 signal(SIGCONT, SIG_DFL);
1400#endif
1401}
1402
1403 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001404catch_signals(
1405 RETSIGTYPE (*func_deadly)(),
1406 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407{
1408 int i;
1409
1410 for (i = 0; signal_info[i].sig != -1; i++)
1411 if (signal_info[i].deadly)
1412 {
1413#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1414 struct sigaction sa;
1415
1416 /* Setup to use the alternate stack for the signal function. */
1417 sa.sa_handler = func_deadly;
1418 sigemptyset(&sa.sa_mask);
1419# if defined(__linux__) && defined(_REENTRANT)
1420 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1421 * thread handling in combination with using the alternate stack:
1422 * pthread library functions try to use the stack pointer to
1423 * identify the current thread, causing a SEGV signal, which
1424 * recursively calls deathtrap() and hangs. */
1425 sa.sa_flags = 0;
1426# else
1427 sa.sa_flags = SA_ONSTACK;
1428# endif
1429 sigaction(signal_info[i].sig, &sa, NULL);
1430#else
1431# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1432 struct sigvec sv;
1433
1434 /* Setup to use the alternate stack for the signal function. */
1435 sv.sv_handler = func_deadly;
1436 sv.sv_mask = 0;
1437 sv.sv_flags = SV_ONSTACK;
1438 sigvec(signal_info[i].sig, &sv, NULL);
1439# else
1440 signal(signal_info[i].sig, func_deadly);
1441# endif
1442#endif
1443 }
1444 else if (func_other != SIG_ERR)
1445 signal(signal_info[i].sig, func_other);
1446}
1447
1448/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001449 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001450 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1451 * return TRUE
1452 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1453 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001454 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001455 * Returns TRUE when Vim should exit.
1456 */
1457 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001458vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001459{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001460 static int got_signal = 0;
1461 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001462
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001463 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001464 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001465 case SIGNAL_BLOCK: blocked = TRUE;
1466 break;
1467
1468 case SIGNAL_UNBLOCK: blocked = FALSE;
1469 if (got_signal != 0)
1470 {
1471 kill(getpid(), got_signal);
1472 got_signal = 0;
1473 }
1474 break;
1475
1476 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001477 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001478 got_signal = sig;
1479#ifdef SIGPWR
1480 if (sig != SIGPWR)
1481#endif
1482 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001483 break;
1484 }
1485 return FALSE;
1486}
1487
1488/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 * Check_win checks whether we have an interactive stdout.
1490 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001492mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 if (isatty(1))
1495 return OK;
1496 return FAIL;
1497}
1498
1499/*
1500 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1501 */
1502 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001503mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504{
1505 if (isatty(read_cmd_fd))
1506 return TRUE;
1507 return FALSE;
1508}
1509
1510#ifdef FEAT_X11
1511
1512# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1513 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1514
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001515static void xopen_message(struct timeval *tvp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516
1517/*
1518 * Give a message about the elapsed time for opening the X window.
1519 */
1520 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001521xopen_message(
1522 struct timeval *tvp) /* must contain start time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523{
1524 struct timeval end_tv;
1525
1526 /* Compute elapsed time. */
1527 gettimeofday(&end_tv, NULL);
1528 smsg((char_u *)_("Opening the X display took %ld msec"),
1529 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001530 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531}
1532# endif
1533#endif
1534
1535#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1536/*
1537 * A few functions shared by X11 title and clipboard code.
1538 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001539static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1540static int x_error_check(Display *dpy, XErrorEvent *error_event);
1541static int x_connect_to_server(void);
1542static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543
1544static int got_x_error = FALSE;
1545
1546/*
1547 * X Error handler, otherwise X just exits! (very rude) -- webb
1548 */
1549 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001550x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001552 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 STRCAT(IObuff, _("\nVim: Got X error\n"));
1554
1555 /* We cannot print a message and continue, because no X calls are allowed
1556 * here (causes my system to hang). Silently continuing might be an
1557 * alternative... */
1558 preserve_exit(); /* preserve files and exit */
1559
1560 return 0; /* NOTREACHED */
1561}
1562
1563/*
1564 * Another X Error handler, just used to check for errors.
1565 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001567x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568{
1569 got_x_error = TRUE;
1570 return 0;
1571}
1572
1573#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1574# if defined(HAVE_SETJMP_H)
1575/*
1576 * An X IO Error handler, used to catch error while opening the display.
1577 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001578static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001581x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582{
1583 /* This function should not return, it causes exit(). Longjump instead. */
1584 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001585# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001586 return 0; /* avoid the compiler complains about missing return value */
1587# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588}
1589# endif
1590
1591/*
1592 * An X IO Error handler, used to catch terminal errors.
1593 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001594static int x_IOerror_handler(Display *dpy);
1595static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001596static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001599x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600{
1601 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001602 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 x11_window = 0;
1604 x11_display = NULL;
1605 xterm_Shell = (Widget)0;
1606
1607 /* This function should not return, it causes exit(). Longjump instead. */
1608 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001609# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001610 return 0; /* avoid the compiler complains about missing return value */
1611# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001613
1614/*
1615 * If the X11 connection was lost try to restore it.
1616 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001617 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001618 */
1619 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001620may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001621{
1622 if (xterm_dpy_was_reset)
1623 {
1624 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001625
1626# ifndef LESSTIF_VERSION
1627 /* This has been reported to avoid Vim getting stuck. */
1628 if (app_context != (XtAppContext)NULL)
1629 {
1630 XtDestroyApplicationContext(app_context);
1631 app_context = (XtAppContext)NULL;
1632 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1633 }
1634# endif
1635
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001636 setup_term_clip();
1637 get_x11_title(FALSE);
1638 }
1639}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640#endif
1641
1642/*
1643 * Return TRUE when connection to the X server is desired.
1644 */
1645 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001646x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648#if defined(FEAT_CLIENTSERVER)
1649 if (x_force_connect)
1650 return TRUE;
1651#endif
1652 if (x_no_connect)
1653 return FALSE;
1654
1655 /* Check for a match with "exclude:" from 'clipboard'. */
1656 if (clip_exclude_prog != NULL)
1657 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001658 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 return FALSE;
1660 }
1661 return TRUE;
1662}
1663
1664/*
1665 * Test if "dpy" and x11_window are valid by getting the window title.
1666 * I don't actually want it yet, so there may be a simpler call to use, but
1667 * this will cause the error handler x_error_check() to be called if anything
1668 * is wrong, such as the window pointer being invalid (as can happen when the
1669 * user changes his DISPLAY, but not his WINDOWID) -- webb
1670 */
1671 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001672test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673{
1674 int (*old_handler)();
1675 XTextProperty text_prop;
1676
1677 old_handler = XSetErrorHandler(x_error_check);
1678 got_x_error = FALSE;
1679 if (XGetWMName(dpy, x11_window, &text_prop))
1680 XFree((void *)text_prop.value);
1681 XSync(dpy, False);
1682 (void)XSetErrorHandler(old_handler);
1683
1684 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001685 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686
1687 return (got_x_error ? FAIL : OK);
1688}
1689#endif
1690
1691#ifdef FEAT_TITLE
1692
1693#ifdef FEAT_X11
1694
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001695static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696
1697/*
1698 * try to get x11 window and display
1699 *
1700 * return FAIL for failure, OK otherwise
1701 */
1702 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001703get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704{
1705 char *winid;
1706 static int result = -1;
1707#define XD_NONE 0 /* x11_display not set here */
1708#define XD_HERE 1 /* x11_display opened here */
1709#define XD_GUI 2 /* x11_display used from gui.dpy */
1710#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1711 static int x11_display_from = XD_NONE;
1712 static int did_set_error_handler = FALSE;
1713
1714 if (!did_set_error_handler)
1715 {
1716 /* X just exits if it finds an error otherwise! */
1717 (void)XSetErrorHandler(x_error_handler);
1718 did_set_error_handler = TRUE;
1719 }
1720
Bram Moolenaar9372a112005-12-06 19:59:18 +00001721#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 if (gui.in_use)
1723 {
1724 /*
1725 * If the X11 display was opened here before, for the window where Vim
1726 * was started, close that one now to avoid a memory leak.
1727 */
1728 if (x11_display_from == XD_HERE && x11_display != NULL)
1729 {
1730 XCloseDisplay(x11_display);
1731 x11_display_from = XD_NONE;
1732 }
1733 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1734 {
1735 x11_display_from = XD_GUI;
1736 return OK;
1737 }
1738 x11_display = NULL;
1739 return FAIL;
1740 }
1741 else if (x11_display_from == XD_GUI)
1742 {
1743 /* GUI must have stopped somehow, clear x11_display */
1744 x11_window = 0;
1745 x11_display = NULL;
1746 x11_display_from = XD_NONE;
1747 }
1748#endif
1749
1750 /* When started with the "-X" argument, don't try connecting. */
1751 if (!x_connect_to_server())
1752 return FAIL;
1753
1754 /*
1755 * If WINDOWID not set, should try another method to find out
1756 * what the current window number is. The only code I know for
1757 * this is very complicated.
1758 * We assume that zero is invalid for WINDOWID.
1759 */
1760 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1761 x11_window = (Window)atol(winid);
1762
1763#ifdef FEAT_XCLIPBOARD
1764 if (xterm_dpy != NULL && x11_window != 0)
1765 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001766 /* We may have checked it already, but Gnome terminal can move us to
1767 * another window, so we need to check every time. */
1768 if (x11_display_from != XD_XTERM)
1769 {
1770 /*
1771 * If the X11 display was opened here before, for the window where
1772 * Vim was started, close that one now to avoid a memory leak.
1773 */
1774 if (x11_display_from == XD_HERE && x11_display != NULL)
1775 XCloseDisplay(x11_display);
1776 x11_display = xterm_dpy;
1777 x11_display_from = XD_XTERM;
1778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 if (test_x11_window(x11_display) == FAIL)
1780 {
1781 /* probably bad $WINDOWID */
1782 x11_window = 0;
1783 x11_display = NULL;
1784 x11_display_from = XD_NONE;
1785 return FAIL;
1786 }
1787 return OK;
1788 }
1789#endif
1790
1791 if (x11_window == 0 || x11_display == NULL)
1792 result = -1;
1793
1794 if (result != -1) /* Have already been here and set this */
1795 return result; /* Don't do all these X calls again */
1796
1797 if (x11_window != 0 && x11_display == NULL)
1798 {
1799#ifdef SET_SIG_ALARM
1800 RETSIGTYPE (*sig_save)();
1801#endif
1802#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1803 struct timeval start_tv;
1804
1805 if (p_verbose > 0)
1806 gettimeofday(&start_tv, NULL);
1807#endif
1808
1809#ifdef SET_SIG_ALARM
1810 /*
1811 * Opening the Display may hang if the DISPLAY setting is wrong, or
1812 * the network connection is bad. Set an alarm timer to get out.
1813 */
1814 sig_alarm_called = FALSE;
1815 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1816 (RETSIGTYPE (*)())sig_alarm);
1817 alarm(2);
1818#endif
1819 x11_display = XOpenDisplay(NULL);
1820
1821#ifdef SET_SIG_ALARM
1822 alarm(0);
1823 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1824 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001825 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826#endif
1827 if (x11_display != NULL)
1828 {
1829# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1830 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001831 {
1832 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001834 verbose_leave();
1835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836# endif
1837 if (test_x11_window(x11_display) == FAIL)
1838 {
1839 /* Maybe window id is bad */
1840 x11_window = 0;
1841 XCloseDisplay(x11_display);
1842 x11_display = NULL;
1843 }
1844 else
1845 x11_display_from = XD_HERE;
1846 }
1847 }
1848 if (x11_window == 0 || x11_display == NULL)
1849 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001850
1851# ifdef FEAT_EVAL
1852 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1853# endif
1854
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 return (result = OK);
1856}
1857
1858/*
1859 * Determine original x11 Window Title
1860 */
1861 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001862get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001864 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
1866
1867/*
1868 * Determine original x11 Window icon
1869 */
1870 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001871get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872{
1873 int retval = FALSE;
1874
1875 retval = get_x11_thing(FALSE, test_only);
1876
1877 /* could not get old icon, use terminal name */
1878 if (oldicon == NULL && !test_only)
1879 {
1880 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001881 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001883 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 }
1885
1886 return retval;
1887}
1888
1889 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001890get_x11_thing(
1891 int get_title, /* get title string */
1892 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893{
1894 XTextProperty text_prop;
1895 int retval = FALSE;
1896 Status status;
1897
1898 if (get_x11_windis() == OK)
1899 {
1900 /* Get window/icon name if any */
1901 if (get_title)
1902 status = XGetWMName(x11_display, x11_window, &text_prop);
1903 else
1904 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1905
1906 /*
1907 * If terminal is xterm, then x11_window may be a child window of the
1908 * outer xterm window that actually contains the window/icon name, so
1909 * keep traversing up the tree until a window with a title/icon is
1910 * found.
1911 */
1912 /* Previously this was only done for xterm and alikes. I don't see a
1913 * reason why it would fail for other terminal emulators.
1914 * if (term_is_xterm) */
1915 {
1916 Window root;
1917 Window parent;
1918 Window win = x11_window;
1919 Window *children;
1920 unsigned int num_children;
1921
1922 while (!status || text_prop.value == NULL)
1923 {
1924 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1925 &num_children))
1926 break;
1927 if (children)
1928 XFree((void *)children);
1929 if (parent == root || parent == 0)
1930 break;
1931
1932 win = parent;
1933 if (get_title)
1934 status = XGetWMName(x11_display, win, &text_prop);
1935 else
1936 status = XGetWMIconName(x11_display, win, &text_prop);
1937 }
1938 }
1939 if (status && text_prop.value != NULL)
1940 {
1941 retval = TRUE;
1942 if (!test_only)
1943 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001944#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1945 if (text_prop.encoding == XA_STRING
1946# ifdef FEAT_MBYTE
1947 && !has_mbyte
1948# endif
1949 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 {
1951#endif
1952 if (get_title)
1953 oldtitle = vim_strsave((char_u *)text_prop.value);
1954 else
1955 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001956#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 }
1958 else
1959 {
1960 char **cl;
1961 Status transform_status;
1962 int n = 0;
1963
1964 transform_status = XmbTextPropertyToTextList(x11_display,
1965 &text_prop,
1966 &cl, &n);
1967 if (transform_status >= Success && n > 0 && cl[0])
1968 {
1969 if (get_title)
1970 oldtitle = vim_strsave((char_u *) cl[0]);
1971 else
1972 oldicon = vim_strsave((char_u *) cl[0]);
1973 XFreeStringList(cl);
1974 }
1975 else
1976 {
1977 if (get_title)
1978 oldtitle = vim_strsave((char_u *)text_prop.value);
1979 else
1980 oldicon = vim_strsave((char_u *)text_prop.value);
1981 }
1982 }
1983#endif
1984 }
1985 XFree((void *)text_prop.value);
1986 }
1987 }
1988 return retval;
1989}
1990
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001991/* Xutf8 functions are not avaialble on older systems. Note that on some
1992 * systems X_HAVE_UTF8_STRING may be defined in a header file but
1993 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
1994 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001996# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997# define USE_UTF8_STRING
1998# endif
1999#endif
2000
2001/*
2002 * Set x11 Window Title
2003 *
2004 * get_x11_windis() must be called before this and have returned OK
2005 */
2006 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002007set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008{
2009 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2010 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2011 * supported everywhere and STRING doesn't work for multi-byte titles.
2012 */
2013#ifdef USE_UTF8_STRING
2014 if (enc_utf8)
2015 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2016 NULL, NULL, 0, NULL, NULL, NULL);
2017 else
2018#endif
2019 {
2020#if XtSpecificationRelease >= 4
2021# ifdef FEAT_XFONTSET
2022 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2023 NULL, NULL, 0, NULL, NULL, NULL);
2024# else
2025 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002026 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002027
2028 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002029 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 XSetWMProperties(x11_display, x11_window, &text_prop,
2031 NULL, NULL, 0, NULL, NULL, NULL);
2032# endif
2033#else
2034 XStoreName(x11_display, x11_window, (char *)title);
2035#endif
2036 }
2037 XFlush(x11_display);
2038}
2039
2040/*
2041 * Set x11 Window icon
2042 *
2043 * get_x11_windis() must be called before this and have returned OK
2044 */
2045 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002046set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047{
2048 /* See above for comments about using X*SetWMProperties(). */
2049#ifdef USE_UTF8_STRING
2050 if (enc_utf8)
2051 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2052 NULL, 0, NULL, NULL, NULL);
2053 else
2054#endif
2055 {
2056#if XtSpecificationRelease >= 4
2057# ifdef FEAT_XFONTSET
2058 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2059 NULL, 0, NULL, NULL, NULL);
2060# else
2061 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002062 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002064 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2066 NULL, 0, NULL, NULL, NULL);
2067# endif
2068#else
2069 XSetIconName(x11_display, x11_window, (char *)icon);
2070#endif
2071 }
2072 XFlush(x11_display);
2073}
2074
2075#else /* FEAT_X11 */
2076
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002078get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079{
2080 return FALSE;
2081}
2082
2083 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002084get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085{
2086 if (!test_only)
2087 {
2088 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002089 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002091 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 }
2093 return FALSE;
2094}
2095
2096#endif /* FEAT_X11 */
2097
2098 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002099mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100{
2101 return get_x11_title(TRUE);
2102}
2103
2104 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002105mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106{
2107 return get_x11_icon(TRUE);
2108}
2109
2110/*
2111 * Set the window title and icon.
2112 */
2113 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002114mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115{
2116 int type = 0;
2117 static int recursive = 0;
2118
2119 if (T_NAME == NULL) /* no terminal name (yet) */
2120 return;
2121 if (title == NULL && icon == NULL) /* nothing to do */
2122 return;
2123
2124 /* When one of the X11 functions causes a deadly signal, we get here again
2125 * recursively. Avoid hanging then (something is probably locked). */
2126 if (recursive)
2127 return;
2128 ++recursive;
2129
2130 /*
2131 * if the window ID and the display is known, we may use X11 calls
2132 */
2133#ifdef FEAT_X11
2134 if (get_x11_windis() == OK)
2135 type = 1;
2136#else
2137# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2138 if (gui.in_use)
2139 type = 1;
2140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141#endif
2142
2143 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002144 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 * than x11 calls, because the x11 calls don't always work
2146 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147 if ((type || *T_TS != NUL) && title != NULL)
2148 {
2149 if (oldtitle == NULL
2150#ifdef FEAT_GUI
2151 && !gui.in_use
2152#endif
2153 ) /* first call but not in GUI, save title */
2154 (void)get_x11_title(FALSE);
2155
2156 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2157 term_settitle(title);
2158#ifdef FEAT_X11
2159 else
2160# ifdef FEAT_GUI_GTK
2161 if (!gui.in_use) /* don't do this if GTK+ is running */
2162# endif
2163 set_x11_title(title); /* x11 */
2164#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002165#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2167 else
2168 gui_mch_settitle(title, icon);
2169#endif
2170 did_set_title = TRUE;
2171 }
2172
2173 if ((type || *T_CIS != NUL) && icon != NULL)
2174 {
2175 if (oldicon == NULL
2176#ifdef FEAT_GUI
2177 && !gui.in_use
2178#endif
2179 ) /* first call, save icon */
2180 get_x11_icon(FALSE);
2181
2182 if (*T_CIS != NUL)
2183 {
2184 out_str(T_CIS); /* set icon start */
2185 out_str_nf(icon);
2186 out_str(T_CIE); /* set icon end */
2187 out_flush();
2188 }
2189#ifdef FEAT_X11
2190 else
2191# ifdef FEAT_GUI_GTK
2192 if (!gui.in_use) /* don't do this if GTK+ is running */
2193# endif
2194 set_x11_icon(icon); /* x11 */
2195#endif
2196 did_set_icon = TRUE;
2197 }
2198 --recursive;
2199}
2200
2201/*
2202 * Restore the window/icon title.
2203 * "which" is one of:
2204 * 1 only restore title
2205 * 2 only restore icon
2206 * 3 restore title and icon
2207 */
2208 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002209mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210{
2211 /* only restore the title or icon when it has been set */
2212 mch_settitle(((which & 1) && did_set_title) ?
2213 (oldtitle ? oldtitle : p_titleold) : NULL,
2214 ((which & 2) && did_set_icon) ? oldicon : NULL);
2215}
2216
2217#endif /* FEAT_TITLE */
2218
2219/*
2220 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002221 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002222 */
2223 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002224vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225{
2226 if (name == NULL)
2227 return FALSE;
2228 return (STRNICMP(name, "xterm", 5) == 0
2229 || STRNICMP(name, "nxterm", 6) == 0
2230 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002231 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 || STRNICMP(name, "rxvt", 4) == 0
2233 || STRCMP(name, "builtin_xterm") == 0);
2234}
2235
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002236#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2237/*
2238 * Return TRUE if "name" appears to be that of a terminal
2239 * known to support the xterm-style mouse protocol.
2240 * Relies on term_is_xterm having been set to its correct value.
2241 */
2242 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002243use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002244{
2245 return (name != NULL
2246 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2247}
2248#endif
2249
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2251/*
2252 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2253 * Return 1 for "xterm".
2254 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002255 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002256 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 */
2258 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002259use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002261 if (ttym_flags == TTYM_SGR)
2262 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002263 if (ttym_flags == TTYM_URXVT)
2264 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 if (ttym_flags == TTYM_XTERM2)
2266 return 2;
2267 if (ttym_flags == TTYM_XTERM)
2268 return 1;
2269 return 0;
2270}
2271#endif
2272
2273 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002274vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275{
2276 if (name == NULL)
2277 return FALSE;
2278 return (STRNICMP(name, "iris-ansi", 9) == 0
2279 || STRCMP(name, "builtin_iris-ansi") == 0);
2280}
2281
2282 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002283vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284{
2285 if (name == NULL)
2286 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002287 /* catch VT100 - VT5xx */
2288 return ((STRNICMP(name, "vt", 2) == 0
2289 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 || STRCMP(name, "builtin_vt320") == 0);
2291}
2292
2293/*
2294 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2295 * This should include all windowed terminal emulators.
2296 */
2297 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002298vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299{
2300 if (name == NULL)
2301 return FALSE;
2302 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2303 return TRUE;
2304 return ( STRNICMP(name, "hpterm", 6) == 0
2305 || STRNICMP(name, "sun-cmd", 7) == 0
2306 || STRNICMP(name, "screen", 6) == 0
2307 || STRNICMP(name, "dtterm", 6) == 0);
2308}
2309
2310/*
2311 * Insert user name in s[len].
2312 * Return OK if a name found.
2313 */
2314 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002315mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316{
2317#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002318 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 return OK;
2320#else
2321 return mch_get_uname(getuid(), s, len);
2322#endif
2323}
2324
2325/*
2326 * Insert user name for "uid" in s[len].
2327 * Return OK if a name found.
2328 */
2329 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002330mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331{
2332#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2333 struct passwd *pw;
2334
2335 if ((pw = getpwuid(uid)) != NULL
2336 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2337 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002338 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 return OK;
2340 }
2341#endif
2342 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2343 return FAIL; /* a number is not a name */
2344}
2345
2346/*
2347 * Insert host name is s[len].
2348 */
2349
2350#ifdef HAVE_SYS_UTSNAME_H
2351 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002352mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353{
2354 struct utsname vutsname;
2355
2356 if (uname(&vutsname) < 0)
2357 *s = NUL;
2358 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002359 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360}
2361#else /* HAVE_SYS_UTSNAME_H */
2362
2363# ifdef HAVE_SYS_SYSTEMINFO_H
2364# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2365# endif
2366
2367 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002368mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369{
2370# ifdef VAXC
2371 vaxc$gethostname((char *)s, len);
2372# else
2373 gethostname((char *)s, len);
2374# endif
2375 s[len - 1] = NUL; /* make sure it's terminated */
2376}
2377#endif /* HAVE_SYS_UTSNAME_H */
2378
2379/*
2380 * return process ID
2381 */
2382 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002383mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384{
2385 return (long)getpid();
2386}
2387
2388#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002389static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390
2391 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002392strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393{
2394 extern int sys_nerr;
2395 extern char *sys_errlist[];
2396 static char er[20];
2397
2398 if (err > 0 && err < sys_nerr)
2399 return (sys_errlist[err]);
2400 sprintf(er, "Error %d", err);
2401 return er;
2402}
2403#endif
2404
2405/*
2406 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2407 * Return OK for success, FAIL for failure.
2408 */
2409 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002410mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
2412#if defined(USE_GETCWD)
2413 if (getcwd((char *)buf, len) == NULL)
2414 {
2415 STRCPY(buf, strerror(errno));
2416 return FAIL;
2417 }
2418 return OK;
2419#else
2420 return (getwd((char *)buf) != NULL ? OK : FAIL);
2421#endif
2422}
2423
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002425 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 *
2427 * return FAIL for failure, OK for success
2428 */
2429 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002430mch_FullName(
2431 char_u *fname,
2432 char_u *buf,
2433 int len,
2434 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435{
2436 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002437#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 int fd = -1;
2439 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002440#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 char_u olddir[MAXPATHL];
2442 char_u *p;
2443 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002444#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002445 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2446 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002447#endif
2448
Bram Moolenaar38323e42007-03-06 19:22:53 +00002449#ifdef VMS
2450 fname = vms_fixfilename(fname);
2451#endif
2452
Bram Moolenaara2442432007-04-26 14:26:37 +00002453#ifdef __CYGWIN__
2454 /*
2455 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2456 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002457# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002458 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2459 * a forward slash. */
2460 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2461 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002462# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002463 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002464# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002465 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002466#endif
2467
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002468 /* Expand it if forced or not an absolute path.
2469 * Do not do it for "/file", the result is always "/". */
2470 if ((force || !mch_isFullName(fname))
2471 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 {
2473 /*
2474 * If the file name has a path, change to that directory for a moment,
2475 * and then do the getwd() (and get back to where we were).
2476 * This will get the correct path name with "../" things.
2477 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002478 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002480#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 /*
2482 * Use fchdir() if possible, it's said to be faster and more
2483 * reliable. But on SunOS 4 it might not work. Check this by
2484 * doing a fchdir() right now.
2485 */
2486 if (!dont_fchdir)
2487 {
2488 fd = open(".", O_RDONLY | O_EXTRA, 0);
2489 if (fd >= 0 && fchdir(fd) < 0)
2490 {
2491 close(fd);
2492 fd = -1;
2493 dont_fchdir = TRUE; /* don't try again */
2494 }
2495 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497
2498 /* Only change directory when we are sure we can return to where
2499 * we are now. After doing "su" chdir(".") might not work. */
2500 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002501#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002503#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 (mch_dirname(olddir, MAXPATHL) == FAIL
2505 || mch_chdir((char *)olddir) != 0))
2506 {
2507 p = NULL; /* can't get current dir: don't chdir */
2508 retval = FAIL;
2509 }
2510 else
2511 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 /* The directory is copied into buf[], to be able to remove
2513 * the file name without changing it (could be a string in
2514 * read-only memory) */
2515 if (p - fname >= len)
2516 retval = FAIL;
2517 else
2518 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002519 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (mch_chdir((char *)buf))
2521 retval = FAIL;
2522 else
2523 fname = p + 1;
2524 *buf = NUL;
2525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 }
2527 }
2528 if (mch_dirname(buf, len) == FAIL)
2529 {
2530 retval = FAIL;
2531 *buf = NUL;
2532 }
2533 if (p != NULL)
2534 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002535#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (fd >= 0)
2537 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002538 if (p_verbose >= 5)
2539 {
2540 verbose_enter();
2541 MSG("fchdir() to previous dir");
2542 verbose_leave();
2543 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 l = fchdir(fd);
2545 close(fd);
2546 }
2547 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002548#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 l = mch_chdir((char *)olddir);
2550 if (l != 0)
2551 EMSG(_(e_prev_dir));
2552 }
2553
2554 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002555 if (l >= len - 1)
2556 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002557#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002558 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002560 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002561#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002563
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002565 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 return FAIL;
2567
2568 /* Do not append ".", "/dir/." is equal to "/dir". */
2569 if (STRCMP(fname, ".") != 0)
2570 STRCAT(buf, fname);
2571
2572 return OK;
2573}
2574
2575/*
2576 * Return TRUE if "fname" does not depend on the current directory.
2577 */
2578 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002579mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580{
2581#ifdef __EMX__
2582 return _fnisabs(fname);
2583#else
2584# ifdef VMS
2585 return ( fname[0] == '/' || fname[0] == '.' ||
2586 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2587 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2588 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2589# else
2590 return (*fname == '/' || *fname == '~');
2591# endif
2592#endif
2593}
2594
Bram Moolenaar24552be2005-12-10 20:17:30 +00002595#if defined(USE_FNAME_CASE) || defined(PROTO)
2596/*
2597 * Set the case of the file name, if it already exists. This will cause the
2598 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002599 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002600 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002601 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002602fname_case(
2603 char_u *name,
2604 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002605{
2606 struct stat st;
2607 char_u *slash, *tail;
2608 DIR *dirp;
2609 struct dirent *dp;
2610
2611 if (lstat((char *)name, &st) >= 0)
2612 {
2613 /* Open the directory where the file is located. */
2614 slash = vim_strrchr(name, '/');
2615 if (slash == NULL)
2616 {
2617 dirp = opendir(".");
2618 tail = name;
2619 }
2620 else
2621 {
2622 *slash = NUL;
2623 dirp = opendir((char *)name);
2624 *slash = '/';
2625 tail = slash + 1;
2626 }
2627
2628 if (dirp != NULL)
2629 {
2630 while ((dp = readdir(dirp)) != NULL)
2631 {
2632 /* Only accept names that differ in case and are the same byte
2633 * length. TODO: accept different length name. */
2634 if (STRICMP(tail, dp->d_name) == 0
2635 && STRLEN(tail) == STRLEN(dp->d_name))
2636 {
2637 char_u newname[MAXPATHL + 1];
2638 struct stat st2;
2639
2640 /* Verify the inode is equal. */
2641 vim_strncpy(newname, name, MAXPATHL);
2642 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2643 MAXPATHL - (tail - name));
2644 if (lstat((char *)newname, &st2) >= 0
2645 && st.st_ino == st2.st_ino
2646 && st.st_dev == st2.st_dev)
2647 {
2648 STRCPY(tail, dp->d_name);
2649 break;
2650 }
2651 }
2652 }
2653
2654 closedir(dirp);
2655 }
2656 }
2657}
2658#endif
2659
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660/*
2661 * Get file permissions for 'name'.
2662 * Returns -1 when it doesn't exist.
2663 */
2664 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002665mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666{
2667 struct stat statb;
2668
2669 /* Keep the #ifdef outside of stat(), it may be a macro. */
2670#ifdef VMS
2671 if (stat((char *)vms_fixfilename(name), &statb))
2672#else
2673 if (stat((char *)name, &statb))
2674#endif
2675 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002676#ifdef __INTERIX
2677 /* The top bit makes the value negative, which means the file doesn't
2678 * exist. Remove the bit, we don't use it. */
2679 return statb.st_mode & ~S_ADDACE;
2680#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002682#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683}
2684
2685/*
2686 * set file permission for 'name' to 'perm'
2687 *
2688 * return FAIL for failure, OK otherwise
2689 */
2690 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002691mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692{
2693 return (chmod((char *)
2694#ifdef VMS
2695 vms_fixfilename(name),
2696#else
2697 name,
2698#endif
2699 (mode_t)perm) == 0 ? OK : FAIL);
2700}
2701
2702#if defined(HAVE_ACL) || defined(PROTO)
2703# ifdef HAVE_SYS_ACL_H
2704# include <sys/acl.h>
2705# endif
2706# ifdef HAVE_SYS_ACCESS_H
2707# include <sys/access.h>
2708# endif
2709
2710# ifdef HAVE_SOLARIS_ACL
2711typedef struct vim_acl_solaris_T {
2712 int acl_cnt;
2713 aclent_t *acl_entry;
2714} vim_acl_solaris_T;
2715# endif
2716
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002717#if defined(HAVE_SELINUX) || defined(PROTO)
2718/*
2719 * Copy security info from "from_file" to "to_file".
2720 */
2721 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002722mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002723{
2724 if (from_file == NULL)
2725 return;
2726
2727 if (selinux_enabled == -1)
2728 selinux_enabled = is_selinux_enabled();
2729
2730 if (selinux_enabled > 0)
2731 {
2732 security_context_t from_context = NULL;
2733 security_context_t to_context = NULL;
2734
2735 if (getfilecon((char *)from_file, &from_context) < 0)
2736 {
2737 /* If the filesystem doesn't support extended attributes,
2738 the original had no special security context and the
2739 target cannot have one either. */
2740 if (errno == EOPNOTSUPP)
2741 return;
2742
2743 MSG_PUTS(_("\nCould not get security context for "));
2744 msg_outtrans(from_file);
2745 msg_putchar('\n');
2746 return;
2747 }
2748 if (getfilecon((char *)to_file, &to_context) < 0)
2749 {
2750 MSG_PUTS(_("\nCould not get security context for "));
2751 msg_outtrans(to_file);
2752 msg_putchar('\n');
2753 freecon (from_context);
2754 return ;
2755 }
2756 if (strcmp(from_context, to_context) != 0)
2757 {
2758 if (setfilecon((char *)to_file, from_context) < 0)
2759 {
2760 MSG_PUTS(_("\nCould not set security context for "));
2761 msg_outtrans(to_file);
2762 msg_putchar('\n');
2763 }
2764 }
2765 freecon(to_context);
2766 freecon(from_context);
2767 }
2768}
2769#endif /* HAVE_SELINUX */
2770
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002771#if defined(HAVE_SMACK) && !defined(PROTO)
2772/*
2773 * Copy security info from "from_file" to "to_file".
2774 */
2775 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002776mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002777{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002778 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002779 {
2780 XATTR_NAME_SMACK,
2781 XATTR_NAME_SMACKEXEC,
2782 XATTR_NAME_SMACKMMAP
2783 };
2784
2785 char buffer[SMACK_LABEL_LEN];
2786 const char *name;
2787 int index;
2788 int ret;
2789 ssize_t size;
2790
2791 if (from_file == NULL)
2792 return;
2793
2794 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2795 / sizeof(smack_copied_attributes)[0]) ; index++)
2796 {
2797 /* get the name of the attribute to copy */
2798 name = smack_copied_attributes[index];
2799
2800 /* get the value of the attribute in buffer */
2801 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2802 if (size >= 0)
2803 {
2804 /* copy the attribute value of buffer */
2805 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2806 if (ret < 0)
2807 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002808 vim_snprintf((char *)IObuff, IOSIZE,
2809 _("Could not set security context %s for %s"),
2810 name, to_file);
2811 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002812 msg_putchar('\n');
2813 }
2814 }
2815 else
2816 {
2817 /* what reason of not having the attribute value? */
2818 switch (errno)
2819 {
2820 case ENOTSUP:
2821 /* extended attributes aren't supported or enabled */
2822 /* should a message be echoed? not sure... */
2823 return; /* leave because it isn't usefull to continue */
2824
2825 case ERANGE:
2826 default:
2827 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002828 vim_snprintf((char *)IObuff, IOSIZE,
2829 _("Could not get security context %s for %s. Removing it!"),
2830 name, from_file);
2831 msg_puts(IObuff);
2832 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002833 /* FALLTHROUGH to remove the attribute */
2834
2835 case ENODATA:
2836 /* no attribute of this name */
2837 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002838 /* Silently ignore errors, apparently this happens when
2839 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002840 break;
2841 }
2842 }
2843 }
2844}
2845#endif /* HAVE_SMACK */
2846
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847/*
2848 * Return a pointer to the ACL of file "fname" in allocated memory.
2849 * Return NULL if the ACL is not available for whatever reason.
2850 */
2851 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002852mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853{
2854 vim_acl_T ret = NULL;
2855#ifdef HAVE_POSIX_ACL
2856 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2857#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002858#ifdef HAVE_SOLARIS_ZFS_ACL
2859 acl_t *aclent;
2860
2861 if (acl_get((char *)fname, 0, &aclent) < 0)
2862 return NULL;
2863 ret = (vim_acl_T)aclent;
2864#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865#ifdef HAVE_SOLARIS_ACL
2866 vim_acl_solaris_T *aclent;
2867
2868 aclent = malloc(sizeof(vim_acl_solaris_T));
2869 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2870 {
2871 free(aclent);
2872 return NULL;
2873 }
2874 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2875 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2876 {
2877 free(aclent->acl_entry);
2878 free(aclent);
2879 return NULL;
2880 }
2881 ret = (vim_acl_T)aclent;
2882#else
2883#if defined(HAVE_AIX_ACL)
2884 int aclsize;
2885 struct acl *aclent;
2886
2887 aclsize = sizeof(struct acl);
2888 aclent = malloc(aclsize);
2889 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2890 {
2891 if (errno == ENOSPC)
2892 {
2893 aclsize = aclent->acl_len;
2894 aclent = realloc(aclent, aclsize);
2895 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2896 {
2897 free(aclent);
2898 return NULL;
2899 }
2900 }
2901 else
2902 {
2903 free(aclent);
2904 return NULL;
2905 }
2906 }
2907 ret = (vim_acl_T)aclent;
2908#endif /* HAVE_AIX_ACL */
2909#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002910#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911#endif /* HAVE_POSIX_ACL */
2912 return ret;
2913}
2914
2915/*
2916 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2917 */
2918 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002919mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920{
2921 if (aclent == NULL)
2922 return;
2923#ifdef HAVE_POSIX_ACL
2924 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2925#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002926#ifdef HAVE_SOLARIS_ZFS_ACL
2927 acl_set((char *)fname, (acl_t *)aclent);
2928#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929#ifdef HAVE_SOLARIS_ACL
2930 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2931 ((vim_acl_solaris_T *)aclent)->acl_entry);
2932#else
2933#ifdef HAVE_AIX_ACL
2934 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2935#endif /* HAVE_AIX_ACL */
2936#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002937#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938#endif /* HAVE_POSIX_ACL */
2939}
2940
2941 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002942mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943{
2944 if (aclent == NULL)
2945 return;
2946#ifdef HAVE_POSIX_ACL
2947 acl_free((acl_t)aclent);
2948#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002949#ifdef HAVE_SOLARIS_ZFS_ACL
2950 acl_free((acl_t *)aclent);
2951#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952#ifdef HAVE_SOLARIS_ACL
2953 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2954 free(aclent);
2955#else
2956#ifdef HAVE_AIX_ACL
2957 free(aclent);
2958#endif /* HAVE_AIX_ACL */
2959#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002960#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961#endif /* HAVE_POSIX_ACL */
2962}
2963#endif
2964
2965/*
2966 * Set hidden flag for "name".
2967 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002969mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970{
2971 /* can't hide a file */
2972}
2973
2974/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002975 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 * return FALSE if "name" is not a directory
2977 * return FALSE for error
2978 */
2979 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002980mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981{
2982 struct stat statb;
2983
2984 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2985 return FALSE;
2986 if (stat((char *)name, &statb))
2987 return FALSE;
2988#ifdef _POSIX_SOURCE
2989 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2990#else
2991 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2992#endif
2993}
2994
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002995/*
2996 * return TRUE if "name" is a directory, NOT a symlink to a directory
2997 * return FALSE if "name" is not a directory
2998 * return FALSE for error
2999 */
3000 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003001mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003002{
3003 struct stat statb;
3004
3005 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3006 return FALSE;
3007 if (lstat((char *)name, &statb))
3008 return FALSE;
3009#ifdef _POSIX_SOURCE
3010 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3011#else
3012 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3013#endif
3014}
3015
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003016static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017
3018/*
3019 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3020 */
3021 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003022executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023{
3024 struct stat st;
3025
3026 if (stat((char *)name, &st))
3027 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003028#ifdef VMS
3029 /* Like on Unix system file can have executable rights but not necessarily
3030 * be an executable, but on Unix is not a default for an ordianry file to
3031 * have an executable flag - on VMS it is in most cases.
3032 * Therefore, this check does not have any sense - let keep us to the
3033 * conventions instead:
3034 * *.COM and *.EXE files are the executables - the rest are not. This is
3035 * not ideal but better then it was.
3036 */
3037 int vms_executable = 0;
3038 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3039 {
3040 if (strstr(vms_tolower((char*)name),".exe") != NULL
3041 || strstr(vms_tolower((char*)name),".com")!= NULL)
3042 vms_executable = 1;
3043 }
3044 return vms_executable;
3045#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003047#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048}
3049
3050/*
3051 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003052 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053 * Return -1 if unknown.
3054 */
3055 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003056mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057{
3058 char_u *buf;
3059 char_u *p, *e;
3060 int retval;
3061
Bram Moolenaarb5971142015-03-21 17:32:19 +01003062 /* When "use_path" is false and if it's an absolute or relative path don't
3063 * need to use $PATH. */
3064 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3065 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003066 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003067 /* There must be a path separator, files in the current directory
3068 * can't be executed. */
3069 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003070 {
3071 if (path != NULL)
3072 {
3073 if (name[0] == '.')
3074 *path = FullName_save(name, TRUE);
3075 else
3076 *path = vim_strsave(name);
3077 }
3078 return TRUE;
3079 }
3080 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003081 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082
3083 p = (char_u *)getenv("PATH");
3084 if (p == NULL || *p == NUL)
3085 return -1;
3086 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3087 if (buf == NULL)
3088 return -1;
3089
3090 /*
3091 * Walk through all entries in $PATH to check if "name" exists there and
3092 * is an executable file.
3093 */
3094 for (;;)
3095 {
3096 e = (char_u *)strchr((char *)p, ':');
3097 if (e == NULL)
3098 e = p + STRLEN(p);
3099 if (e - p <= 1) /* empty entry means current dir */
3100 STRCPY(buf, "./");
3101 else
3102 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003103 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104 add_pathsep(buf);
3105 }
3106 STRCAT(buf, name);
3107 retval = executable_file(buf);
3108 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003109 {
3110 if (path != NULL)
3111 {
3112 if (buf[0] == '.')
3113 *path = FullName_save(buf, TRUE);
3114 else
3115 *path = vim_strsave(buf);
3116 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003118 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119
3120 if (*e != ':')
3121 break;
3122 p = e + 1;
3123 }
3124
3125 vim_free(buf);
3126 return retval;
3127}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128
3129/*
3130 * Check what "name" is:
3131 * NODE_NORMAL: file or directory (or doesn't exist)
3132 * NODE_WRITABLE: writable device, socket, fifo, etc.
3133 * NODE_OTHER: non-writable things
3134 */
3135 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003136mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137{
3138 struct stat st;
3139
3140 if (stat((char *)name, &st))
3141 return NODE_NORMAL;
3142 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3143 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3145 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 /* Everything else is writable? */
3147 return NODE_WRITABLE;
3148}
3149
3150 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003151mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152{
3153#ifdef HAVE_CHECK_STACK_GROWTH
3154 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156 check_stack_growth((char *)&i);
3157
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003158# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 get_stack_limit();
3160# endif
3161
3162#endif
3163
3164 /*
3165 * Setup an alternative stack for signals. Helps to catch signals when
3166 * running out of stack space.
3167 * Use of sigaltstack() is preferred, it's more portable.
3168 * Ignore any errors.
3169 */
3170#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003171 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 init_signal_stack();
3173#endif
3174}
3175
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003176#if defined(EXITFREE) || defined(PROTO)
3177 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003178mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003179{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003180# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3181 if (clip_star.owned)
3182 clip_lose_selection(&clip_star);
3183 if (clip_plus.owned)
3184 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003185# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003186# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003187 if (xterm_Shell != (Widget)0)
3188 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003189# ifndef LESSTIF_VERSION
3190 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003191 if (xterm_dpy != NULL)
3192 XtCloseDisplay(xterm_dpy);
3193 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003194 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003195 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003196# ifdef FEAT_X11
3197 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3198# endif
3199 }
3200# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003201# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003202# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003203 if (x11_display != NULL
3204# ifdef FEAT_XCLIPBOARD
3205 && x11_display != xterm_dpy
3206# endif
3207 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003208 XCloseDisplay(x11_display);
3209# endif
3210# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3211 vim_free(signal_stack);
3212 signal_stack = NULL;
3213# endif
3214# ifdef FEAT_TITLE
3215 vim_free(oldtitle);
3216 vim_free(oldicon);
3217# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003218}
3219#endif
3220
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003221static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222
3223/*
3224 * Output a newline when exiting.
3225 * Make sure the newline goes to the same stream as the text.
3226 */
3227 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003228exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003230 if (silent_mode)
3231 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 if (newline_on_exit || msg_didout)
3233 {
3234 if (msg_use_printf())
3235 {
3236 if (info_message)
3237 mch_msg("\n");
3238 else
3239 mch_errmsg("\r\n");
3240 }
3241 else
3242 out_char('\n');
3243 }
3244 else
3245 {
3246 restore_cterm_colors(); /* get original colors back */
3247 msg_clr_eos_force(); /* clear the rest of the display */
3248 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3249 }
3250}
3251
3252 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003253mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254{
3255 exiting = TRUE;
3256
3257#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3258 x11_export_final_selection();
3259#endif
3260
3261#ifdef FEAT_GUI
3262 if (!gui.in_use)
3263#endif
3264 {
3265 settmode(TMODE_COOK);
3266#ifdef FEAT_TITLE
3267 mch_restore_title(3); /* restore xterm title and icon name */
3268#endif
3269 /*
3270 * When t_ti is not empty but it doesn't cause swapping terminal
3271 * pages, need to output a newline when msg_didout is set. But when
3272 * t_ti does swap pages it should not go to the shell page. Do this
3273 * before stoptermcap().
3274 */
3275 if (swapping_screen() && !newline_on_exit)
3276 exit_scroll();
3277
3278 /* Stop termcap: May need to check for T_CRV response, which
3279 * requires RAW mode. */
3280 stoptermcap();
3281
3282 /*
3283 * A newline is only required after a message in the alternate screen.
3284 * This is set to TRUE by wait_return().
3285 */
3286 if (!swapping_screen() || newline_on_exit)
3287 exit_scroll();
3288
3289 /* Cursor may have been switched off without calling starttermcap()
3290 * when doing "vim -u vimrc" and vimrc contains ":q". */
3291 if (full_screen)
3292 cursor_on();
3293 }
3294 out_flush();
3295 ml_close_all(TRUE); /* remove all memfiles */
3296 may_core_dump();
3297#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 gui_exit(r);
3300#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003301
Bram Moolenaar56718732006-03-15 22:53:57 +00003302#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003303 mac_conv_cleanup();
3304#endif
3305
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306#ifdef __QNX__
3307 /* A core dump won't be created if the signal handler
3308 * doesn't return, so we can't call exit() */
3309 if (deadly_signal != 0)
3310 return;
3311#endif
3312
Bram Moolenaar009b2592004-10-24 19:18:58 +00003313#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003314 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003315#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003316
3317#ifdef EXITFREE
3318 free_all_mem();
3319#endif
3320
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 exit(r);
3322}
3323
3324 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003325may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326{
3327 if (deadly_signal != 0)
3328 {
3329 signal(deadly_signal, SIG_DFL);
3330 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3331 }
3332}
3333
3334#ifndef VMS
3335
3336 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003337mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338{
3339 static int first = TRUE;
3340
3341 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3342#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3343 /*
3344 * for "new" tty systems
3345 */
3346# ifdef HAVE_TERMIOS_H
3347 static struct termios told;
3348 struct termios tnew;
3349# else
3350 static struct termio told;
3351 struct termio tnew;
3352# endif
3353
3354 if (first)
3355 {
3356 first = FALSE;
3357# if defined(HAVE_TERMIOS_H)
3358 tcgetattr(read_cmd_fd, &told);
3359# else
3360 ioctl(read_cmd_fd, TCGETA, &told);
3361# endif
3362 }
3363
3364 tnew = told;
3365 if (tmode == TMODE_RAW)
3366 {
3367 /*
3368 * ~ICRNL enables typing ^V^M
3369 */
3370 tnew.c_iflag &= ~ICRNL;
3371 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3372# if defined(IEXTEN) && !defined(__MINT__)
3373 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3374 /* but it breaks function keys on MINT */
3375# endif
3376 );
3377# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3378 tnew.c_oflag &= ~ONLCR;
3379# endif
3380 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3381 tnew.c_cc[VTIME] = 0; /* don't wait */
3382 }
3383 else if (tmode == TMODE_SLEEP)
3384 tnew.c_lflag &= ~(ECHO);
3385
3386# if defined(HAVE_TERMIOS_H)
3387 {
3388 int n = 10;
3389
3390 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3391 * few times. */
3392 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3393 && errno == EINTR && n > 0)
3394 --n;
3395 }
3396# else
3397 ioctl(read_cmd_fd, TCSETA, &tnew);
3398# endif
3399
3400#else
3401
3402 /*
3403 * for "old" tty systems
3404 */
3405# ifndef TIOCSETN
3406# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3407# endif
3408 static struct sgttyb ttybold;
3409 struct sgttyb ttybnew;
3410
3411 if (first)
3412 {
3413 first = FALSE;
3414 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3415 }
3416
3417 ttybnew = ttybold;
3418 if (tmode == TMODE_RAW)
3419 {
3420 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3421 ttybnew.sg_flags |= RAW;
3422 }
3423 else if (tmode == TMODE_SLEEP)
3424 ttybnew.sg_flags &= ~(ECHO);
3425 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3426#endif
3427 curr_tmode = tmode;
3428}
3429
3430/*
3431 * Try to get the code for "t_kb" from the stty setting
3432 *
3433 * Even if termcap claims a backspace key, the user's setting *should*
3434 * prevail. stty knows more about reality than termcap does, and if
3435 * somebody's usual erase key is DEL (which, for most BSD users, it will
3436 * be), they're going to get really annoyed if their erase key starts
3437 * doing forward deletes for no reason. (Eric Fischer)
3438 */
3439 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003440get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441{
3442 char_u buf[2];
3443 char_u *p;
3444
3445 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3446#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3447 /* for "new" tty systems */
3448# ifdef HAVE_TERMIOS_H
3449 struct termios keys;
3450# else
3451 struct termio keys;
3452# endif
3453
3454# if defined(HAVE_TERMIOS_H)
3455 if (tcgetattr(read_cmd_fd, &keys) != -1)
3456# else
3457 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3458# endif
3459 {
3460 buf[0] = keys.c_cc[VERASE];
3461 intr_char = keys.c_cc[VINTR];
3462#else
3463 /* for "old" tty systems */
3464 struct sgttyb keys;
3465
3466 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3467 {
3468 buf[0] = keys.sg_erase;
3469 intr_char = keys.sg_kill;
3470#endif
3471 buf[1] = NUL;
3472 add_termcode((char_u *)"kb", buf, FALSE);
3473
3474 /*
3475 * If <BS> and <DEL> are now the same, redefine <DEL>.
3476 */
3477 p = find_termcode((char_u *)"kD");
3478 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3479 do_fixdel(NULL);
3480 }
3481#if 0
3482 } /* to keep cindent happy */
3483#endif
3484}
3485
3486#endif /* VMS */
3487
3488#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3489/*
3490 * Set mouse clicks on or off.
3491 */
3492 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003493mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494{
3495 static int ison = FALSE;
3496 int xterm_mouse_vers;
3497
3498 if (on == ison) /* return quickly if nothing to do */
3499 return;
3500
3501 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003502
3503# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003504 if (ttym_flags == TTYM_URXVT)
3505 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003506 out_str_nf((char_u *)
3507 (on
3508 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3509 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3510 ison = on;
3511 }
3512# endif
3513
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003514# ifdef FEAT_MOUSE_SGR
3515 if (ttym_flags == TTYM_SGR)
3516 {
3517 out_str_nf((char_u *)
3518 (on
3519 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3520 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3521 ison = on;
3522 }
3523# endif
3524
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 if (xterm_mouse_vers > 0)
3526 {
3527 if (on) /* enable mouse events, use mouse tracking if available */
3528 out_str_nf((char_u *)
3529 (xterm_mouse_vers > 1
3530 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3531 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3532 else /* disable mouse events, could probably always send the same */
3533 out_str_nf((char_u *)
3534 (xterm_mouse_vers > 1
3535 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3536 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3537 ison = on;
3538 }
3539
3540# ifdef FEAT_MOUSE_DEC
3541 else if (ttym_flags == TTYM_DEC)
3542 {
3543 if (on) /* enable mouse events */
3544 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3545 else /* disable mouse events */
3546 out_str_nf((char_u *)"\033['z");
3547 ison = on;
3548 }
3549# endif
3550
3551# ifdef FEAT_MOUSE_GPM
3552 else
3553 {
3554 if (on)
3555 {
3556 if (gpm_open())
3557 ison = TRUE;
3558 }
3559 else
3560 {
3561 gpm_close();
3562 ison = FALSE;
3563 }
3564 }
3565# endif
3566
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003567# ifdef FEAT_SYSMOUSE
3568 else
3569 {
3570 if (on)
3571 {
3572 if (sysmouse_open() == OK)
3573 ison = TRUE;
3574 }
3575 else
3576 {
3577 sysmouse_close();
3578 ison = FALSE;
3579 }
3580 }
3581# endif
3582
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583# ifdef FEAT_MOUSE_JSB
3584 else
3585 {
3586 if (on)
3587 {
3588 /* D - Enable Mouse up/down messages
3589 * L - Enable Left Button Reporting
3590 * M - Enable Middle Button Reporting
3591 * R - Enable Right Button Reporting
3592 * K - Enable SHIFT and CTRL key Reporting
3593 * + - Enable Advanced messaging of mouse moves and up/down messages
3594 * Q - Quiet No Ack
3595 * # - Numeric value of mouse pointer required
3596 * 0 = Multiview 2000 cursor, used as standard
3597 * 1 = Windows Arrow
3598 * 2 = Windows I Beam
3599 * 3 = Windows Hour Glass
3600 * 4 = Windows Cross Hair
3601 * 5 = Windows UP Arrow
3602 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003603# ifdef JSBTERM_MOUSE_NONADVANCED
3604 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3606 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003607# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3609 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003610# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 ison = TRUE;
3612 }
3613 else
3614 {
3615 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3616 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3617 ison = FALSE;
3618 }
3619 }
3620# endif
3621# ifdef FEAT_MOUSE_PTERM
3622 else
3623 {
3624 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3625 if (on)
3626 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3627 else
3628 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3629 ison = on;
3630 }
3631# endif
3632}
3633
3634/*
3635 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3636 */
3637 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003638check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639{
3640# ifdef FEAT_MOUSE_XTERM
3641 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003642# ifdef FEAT_MOUSE_URXVT
3643 && use_xterm_mouse() != 3
3644# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645# ifdef FEAT_GUI
3646 && !gui.in_use
3647# endif
3648 )
3649 {
3650 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003651 ? IF_EB("\233M", CSI_STR "M")
3652 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653 if (*p_mouse != NUL)
3654 {
3655 /* force mouse off and maybe on to send possibly new mouse
3656 * activation sequence to the xterm, with(out) drag tracing. */
3657 mch_setmouse(FALSE);
3658 setmouse();
3659 }
3660 }
3661 else
3662 del_mouse_termcode(KS_MOUSE);
3663# endif
3664
3665# ifdef FEAT_MOUSE_GPM
3666 if (!use_xterm_mouse()
3667# ifdef FEAT_GUI
3668 && !gui.in_use
3669# endif
3670 )
3671 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3672# endif
3673
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003674# ifdef FEAT_SYSMOUSE
3675 if (!use_xterm_mouse()
3676# ifdef FEAT_GUI
3677 && !gui.in_use
3678# endif
3679 )
3680 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3681# endif
3682
Bram Moolenaar071d4272004-06-13 20:20:40 +00003683# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003684 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685 if (!use_xterm_mouse()
3686# ifdef FEAT_GUI
3687 && !gui.in_use
3688# endif
3689 )
3690 set_mouse_termcode(KS_JSBTERM_MOUSE,
3691 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3692 else
3693 del_mouse_termcode(KS_JSBTERM_MOUSE);
3694# endif
3695
3696# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003697 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 * define it in the GUI or when using an xterm. */
3699 if (!use_xterm_mouse()
3700# ifdef FEAT_GUI
3701 && !gui.in_use
3702# endif
3703 )
3704 set_mouse_termcode(KS_NETTERM_MOUSE,
3705 (char_u *)IF_EB("\033}", ESC_STR "}"));
3706 else
3707 del_mouse_termcode(KS_NETTERM_MOUSE);
3708# endif
3709
3710# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003711 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003712 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713# ifdef FEAT_GUI
3714 && !gui.in_use
3715# endif
3716 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003717 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3718 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 else
3720 del_mouse_termcode(KS_DEC_MOUSE);
3721# endif
3722# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003723 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003724 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725# ifdef FEAT_GUI
3726 && !gui.in_use
3727# endif
3728 )
3729 set_mouse_termcode(KS_PTERM_MOUSE,
3730 (char_u *) IF_EB("\033[", ESC_STR "["));
3731 else
3732 del_mouse_termcode(KS_PTERM_MOUSE);
3733# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003734# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003735 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003736 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003737# ifdef FEAT_GUI
3738 && !gui.in_use
3739# endif
3740 )
3741 {
3742 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3743 ? IF_EB("\233", CSI_STR)
3744 : IF_EB("\033[", ESC_STR "[")));
3745
3746 if (*p_mouse != NUL)
3747 {
3748 mch_setmouse(FALSE);
3749 setmouse();
3750 }
3751 }
3752 else
3753 del_mouse_termcode(KS_URXVT_MOUSE);
3754# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003755# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003756 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003757 if (use_xterm_mouse() == 4
3758# ifdef FEAT_GUI
3759 && !gui.in_use
3760# endif
3761 )
3762 {
3763 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3764 ? IF_EB("\233<", CSI_STR "<")
3765 : IF_EB("\033[<", ESC_STR "[<")));
3766
3767 if (*p_mouse != NUL)
3768 {
3769 mch_setmouse(FALSE);
3770 setmouse();
3771 }
3772 }
3773 else
3774 del_mouse_termcode(KS_SGR_MOUSE);
3775# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776}
3777#endif
3778
3779/*
3780 * set screen mode, always fails.
3781 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003783mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784{
3785 EMSG(_(e_screenmode));
3786 return FAIL;
3787}
3788
3789#ifndef VMS
3790
3791/*
3792 * Try to get the current window size:
3793 * 1. with an ioctl(), most accurate method
3794 * 2. from the environment variables LINES and COLUMNS
3795 * 3. from the termcap
3796 * 4. keep using the old values
3797 * Return OK when size could be determined, FAIL otherwise.
3798 */
3799 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003800mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801{
3802 long rows = 0;
3803 long columns = 0;
3804 char_u *p;
3805
3806 /*
3807 * For OS/2 use _scrsize().
3808 */
3809# ifdef __EMX__
3810 {
3811 int s[2];
3812
3813 _scrsize(s);
3814 columns = s[0];
3815 rows = s[1];
3816 }
3817# endif
3818
3819 /*
3820 * 1. try using an ioctl. It is the most accurate method.
3821 *
3822 * Try using TIOCGWINSZ first, some systems that have it also define
3823 * TIOCGSIZE but don't have a struct ttysize.
3824 */
3825# ifdef TIOCGWINSZ
3826 {
3827 struct winsize ws;
3828 int fd = 1;
3829
3830 /* When stdout is not a tty, use stdin for the ioctl(). */
3831 if (!isatty(fd) && isatty(read_cmd_fd))
3832 fd = read_cmd_fd;
3833 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3834 {
3835 columns = ws.ws_col;
3836 rows = ws.ws_row;
3837 }
3838 }
3839# else /* TIOCGWINSZ */
3840# ifdef TIOCGSIZE
3841 {
3842 struct ttysize ts;
3843 int fd = 1;
3844
3845 /* When stdout is not a tty, use stdin for the ioctl(). */
3846 if (!isatty(fd) && isatty(read_cmd_fd))
3847 fd = read_cmd_fd;
3848 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3849 {
3850 columns = ts.ts_cols;
3851 rows = ts.ts_lines;
3852 }
3853 }
3854# endif /* TIOCGSIZE */
3855# endif /* TIOCGWINSZ */
3856
3857 /*
3858 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003859 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3860 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003862 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 {
3864 if ((p = (char_u *)getenv("LINES")))
3865 rows = atoi((char *)p);
3866 if ((p = (char_u *)getenv("COLUMNS")))
3867 columns = atoi((char *)p);
3868 }
3869
3870#ifdef HAVE_TGETENT
3871 /*
3872 * 3. try reading "co" and "li" entries from termcap
3873 */
3874 if (columns == 0 || rows == 0)
3875 getlinecol(&columns, &rows);
3876#endif
3877
3878 /*
3879 * 4. If everything fails, use the old values
3880 */
3881 if (columns <= 0 || rows <= 0)
3882 return FAIL;
3883
3884 Rows = rows;
3885 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003886 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 return OK;
3888}
3889
3890/*
3891 * Try to set the window size to Rows and Columns.
3892 */
3893 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003894mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895{
3896 if (*T_CWS)
3897 {
3898 /*
3899 * NOTE: if you get an error here that term_set_winsize() is
3900 * undefined, check the output of configure. It could probably not
3901 * find a ncurses, termcap or termlib library.
3902 */
3903 term_set_winsize((int)Rows, (int)Columns);
3904 out_flush();
3905 screen_start(); /* don't know where cursor is now */
3906 }
3907}
3908
3909#endif /* VMS */
3910
3911/*
3912 * Rows and/or Columns has changed.
3913 */
3914 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003915mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916{
3917 /* Nothing to do. */
3918}
3919
Bram Moolenaar205b8862011-09-07 15:04:31 +02003920/*
3921 * Wait for process "child" to end.
3922 * Return "child" if it exited properly, <= 0 on error.
3923 */
3924 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003925wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003926{
3927 pid_t wait_pid = 0;
3928
3929 while (wait_pid != child)
3930 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003931 /* When compiled with Python threads are probably used, in which case
3932 * wait() sometimes hangs for no obvious reason. Use waitpid()
3933 * instead and loop (like the GUI). Also needed for other interfaces,
3934 * they might call system(). */
3935# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003936 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003937# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003938 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003939# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003940 if (wait_pid == 0)
3941 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003942 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003943 mch_delay(10L, TRUE);
3944 continue;
3945 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003946 if (wait_pid <= 0
3947# ifdef ECHILD
3948 && errno == ECHILD
3949# endif
3950 )
3951 break;
3952 }
3953 return wait_pid;
3954}
3955
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003956#if defined(FEAT_JOB_CHANNEL) || !defined(USE_SYSTEM) || defined(PROTO)
Bram Moolenaar72801402016-02-09 11:37:50 +01003957/*
3958 * Parse "cmd" and put the white-separated parts in "argv".
3959 * "argv" is an allocated array with "argc" entries.
3960 * Returns FAIL when out of memory.
3961 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01003962 int
3963mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
3964{
3965 int i;
3966 char_u *p;
3967 int inquote;
3968
3969 /*
3970 * Do this loop twice:
3971 * 1: find number of arguments
3972 * 2: separate them and build argv[]
3973 */
3974 for (i = 0; i < 2; ++i)
3975 {
Bram Moolenaar6231cb82016-04-26 19:42:42 +02003976 p = skipwhite(cmd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01003977 inquote = FALSE;
3978 *argc = 0;
3979 for (;;)
3980 {
3981 if (i == 1)
3982 (*argv)[*argc] = (char *)p;
3983 ++*argc;
3984 while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
3985 {
3986 if (*p == '"')
3987 inquote = !inquote;
3988 ++p;
3989 }
3990 if (*p == NUL)
3991 break;
3992 if (i == 1)
3993 *p++ = NUL;
3994 p = skipwhite(p);
3995 }
3996 if (*argv == NULL)
3997 {
3998 if (use_shcf)
3999 {
4000 /* Account for possible multiple args in p_shcf. */
4001 p = p_shcf;
4002 for (;;)
4003 {
4004 p = skiptowhite(p);
4005 if (*p == NUL)
4006 break;
4007 ++*argc;
4008 p = skipwhite(p);
4009 }
4010 }
4011
4012 *argv = (char **)alloc((unsigned)((*argc + 4) * sizeof(char *)));
4013 if (*argv == NULL) /* out of memory */
4014 return FAIL;
4015 }
4016 }
4017 return OK;
4018}
4019#endif
4020
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004021#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004022 static void
4023set_child_environment(void)
4024{
4025# ifdef HAVE_SETENV
4026 char envbuf[50];
4027# else
4028 static char envbuf_Rows[20];
4029 static char envbuf_Columns[20];
4030# endif
4031
4032 /* Simulate to have a dumb terminal (for now) */
4033# ifdef HAVE_SETENV
4034 setenv("TERM", "dumb", 1);
4035 sprintf((char *)envbuf, "%ld", Rows);
4036 setenv("ROWS", (char *)envbuf, 1);
4037 sprintf((char *)envbuf, "%ld", Rows);
4038 setenv("LINES", (char *)envbuf, 1);
4039 sprintf((char *)envbuf, "%ld", Columns);
4040 setenv("COLUMNS", (char *)envbuf, 1);
4041# else
4042 /*
4043 * Putenv does not copy the string, it has to remain valid.
4044 * Use a static array to avoid losing allocated memory.
4045 */
4046 putenv("TERM=dumb");
4047 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4048 putenv(envbuf_Rows);
4049 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4050 putenv(envbuf_Rows);
4051 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4052 putenv(envbuf_Columns);
4053# endif
4054}
4055#endif
4056
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004058mch_call_shell(
4059 char_u *cmd,
4060 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061{
4062#ifdef VMS
4063 char *ifn = NULL;
4064 char *ofn = NULL;
4065#endif
4066 int tmode = cur_tmode;
4067#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
4068 int x;
4069# ifndef __EMX__
4070 char_u *newcmd; /* only needed for unix */
4071# else
4072 /*
4073 * Set the preferred shell in the EMXSHELL environment variable (but
4074 * only if it is different from what is already in the environment).
4075 * Emx then takes care of whether to use "/c" or "-c" in an
4076 * intelligent way. Simply pass the whole thing to emx's system() call.
4077 * Emx also starts an interactive shell if system() is passed an empty
4078 * string.
4079 */
4080 char_u *p, *old;
4081
4082 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4083 {
4084 /* should check HAVE_SETENV, but I know we don't have it. */
4085 p = alloc(10 + strlen(p_sh));
4086 if (p)
4087 {
4088 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4089 putenv((char *)p); /* don't free the pointer! */
4090 }
4091 }
4092# endif
4093
4094 out_flush();
4095
4096 if (options & SHELL_COOKED)
4097 settmode(TMODE_COOK); /* set to normal mode */
4098
Bram Moolenaar62b42182010-09-21 22:09:37 +02004099# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004100 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004101 loose_clipboard();
4102# endif
4103
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104# ifdef __EMX__
4105 if (cmd == NULL)
4106 x = system(""); /* this starts an interactive shell in emx */
4107 else
4108 x = system((char *)cmd);
4109 /* system() returns -1 when error occurs in starting shell */
4110 if (x == -1 && !emsg_silent)
4111 {
4112 MSG_PUTS(_("\nCannot execute shell "));
4113 msg_outtrans(p_sh);
4114 msg_putchar('\n');
4115 }
4116# else /* not __EMX__ */
4117 if (cmd == NULL)
4118 x = system((char *)p_sh);
4119 else
4120 {
4121# ifdef VMS
4122 if (ofn = strchr((char *)cmd, '>'))
4123 *ofn++ = '\0';
4124 if (ifn = strchr((char *)cmd, '<'))
4125 {
4126 char *p;
4127
4128 *ifn++ = '\0';
4129 p = strchr(ifn,' '); /* chop off any trailing spaces */
4130 if (p)
4131 *p = '\0';
4132 }
4133 if (ofn)
4134 x = vms_sys((char *)cmd, ofn, ifn);
4135 else
4136 x = system((char *)cmd);
4137# else
4138 newcmd = lalloc(STRLEN(p_sh)
4139 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4140 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4141 if (newcmd == NULL)
4142 x = 0;
4143 else
4144 {
4145 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4146 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4147 (char *)p_shcf,
4148 (char *)cmd);
4149 x = system((char *)newcmd);
4150 vim_free(newcmd);
4151 }
4152# endif
4153 }
4154# ifdef VMS
4155 x = vms_sys_status(x);
4156# endif
4157 if (emsg_silent)
4158 ;
4159 else if (x == 127)
4160 MSG_PUTS(_("\nCannot execute shell sh\n"));
4161# endif /* __EMX__ */
4162 else if (x && !(options & SHELL_SILENT))
4163 {
4164 MSG_PUTS(_("\nshell returned "));
4165 msg_outnum((long)x);
4166 msg_putchar('\n');
4167 }
4168
4169 if (tmode == TMODE_RAW)
4170 settmode(TMODE_RAW); /* set to raw mode */
4171# ifdef FEAT_TITLE
4172 resettitle();
4173# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004174# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4175 restore_clipboard();
4176# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 return x;
4178
4179#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4180
Bram Moolenaardf177f62005-02-22 08:39:57 +00004181# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4182 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183
Bram Moolenaar835dc632016-02-07 14:27:38 +01004184 char_u *newcmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004186 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 pid_t wait_pid = 0;
4188# ifdef HAVE_UNION_WAIT
4189 union wait status;
4190# else
4191 int status = -1;
4192# endif
4193 int retval = -1;
4194 char **argv = NULL;
4195 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004196 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 int i;
4198 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004200# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 int pty_slave_fd = -1;
4202 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004203# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004204 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205 int fd_fromshell[2];
4206 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004207 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208
Bram Moolenaar62b42182010-09-21 22:09:37 +02004209 newcmd = vim_strsave(p_sh);
4210 if (newcmd == NULL) /* out of memory */
4211 goto error;
4212
Bram Moolenaar071d4272004-06-13 20:20:40 +00004213 out_flush();
4214 if (options & SHELL_COOKED)
4215 settmode(TMODE_COOK); /* set to normal mode */
4216
Bram Moolenaar835dc632016-02-07 14:27:38 +01004217 if (mch_parse_cmd(newcmd, TRUE, &argv, &argc) == FAIL)
4218 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004219
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 if (cmd != NULL)
4221 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004222 char_u *s;
4223
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224 if (extra_shell_arg != NULL)
4225 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004226
4227 /* Break 'shellcmdflag' into white separated parts. This doesn't
4228 * handle quoted strings, they are very unlikely to appear. */
4229 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4230 if (p_shcf_copy == NULL) /* out of memory */
4231 goto error;
4232 s = p_shcf_copy;
4233 p = p_shcf;
4234 while (*p != NUL)
4235 {
4236 argv[argc++] = (char *)s;
4237 while (*p && *p != ' ' && *p != TAB)
4238 *s++ = *p++;
4239 *s++ = NUL;
4240 p = skipwhite(p);
4241 }
4242
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 argv[argc++] = (char *)cmd;
4244 }
4245 argv[argc] = NULL;
4246
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004248 * For the GUI, when writing the output into the buffer and when reading
4249 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4250 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004252 if ((options & (SHELL_READ|SHELL_WRITE))
4253# ifdef FEAT_GUI
4254 || (gui.in_use && show_shell_mess)
4255# endif
4256 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004258# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 /*
4260 * Try to open a master pty.
4261 * If this works, open the slave pty.
4262 * If the slave can't be opened, close the master pty.
4263 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004264 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004265 {
4266 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004267 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004269 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4270 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4271 * adding O_NOCTTY always works when defined. */
4272#ifdef O_NOCTTY
4273 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4274#else
4275 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4276#endif
4277 if (pty_slave_fd < 0)
4278 {
4279 close(pty_master_fd);
4280 pty_master_fd = -1;
4281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282 }
4283 }
4284 /*
4285 * If not opening a pty or it didn't work, try using pipes.
4286 */
4287 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004288# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 {
4290 pipe_error = (pipe(fd_toshell) < 0);
4291 if (!pipe_error) /* pipe create OK */
4292 {
4293 pipe_error = (pipe(fd_fromshell) < 0);
4294 if (pipe_error) /* pipe create failed */
4295 {
4296 close(fd_toshell[0]);
4297 close(fd_toshell[1]);
4298 }
4299 }
4300 if (pipe_error)
4301 {
4302 MSG_PUTS(_("\nCannot create pipes\n"));
4303 out_flush();
4304 }
4305 }
4306 }
4307
4308 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 {
4310# ifdef __BEOS__
4311 beos_cleanup_read_thread();
4312# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004313
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4315 {
4316 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004317 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004319 || (gui.in_use && show_shell_mess)
4320# endif
4321 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004323# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 if (pty_master_fd >= 0) /* close the pseudo tty */
4325 {
4326 close(pty_master_fd);
4327 close(pty_slave_fd);
4328 }
4329 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004330# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 {
4332 close(fd_toshell[0]);
4333 close(fd_toshell[1]);
4334 close(fd_fromshell[0]);
4335 close(fd_fromshell[1]);
4336 }
4337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338 }
4339 else if (pid == 0) /* child */
4340 {
4341 reset_signals(); /* handle signals normally */
4342
4343 if (!show_shell_mess || (options & SHELL_EXPAND))
4344 {
4345 int fd;
4346
4347 /*
4348 * Don't want to show any message from the shell. Can't just
4349 * close stdout and stderr though, because some systems will
4350 * break if you try to write to them after that, so we must
4351 * use dup() to replace them with something else -- webb
4352 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4353 * waiting for input.
4354 */
4355 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4356 fclose(stdin);
4357 fclose(stdout);
4358 fclose(stderr);
4359
4360 /*
4361 * If any of these open()'s and dup()'s fail, we just continue
4362 * anyway. It's not fatal, and on most systems it will make
4363 * no difference at all. On a few it will cause the execvp()
4364 * to exit with a non-zero status even when the completion
4365 * could be done, which is nothing too serious. If the open()
4366 * or dup() failed we'd just do the same thing ourselves
4367 * anyway -- webb
4368 */
4369 if (fd >= 0)
4370 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004371 ignored = dup(fd); /* To replace stdin (fd 0) */
4372 ignored = dup(fd); /* To replace stdout (fd 1) */
4373 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374
4375 /* Don't need this now that we've duplicated it */
4376 close(fd);
4377 }
4378 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004379 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004381 || gui.in_use
4382# endif
4383 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004384 {
4385
Bram Moolenaardf177f62005-02-22 08:39:57 +00004386# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004387 /* Create our own process group, so that the child and all its
4388 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004389 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004390 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004391 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004392 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004393# if defined(SIGHUP)
4394 /* When doing "!xterm&" and 'shell' is bash: the shell
4395 * will exit and send SIGHUP to all processes in its
4396 * group, killing the just started process. Ignore SIGHUP
4397 * to avoid that. (suggested by Simon Schubert)
4398 */
4399 signal(SIGHUP, SIG_IGN);
4400# endif
4401 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004402# endif
4403# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004404 if (pty_slave_fd >= 0)
4405 {
4406 /* push stream discipline modules */
4407 if (options & SHELL_COOKED)
4408 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004410 /* Try to become controlling tty (probably doesn't work,
4411 * unless run by root) */
4412 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004414 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004415# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004416 set_child_environment();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417
Bram Moolenaara5792f52005-11-23 21:25:05 +00004418 /*
4419 * stderr is only redirected when using the GUI, so that a
4420 * program like gpg can still access the terminal to get a
4421 * passphrase using stderr.
4422 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004423# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004424 if (pty_master_fd >= 0)
4425 {
4426 close(pty_master_fd); /* close master side of pty */
4427
4428 /* set up stdin/stdout/stderr for the child */
4429 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004430 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004432 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004433 if (gui.in_use)
4434 {
4435 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004436 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004437 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438
4439 close(pty_slave_fd); /* has been dupped, close it now */
4440 }
4441 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004442# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 {
4444 /* set up stdin for the child */
4445 close(fd_toshell[1]);
4446 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004447 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 close(fd_toshell[0]);
4449
4450 /* set up stdout for the child */
4451 close(fd_fromshell[0]);
4452 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004453 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 close(fd_fromshell[1]);
4455
Bram Moolenaara5792f52005-11-23 21:25:05 +00004456# ifdef FEAT_GUI
4457 if (gui.in_use)
4458 {
4459 /* set up stderr for the child */
4460 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004461 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004462 }
4463# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 }
4465 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004466
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 /*
4468 * There is no type cast for the argv, because the type may be
4469 * different on different machines. This may cause a warning
4470 * message with strict compilers, don't worry about it.
4471 * Call _exit() instead of exit() to avoid closing the connection
4472 * to the X server (esp. with GTK, which uses atexit()).
4473 */
4474 execvp(argv[0], argv);
4475 _exit(EXEC_FAILED); /* exec failed, return failure code */
4476 }
4477 else /* parent */
4478 {
4479 /*
4480 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004481 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 */
4483 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004484 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485
4486 /*
4487 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004488 * This is also used to pipe stdin/stdout to/from the external
4489 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004491 if ((options & (SHELL_READ|SHELL_WRITE))
4492# ifdef FEAT_GUI
4493 || (gui.in_use && show_shell_mess)
4494# endif
4495 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004497# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004499# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004501# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4503 int ta_len = 0; /* valid bytes in ta_buf[] */
4504 int len;
4505 int p_more_save;
4506 int old_State;
4507 int c;
4508 int toshell_fd;
4509 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004510 garray_T ga;
4511 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004512# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4513 struct timeval start_tv;
4514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515
Bram Moolenaardf177f62005-02-22 08:39:57 +00004516# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 if (pty_master_fd >= 0)
4518 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 fromshell_fd = pty_master_fd;
4520 toshell_fd = dup(pty_master_fd);
4521 }
4522 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004523# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 {
4525 close(fd_toshell[0]);
4526 close(fd_fromshell[1]);
4527 toshell_fd = fd_toshell[1];
4528 fromshell_fd = fd_fromshell[0];
4529 }
4530
4531 /*
4532 * Write to the child if there are typed characters.
4533 * Read from the child if there are characters available.
4534 * Repeat the reading a few times if more characters are
4535 * available. Need to check for typed keys now and then, but
4536 * not too often (delays when no chars are available).
4537 * This loop is quit if no characters can be read from the pty
4538 * (WaitForChar detected special condition), or there are no
4539 * characters available and the child has exited.
4540 * Only check if the child has exited when there is no more
4541 * output. The child may exit before all the output has
4542 * been printed.
4543 *
4544 * Currently this busy loops!
4545 * This can probably dead-lock when the write blocks!
4546 */
4547 p_more_save = p_more;
4548 p_more = FALSE;
4549 old_State = State;
4550 State = EXTERNCMD; /* don't redraw at window resize */
4551
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004552 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004553 {
4554 /* Fork a process that will write the lines to the
4555 * external program. */
4556 if ((wpid = fork()) == -1)
4557 {
4558 MSG_PUTS(_("\nCannot fork\n"));
4559 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004560 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004561 {
4562 linenr_T lnum = curbuf->b_op_start.lnum;
4563 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004564 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004565 size_t l;
4566
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004567 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004568 for (;;)
4569 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004570 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004571 if (l == 0)
4572 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004573 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004574 /* NL -> NUL translation */
4575 len = write(toshell_fd, "", (size_t)1);
4576 else
4577 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004578 char_u *s = vim_strchr(lp + written, NL);
4579
Bram Moolenaar89d40322006-08-29 15:30:07 +00004580 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004581 s == NULL ? l
4582 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004583 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004584 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004585 {
4586 /* Finished a line, add a NL, unless this line
4587 * should not have one. */
4588 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004589 || (!curbuf->b_p_bin
4590 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004591 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004592 && (lnum !=
4593 curbuf->b_ml.ml_line_count
4594 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004595 ignored = write(toshell_fd, "\n",
4596 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004597 ++lnum;
4598 if (lnum > curbuf->b_op_end.lnum)
4599 {
4600 /* finished all the lines, close pipe */
4601 close(toshell_fd);
4602 toshell_fd = -1;
4603 break;
4604 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004605 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004606 written = 0;
4607 }
4608 else if (len > 0)
4609 written += len;
4610 }
4611 _exit(0);
4612 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004613 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004614 {
4615 close(toshell_fd);
4616 toshell_fd = -1;
4617 }
4618 }
4619
4620 if (options & SHELL_READ)
4621 ga_init2(&ga, 1, BUFLEN);
4622
4623 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004624# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4625 gettimeofday(&start_tv, NULL);
4626# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 for (;;)
4628 {
4629 /*
4630 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004631 * if there are any.
4632 * Don't do this if we are expanding wild cards (would eat
4633 * typeahead).
4634 * Don't do this when filtering and terminal is in cooked
4635 * mode, the shell command will handle the I/O. Avoids
4636 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004637 * Don't get characters when the child has already
4638 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004639 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004640 * while (noread_cnt > 4), avoids that ":r !ls" eats
4641 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 */
4643 len = 0;
4644 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004645 && ((options &
4646 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4647 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004648# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004649 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004650# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004651 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004652 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004653 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004655 if (ta_len == 0)
4656 {
4657 /* Get extra characters when we don't have any.
4658 * Reset the counter and timer. */
4659 noread_cnt = 0;
4660# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4661 gettimeofday(&start_tv, NULL);
4662# endif
4663 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4664 }
4665 if (ta_len > 0 || len > 0)
4666 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 /*
4668 * For pipes:
4669 * Check for CTRL-C: send interrupt signal to child.
4670 * Check for CTRL-D: EOF, close pipe to child.
4671 */
4672 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4673 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004674# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675 /*
4676 * Send SIGINT to the child's group or all
4677 * processes in our group.
4678 */
4679 if (ta_buf[ta_len] == Ctrl_C
4680 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004681 {
4682# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004684# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004687 if (wpid > 0)
4688 kill(wpid, SIGINT);
4689 }
4690# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 if (pty_master_fd < 0 && toshell_fd >= 0
4692 && ta_buf[ta_len] == Ctrl_D)
4693 {
4694 close(toshell_fd);
4695 toshell_fd = -1;
4696 }
4697 }
4698
4699 /* replace K_BS by <BS> and K_DEL by <DEL> */
4700 for (i = ta_len; i < ta_len + len; ++i)
4701 {
4702 if (ta_buf[i] == CSI && len - i > 2)
4703 {
4704 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4705 if (c == K_DEL || c == K_KDEL || c == K_BS)
4706 {
4707 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4708 (size_t)(len - i - 2));
4709 if (c == K_DEL || c == K_KDEL)
4710 ta_buf[i] = DEL;
4711 else
4712 ta_buf[i] = Ctrl_H;
4713 len -= 2;
4714 }
4715 }
4716 else if (ta_buf[i] == '\r')
4717 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004718# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004720 i += (*mb_ptr2len_len)(ta_buf + i,
4721 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 }
4724
4725 /*
4726 * For pipes: echo the typed characters.
4727 * For a pty this does not seem to work.
4728 */
4729 if (pty_master_fd < 0)
4730 {
4731 for (i = ta_len; i < ta_len + len; ++i)
4732 {
4733 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4734 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004735# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 else if (has_mbyte)
4737 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004738 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739
4740 msg_outtrans_len(ta_buf + i, l);
4741 i += l - 1;
4742 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004743# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 else
4745 msg_outtrans_len(ta_buf + i, 1);
4746 }
4747 windgoto(msg_row, msg_col);
4748 out_flush();
4749 }
4750
4751 ta_len += len;
4752
4753 /*
4754 * Write the characters to the child, unless EOF has
4755 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004756 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004757 * When writing buffer lines, drop the typed
4758 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004760 if (options & SHELL_WRITE)
4761 ta_len = 0;
4762 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 {
4764 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4765 if (len > 0)
4766 {
4767 ta_len -= len;
4768 mch_memmove(ta_buf, ta_buf + len, ta_len);
4769 }
4770 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 }
4773
Bram Moolenaardf177f62005-02-22 08:39:57 +00004774 if (got_int)
4775 {
4776 /* CTRL-C sends a signal to the child, we ignore it
4777 * ourselves */
4778# ifdef HAVE_SETSID
4779 kill(-pid, SIGINT);
4780# else
4781 kill(0, SIGINT);
4782# endif
4783 if (wpid > 0)
4784 kill(wpid, SIGINT);
4785 got_int = FALSE;
4786 }
4787
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 /*
4789 * Check if the child has any characters to be printed.
4790 * Read them and write them to our window. Repeat this as
4791 * long as there is something to do, avoid the 10ms wait
4792 * for mch_inchar(), or sending typeahead characters to
4793 * the external process.
4794 * TODO: This should handle escape sequences, compatible
4795 * to some terminal (vt52?).
4796 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004797 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01004798 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004800 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004801# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004803# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004805# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 );
4807 if (len <= 0) /* end of file or error */
4808 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004809
4810 noread_cnt = 0;
4811 if (options & SHELL_READ)
4812 {
4813 /* Do NUL -> NL translation, append NL separated
4814 * lines to the current buffer. */
4815 for (i = 0; i < len; ++i)
4816 {
4817 if (buffer[i] == NL)
4818 append_ga_line(&ga);
4819 else if (buffer[i] == NUL)
4820 ga_append(&ga, NL);
4821 else
4822 ga_append(&ga, buffer[i]);
4823 }
4824 }
4825# ifdef FEAT_MBYTE
4826 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 {
4828 int l;
4829
Bram Moolenaardf177f62005-02-22 08:39:57 +00004830 len += buffer_off;
4831 buffer[len] = NUL;
4832
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 /* Check if the last character in buffer[] is
4834 * incomplete, keep these bytes for the next
4835 * round. */
4836 for (p = buffer; p < buffer + len; p += l)
4837 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004838 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 if (l == 0)
4840 l = 1; /* NUL byte? */
4841 else if (MB_BYTE2LEN(*p) != l)
4842 break;
4843 }
4844 if (p == buffer) /* no complete character */
4845 {
4846 /* avoid getting stuck at an illegal byte */
4847 if (len >= 12)
4848 ++p;
4849 else
4850 {
4851 buffer_off = len;
4852 continue;
4853 }
4854 }
4855 c = *p;
4856 *p = NUL;
4857 msg_puts(buffer);
4858 if (p < buffer + len)
4859 {
4860 *p = c;
4861 buffer_off = (buffer + len) - p;
4862 mch_memmove(buffer, p, buffer_off);
4863 continue;
4864 }
4865 buffer_off = 0;
4866 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004867# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 {
4870 buffer[len] = NUL;
4871 msg_puts(buffer);
4872 }
4873
4874 windgoto(msg_row, msg_col);
4875 cursor_on();
4876 out_flush();
4877 if (got_int)
4878 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004879
4880# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004881 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004882 {
4883 struct timeval now_tv;
4884 long msec;
4885
4886 /* Avoid that we keep looping here without
4887 * checking for a CTRL-C for a long time. Don't
4888 * break out too often to avoid losing typeahead. */
4889 gettimeofday(&now_tv, NULL);
4890 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004891 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004892 if (msec > 2000)
4893 {
4894 noread_cnt = 5;
4895 break;
4896 }
4897 }
4898# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 }
4900
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004901 /* If we already detected the child has finished, continue
4902 * reading output for a short while. Some text may be
4903 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004904 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004905 {
4906 if (noread_cnt < 5)
4907 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004908 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02004909 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004910
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 /*
4912 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004913 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004915# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004916 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004917# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004919# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4921 || (wait_pid == pid && WIFEXITED(status)))
4922 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004923 /* Don't break the loop yet, try reading more
4924 * characters from "fromshell_fd" first. When using
4925 * pipes there might still be something to read and
4926 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004929 else
4930 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004931
Bram Moolenaar95a51352013-03-21 22:53:50 +01004932# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004933 /* Handle any X events, e.g. serving the clipboard. */
4934 clip_update();
4935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 }
4937finished:
4938 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004939 if (options & SHELL_READ)
4940 {
4941 if (ga.ga_len > 0)
4942 {
4943 append_ga_line(&ga);
4944 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004945 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004946 }
4947 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004948 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004949 ga_clear(&ga);
4950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 /*
4953 * Give all typeahead that wasn't used back to ui_inchar().
4954 */
4955 if (ta_len)
4956 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 State = old_State;
4958 if (toshell_fd >= 0)
4959 close(toshell_fd);
4960 close(fromshell_fd);
4961 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004962# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004963 else
4964 {
4965 /*
4966 * Similar to the loop above, but only handle X events, no
4967 * I/O.
4968 */
4969 for (;;)
4970 {
4971 if (got_int)
4972 {
4973 /* CTRL-C sends a signal to the child, we ignore it
4974 * ourselves */
4975# ifdef HAVE_SETSID
4976 kill(-pid, SIGINT);
4977# else
4978 kill(0, SIGINT);
4979# endif
4980 got_int = FALSE;
4981 }
4982# ifdef __NeXT__
4983 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4984# else
4985 wait_pid = waitpid(pid, &status, WNOHANG);
4986# endif
4987 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4988 || (wait_pid == pid && WIFEXITED(status)))
4989 {
4990 wait_pid = pid;
4991 break;
4992 }
4993
4994 /* Handle any X events, e.g. serving the clipboard. */
4995 clip_update();
4996
4997 mch_delay(10L, TRUE);
4998 }
4999 }
5000# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001
5002 /*
5003 * Wait until our child has exited.
5004 * Ignore wait() returning pids of other children and returning
5005 * because of some signal like SIGWINCH.
5006 * Don't wait if wait_pid was already set above, indicating the
5007 * child already exited.
5008 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005009 if (wait_pid != pid)
5010 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011
Bram Moolenaar624891f2010-10-13 16:22:09 +02005012# ifdef FEAT_GUI
5013 /* Close slave side of pty. Only do this after the child has
5014 * exited, otherwise the child may hang when it tries to write on
5015 * the pty. */
5016 if (pty_master_fd >= 0)
5017 close(pty_slave_fd);
5018# endif
5019
Bram Moolenaardf177f62005-02-22 08:39:57 +00005020 /* Make sure the child that writes to the external program is
5021 * dead. */
5022 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005023 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005024 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005025 wait4pid(wpid, NULL);
5026 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005027
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 /*
5029 * Set to raw mode right now, otherwise a CTRL-C after
5030 * catch_signals() will kill Vim.
5031 */
5032 if (tmode == TMODE_RAW)
5033 settmode(TMODE_RAW);
5034 did_settmode = TRUE;
5035 set_signals();
5036
5037 if (WIFEXITED(status))
5038 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005039 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005041 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 {
5043 if (retval == EXEC_FAILED)
5044 {
5045 MSG_PUTS(_("\nCannot execute shell "));
5046 msg_outtrans(p_sh);
5047 msg_putchar('\n');
5048 }
5049 else if (!(options & SHELL_SILENT))
5050 {
5051 MSG_PUTS(_("\nshell returned "));
5052 msg_outnum((long)retval);
5053 msg_putchar('\n');
5054 }
5055 }
5056 }
5057 else
5058 MSG_PUTS(_("\nCommand terminated\n"));
5059 }
5060 }
5061 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005062 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063
5064error:
5065 if (!did_settmode)
5066 if (tmode == TMODE_RAW)
5067 settmode(TMODE_RAW); /* set to raw mode */
5068# ifdef FEAT_TITLE
5069 resettitle();
5070# endif
5071 vim_free(newcmd);
5072
5073 return retval;
5074
5075#endif /* USE_SYSTEM */
5076}
5077
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005078#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005079 void
Bram Moolenaar802d5592016-03-05 22:05:27 +01005080mch_start_job(char **argv, job_T *job, jobopt_T *options UNUSED)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005081{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005082 pid_t pid;
5083 int fd_in[2]; /* for stdin */
5084 int fd_out[2]; /* for stdout */
5085 int fd_err[2]; /* for stderr */
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005086 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005087 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5088 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5089 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005090 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005091 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5092 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005093 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005094
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005095 if (use_out_for_err && use_null_for_out)
5096 use_null_for_err = TRUE;
5097
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005098 /* default is to fail */
5099 job->jv_status = JOB_FAILED;
5100 fd_in[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005101 fd_in[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005102 fd_out[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005103 fd_out[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005104 fd_err[0] = -1;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005105 fd_err[1] = -1;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005106
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005107 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005108 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005109 if (use_file_for_in)
5110 {
5111 char_u *fname = options->jo_io_name[PART_IN];
5112
5113 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5114 if (fd_in[0] < 0)
5115 {
5116 EMSG2(_(e_notopen), fname);
5117 goto failed;
5118 }
5119 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005120 else if (!use_null_for_in && pipe(fd_in) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005121 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005122
5123 if (use_file_for_out)
5124 {
5125 char_u *fname = options->jo_io_name[PART_OUT];
5126
5127 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5128 if (fd_out[1] < 0)
5129 {
5130 EMSG2(_(e_notopen), fname);
5131 goto failed;
5132 }
5133 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005134 else if (!use_null_for_out && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005135 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005136
5137 if (use_file_for_err)
5138 {
5139 char_u *fname = options->jo_io_name[PART_ERR];
5140
5141 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5142 if (fd_err[1] < 0)
5143 {
5144 EMSG2(_(e_notopen), fname);
5145 goto failed;
5146 }
5147 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005148 else if (!use_out_for_err && !use_null_for_err && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005149 goto failed;
5150
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005151 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5152 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005153 if (options->jo_set & JO_CHANNEL)
5154 {
5155 channel = options->jo_channel;
5156 if (channel != NULL)
5157 ++channel->ch_refcount;
5158 }
5159 else
5160 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005161 if (channel == NULL)
5162 goto failed;
5163 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005164
5165 pid = fork(); /* maybe we should use vfork() */
5166 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005167 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005168 /* failed to fork */
5169 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005170 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005171
5172 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005173 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005174 int null_fd = -1;
5175 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005176
Bram Moolenaar835dc632016-02-07 14:27:38 +01005177 /* child */
5178 reset_signals(); /* handle signals normally */
5179
5180# ifdef HAVE_SETSID
5181 /* Create our own process group, so that the child and all its
5182 * children can be kill()ed. Don't do this when using pipes,
5183 * because stdin is not a tty, we would lose /dev/tty. */
5184 (void)setsid();
5185# endif
5186
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005187 set_child_environment();
5188
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005189 if (use_null_for_in || use_null_for_out || use_null_for_err)
5190 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5191
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005192 /* set up stdin for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005193 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005194 {
5195 close(0);
5196 ignored = dup(null_fd);
5197 }
5198 else
5199 {
5200 if (!use_file_for_in)
5201 close(fd_in[1]);
5202 close(0);
5203 ignored = dup(fd_in[0]);
5204 close(fd_in[0]);
5205 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005206
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005207 /* set up stderr for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005208 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005209 {
5210 close(2);
5211 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005212 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005213 }
5214 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005215 {
5216 close(2);
5217 ignored = dup(fd_out[1]);
5218 }
5219 else
5220 {
Bram Moolenaare98d1212016-03-08 15:37:41 +01005221 if (!use_file_for_err)
5222 close(fd_err[0]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005223 close(2);
5224 ignored = dup(fd_err[1]);
5225 close(fd_err[1]);
5226 }
5227
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005228 /* set up stdout for the child */
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005229 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005230 {
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005231 close(1);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005232 ignored = dup(null_fd);
5233 }
5234 else
5235 {
5236 if (!use_file_for_out)
5237 close(fd_out[0]);
5238 close(1);
5239 ignored = dup(fd_out[1]);
5240 close(fd_out[1]);
5241 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005242
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005243 if (null_fd >= 0)
5244 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005245
Bram Moolenaar835dc632016-02-07 14:27:38 +01005246 /* See above for type of argv. */
5247 execvp(argv[0], argv);
5248
Bram Moolenaar4694a172016-04-21 14:05:23 +02005249 if (stderr_works)
5250 perror("executing job failed");
Bram Moolenaarcda77642016-06-04 13:32:35 +02005251#ifdef EXITFREE
5252 /* calling free_all_mem() here causes problems. Ignore valgrind
5253 * reporting possibly leaked memory. */
5254#endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005255 _exit(EXEC_FAILED); /* exec failed, return failure code */
5256 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005257
5258 /* parent */
5259 job->jv_pid = pid;
5260 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005261 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005262
5263 /* child stdin, stdout and stderr */
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005264 if (!use_file_for_in && fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005265 close(fd_in[0]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005266 if (!use_file_for_out && fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005267 close(fd_out[1]);
Bram Moolenaarbe6aa462016-03-20 21:02:00 +01005268 if (!use_out_for_err && !use_file_for_err && fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005269 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005270 if (channel != NULL)
5271 {
5272 channel_set_pipes(channel,
5273 use_file_for_in || use_null_for_in
5274 ? INVALID_FD : fd_in[1],
5275 use_file_for_out || use_null_for_out
5276 ? INVALID_FD : fd_out[0],
5277 use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaare98d1212016-03-08 15:37:41 +01005278 ? INVALID_FD : fd_err[0]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005279 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005280 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005281
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005282 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005283 return;
5284
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005285failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005286 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005287 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005288 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005289 if (fd_in[1] >= 0)
5290 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005291 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005292 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005293 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005294 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005295 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005296 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005297 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005298 close(fd_err[1]);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005299}
5300
5301 char *
5302mch_job_status(job_T *job)
5303{
5304# ifdef HAVE_UNION_WAIT
5305 union wait status;
5306# else
5307 int status = -1;
5308# endif
5309 pid_t wait_pid = 0;
5310
5311# ifdef __NeXT__
5312 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5313# else
5314 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5315# endif
5316 if (wait_pid == -1)
5317 {
5318 /* process must have exited */
5319 job->jv_status = JOB_ENDED;
5320 return "dead";
5321 }
5322 if (wait_pid == 0)
5323 return "run";
5324 if (WIFEXITED(status))
5325 {
5326 /* LINTED avoid "bitwise operation on signed value" */
5327 job->jv_exitval = WEXITSTATUS(status);
5328 job->jv_status = JOB_ENDED;
5329 return "dead";
5330 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005331 if (WIFSIGNALED(status))
5332 {
5333 job->jv_exitval = -1;
5334 job->jv_status = JOB_ENDED;
5335 return "dead";
5336 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005337 return "run";
5338}
5339
5340 int
5341mch_stop_job(job_T *job, char_u *how)
5342{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005343 int sig = -1;
5344 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005345
Bram Moolenaar923d9262016-02-25 20:56:01 +01005346 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005347 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005348 else if (STRCMP(how, "hup") == 0)
5349 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005350 else if (STRCMP(how, "quit") == 0)
5351 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005352 else if (STRCMP(how, "int") == 0)
5353 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005354 else if (STRCMP(how, "kill") == 0)
5355 sig = SIGKILL;
5356 else if (isdigit(*how))
5357 sig = atoi((char *)how);
5358 else
5359 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005360
Bram Moolenaar72801402016-02-09 11:37:50 +01005361 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005362 job_pid = job->jv_pid;
5363 if (job_pid == getpgid(job_pid))
5364 job_pid = -job_pid;
5365
5366 kill(job_pid, sig);
5367
Bram Moolenaar835dc632016-02-07 14:27:38 +01005368 return OK;
5369}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005370
5371/*
5372 * Clear the data related to "job".
5373 */
5374 void
5375mch_clear_job(job_T *job)
5376{
5377 /* call waitpid because child process may become zombie */
5378# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005379 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005380# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005381 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005382# endif
5383}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005384#endif
5385
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386/*
5387 * Check for CTRL-C typed by reading all available characters.
5388 * In cooked mode we should get SIGINT, no need to check.
5389 */
5390 void
Bram Moolenaar05540972016-01-30 20:31:25 +01005391mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392{
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005393 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005394 fill_input_buf(FALSE);
5395}
5396
5397/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005398 * Wait "msec" msec until a character is available from the mouse, keyboard,
5399 * from inbuf[].
5400 * "msec" == -1 will block forever.
5401 * Invokes timer callbacks when needed.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005402 * "interrupted" (if not NULL) is set to TRUE when no character is available
5403 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005404 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005405 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406 */
5407 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005408WaitForChar(long msec, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005410#ifdef FEAT_TIMERS
5411 long due_time;
5412 long remaining = msec;
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005413 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005414
5415 /* When waiting very briefly don't trigger timers. */
5416 if (msec >= 0 && msec < 10L)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005417 return WaitForCharOrMouse(msec, NULL);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005418
5419 while (msec < 0 || remaining > 0)
5420 {
5421 /* Trigger timers and then get the time in msec until the next one is
5422 * due. Wait up to that time. */
5423 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005424 if (typebuf.tb_change_cnt != tb_change_cnt)
5425 {
5426 /* timer may have used feedkeys() */
5427 return FALSE;
5428 }
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005429 if (due_time <= 0 || (msec > 0 && due_time > remaining))
5430 due_time = remaining;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005431 if (WaitForCharOrMouse(due_time, interrupted))
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005432 return TRUE;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005433 if (interrupted != NULL && *interrupted)
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005434 /* Nothing available, but need to return so that side effects get
5435 * handled, such as handling a message on a channel. */
5436 return FALSE;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005437 if (msec > 0)
5438 remaining -= due_time;
5439 }
5440 return FALSE;
5441#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005442 return WaitForCharOrMouse(msec, interrupted);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005443#endif
5444}
5445
5446/*
5447 * Wait "msec" msec until a character is available from the mouse or keyboard
5448 * or from inbuf[].
5449 * "msec" == -1 will block forever.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005450 * "interrupted" (if not NULL) is set to TRUE when no character is available
5451 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005452 * When a GUI is being used, this will never get called -- webb
5453 */
5454 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02005455WaitForCharOrMouse(long msec, int *interrupted)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005456{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005457#ifdef FEAT_MOUSE_GPM
5458 int gpm_process_wanted;
5459#endif
5460#ifdef FEAT_XCLIPBOARD
5461 int rest;
5462#endif
5463 int avail;
5464
5465 if (input_available()) /* something in inbuf[] */
5466 return 1;
5467
5468#if defined(FEAT_MOUSE_DEC)
5469 /* May need to query the mouse position. */
5470 if (WantQueryMouse)
5471 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005472 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005473 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5474 }
5475#endif
5476
5477 /*
5478 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5479 * events. This is a bit complicated, because they might both be defined.
5480 */
5481#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5482# ifdef FEAT_XCLIPBOARD
5483 rest = 0;
5484 if (do_xterm_trace())
5485 rest = msec;
5486# endif
5487 do
5488 {
5489# ifdef FEAT_XCLIPBOARD
5490 if (rest != 0)
5491 {
5492 msec = XT_TRACE_DELAY;
5493 if (rest >= 0 && rest < XT_TRACE_DELAY)
5494 msec = rest;
5495 if (rest >= 0)
5496 rest -= msec;
5497 }
5498# endif
5499# ifdef FEAT_MOUSE_GPM
5500 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005501 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02005502 &gpm_process_wanted, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005504 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505# endif
5506 if (!avail)
5507 {
5508 if (input_available())
5509 return 1;
5510# ifdef FEAT_XCLIPBOARD
5511 if (rest == 0 || !do_xterm_trace())
5512# endif
5513 break;
5514 }
5515 }
5516 while (FALSE
5517# ifdef FEAT_MOUSE_GPM
5518 || (gpm_process_wanted && mch_gpm_process() == 0)
5519# endif
5520# ifdef FEAT_XCLIPBOARD
5521 || (!avail && rest != 0)
5522# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005523 )
5524 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005525
5526#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02005527 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528#endif
5529 return avail;
5530}
5531
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005532#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533/*
5534 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005535 * "msec" == 0 will check for characters once.
5536 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005539 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005540 * "interrupted" (if not NULL) is set to TRUE when no character is available
5541 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543#if defined(__BEOS__)
5544 int
5545#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005546 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005548RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549{
5550 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005551 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005552#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553 static int busy = FALSE;
5554
5555 /* May retry getting characters after an event was handled. */
5556# define MAY_LOOP
5557
5558# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5559 /* Remember at what time we started, so that we know how much longer we
5560 * should wait after being interrupted. */
5561# define USE_START_TV
5562 struct timeval start_tv;
5563
5564 if (msec > 0 && (
5565# ifdef FEAT_XCLIPBOARD
5566 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005567# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568 ||
5569# endif
5570# endif
5571# ifdef USE_XSMP
5572 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005573# ifdef FEAT_MZSCHEME
5574 ||
5575# endif
5576# endif
5577# ifdef FEAT_MZSCHEME
5578 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579# endif
5580 ))
5581 gettimeofday(&start_tv, NULL);
5582# endif
5583
5584 /* Handle being called recursively. This may happen for the session
5585 * manager stuff, it may save the file, which does a breakcheck. */
5586 if (busy)
5587 return 0;
5588#endif
5589
5590#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005591 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592#endif
5593 {
5594#ifdef MAY_LOOP
5595 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005596# ifdef FEAT_MZSCHEME
5597 int mzquantum_used = FALSE;
5598# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599#endif
5600#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005601 /* each channel may use in, out and err */
5602 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603 int nfd;
5604# ifdef FEAT_XCLIPBOARD
5605 int xterm_idx = -1;
5606# endif
5607# ifdef FEAT_MOUSE_GPM
5608 int gpm_idx = -1;
5609# endif
5610# ifdef USE_XSMP
5611 int xsmp_idx = -1;
5612# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005613 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005615# ifdef FEAT_MZSCHEME
5616 mzvim_check_threads();
5617 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5618 {
5619 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5620 mzquantum_used = TRUE;
5621 }
5622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 fds[0].fd = fd;
5624 fds[0].events = POLLIN;
5625 nfd = 1;
5626
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005628 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 if (xterm_Shell != (Widget)0)
5630 {
5631 xterm_idx = nfd;
5632 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5633 fds[nfd].events = POLLIN;
5634 nfd++;
5635 }
5636# endif
5637# ifdef FEAT_MOUSE_GPM
5638 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5639 {
5640 gpm_idx = nfd;
5641 fds[nfd].fd = gpm_fd;
5642 fds[nfd].events = POLLIN;
5643 nfd++;
5644 }
5645# endif
5646# ifdef USE_XSMP
5647 if (xsmp_icefd != -1)
5648 {
5649 xsmp_idx = nfd;
5650 fds[nfd].fd = xsmp_icefd;
5651 fds[nfd].events = POLLIN;
5652 nfd++;
5653 }
5654# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005655#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005656 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005657#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005658 if (interrupted != NULL)
5659 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005661 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005662
5663 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02005664 if (result == 0 && interrupted != NULL && ret > 0)
5665 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005666
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005667# ifdef FEAT_MZSCHEME
5668 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005669 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005670 finished = FALSE;
5671# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673# ifdef FEAT_XCLIPBOARD
5674 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5675 {
5676 xterm_update(); /* Maybe we should hand out clipboard */
5677 if (--ret == 0 && !input_available())
5678 /* Try again */
5679 finished = FALSE;
5680 }
5681# endif
5682# ifdef FEAT_MOUSE_GPM
5683 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5684 {
5685 *check_for_gpm = 1;
5686 }
5687# endif
5688# ifdef USE_XSMP
5689 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5690 {
5691 if (fds[xsmp_idx].revents & POLLIN)
5692 {
5693 busy = TRUE;
5694 xsmp_handle_requests();
5695 busy = FALSE;
5696 }
5697 else if (fds[xsmp_idx].revents & POLLHUP)
5698 {
5699 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005700 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 xsmp_close();
5702 }
5703 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005704 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705 }
5706# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005707#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005708 if (ret > 0)
5709 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005710#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712#else /* HAVE_SELECT */
5713
5714 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005715 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005716 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005718 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005720# ifdef FEAT_MZSCHEME
5721 mzvim_check_threads();
5722 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5723 {
5724 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5725 mzquantum_used = TRUE;
5726 }
5727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728# ifdef __EMX__
5729 /* don't check for incoming chars if not in raw mode, because select()
5730 * always returns TRUE then (in some version of emx.dll) */
5731 if (curr_tmode != TMODE_RAW)
5732 return 0;
5733# endif
5734
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005735 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005737 tv.tv_sec = towait / 1000;
5738 tv.tv_usec = (towait % 1000) * (1000000/1000);
5739 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005741 else
5742 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743
5744 /*
5745 * Select on ready for reading and exceptional condition (end of file).
5746 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005747select_eintr:
5748 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005749 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 FD_ZERO(&efds);
5751 FD_SET(fd, &rfds);
5752# if !defined(__QNX__) && !defined(__CYGWIN32__)
5753 /* For QNX select() always returns 1 if this is set. Why? */
5754 FD_SET(fd, &efds);
5755# endif
5756 maxfd = fd;
5757
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005759 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 if (xterm_Shell != (Widget)0)
5761 {
5762 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5763 if (maxfd < ConnectionNumber(xterm_dpy))
5764 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005765
5766 /* An event may have already been read but not handled. In
5767 * particulary, XFlush may cause this. */
5768 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 }
5770# endif
5771# ifdef FEAT_MOUSE_GPM
5772 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5773 {
5774 FD_SET(gpm_fd, &rfds);
5775 FD_SET(gpm_fd, &efds);
5776 if (maxfd < gpm_fd)
5777 maxfd = gpm_fd;
5778 }
5779# endif
5780# ifdef USE_XSMP
5781 if (xsmp_icefd != -1)
5782 {
5783 FD_SET(xsmp_icefd, &rfds);
5784 FD_SET(xsmp_icefd, &efds);
5785 if (maxfd < xsmp_icefd)
5786 maxfd = xsmp_icefd;
5787 }
5788# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005789# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005790 maxfd = channel_select_setup(maxfd, &rfds, &wfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005791# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02005792 if (interrupted != NULL)
5793 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005795 ret = select(maxfd + 1, &rfds, &wfds, &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005796 result = ret > 0 && FD_ISSET(fd, &rfds);
5797 if (result)
5798 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02005799 else if (interrupted != NULL && ret > 0)
5800 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005801
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005802# ifdef EINTR
5803 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005804 {
5805 /* Check whether window has been resized, EINTR may be caused by
5806 * SIGWINCH. */
5807 if (do_resize)
5808 handle_resize();
5809
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005810 /* Interrupted by a signal, need to try again. We ignore msec
5811 * here, because we do want to check even after a timeout if
5812 * characters are available. Needed for reading output of an
5813 * external command after the process has finished. */
5814 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005815 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005816# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005817# ifdef __TANDEM
5818 if (ret == -1 && errno == ENOTSUP)
5819 {
5820 FD_ZERO(&rfds);
5821 FD_ZERO(&efds);
5822 ret = 0;
5823 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005824# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005825# ifdef FEAT_MZSCHEME
5826 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005827 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005828 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829# endif
5830
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831# ifdef FEAT_XCLIPBOARD
5832 if (ret > 0 && xterm_Shell != (Widget)0
5833 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5834 {
5835 xterm_update(); /* Maybe we should hand out clipboard */
5836 /* continue looping when we only got the X event and the input
5837 * buffer is empty */
5838 if (--ret == 0 && !input_available())
5839 {
5840 /* Try again */
5841 finished = FALSE;
5842 }
5843 }
5844# endif
5845# ifdef FEAT_MOUSE_GPM
5846 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5847 {
5848 if (FD_ISSET(gpm_fd, &efds))
5849 gpm_close();
5850 else if (FD_ISSET(gpm_fd, &rfds))
5851 *check_for_gpm = 1;
5852 }
5853# endif
5854# ifdef USE_XSMP
5855 if (ret > 0 && xsmp_icefd != -1)
5856 {
5857 if (FD_ISSET(xsmp_icefd, &efds))
5858 {
5859 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005860 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861 xsmp_close();
5862 if (--ret == 0)
5863 finished = FALSE; /* keep going if event was only one */
5864 }
5865 else if (FD_ISSET(xsmp_icefd, &rfds))
5866 {
5867 busy = TRUE;
5868 xsmp_handle_requests();
5869 busy = FALSE;
5870 if (--ret == 0)
5871 finished = FALSE; /* keep going if event was only one */
5872 }
5873 }
5874# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005875#ifdef FEAT_JOB_CHANNEL
Bram Moolenaare0874f82016-01-24 20:36:41 +01005876 if (ret > 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02005877 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005878#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879
5880#endif /* HAVE_SELECT */
5881
5882#ifdef MAY_LOOP
5883 if (finished || msec == 0)
5884 break;
5885
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005886# ifdef FEAT_CLIENTSERVER
5887 if (server_waiting())
5888 break;
5889# endif
5890
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891 /* We're going to loop around again, find out for how long */
5892 if (msec > 0)
5893 {
5894# ifdef USE_START_TV
5895 struct timeval mtv;
5896
5897 /* Compute remaining wait time. */
5898 gettimeofday(&mtv, NULL);
5899 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5900 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5901# else
5902 /* Guess we got interrupted halfway. */
5903 msec = msec / 2;
5904# endif
5905 if (msec <= 0)
5906 break; /* waited long enough */
5907 }
5908#endif
5909 }
5910
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01005911 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912}
5913
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005916 * Expand a path into all matching files and/or directories. Handles "*",
5917 * "?", "[a-z]", "**", etc.
5918 * "path" has backslashes before chars that are not to be expanded.
5919 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 */
5921 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005922mch_expandpath(
5923 garray_T *gap,
5924 char_u *path,
5925 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926{
Bram Moolenaar02743632005-07-25 20:42:36 +00005927 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928}
5929#endif
5930
5931/*
5932 * mch_expand_wildcards() - this code does wild-card pattern matching using
5933 * the shell
5934 *
5935 * return OK for success, FAIL for error (you may lose some memory) and put
5936 * an error message in *file.
5937 *
5938 * num_pat is number of input patterns
5939 * pat is array of pointers to input patterns
5940 * num_file is pointer to number of matched file names
5941 * file is pointer to array of pointers to matched file names
5942 */
5943
5944#ifndef SEEK_SET
5945# define SEEK_SET 0
5946#endif
5947#ifndef SEEK_END
5948# define SEEK_END 2
5949#endif
5950
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005951#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005952
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005954mch_expand_wildcards(
5955 int num_pat,
5956 char_u **pat,
5957 int *num_file,
5958 char_u ***file,
5959 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 int i;
5962 size_t len;
5963 char_u *p;
5964 int dir;
5965#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005966 /*
5967 * This is the OS/2 implementation.
5968 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969# define EXPL_ALLOC_INC 16
5970 char_u **expl_files;
5971 size_t files_alloced, files_free;
5972 char_u *buf;
5973 int has_wildcard;
5974
5975 *num_file = 0; /* default: no files found */
5976 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5977 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5978 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5979 if (*file == NULL)
5980 return FAIL;
5981
5982 for (; num_pat > 0; num_pat--, pat++)
5983 {
5984 expl_files = NULL;
5985 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5986 /* expand environment var or home dir */
5987 buf = expand_env_save(*pat);
5988 else
5989 buf = vim_strsave(*pat);
5990 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005991 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 if (has_wildcard) /* yes, so expand them */
5993 expl_files = (char_u **)_fnexplode(buf);
5994
5995 /*
5996 * return value of buf if no wildcards left,
5997 * OR if no match AND EW_NOTFOUND is set.
5998 */
5999 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
6000 || (expl_files == NULL && (flags & EW_NOTFOUND)))
6001 { /* simply save the current contents of *buf */
6002 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
6003 if (expl_files != NULL)
6004 {
6005 expl_files[0] = vim_strsave(buf);
6006 expl_files[1] = NULL;
6007 }
6008 }
6009 vim_free(buf);
6010
6011 /*
6012 * Count number of names resulting from expansion,
6013 * At the same time add a backslash to the end of names that happen to
6014 * be directories, and replace slashes with backslashes.
6015 */
6016 if (expl_files)
6017 {
6018 for (i = 0; (p = expl_files[i]) != NULL; i++)
6019 {
6020 dir = mch_isdir(p);
6021 /* If we don't want dirs and this is one, skip it */
6022 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6023 continue;
6024
Bram Moolenaara2031822006-03-07 22:29:51 +00006025 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006026 if (!dir && (flags & EW_EXEC)
6027 && !mch_can_exe(p, NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006028 continue;
6029
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030 if (--files_free == 0)
6031 {
6032 /* need more room in table of pointers */
6033 files_alloced += EXPL_ALLOC_INC;
6034 *file = (char_u **)vim_realloc(*file,
6035 sizeof(char_u **) * files_alloced);
6036 if (*file == NULL)
6037 {
6038 EMSG(_(e_outofmem));
6039 *num_file = 0;
6040 return FAIL;
6041 }
6042 files_free = EXPL_ALLOC_INC;
6043 }
6044 slash_adjust(p);
6045 if (dir)
6046 {
6047 /* For a directory we add a '/', unless it's already
6048 * there. */
6049 len = STRLEN(p);
6050 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
6051 {
6052 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00006053 if (!after_pathsep((*file)[*num_file],
6054 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006055 {
6056 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006057 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 }
6059 }
6060 }
6061 else
6062 {
6063 (*file)[*num_file] = vim_strsave(p);
6064 }
6065
6066 /*
6067 * Error message already given by either alloc or vim_strsave.
6068 * Should return FAIL, but returning OK works also.
6069 */
6070 if ((*file)[*num_file] == NULL)
6071 break;
6072 (*num_file)++;
6073 }
6074 _fnexplodefree((char **)expl_files);
6075 }
6076 }
6077 return OK;
6078
6079#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006080 /*
6081 * This is the non-OS/2 implementation (really Unix).
6082 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 int j;
6084 char_u *tempname;
6085 char_u *command;
6086 FILE *fd;
6087 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006088#define STYLE_ECHO 0 /* use "echo", the default */
6089#define STYLE_GLOB 1 /* use "glob", for csh */
6090#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6091#define STYLE_PRINT 3 /* use "print -N", for zsh */
6092#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6093 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 int shell_style = STYLE_ECHO;
6095 int check_spaces;
6096 static int did_find_nul = FALSE;
6097 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006098 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006099 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100
6101 *num_file = 0; /* default: no files found */
6102 *file = NULL;
6103
6104 /*
6105 * If there are no wildcards, just copy the names to allocated memory.
6106 * Saves a lot of time, because we don't have to start a new shell.
6107 */
6108 if (!have_wildcard(num_pat, pat))
6109 return save_patterns(num_pat, pat, num_file, file);
6110
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006111# ifdef HAVE_SANDBOX
6112 /* Don't allow any shell command in the sandbox. */
6113 if (sandbox != 0 && check_secure())
6114 return FAIL;
6115# endif
6116
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 /*
6118 * Don't allow the use of backticks in secure and restricted mode.
6119 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006120 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 for (i = 0; i < num_pat; ++i)
6122 if (vim_strchr(pat[i], '`') != NULL
6123 && (check_restricted() || check_secure()))
6124 return FAIL;
6125
6126 /*
6127 * get a name for the temp file
6128 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006129 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 {
6131 EMSG(_(e_notmp));
6132 return FAIL;
6133 }
6134
6135 /*
6136 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006137 * file.
6138 * STYLE_BT: NL separated
6139 * If expanding `cmd` execute it directly.
6140 * STYLE_GLOB: NUL separated
6141 * If we use *csh, "glob" will work better than "echo".
6142 * STYLE_PRINT: NL or NUL separated
6143 * If we use *zsh, "print -N" will work better than "glob".
6144 * STYLE_VIMGLOB: NL separated
6145 * If we use *sh*, we define "vimglob()".
6146 * STYLE_ECHO: space separated.
6147 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 */
6149 if (num_pat == 1 && *pat[0] == '`'
6150 && (len = STRLEN(pat[0])) > 2
6151 && *(pat[0] + len - 1) == '`')
6152 shell_style = STYLE_BT;
6153 else if ((len = STRLEN(p_sh)) >= 3)
6154 {
6155 if (STRCMP(p_sh + len - 3, "csh") == 0)
6156 shell_style = STYLE_GLOB;
6157 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6158 shell_style = STYLE_PRINT;
6159 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006160 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6161 "sh") != NULL)
6162 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163
Bram Moolenaarc7247912008-01-13 12:54:11 +00006164 /* Compute the length of the command. We need 2 extra bytes: for the
6165 * optional '&' and for the NUL.
6166 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006168 if (shell_style == STYLE_VIMGLOB)
6169 len += STRLEN(sh_vimglob_func);
6170
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006171 for (i = 0; i < num_pat; ++i)
6172 {
6173 /* Count the length of the patterns in the same way as they are put in
6174 * "command" below. */
6175#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006177#else
6178 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006179 for (j = 0; pat[i][j] != NUL; ++j)
6180 {
6181 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6182 ++len; /* may add a backslash */
6183 ++len;
6184 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006185#endif
6186 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 command = alloc(len);
6188 if (command == NULL)
6189 {
6190 /* out of memory */
6191 vim_free(tempname);
6192 return FAIL;
6193 }
6194
6195 /*
6196 * Build the shell command:
6197 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6198 * recognizes this).
6199 * - Add the shell command to print the expanded names.
6200 * - Add the temp file name.
6201 * - Add the file name patterns.
6202 */
6203 if (shell_style == STYLE_BT)
6204 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006205 /* change `command; command& ` to (command; command ) */
6206 STRCPY(command, "(");
6207 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006209 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 while (p > command && vim_iswhite(*p))
6211 --p;
6212 if (*p == '&') /* remove trailing '&' */
6213 {
6214 ampersent = TRUE;
6215 *p = ' ';
6216 }
6217 STRCAT(command, ">");
6218 }
6219 else
6220 {
6221 if (flags & EW_NOTFOUND)
6222 STRCPY(command, "set nonomatch; ");
6223 else
6224 STRCPY(command, "unset nonomatch; ");
6225 if (shell_style == STYLE_GLOB)
6226 STRCAT(command, "glob >");
6227 else if (shell_style == STYLE_PRINT)
6228 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006229 else if (shell_style == STYLE_VIMGLOB)
6230 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 else
6232 STRCAT(command, "echo >");
6233 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006234
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006236
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 if (shell_style != STYLE_BT)
6238 for (i = 0; i < num_pat; ++i)
6239 {
6240 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006241 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006242 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243#ifdef USE_SYSTEM
6244 STRCAT(command, " \"");
6245 STRCAT(command, pat[i]);
6246 STRCAT(command, "\"");
6247#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006248 int intick = FALSE;
6249
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 p = command + STRLEN(command);
6251 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006252 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006253 {
6254 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006255 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006256 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6257 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006258 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006259 * backslash inside backticks, before a special character
6260 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006261 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006262 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6263 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006264 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006265 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006266 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006267 else if (!intick
6268 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6269 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006270 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006271 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6272 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006273 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006274
6275 /* Copy one character. */
6276 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006277 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 *p = NUL;
6279#endif
6280 }
6281 if (flags & EW_SILENT)
6282 show_shell_mess = FALSE;
6283 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006284 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285
6286 /*
6287 * Using zsh -G: If a pattern has no matches, it is just deleted from
6288 * the argument list, otherwise zsh gives an error message and doesn't
6289 * expand any other pattern.
6290 */
6291 if (shell_style == STYLE_PRINT)
6292 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6293
6294 /*
6295 * If we use -f then shell variables set in .cshrc won't get expanded.
6296 * vi can do it, so we will too, but it is only necessary if there is a "$"
6297 * in one of the patterns, otherwise we can still use the fast option.
6298 */
6299 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6300 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6301
6302 /*
6303 * execute the shell command
6304 */
6305 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6306
6307 /* When running in the background, give it some time to create the temp
6308 * file, but don't wait for it to finish. */
6309 if (ampersent)
6310 mch_delay(10L, TRUE);
6311
6312 extra_shell_arg = NULL; /* cleanup */
6313 show_shell_mess = TRUE;
6314 vim_free(command);
6315
Bram Moolenaarc7247912008-01-13 12:54:11 +00006316 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 {
6318 mch_remove(tempname);
6319 vim_free(tempname);
6320 /*
6321 * With interactive completion, the error message is not printed.
6322 * However with USE_SYSTEM, I don't know how to turn off error messages
6323 * from the shell, so screen may still get messed up -- webb.
6324 */
6325#ifndef USE_SYSTEM
6326 if (!(flags & EW_SILENT))
6327#endif
6328 {
6329 redraw_later_clear(); /* probably messed up screen */
6330 msg_putchar('\n'); /* clear bottom line quickly */
6331 cmdline_row = Rows - 1; /* continue on last line */
6332#ifdef USE_SYSTEM
6333 if (!(flags & EW_SILENT))
6334#endif
6335 {
6336 MSG(_(e_wildexpand));
6337 msg_start(); /* don't overwrite this message */
6338 }
6339 }
6340 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6341 * EW_NOTFOUND is given */
6342 if (shell_style == STYLE_BT)
6343 return FAIL;
6344 goto notfound;
6345 }
6346
6347 /*
6348 * read the names from the file into memory
6349 */
6350 fd = fopen((char *)tempname, READBIN);
6351 if (fd == NULL)
6352 {
6353 /* Something went wrong, perhaps a file name with a special char. */
6354 if (!(flags & EW_SILENT))
6355 {
6356 MSG(_(e_wildexpand));
6357 msg_start(); /* don't overwrite this message */
6358 }
6359 vim_free(tempname);
6360 goto notfound;
6361 }
6362 fseek(fd, 0L, SEEK_END);
6363 len = ftell(fd); /* get size of temp file */
6364 fseek(fd, 0L, SEEK_SET);
6365 buffer = alloc(len + 1);
6366 if (buffer == NULL)
6367 {
6368 /* out of memory */
6369 mch_remove(tempname);
6370 vim_free(tempname);
6371 fclose(fd);
6372 return FAIL;
6373 }
6374 i = fread((char *)buffer, 1, len, fd);
6375 fclose(fd);
6376 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006377 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 {
6379 /* unexpected read error */
6380 EMSG2(_(e_notread), tempname);
6381 vim_free(tempname);
6382 vim_free(buffer);
6383 return FAIL;
6384 }
6385 vim_free(tempname);
6386
Bram Moolenaarc7247912008-01-13 12:54:11 +00006387# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6389 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006390 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6392 *p++ = buffer[i];
6393 len = p - buffer;
6394# endif
6395
6396
6397 /* file names are separated with Space */
6398 if (shell_style == STYLE_ECHO)
6399 {
6400 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6401 p = buffer;
6402 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6403 {
6404 while (*p != ' ' && *p != '\n')
6405 ++p;
6406 p = skipwhite(p); /* skip to next entry */
6407 }
6408 }
6409 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006410 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 {
6412 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6413 p = buffer;
6414 for (i = 0; *p != NUL; ++i) /* count number of entries */
6415 {
6416 while (*p != '\n' && *p != NUL)
6417 ++p;
6418 if (*p != NUL)
6419 ++p;
6420 p = skipwhite(p); /* skip leading white space */
6421 }
6422 }
6423 /* file names are separated with NUL */
6424 else
6425 {
6426 /*
6427 * Some versions of zsh use spaces instead of NULs to separate
6428 * results. Only do this when there is no NUL before the end of the
6429 * buffer, otherwise we would never be able to use file names with
6430 * embedded spaces when zsh does use NULs.
6431 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6432 * don't check for spaces again.
6433 */
6434 check_spaces = FALSE;
6435 if (shell_style == STYLE_PRINT && !did_find_nul)
6436 {
6437 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006438 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006439 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 did_find_nul = TRUE;
6441 else
6442 check_spaces = TRUE;
6443 }
6444
6445 /*
6446 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6447 * already is one, for STYLE_GLOB it needs to be added.
6448 */
6449 if (len && buffer[len - 1] == NUL)
6450 --len;
6451 else
6452 buffer[len] = NUL;
6453 i = 0;
6454 for (p = buffer; p < buffer + len; ++p)
6455 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6456 {
6457 ++i;
6458 *p = NUL;
6459 }
6460 if (len)
6461 ++i; /* count last entry */
6462 }
6463 if (i == 0)
6464 {
6465 /*
6466 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6467 * /bin/sh will happily expand it to nothing rather than returning an
6468 * error; and hey, it's good to check anyway -- webb.
6469 */
6470 vim_free(buffer);
6471 goto notfound;
6472 }
6473 *num_file = i;
6474 *file = (char_u **)alloc(sizeof(char_u *) * i);
6475 if (*file == NULL)
6476 {
6477 /* out of memory */
6478 vim_free(buffer);
6479 return FAIL;
6480 }
6481
6482 /*
6483 * Isolate the individual file names.
6484 */
6485 p = buffer;
6486 for (i = 0; i < *num_file; ++i)
6487 {
6488 (*file)[i] = p;
6489 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006490 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6491 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006493 while (!(shell_style == STYLE_ECHO && *p == ' ')
6494 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 ++p;
6496 if (p == buffer + len) /* last entry */
6497 *p = NUL;
6498 else
6499 {
6500 *p++ = NUL;
6501 p = skipwhite(p); /* skip to next entry */
6502 }
6503 }
6504 else /* NUL separates */
6505 {
6506 while (*p && p < buffer + len) /* skip entry */
6507 ++p;
6508 ++p; /* skip NUL */
6509 }
6510 }
6511
6512 /*
6513 * Move the file names to allocated memory.
6514 */
6515 for (j = 0, i = 0; i < *num_file; ++i)
6516 {
6517 /* Require the files to exist. Helps when using /bin/sh */
6518 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6519 continue;
6520
6521 /* check if this entry should be included */
6522 dir = (mch_isdir((*file)[i]));
6523 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6524 continue;
6525
Bram Moolenaara2031822006-03-07 22:29:51 +00006526 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006527 if (!dir && (flags & EW_EXEC)
6528 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006529 continue;
6530
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6532 if (p)
6533 {
6534 STRCPY(p, (*file)[i]);
6535 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006536 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 (*file)[j++] = p;
6538 }
6539 }
6540 vim_free(buffer);
6541 *num_file = j;
6542
6543 if (*num_file == 0) /* rejected all entries */
6544 {
6545 vim_free(*file);
6546 *file = NULL;
6547 goto notfound;
6548 }
6549
6550 return OK;
6551
6552notfound:
6553 if (flags & EW_NOTFOUND)
6554 return save_patterns(num_pat, pat, num_file, file);
6555 return FAIL;
6556
6557#endif /* __EMX__ */
6558}
6559
6560#endif /* VMS */
6561
6562#ifndef __EMX__
6563 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006564save_patterns(
6565 int num_pat,
6566 char_u **pat,
6567 int *num_file,
6568 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569{
6570 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006571 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572
6573 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6574 if (*file == NULL)
6575 return FAIL;
6576 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006577 {
6578 s = vim_strsave(pat[i]);
6579 if (s != NULL)
6580 /* Be compatible with expand_filename(): halve the number of
6581 * backslashes. */
6582 backslash_halve(s);
6583 (*file)[i] = s;
6584 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 *num_file = num_pat;
6586 return OK;
6587}
6588#endif
6589
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590/*
6591 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6592 * expand.
6593 */
6594 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006595mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006597 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 if (*p == '\\' && p[1] != NUL)
6600 ++p;
6601 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 if (vim_strchr((char_u *)
6603#ifdef VMS
6604 "*?%"
6605#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607#endif
6608 , *p) != NULL)
6609 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 }
6611 return FALSE;
6612}
6613
6614/*
6615 * Return TRUE if the string "p" contains a wildcard.
6616 * Don't recognize '~' at the end as a wildcard.
6617 */
6618 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006619mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006621 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 if (*p == '\\' && p[1] != NUL)
6624 ++p;
6625 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (vim_strchr((char_u *)
6627#ifdef VMS
6628 "*?%$"
6629#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631#endif
6632 , *p) != NULL
6633 || (*p == '~' && p[1] != NUL))
6634 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006635 }
6636 return FALSE;
6637}
6638
6639#ifndef __EMX__
6640 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006641have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642{
6643 int i;
6644
6645 for (i = 0; i < num; i++)
6646 if (mch_has_wildcard(file[i]))
6647 return 1;
6648 return 0;
6649}
6650
6651 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006652have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653{
6654 int i;
6655
6656 for (i = 0; i < num; i++)
6657 if (vim_strchr(file[i], '$') != NULL)
6658 return TRUE;
6659 return FALSE;
6660}
6661#endif /* ifndef __EMX__ */
6662
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006663#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664/*
6665 * Scaled-down version of rename(), which is missing in Xenix.
6666 * This version can only move regular files and will fail if the
6667 * destination exists.
6668 */
6669 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01006670mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671{
6672 struct stat st;
6673
6674 if (stat(dest, &st) >= 0) /* fail if destination exists */
6675 return -1;
6676 if (link(src, dest) != 0) /* link file to new name */
6677 return -1;
6678 if (mch_remove(src) == 0) /* delete link to old name */
6679 return 0;
6680 return -1;
6681}
6682#endif /* !HAVE_RENAME */
6683
6684#ifdef FEAT_MOUSE_GPM
6685/*
6686 * Initializes connection with gpm (if it isn't already opened)
6687 * Return 1 if succeeded (or connection already opened), 0 if failed
6688 */
6689 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006690gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691{
6692 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6693
6694 if (!gpm_flag)
6695 {
6696 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6697 gpm_connect.defaultMask = ~GPM_HARD;
6698 /* Default handling for mouse move*/
6699 gpm_connect.minMod = 0; /* Handle any modifier keys */
6700 gpm_connect.maxMod = 0xffff;
6701 if (Gpm_Open(&gpm_connect, 0) > 0)
6702 {
6703 /* gpm library tries to handling TSTP causes
6704 * problems. Anyways, we close connection to Gpm whenever
6705 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006706 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006708# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 return 1; /* succeed */
6712 }
6713 if (gpm_fd == -2)
6714 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6715 return 0;
6716 }
6717 return 1; /* already open */
6718}
6719
6720/*
6721 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 */
6723 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006724gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725{
6726 if (gpm_flag && gpm_fd >= 0) /* if Open */
6727 Gpm_Close();
6728}
6729
6730/* Reads gpm event and adds special keys to input buf. Returns length of
6731 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006732 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 */
6734 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006735mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736{
6737 int button;
6738 static Gpm_Event gpm_event;
6739 char_u string[6];
6740 int_u vim_modifiers;
6741 int row,col;
6742 unsigned char buttons_mask;
6743 unsigned char gpm_modifiers;
6744 static unsigned char old_buttons = 0;
6745
6746 Gpm_GetEvent(&gpm_event);
6747
6748#ifdef FEAT_GUI
6749 /* Don't put events in the input queue now. */
6750 if (hold_gui_events)
6751 return 0;
6752#endif
6753
6754 row = gpm_event.y - 1;
6755 col = gpm_event.x - 1;
6756
6757 string[0] = ESC; /* Our termcode */
6758 string[1] = 'M';
6759 string[2] = 'G';
6760 switch (GPM_BARE_EVENTS(gpm_event.type))
6761 {
6762 case GPM_DRAG:
6763 string[3] = MOUSE_DRAG;
6764 break;
6765 case GPM_DOWN:
6766 buttons_mask = gpm_event.buttons & ~old_buttons;
6767 old_buttons = gpm_event.buttons;
6768 switch (buttons_mask)
6769 {
6770 case GPM_B_LEFT:
6771 button = MOUSE_LEFT;
6772 break;
6773 case GPM_B_MIDDLE:
6774 button = MOUSE_MIDDLE;
6775 break;
6776 case GPM_B_RIGHT:
6777 button = MOUSE_RIGHT;
6778 break;
6779 default:
6780 return 0;
6781 /*Don't know what to do. Can more than one button be
6782 * reported in one event? */
6783 }
6784 string[3] = (char_u)(button | 0x20);
6785 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6786 break;
6787 case GPM_UP:
6788 string[3] = MOUSE_RELEASE;
6789 old_buttons &= ~gpm_event.buttons;
6790 break;
6791 default:
6792 return 0;
6793 }
6794 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6795 gpm_modifiers = gpm_event.modifiers;
6796 vim_modifiers = 0x0;
6797 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6798 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6799 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6800 */
6801 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6802 vim_modifiers |= MOUSE_SHIFT;
6803
6804 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6805 vim_modifiers |= MOUSE_CTRL;
6806 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6807 vim_modifiers |= MOUSE_ALT;
6808 string[3] |= vim_modifiers;
6809 string[4] = (char_u)(col + ' ' + 1);
6810 string[5] = (char_u)(row + ' ' + 1);
6811 add_to_input_buf(string, 6);
6812 return 6;
6813}
6814#endif /* FEAT_MOUSE_GPM */
6815
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006816#ifdef FEAT_SYSMOUSE
6817/*
6818 * Initialize connection with sysmouse.
6819 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6820 * output, any sysmouse output than will be processed via sig_sysmouse().
6821 * Return OK if succeeded, FAIL if failed.
6822 */
6823 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006824sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006825{
6826 struct mouse_info mouse;
6827
6828 mouse.operation = MOUSE_MODE;
6829 mouse.u.mode.mode = 0;
6830 mouse.u.mode.signal = SIGUSR2;
6831 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6832 {
6833 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6834 mouse.operation = MOUSE_SHOW;
6835 ioctl(1, CONS_MOUSECTL, &mouse);
6836 return OK;
6837 }
6838 return FAIL;
6839}
6840
6841/*
6842 * Stop processing SIGUSR2 signals, and also make sure that
6843 * virtual console do not send us any sysmouse related signal.
6844 */
6845 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006846sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006847{
6848 struct mouse_info mouse;
6849
6850 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6851 mouse.operation = MOUSE_MODE;
6852 mouse.u.mode.mode = 0;
6853 mouse.u.mode.signal = 0;
6854 ioctl(1, CONS_MOUSECTL, &mouse);
6855}
6856
6857/*
6858 * Gets info from sysmouse and adds special keys to input buf.
6859 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006860 static RETSIGTYPE
6861sig_sysmouse SIGDEFARG(sigarg)
6862{
6863 struct mouse_info mouse;
6864 struct video_info video;
6865 char_u string[6];
6866 int row, col;
6867 int button;
6868 int buttons;
6869 static int oldbuttons = 0;
6870
6871#ifdef FEAT_GUI
6872 /* Don't put events in the input queue now. */
6873 if (hold_gui_events)
6874 return;
6875#endif
6876
6877 mouse.operation = MOUSE_GETINFO;
6878 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6879 && ioctl(1, FBIO_MODEINFO, &video) != -1
6880 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6881 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6882 {
6883 row = mouse.u.data.y / video.vi_cheight;
6884 col = mouse.u.data.x / video.vi_cwidth;
6885 buttons = mouse.u.data.buttons;
6886 string[0] = ESC; /* Our termcode */
6887 string[1] = 'M';
6888 string[2] = 'S';
6889 if (oldbuttons == buttons && buttons != 0)
6890 {
6891 button = MOUSE_DRAG;
6892 }
6893 else
6894 {
6895 switch (buttons)
6896 {
6897 case 0:
6898 button = MOUSE_RELEASE;
6899 break;
6900 case 1:
6901 button = MOUSE_LEFT;
6902 break;
6903 case 2:
6904 button = MOUSE_MIDDLE;
6905 break;
6906 case 4:
6907 button = MOUSE_RIGHT;
6908 break;
6909 default:
6910 return;
6911 }
6912 oldbuttons = buttons;
6913 }
6914 string[3] = (char_u)(button);
6915 string[4] = (char_u)(col + ' ' + 1);
6916 string[5] = (char_u)(row + ' ' + 1);
6917 add_to_input_buf(string, 6);
6918 }
6919 return;
6920}
6921#endif /* FEAT_SYSMOUSE */
6922
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006924typedef char_u * (*STRPROCSTR)(char_u *);
6925typedef char_u * (*INTPROCSTR)(int);
6926typedef int (*STRPROCINT)(char_u *);
6927typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928
6929/*
6930 * Call a DLL routine which takes either a string or int param
6931 * and returns an allocated string.
6932 */
6933 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006934mch_libcall(
6935 char_u *libname,
6936 char_u *funcname,
6937 char_u *argstring, /* NULL when using a argint */
6938 int argint,
6939 char_u **string_result,/* NULL when using number_result */
6940 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941{
6942# if defined(USE_DLOPEN)
6943 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006944 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945# else
6946 shl_t hinstLib;
6947# endif
6948 STRPROCSTR ProcAdd;
6949 INTPROCSTR ProcAddI;
6950 char_u *retval_str = NULL;
6951 int retval_int = 0;
6952 int success = FALSE;
6953
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006954 /*
6955 * Get a handle to the DLL module.
6956 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006958 /* First clear any error, it's not cleared by the dlopen() call. */
6959 (void)dlerror();
6960
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 hinstLib = dlopen((char *)libname, RTLD_LAZY
6962# ifdef RTLD_LOCAL
6963 | RTLD_LOCAL
6964# endif
6965 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006966 if (hinstLib == NULL)
6967 {
6968 /* "dlerr" must be used before dlclose() */
6969 dlerr = (char *)dlerror();
6970 if (dlerr != NULL)
6971 EMSG2(_("dlerror = \"%s\""), dlerr);
6972 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973# else
6974 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6975# endif
6976
6977 /* If the handle is valid, try to get the function address. */
6978 if (hinstLib != NULL)
6979 {
6980# ifdef HAVE_SETJMP_H
6981 /*
6982 * Catch a crash when calling the library function. For example when
6983 * using a number where a string pointer is expected.
6984 */
6985 mch_startjmp();
6986 if (SETJMP(lc_jump_env) != 0)
6987 {
6988 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006989# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006990 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006991# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 mch_didjmp();
6993 }
6994 else
6995# endif
6996 {
6997 retval_str = NULL;
6998 retval_int = 0;
6999
7000 if (argstring != NULL)
7001 {
7002# if defined(USE_DLOPEN)
7003 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007004 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005# else
7006 if (shl_findsym(&hinstLib, (const char *)funcname,
7007 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
7008 ProcAdd = NULL;
7009# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007010 if ((success = (ProcAdd != NULL
7011# if defined(USE_DLOPEN)
7012 && dlerr == NULL
7013# endif
7014 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 {
7016 if (string_result == NULL)
7017 retval_int = ((STRPROCINT)ProcAdd)(argstring);
7018 else
7019 retval_str = (ProcAdd)(argstring);
7020 }
7021 }
7022 else
7023 {
7024# if defined(USE_DLOPEN)
7025 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007026 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027# else
7028 if (shl_findsym(&hinstLib, (const char *)funcname,
7029 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
7030 ProcAddI = NULL;
7031# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007032 if ((success = (ProcAddI != NULL
7033# if defined(USE_DLOPEN)
7034 && dlerr == NULL
7035# endif
7036 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 {
7038 if (string_result == NULL)
7039 retval_int = ((INTPROCINT)ProcAddI)(argint);
7040 else
7041 retval_str = (ProcAddI)(argint);
7042 }
7043 }
7044
7045 /* Save the string before we free the library. */
7046 /* Assume that a "1" or "-1" result is an illegal pointer. */
7047 if (string_result == NULL)
7048 *number_result = retval_int;
7049 else if (retval_str != NULL
7050 && retval_str != (char_u *)1
7051 && retval_str != (char_u *)-1)
7052 *string_result = vim_strsave(retval_str);
7053 }
7054
7055# ifdef HAVE_SETJMP_H
7056 mch_endjmp();
7057# ifdef SIGHASARG
7058 if (lc_signal != 0)
7059 {
7060 int i;
7061
7062 /* try to find the name of this signal */
7063 for (i = 0; signal_info[i].sig != -1; i++)
7064 if (lc_signal == signal_info[i].sig)
7065 break;
7066 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
7067 }
7068# endif
7069# endif
7070
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007072 /* "dlerr" must be used before dlclose() */
7073 if (dlerr != NULL)
7074 EMSG2(_("dlerror = \"%s\""), dlerr);
7075
7076 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 (void)dlclose(hinstLib);
7078# else
7079 (void)shl_unload(hinstLib);
7080# endif
7081 }
7082
7083 if (!success)
7084 {
7085 EMSG2(_(e_libcall), funcname);
7086 return FAIL;
7087 }
7088
7089 return OK;
7090}
7091#endif
7092
7093#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7094static int xterm_trace = -1; /* default: disabled */
7095static int xterm_button;
7096
7097/*
7098 * Setup a dummy window for X selections in a terminal.
7099 */
7100 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007101setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102{
7103 int z = 0;
7104 char *strp = "";
7105 Widget AppShell;
7106
7107 if (!x_connect_to_server())
7108 return;
7109
7110 open_app_context();
7111 if (app_context != NULL && xterm_Shell == (Widget)0)
7112 {
7113 int (*oldhandler)();
7114#if defined(HAVE_SETJMP_H)
7115 int (*oldIOhandler)();
7116#endif
7117# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7118 struct timeval start_tv;
7119
7120 if (p_verbose > 0)
7121 gettimeofday(&start_tv, NULL);
7122# endif
7123
7124 /* Ignore X errors while opening the display */
7125 oldhandler = XSetErrorHandler(x_error_check);
7126
7127#if defined(HAVE_SETJMP_H)
7128 /* Ignore X IO errors while opening the display */
7129 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7130 mch_startjmp();
7131 if (SETJMP(lc_jump_env) != 0)
7132 {
7133 mch_didjmp();
7134 xterm_dpy = NULL;
7135 }
7136 else
7137#endif
7138 {
7139 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7140 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7141#if defined(HAVE_SETJMP_H)
7142 mch_endjmp();
7143#endif
7144 }
7145
7146#if defined(HAVE_SETJMP_H)
7147 /* Now handle X IO errors normally. */
7148 (void)XSetIOErrorHandler(oldIOhandler);
7149#endif
7150 /* Now handle X errors normally. */
7151 (void)XSetErrorHandler(oldhandler);
7152
7153 if (xterm_dpy == NULL)
7154 {
7155 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007156 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 return;
7158 }
7159
7160 /* Catch terminating error of the X server connection. */
7161 (void)XSetIOErrorHandler(x_IOerror_handler);
7162
7163# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
7164 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007165 {
7166 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007168 verbose_leave();
7169 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170# endif
7171
7172 /* Create a Shell to make converters work. */
7173 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7174 applicationShellWidgetClass, xterm_dpy,
7175 NULL);
7176 if (AppShell == (Widget)0)
7177 return;
7178 xterm_Shell = XtVaCreatePopupShell("VIM",
7179 topLevelShellWidgetClass, AppShell,
7180 XtNmappedWhenManaged, 0,
7181 XtNwidth, 1,
7182 XtNheight, 1,
7183 NULL);
7184 if (xterm_Shell == (Widget)0)
7185 return;
7186
7187 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007188 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189 if (x11_display == NULL)
7190 x11_display = xterm_dpy;
7191
7192 XtRealizeWidget(xterm_Shell);
7193 XSync(xterm_dpy, False);
7194 xterm_update();
7195 }
7196 if (xterm_Shell != (Widget)0)
7197 {
7198 clip_init(TRUE);
7199 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7200 x11_window = (Window)atol(strp);
7201 /* Check if $WINDOWID is valid. */
7202 if (test_x11_window(xterm_dpy) == FAIL)
7203 x11_window = 0;
7204 if (x11_window != 0)
7205 xterm_trace = 0;
7206 }
7207}
7208
7209 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007210start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211{
7212 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7213 return;
7214 xterm_trace = 1;
7215 xterm_button = button;
7216 do_xterm_trace();
7217}
7218
7219
7220 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007221stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222{
7223 if (xterm_trace < 0)
7224 return;
7225 xterm_trace = 0;
7226}
7227
7228/*
7229 * Query the xterm pointer and generate mouse termcodes if necessary
7230 * return TRUE if dragging is active, else FALSE
7231 */
7232 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007233do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234{
7235 Window root, child;
7236 int root_x, root_y;
7237 int win_x, win_y;
7238 int row, col;
7239 int_u mask_return;
7240 char_u buf[50];
7241 char_u *strp;
7242 long got_hints;
7243 static char_u *mouse_code;
7244 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7245 static int prev_row = 0, prev_col = 0;
7246 static XSizeHints xterm_hints;
7247
7248 if (xterm_trace <= 0)
7249 return FALSE;
7250
7251 if (xterm_trace == 1)
7252 {
7253 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007254 * have changed recently. */
7255 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7256 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 || xterm_hints.width_inc <= 1
7258 || xterm_hints.height_inc <= 1)
7259 {
7260 xterm_trace = -1; /* Not enough data -- disable tracing */
7261 return FALSE;
7262 }
7263
7264 /* Rely on the same mouse code for the duration of this */
7265 mouse_code = find_termcode(mouse_name);
7266 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007267 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 xterm_trace = 2;
7269
7270 /* Find the offset of the chars, there might be a scrollbar on the
7271 * left of the window and/or a menu on the top (eterm etc.) */
7272 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7273 &win_x, &win_y, &mask_return);
7274 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7275 - (xterm_hints.height_inc / 2);
7276 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7277 xterm_hints.y = 2;
7278 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7279 - (xterm_hints.width_inc / 2);
7280 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7281 xterm_hints.x = 2;
7282 return TRUE;
7283 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007284 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 {
7286 xterm_trace = 0;
7287 return FALSE;
7288 }
7289
7290 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7291 &win_x, &win_y, &mask_return);
7292
7293 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7294 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7295 if (row == prev_row && col == prev_col)
7296 return TRUE;
7297
7298 STRCPY(buf, mouse_code);
7299 strp = buf + STRLEN(buf);
7300 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7301 *strp++ = (char_u)(col + ' ' + 1);
7302 *strp++ = (char_u)(row + ' ' + 1);
7303 *strp = 0;
7304 add_to_input_buf(buf, STRLEN(buf));
7305
7306 prev_row = row;
7307 prev_col = col;
7308 return TRUE;
7309}
7310
7311# if defined(FEAT_GUI) || defined(PROTO)
7312/*
7313 * Destroy the display, window and app_context. Required for GTK.
7314 */
7315 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007316clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317{
7318 if (xterm_Shell != (Widget)0)
7319 {
7320 XtDestroyWidget(xterm_Shell);
7321 xterm_Shell = (Widget)0;
7322 }
7323 if (xterm_dpy != NULL)
7324 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007325# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 /* Lesstif and Solaris crash here, lose some memory */
7327 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 if (x11_display == xterm_dpy)
7330 x11_display = NULL;
7331 xterm_dpy = NULL;
7332 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007333# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 if (app_context != (XtAppContext)NULL)
7335 {
7336 /* Lesstif and Solaris crash here, lose some memory */
7337 XtDestroyApplicationContext(app_context);
7338 app_context = (XtAppContext)NULL;
7339 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007340# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341}
7342# endif
7343
7344/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007345 * Catch up with GUI or X events.
7346 */
7347 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007348clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007349{
7350# ifdef FEAT_GUI
7351 if (gui.in_use)
7352 gui_mch_update();
7353 else
7354# endif
7355 if (xterm_Shell != (Widget)0)
7356 xterm_update();
7357}
7358
7359/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360 * Catch up with any queued X events. This may put keyboard input into the
7361 * input buffer, call resize call-backs, trigger timers etc. If there is
7362 * nothing in the X event queue (& no timers pending), then we return
7363 * immediately.
7364 */
7365 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007366xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367{
7368 XEvent event;
7369
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007370 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007372 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007374 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007375 break;
7376
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007377 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007378 {
7379 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007380 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007381#ifdef FEAT_CLIENTSERVER
7382 {
7383 XPropertyEvent *e = (XPropertyEvent *)&event;
7384
7385 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007387 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007388 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007390 XtDispatchEvent(&event);
7391 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007392 else
7393 {
7394 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007395 XtAppProcessEvent(app_context, mask);
7396 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 }
7398}
7399
7400 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007401clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402{
7403 if (xterm_Shell != (Widget)0)
7404 return clip_x11_own_selection(xterm_Shell, cbd);
7405 return FAIL;
7406}
7407
7408 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007409clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410{
7411 if (xterm_Shell != (Widget)0)
7412 clip_x11_lose_selection(xterm_Shell, cbd);
7413}
7414
7415 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007416clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417{
7418 if (xterm_Shell != (Widget)0)
7419 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7420}
7421
7422 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007423clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
7425 clip_x11_set_selection(cbd);
7426}
7427#endif
7428
7429
7430#if defined(USE_XSMP) || defined(PROTO)
7431/*
7432 * Code for X Session Management Protocol.
7433 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007434static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7435static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7436static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7437static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7438static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439
7440
7441# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007442static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443
7444/*
7445 * This is our chance to ask the user if they want to save,
7446 * or abort the logout
7447 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007449xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450{
7451 cmdmod_T save_cmdmod;
7452 int cancel_shutdown = False;
7453
7454 save_cmdmod = cmdmod;
7455 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007456 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 /* Mustn't logout */
7458 cancel_shutdown = True;
7459 cmdmod = save_cmdmod;
7460 setcursor(); /* position cursor */
7461 out_flush();
7462
7463 /* Done interaction */
7464 SmcInteractDone(smc_conn, cancel_shutdown);
7465
7466 /* Finish off
7467 * Only end save-yourself here if we're not cancelling shutdown;
7468 * we'll get a cancelled callback later in which we'll end it.
7469 * Hopefully get around glitchy SMs (like GNOME-1)
7470 */
7471 if (!cancel_shutdown)
7472 {
7473 xsmp.save_yourself = False;
7474 SmcSaveYourselfDone(smc_conn, True);
7475 }
7476}
7477# endif
7478
7479/*
7480 * Callback that starts save-yourself.
7481 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007483xsmp_handle_save_yourself(
7484 SmcConn smc_conn,
7485 SmPointer client_data UNUSED,
7486 int save_type UNUSED,
7487 Bool shutdown,
7488 int interact_style UNUSED,
7489 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490{
7491 /* Handle already being in saveyourself */
7492 if (xsmp.save_yourself)
7493 SmcSaveYourselfDone(smc_conn, True);
7494 xsmp.save_yourself = True;
7495 xsmp.shutdown = shutdown;
7496
7497 /* First up, preserve all files */
7498 out_flush();
7499 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7500
7501 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007502 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503
7504# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7505 /* Now see if we can ask about unsaved files */
7506 if (shutdown && !fast && gui.in_use)
7507 /* Need to interact with user, but need SM's permission */
7508 SmcInteractRequest(smc_conn, SmDialogError,
7509 xsmp_handle_interaction, client_data);
7510 else
7511# endif
7512 {
7513 /* Can stop the cycle here */
7514 SmcSaveYourselfDone(smc_conn, True);
7515 xsmp.save_yourself = False;
7516 }
7517}
7518
7519
7520/*
7521 * Callback to warn us of imminent death.
7522 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007524xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525{
7526 xsmp_close();
7527
7528 /* quit quickly leaving swapfiles for modified buffers behind */
7529 getout_preserve_modified(0);
7530}
7531
7532
7533/*
7534 * Callback to tell us that save-yourself has completed.
7535 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007537xsmp_save_complete(
7538 SmcConn smc_conn UNUSED,
7539 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540{
7541 xsmp.save_yourself = False;
7542}
7543
7544
7545/*
7546 * Callback to tell us that an instigated shutdown was cancelled
7547 * (maybe even by us)
7548 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007550xsmp_shutdown_cancelled(
7551 SmcConn smc_conn,
7552 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553{
7554 if (xsmp.save_yourself)
7555 SmcSaveYourselfDone(smc_conn, True);
7556 xsmp.save_yourself = False;
7557 xsmp.shutdown = False;
7558}
7559
7560
7561/*
7562 * Callback to tell us that a new ICE connection has been established.
7563 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007565xsmp_ice_connection(
7566 IceConn iceConn,
7567 IcePointer clientData UNUSED,
7568 Bool opening,
7569 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570{
7571 /* Intercept creation of ICE connection fd */
7572 if (opening)
7573 {
7574 xsmp_icefd = IceConnectionNumber(iceConn);
7575 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7576 }
7577}
7578
7579
7580/* Handle any ICE processing that's required; return FAIL if SM lost */
7581 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007582xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583{
7584 Bool rep;
7585
7586 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7587 == IceProcessMessagesIOError)
7588 {
7589 /* Lost ICE */
7590 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007591 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592 xsmp_close();
7593 return FAIL;
7594 }
7595 else
7596 return OK;
7597}
7598
7599static int dummy;
7600
7601/* Set up X Session Management Protocol */
7602 void
7603xsmp_init(void)
7604{
7605 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 SmcCallbacks smcallbacks;
7607#if 0
7608 SmPropValue smname;
7609 SmProp smnameprop;
7610 SmProp *smprops[1];
7611#endif
7612
7613 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007614 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007615
7616 xsmp.save_yourself = xsmp.shutdown = False;
7617
7618 /* Set up SM callbacks - must have all, even if they're not used */
7619 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7620 smcallbacks.save_yourself.client_data = NULL;
7621 smcallbacks.die.callback = xsmp_die;
7622 smcallbacks.die.client_data = NULL;
7623 smcallbacks.save_complete.callback = xsmp_save_complete;
7624 smcallbacks.save_complete.client_data = NULL;
7625 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7626 smcallbacks.shutdown_cancelled.client_data = NULL;
7627
7628 /* Set up a watch on ICE connection creations. The "dummy" argument is
7629 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7630 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7631 {
7632 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007633 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 return;
7635 }
7636
7637 /* Create an SM connection */
7638 xsmp.smcconn = SmcOpenConnection(
7639 NULL,
7640 NULL,
7641 SmProtoMajor,
7642 SmProtoMinor,
7643 SmcSaveYourselfProcMask | SmcDieProcMask
7644 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7645 &smcallbacks,
7646 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007647 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648 sizeof(errorstring),
7649 errorstring);
7650 if (xsmp.smcconn == NULL)
7651 {
7652 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007653
Bram Moolenaar071d4272004-06-13 20:20:40 +00007654 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007655 {
7656 vim_snprintf(errorreport, sizeof(errorreport),
7657 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7658 verb_msg((char_u *)errorreport);
7659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660 return;
7661 }
7662 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7663
7664#if 0
7665 /* ID ourselves */
7666 smname.value = "vim";
7667 smname.length = 3;
7668 smnameprop.name = "SmProgram";
7669 smnameprop.type = "SmARRAY8";
7670 smnameprop.num_vals = 1;
7671 smnameprop.vals = &smname;
7672
7673 smprops[0] = &smnameprop;
7674 SmcSetProperties(xsmp.smcconn, 1, smprops);
7675#endif
7676}
7677
7678
7679/* Shut down XSMP comms. */
7680 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007681xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682{
7683 if (xsmp_icefd != -1)
7684 {
7685 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007686 if (xsmp.clientid != NULL)
7687 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007688 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689 xsmp_icefd = -1;
7690 }
7691}
7692#endif /* USE_XSMP */
7693
7694
7695#ifdef EBCDIC
7696/* Translate character to its CTRL- value */
7697char CtrlTable[] =
7698{
7699/* 00 - 5E */
7700 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7701 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7703 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7704 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7705 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7706/* ^ */ 0x1E,
7707/* - */ 0x1F,
7708/* 61 - 6C */
7709 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7710/* _ */ 0x1F,
7711/* 6E - 80 */
7712 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7713/* a */ 0x01,
7714/* b */ 0x02,
7715/* c */ 0x03,
7716/* d */ 0x37,
7717/* e */ 0x2D,
7718/* f */ 0x2E,
7719/* g */ 0x2F,
7720/* h */ 0x16,
7721/* i */ 0x05,
7722/* 8A - 90 */
7723 0, 0, 0, 0, 0, 0, 0,
7724/* j */ 0x15,
7725/* k */ 0x0B,
7726/* l */ 0x0C,
7727/* m */ 0x0D,
7728/* n */ 0x0E,
7729/* o */ 0x0F,
7730/* p */ 0x10,
7731/* q */ 0x11,
7732/* r */ 0x12,
7733/* 9A - A1 */
7734 0, 0, 0, 0, 0, 0, 0, 0,
7735/* s */ 0x13,
7736/* t */ 0x3C,
7737/* u */ 0x3D,
7738/* v */ 0x32,
7739/* w */ 0x26,
7740/* x */ 0x18,
7741/* y */ 0x19,
7742/* z */ 0x3F,
7743/* AA - AC */
7744 0, 0, 0,
7745/* [ */ 0x27,
7746/* AE - BC */
7747 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7748/* ] */ 0x1D,
7749/* BE - C0 */ 0, 0, 0,
7750/* A */ 0x01,
7751/* B */ 0x02,
7752/* C */ 0x03,
7753/* D */ 0x37,
7754/* E */ 0x2D,
7755/* F */ 0x2E,
7756/* G */ 0x2F,
7757/* H */ 0x16,
7758/* I */ 0x05,
7759/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7760/* J */ 0x15,
7761/* K */ 0x0B,
7762/* L */ 0x0C,
7763/* M */ 0x0D,
7764/* N */ 0x0E,
7765/* O */ 0x0F,
7766/* P */ 0x10,
7767/* Q */ 0x11,
7768/* R */ 0x12,
7769/* DA - DF */ 0, 0, 0, 0, 0, 0,
7770/* \ */ 0x1C,
7771/* E1 */ 0,
7772/* S */ 0x13,
7773/* T */ 0x3C,
7774/* U */ 0x3D,
7775/* V */ 0x32,
7776/* W */ 0x26,
7777/* X */ 0x18,
7778/* Y */ 0x19,
7779/* Z */ 0x3F,
7780/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7781 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7782};
7783
7784char MetaCharTable[]=
7785{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7786 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7787 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7788 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7789 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7790};
7791
7792
7793/* TODO: Use characters NOT numbers!!! */
7794char CtrlCharTable[]=
7795{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7796 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7797 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7798 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7799 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7800};
7801
7802
7803#endif