blob: 8d10b14dcb866f7dd3aef709cc39c6ce42fa2dd0 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
6 *
7 * Do ":help uganda" in Vim to read copying and usage conditions.
8 * Do ":help credits" in Vim to see a list of people who contributed.
9 * See README.txt for an overview of the Vim source code.
10 */
11
12/*
13 * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
14 * Also for OS/2, using the excellent EMX package!!!
15 * Also for BeOS and Atari MiNT.
16 *
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
19 */
20
21/*
22 * Some systems have a prototype for select() that has (int *) instead of
23 * (fd_set *), which is wrong. This define removes that prototype. We define
24 * our own prototype below.
25 * Don't use it for the Mac, it causes a warning for precompiled headers.
26 * TODO: use a configure check for precompiled headers?
27 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000028#if !defined(__APPLE__) && !defined(__TANDEM)
Bram Moolenaar071d4272004-06-13 20:20:40 +000029# define select select_declared_wrong
30#endif
31
32#include "vim.h"
33
Bram Moolenaar325b7a22004-07-05 15:58:32 +000034#ifdef FEAT_MZSCHEME
35# include "if_mzsch.h"
36#endif
37
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#include "os_unixx.h" /* unix includes for os_unix.c only */
39
40#ifdef USE_XSMP
41# include <X11/SM/SMlib.h>
42#endif
43
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000044#ifdef HAVE_SELINUX
45# include <selinux/selinux.h>
46static int selinux_enabled = -1;
47#endif
48
Bram Moolenaar5bd32f42014-04-02 14:05:38 +020049#ifdef HAVE_SMACK
50# include <attr/xattr.h>
51# include <linux/xattr.h>
52# ifndef SMACK_LABEL_LEN
53# define SMACK_LABEL_LEN 1024
54# endif
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057/*
58 * Use this prototype for select, some include files have a wrong prototype
59 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000060#ifndef __TANDEM
61# undef select
62# ifdef __BEOS__
63# define select beos_select
64# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#endif
66
Bram Moolenaara2442432007-04-26 14:26:37 +000067#ifdef __CYGWIN__
68# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000069# include <cygwin/version.h>
70# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
71 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010072# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
73# define WIN32_LEAN_AND_MEAN
74# include <windows.h>
75# include "winclip.pro"
76# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000077# endif
78#endif
79
Bram Moolenaar071d4272004-06-13 20:20:40 +000080#if defined(HAVE_SELECT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +010081extern int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
Bram Moolenaar071d4272004-06-13 20:20:40 +000082#endif
83
84#ifdef FEAT_MOUSE_GPM
85# include <gpm.h>
86/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
87 * I just copied relevant defines here. A cleaner solution would be to put gpm
88 * code into separate file and include there linux/keyboard.h
89 */
90/* #include <linux/keyboard.h> */
91# define KG_SHIFT 0
92# define KG_CTRL 2
93# define KG_ALT 3
94# define KG_ALTGR 1
95# define KG_SHIFTL 4
96# define KG_SHIFTR 5
97# define KG_CTRLL 6
98# define KG_CTRLR 7
99# define KG_CAPSSHIFT 8
100
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100101static void gpm_close(void);
102static int gpm_open(void);
103static int mch_gpm_process(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104#endif
105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000106#ifdef FEAT_SYSMOUSE
107# include <sys/consio.h>
108# include <sys/fbio.h>
109
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100110static int sysmouse_open(void);
111static void sysmouse_close(void);
Bram Moolenaard99df422016-01-29 23:20:40 +0100112static RETSIGTYPE sig_sysmouse SIGPROTOARG;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000113#endif
114
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115/*
116 * end of autoconf section. To be extended...
117 */
118
119/* Are the following #ifdefs still required? And why? Is that for X11? */
120
121#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
122# ifdef SIGWINCH
123# undef SIGWINCH
124# endif
125# ifdef TIOCGWINSZ
126# undef TIOCGWINSZ
127# endif
128#endif
129
130#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
131# define SIGWINCH SIGWINDOW
132#endif
133
134#ifdef FEAT_X11
135# include <X11/Xlib.h>
136# include <X11/Xutil.h>
137# include <X11/Xatom.h>
138# ifdef FEAT_XCLIPBOARD
139# include <X11/Intrinsic.h>
140# include <X11/Shell.h>
141# include <X11/StringDefs.h>
142static Widget xterm_Shell = (Widget)0;
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100143static void clip_update(void);
144static void xterm_update(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145# endif
146
147# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
148Window x11_window = 0;
149# endif
150Display *x11_display = NULL;
151
152# ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100153static int get_x11_windis(void);
154static void set_x11_title(char_u *);
155static void set_x11_icon(char_u *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156# endif
157#endif
158
159#ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100160static int get_x11_title(int);
161static int get_x11_icon(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162
163static char_u *oldtitle = NULL;
164static int did_set_title = FALSE;
165static char_u *oldicon = NULL;
166static int did_set_icon = FALSE;
167#endif
168
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100169static void may_core_dump(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000170
Bram Moolenaar205b8862011-09-07 15:04:31 +0200171#ifdef HAVE_UNION_WAIT
172typedef union wait waitstatus;
173#else
174typedef int waitstatus;
175#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100176static pid_t wait4pid(pid_t, waitstatus *);
Bram Moolenaar205b8862011-09-07 15:04:31 +0200177
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100178static int WaitForChar(long);
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100179#if defined(__BEOS__) || defined(VMS)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100180int RealWaitForChar(int, long, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181#else
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100182static int RealWaitForChar(int, long, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000183#endif
184
185#ifdef FEAT_XCLIPBOARD
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100186static int do_xterm_trace(void);
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000187# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000188#endif
189
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100190static void handle_resize(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191
192#if defined(SIGWINCH)
Bram Moolenaard99df422016-01-29 23:20:40 +0100193static RETSIGTYPE sig_winch SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000194#endif
195#if defined(SIGINT)
Bram Moolenaard99df422016-01-29 23:20:40 +0100196static RETSIGTYPE catch_sigint SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197#endif
198#if defined(SIGPWR)
Bram Moolenaard99df422016-01-29 23:20:40 +0100199static RETSIGTYPE catch_sigpwr SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200#endif
201#if defined(SIGALRM) && defined(FEAT_X11) \
202 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
203# define SET_SIG_ALARM
Bram Moolenaard99df422016-01-29 23:20:40 +0100204static RETSIGTYPE sig_alarm SIGPROTOARG;
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000205/* volatile because it is used in signal handler sig_alarm(). */
206static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207#endif
Bram Moolenaard99df422016-01-29 23:20:40 +0100208static RETSIGTYPE deathtrap SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100210static void catch_int_signal(void);
211static void set_signals(void);
212static void catch_signals(RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)());
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100214static int have_wildcard(int, char_u **);
215static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216#endif
217
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218#ifndef __EMX__
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100219static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#endif
221
222#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000223# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224#endif
225
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000226/* volatile because it is used in signal handler sig_winch(). */
227static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228#ifndef __EMX__
229static char_u *extra_shell_arg = NULL;
230static int show_shell_mess = TRUE;
231#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000232/* volatile because it is used in signal handler deathtrap(). */
233static volatile int deadly_signal = 0; /* The signal we caught */
234/* volatile because it is used in signal handler deathtrap(). */
235static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
238
239#ifdef USE_XSMP
240typedef struct
241{
242 SmcConn smcconn; /* The SM connection ID */
243 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200244 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245 Bool save_yourself; /* If we're in the middle of a save_yourself */
246 Bool shutdown; /* If we're in shutdown mode */
247} xsmp_config_T;
248
249static xsmp_config_T xsmp;
250#endif
251
252#ifdef SYS_SIGLIST_DECLARED
253/*
254 * I have seen
255 * extern char *_sys_siglist[NSIG];
256 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
257 * that describe the signals. That is nearly what we want here. But
258 * autoconf does only check for sys_siglist (without the underscore), I
259 * do not want to change everything today.... jw.
260 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
261 */
262#endif
263
264static struct signalinfo
265{
266 int sig; /* Signal number, eg. SIGSEGV etc */
267 char *name; /* Signal name (not char_u!). */
268 char deadly; /* Catch as a deadly signal? */
269} signal_info[] =
270{
271#ifdef SIGHUP
272 {SIGHUP, "HUP", TRUE},
273#endif
274#ifdef SIGQUIT
275 {SIGQUIT, "QUIT", TRUE},
276#endif
277#ifdef SIGILL
278 {SIGILL, "ILL", TRUE},
279#endif
280#ifdef SIGTRAP
281 {SIGTRAP, "TRAP", TRUE},
282#endif
283#ifdef SIGABRT
284 {SIGABRT, "ABRT", TRUE},
285#endif
286#ifdef SIGEMT
287 {SIGEMT, "EMT", TRUE},
288#endif
289#ifdef SIGFPE
290 {SIGFPE, "FPE", TRUE},
291#endif
292#ifdef SIGBUS
293 {SIGBUS, "BUS", TRUE},
294#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100295#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
296 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297 {SIGSEGV, "SEGV", TRUE},
298#endif
299#ifdef SIGSYS
300 {SIGSYS, "SYS", TRUE},
301#endif
302#ifdef SIGALRM
303 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
304#endif
305#ifdef SIGTERM
306 {SIGTERM, "TERM", TRUE},
307#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100308#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309 {SIGVTALRM, "VTALRM", TRUE},
310#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000311#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
312 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
313 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314 {SIGPROF, "PROF", TRUE},
315#endif
316#ifdef SIGXCPU
317 {SIGXCPU, "XCPU", TRUE},
318#endif
319#ifdef SIGXFSZ
320 {SIGXFSZ, "XFSZ", TRUE},
321#endif
322#ifdef SIGUSR1
323 {SIGUSR1, "USR1", TRUE},
324#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000325#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
326 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 {SIGUSR2, "USR2", TRUE},
328#endif
329#ifdef SIGINT
330 {SIGINT, "INT", FALSE},
331#endif
332#ifdef SIGWINCH
333 {SIGWINCH, "WINCH", FALSE},
334#endif
335#ifdef SIGTSTP
336 {SIGTSTP, "TSTP", FALSE},
337#endif
338#ifdef SIGPIPE
339 {SIGPIPE, "PIPE", FALSE},
340#endif
341 {-1, "Unknown!", FALSE}
342};
343
Bram Moolenaar25724922009-07-14 15:38:41 +0000344 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100345mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000346{
347 if (p_verbose >= 5)
348 {
349 verbose_enter();
350 smsg((char_u *)"chdir(%s)", path);
351 verbose_leave();
352 }
353# ifdef VMS
354 return chdir(vms_fixfilename(path));
355# else
356 return chdir(path);
357# endif
358}
359
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000360/*
361 * Write s[len] to the screen.
362 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000363 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100364mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000366 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 if (p_wd) /* Unix is too fast, slow down a bit more */
368 RealWaitForChar(read_cmd_fd, p_wd, NULL);
369}
370
371/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000372 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373 * Get a characters from the keyboard.
374 * Return the number of characters that are available.
375 * If wtime == 0 do not wait for characters.
376 * If wtime == n wait a short time for characters.
377 * If wtime == -1 wait forever for characters.
378 */
379 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100380mch_inchar(
381 char_u *buf,
382 int maxlen,
383 long wtime, /* don't use "time", MIPS cannot handle it */
384 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385{
386 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200388#ifdef MESSAGE_QUEUE
389 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200390#endif
391
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 /* Check if window changed size while we were busy, perhaps the ":set
393 * columns=99" command was used. */
394 while (do_resize)
395 handle_resize();
396
397 if (wtime >= 0)
398 {
399 while (WaitForChar(wtime) == 0) /* no character available */
400 {
Bram Moolenaar5d8afeb2015-11-19 19:55:16 +0100401 if (do_resize)
402 handle_resize();
403#ifdef FEAT_CLIENTSERVER
404 else if (!server_waiting())
405#else
406 else
407#endif
408 /* return if not interrupted by resize or server */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 return 0;
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200410#ifdef MESSAGE_QUEUE
411 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200412#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000413 }
414 }
415 else /* wtime == -1 */
416 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417 /*
418 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000419 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 * Also done when interrupted by SIGWINCH.
421 */
422 if (WaitForChar(p_ut) == 0)
423 {
424#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000425 if (trigger_cursorhold() && maxlen >= 3
426 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000428 buf[0] = K_SPECIAL;
429 buf[1] = KS_EXTRA;
430 buf[2] = (int)KE_CURSORHOLD;
431 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000434 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 }
436 }
437
438 for (;;) /* repeat until we got a character */
439 {
440 while (do_resize) /* window changed size */
441 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200442
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200443#ifdef MESSAGE_QUEUE
444 parse_queued_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200445#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200447 * We want to be interrupted by the winch signal
448 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200450 if (WaitForChar(-1L) == 0)
451 {
452 if (do_resize) /* interrupted by SIGWINCH signal */
453 handle_resize();
454 return 0;
455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456
457 /* If input was put directly in typeahead buffer bail out here. */
458 if (typebuf_changed(tb_change_cnt))
459 return 0;
460
461 /*
462 * For some terminals we only get one character at a time.
463 * We want the get all available characters, so we could keep on
464 * trying until none is available
465 * For some other terminals this is quite slow, that's why we don't do
466 * it.
467 */
468 len = read_from_input_buf(buf, (long)maxlen);
469 if (len > 0)
470 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 return len;
472 }
473 }
474}
475
476 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100477handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478{
479 do_resize = FALSE;
480 shell_resized();
481}
482
483/*
484 * return non-zero if a character is available
485 */
486 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100487mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488{
489 return WaitForChar(0L);
490}
491
492#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
493# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000494# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495# endif
496# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
497# include <sys/sysctl.h>
498# endif
499# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
500# include <sys/sysinfo.h>
501# endif
502
503/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000504 * Return total amount of memory available in Kbyte.
505 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100508mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509{
510# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000511 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512# else
513 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000514 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515
516# ifdef HAVE_SYSCTL
517 int mib[2], physmem;
518 size_t len;
519
520 /* BSD way of getting the amount of RAM available. */
521 mib[0] = CTL_HW;
522 mib[1] = HW_USERMEM;
523 len = sizeof(physmem);
524 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
525 mem = (long_u)physmem;
526# endif
527
528# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
529 if (mem == 0)
530 {
531 struct sysinfo sinfo;
532
533 /* Linux way of getting amount of RAM available */
534 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000535 {
536# ifdef HAVE_SYSINFO_MEM_UNIT
537 /* avoid overflow as much as possible */
538 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
539 {
540 sinfo.mem_unit = sinfo.mem_unit >> 1;
541 --shiftright;
542 }
543 mem = sinfo.totalram * sinfo.mem_unit;
544# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000546# endif
547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548 }
549# endif
550
551# ifdef HAVE_SYSCONF
552 if (mem == 0)
553 {
554 long pagesize, pagecount;
555
556 /* Solaris way of getting amount of RAM available */
557 pagesize = sysconf(_SC_PAGESIZE);
558 pagecount = sysconf(_SC_PHYS_PAGES);
559 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000560 {
561 /* avoid overflow as much as possible */
562 while (shiftright > 0 && (pagesize & 1) == 0)
563 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000564 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000565 --shiftright;
566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000568 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 }
570# endif
571
572 /* Return the minimum of the physical memory and the user limit, because
573 * using more than the user limit may cause Vim to be terminated. */
574# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
575 {
576 struct rlimit rlp;
577
578 if (getrlimit(RLIMIT_DATA, &rlp) == 0
579 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
580# ifdef RLIM_INFINITY
581 && rlp.rlim_cur != RLIM_INFINITY
582# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000583 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000585 {
586 mem = (long_u)rlp.rlim_cur;
587 shiftright = 10;
588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000589 }
590# endif
591
592 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000593 return mem >> shiftright;
594 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595# endif
596}
597#endif
598
599 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100600mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000603#ifdef FEAT_MZSCHEME
604 long total = msec; /* remember original value */
605#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606
607 if (ignoreinput)
608 {
609 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000610 * here. But we don't want QUIT to kill us (CTRL-\ used in a
611 * shell may produce SIGQUIT). */
612 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613 old_tmode = curr_tmode;
614 if (curr_tmode == TMODE_RAW)
615 settmode(TMODE_SLEEP);
616
617 /*
618 * Everybody sleeps in a different way...
619 * Prefer nanosleep(), some versions of usleep() can only sleep up to
620 * one second.
621 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000622#ifdef FEAT_MZSCHEME
623 do
624 {
625 /* if total is large enough, wait by portions in p_mzq */
626 if (total > p_mzq)
627 msec = p_mzq;
628 else
629 msec = total;
630 total -= msec;
631#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632#ifdef HAVE_NANOSLEEP
633 {
634 struct timespec ts;
635
636 ts.tv_sec = msec / 1000;
637 ts.tv_nsec = (msec % 1000) * 1000000;
638 (void)nanosleep(&ts, NULL);
639 }
640#else
641# ifdef HAVE_USLEEP
642 while (msec >= 1000)
643 {
644 usleep((unsigned int)(999 * 1000));
645 msec -= 999;
646 }
647 usleep((unsigned int)(msec * 1000));
648# else
649# ifndef HAVE_SELECT
650 poll(NULL, 0, (int)msec);
651# else
652# ifdef __EMX__
653 _sleep2(msec);
654# else
655 {
656 struct timeval tv;
657
658 tv.tv_sec = msec / 1000;
659 tv.tv_usec = (msec % 1000) * 1000;
660 /*
661 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
662 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
663 */
664 select(0, NULL, NULL, NULL, &tv);
665 }
666# endif /* __EMX__ */
667# endif /* HAVE_SELECT */
668# endif /* HAVE_NANOSLEEP */
669#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000670#ifdef FEAT_MZSCHEME
671 }
672 while (total > 0);
673#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674
675 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000676 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 }
678 else
679 WaitForChar(msec);
680}
681
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000682#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
684# define HAVE_CHECK_STACK_GROWTH
685/*
686 * Support for checking for an almost-out-of-stack-space situation.
687 */
688
689/*
690 * Return a pointer to an item on the stack. Used to find out if the stack
691 * grows up or down.
692 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100693static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694static int stack_grows_downwards;
695
696/*
697 * Find out if the stack grows upwards or downwards.
698 * "p" points to a variable on the stack of the caller.
699 */
700 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100701check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702{
703 int i;
704
705 stack_grows_downwards = (p > (char *)&i);
706}
707#endif
708
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000709#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710static char *stack_limit = NULL;
711
712#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
713# include <pthread.h>
714# include <pthread_np.h>
715#endif
716
717/*
718 * Find out until how var the stack can grow without getting into trouble.
719 * Called when starting up and when switching to the signal stack in
720 * deathtrap().
721 */
722 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100723get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724{
725 struct rlimit rlp;
726 int i;
727 long lim;
728
729 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
730 * limit doesn't fit in a long (rlim_cur might be "long long"). */
731 if (getrlimit(RLIMIT_STACK, &rlp) == 0
732 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
733# ifdef RLIM_INFINITY
734 && rlp.rlim_cur != RLIM_INFINITY
735# endif
736 )
737 {
738 lim = (long)rlp.rlim_cur;
739#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
740 {
741 pthread_attr_t attr;
742 size_t size;
743
744 /* On FreeBSD the initial thread always has a fixed stack size, no
745 * matter what the limits are set to. Normally it's 1 Mbyte. */
746 pthread_attr_init(&attr);
747 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
748 {
749 pthread_attr_getstacksize(&attr, &size);
750 if (lim > (long)size)
751 lim = (long)size;
752 }
753 pthread_attr_destroy(&attr);
754 }
755#endif
756 if (stack_grows_downwards)
757 {
758 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
759 if (stack_limit >= (char *)&i)
760 /* overflow, set to 1/16 of current stack position */
761 stack_limit = (char *)((long)&i / 16L);
762 }
763 else
764 {
765 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
766 if (stack_limit <= (char *)&i)
767 stack_limit = NULL; /* overflow */
768 }
769 }
770}
771
772/*
773 * Return FAIL when running out of stack space.
774 * "p" must point to any variable local to the caller that's on the stack.
775 */
776 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100777mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778{
779 if (stack_limit != NULL)
780 {
781 if (stack_grows_downwards)
782 {
783 if (p < stack_limit)
784 return FAIL;
785 }
786 else if (p > stack_limit)
787 return FAIL;
788 }
789 return OK;
790}
791#endif
792
793#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
794/*
795 * Support for using the signal stack.
796 * This helps when we run out of stack space, which causes a SIGSEGV. The
797 * signal handler then must run on another stack, since the normal stack is
798 * completely full.
799 */
800
Bram Moolenaar39766a72013-11-03 00:41:00 +0100801#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100802# include <AvailabilityMacros.h>
803#endif
804
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805#ifndef SIGSTKSZ
806# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
807#endif
808
809# ifdef HAVE_SIGALTSTACK
810static stack_t sigstk; /* for sigaltstack() */
811# else
812static struct sigstack sigstk; /* for sigstack() */
813# endif
814
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100815static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816static char *signal_stack;
817
818 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100819init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820{
821 if (signal_stack != NULL)
822 {
823# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000824# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
825 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
827 * "struct sigaltstack" needs to be declared. */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100828 extern int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829# endif
830
831# ifdef HAVE_SS_BASE
832 sigstk.ss_base = signal_stack;
833# else
834 sigstk.ss_sp = signal_stack;
835# endif
836 sigstk.ss_size = SIGSTKSZ;
837 sigstk.ss_flags = 0;
838 (void)sigaltstack(&sigstk, NULL);
839# else
840 sigstk.ss_sp = signal_stack;
841 if (stack_grows_downwards)
842 sigstk.ss_sp += SIGSTKSZ - 1;
843 sigstk.ss_onstack = 0;
844 (void)sigstack(&sigstk, NULL);
845# endif
846 }
847}
848#endif
849
850/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000851 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 * will barf when the second argument to signal() is ``wrong''.
853 * Let me try it with a few tricky defines from my own osdef.h (jw).
854 */
855#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 static RETSIGTYPE
857sig_winch SIGDEFARG(sigarg)
858{
859 /* this is not required on all systems, but it doesn't hurt anybody */
860 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
861 do_resize = TRUE;
862 SIGRETURN;
863}
864#endif
865
866#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867 static RETSIGTYPE
868catch_sigint SIGDEFARG(sigarg)
869{
870 /* this is not required on all systems, but it doesn't hurt anybody */
871 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
872 got_int = TRUE;
873 SIGRETURN;
874}
875#endif
876
877#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878 static RETSIGTYPE
879catch_sigpwr SIGDEFARG(sigarg)
880{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000881 /* this is not required on all systems, but it doesn't hurt anybody */
882 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883 /*
884 * I'm not sure we get the SIGPWR signal when the system is really going
885 * down or when the batteries are almost empty. Just preserve the swap
886 * files and don't exit, that can't do any harm.
887 */
888 ml_sync_all(FALSE, FALSE);
889 SIGRETURN;
890}
891#endif
892
893#ifdef SET_SIG_ALARM
894/*
895 * signal function for alarm().
896 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 static RETSIGTYPE
898sig_alarm SIGDEFARG(sigarg)
899{
900 /* doesn't do anything, just to break a system call */
901 sig_alarm_called = TRUE;
902 SIGRETURN;
903}
904#endif
905
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000906#if (defined(HAVE_SETJMP_H) \
907 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
908 || defined(FEAT_LIBCALL))) \
909 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910/*
911 * A simplistic version of setjmp() that only allows one level of using.
912 * Don't call twice before calling mch_endjmp()!.
913 * Usage:
914 * mch_startjmp();
915 * if (SETJMP(lc_jump_env) != 0)
916 * {
917 * mch_didjmp();
918 * EMSG("crash!");
919 * }
920 * else
921 * {
922 * do_the_work;
923 * mch_endjmp();
924 * }
925 * Note: Can't move SETJMP() here, because a function calling setjmp() must
926 * not return before the saved environment is used.
927 * Returns OK for normal return, FAIL when the protected code caused a
928 * problem and LONGJMP() was used.
929 */
930 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100931mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932{
933#ifdef SIGHASARG
934 lc_signal = 0;
935#endif
936 lc_active = TRUE;
937}
938
939 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100940mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941{
942 lc_active = FALSE;
943}
944
945 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100946mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947{
948# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
949 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
950 * otherwise catching the signal only works once. */
951 init_signal_stack();
952# endif
953}
954#endif
955
956/*
957 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200958 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200960 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
961 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 */
963 static RETSIGTYPE
964deathtrap SIGDEFARG(sigarg)
965{
966 static int entered = 0; /* count the number of times we got here.
967 Note: when memory has been corrupted
968 this may get an arbitrary value! */
969#ifdef SIGHASARG
970 int i;
971#endif
972
973#if defined(HAVE_SETJMP_H)
974 /*
975 * Catch a crash in protected code.
976 * Restores the environment saved in lc_jump_env, which looks like
977 * SETJMP() returns 1.
978 */
979 if (lc_active)
980 {
981# if defined(SIGHASARG)
982 lc_signal = sigarg;
983# endif
984 lc_active = FALSE; /* don't jump again */
985 LONGJMP(lc_jump_env, 1);
986 /* NOTREACHED */
987 }
988#endif
989
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000990#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000991# ifdef SIGQUIT
992 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
993 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
994 * pressing CTRL-\, but we don't want Vim to exit then. */
995 if (in_mch_delay && sigarg == SIGQUIT)
996 SIGRETURN;
997# endif
998
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000999 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1000 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1001 * free(). Calling free() again may then cause a crash. */
1002 if (entered == 0
1003 && (0
1004# ifdef SIGHUP
1005 || sigarg == SIGHUP
1006# endif
1007# ifdef SIGQUIT
1008 || sigarg == SIGQUIT
1009# endif
1010# ifdef SIGTERM
1011 || sigarg == SIGTERM
1012# endif
1013# ifdef SIGPWR
1014 || sigarg == SIGPWR
1015# endif
1016# ifdef SIGUSR1
1017 || sigarg == SIGUSR1
1018# endif
1019# ifdef SIGUSR2
1020 || sigarg == SIGUSR2
1021# endif
1022 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001023 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001024 SIGRETURN;
1025#endif
1026
Bram Moolenaar071d4272004-06-13 20:20:40 +00001027 /* Remember how often we have been called. */
1028 ++entered;
1029
1030#ifdef FEAT_EVAL
1031 /* Set the v:dying variable. */
1032 set_vim_var_nr(VV_DYING, (long)entered);
1033#endif
1034
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001035#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036 /* Since we are now using the signal stack, need to reset the stack
1037 * limit. Otherwise using a regexp will fail. */
1038 get_stack_limit();
1039#endif
1040
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001041#if 0
1042 /* This is for opening gdb the moment Vim crashes.
1043 * You need to manually adjust the file name and Vim executable name.
1044 * Suggested by SungHyun Nam. */
1045 {
1046# define VI_GDB_FILE "/tmp/vimgdb"
1047# define VIM_NAME "/usr/bin/vim"
1048 FILE *fp = fopen(VI_GDB_FILE, "w");
1049 if (fp)
1050 {
1051 fprintf(fp,
1052 "file %s\n"
1053 "attach %d\n"
1054 "set height 1000\n"
1055 "bt full\n"
1056 , VIM_NAME, getpid());
1057 fclose(fp);
1058 system("xterm -e gdb -x "VI_GDB_FILE);
1059 unlink(VI_GDB_FILE);
1060 }
1061 }
1062#endif
1063
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064#ifdef SIGHASARG
1065 /* try to find the name of this signal */
1066 for (i = 0; signal_info[i].sig != -1; i++)
1067 if (sigarg == signal_info[i].sig)
1068 break;
1069 deadly_signal = sigarg;
1070#endif
1071
1072 full_screen = FALSE; /* don't write message to the GUI, it might be
1073 * part of the problem... */
1074 /*
1075 * If something goes wrong after entering here, we may get here again.
1076 * When this happens, give a message and try to exit nicely (resetting the
1077 * terminal mode, etc.)
1078 * When this happens twice, just exit, don't even try to give a message,
1079 * stack may be corrupt or something weird.
1080 * When this still happens again (or memory was corrupted in such a way
1081 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1082 */
1083 if (entered >= 3)
1084 {
1085 reset_signals(); /* don't catch any signals anymore */
1086 may_core_dump();
1087 if (entered >= 4)
1088 _exit(8);
1089 exit(7);
1090 }
1091 if (entered == 2)
1092 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001093 /* No translation, it may call malloc(). */
1094 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 out_flush();
1096 getout(1);
1097 }
1098
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001099 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001101 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 signal_info[i].name);
1103#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001104 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001106
1107 /* Preserve files and exit. This sets the really_exiting flag to prevent
1108 * calling free(). */
1109 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110
Bram Moolenaar009b2592004-10-24 19:18:58 +00001111#ifdef NBDEBUG
1112 reset_signals();
1113 may_core_dump();
1114 abort();
1115#endif
1116
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 SIGRETURN;
1118}
1119
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001120#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121/*
1122 * On Solaris with multi-threading, suspending might not work immediately.
1123 * Catch the SIGCONT signal, which will be used as an indication whether the
1124 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001125 *
1126 * On Linux, signal is not always handled immediately either.
1127 * See https://bugs.launchpad.net/bugs/291373
1128 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001129 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001131static volatile int sigcont_received;
Bram Moolenaard99df422016-01-29 23:20:40 +01001132static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133
1134/*
1135 * signal handler for SIGCONT
1136 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 static RETSIGTYPE
1138sigcont_handler SIGDEFARG(sigarg)
1139{
1140 sigcont_received = TRUE;
1141 SIGRETURN;
1142}
1143#endif
1144
Bram Moolenaar62b42182010-09-21 22:09:37 +02001145# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001146static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001147# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001148static void save_clipboard(void);
1149static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001150
1151static void *clip_star_save = NULL;
1152static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001153# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001154
1155/*
1156 * Called when Vim is going to sleep or execute a shell command.
1157 * We can't respond to requests for the X selections. Lose them, otherwise
1158 * other applications will hang. But first copy the text to cut buffer 0.
1159 */
1160 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001161loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001162{
1163 if (clip_star.owned || clip_plus.owned)
1164 {
1165 x11_export_final_selection();
1166 if (clip_star.owned)
1167 clip_lose_selection(&clip_star);
1168 if (clip_plus.owned)
1169 clip_lose_selection(&clip_plus);
1170 if (x11_display != NULL)
1171 XFlush(x11_display);
1172 }
1173}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001174
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001175# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001176/*
1177 * Save clipboard text to restore later.
1178 */
1179 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001180save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001181{
1182 if (clip_star.owned)
1183 clip_star_save = get_register('*', TRUE);
1184 if (clip_plus.owned)
1185 clip_plus_save = get_register('+', TRUE);
1186}
1187
1188/*
1189 * Restore clipboard text if no one own the X selection.
1190 */
1191 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001192restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001193{
1194 if (clip_star_save != NULL)
1195 {
1196 if (!clip_gen_owner_exists(&clip_star))
1197 put_register('*', clip_star_save);
1198 else
1199 free_register(clip_star_save);
1200 clip_star_save = NULL;
1201 }
1202 if (clip_plus_save != NULL)
1203 {
1204 if (!clip_gen_owner_exists(&clip_plus))
1205 put_register('+', clip_plus_save);
1206 else
1207 free_register(clip_plus_save);
1208 clip_plus_save = NULL;
1209 }
1210}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001211# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001212#endif
1213
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214/*
1215 * If the machine has job control, use it to suspend the program,
1216 * otherwise fake it by starting a new shell.
1217 */
1218 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001219mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220{
1221 /* BeOS does have SIGTSTP, but it doesn't work. */
1222#if defined(SIGTSTP) && !defined(__BEOS__)
1223 out_flush(); /* needed to make cursor visible on some systems */
1224 settmode(TMODE_COOK);
1225 out_flush(); /* needed to disable mouse on some systems */
1226
1227# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001228 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229# endif
1230
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001231# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 sigcont_received = FALSE;
1233# endif
1234 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001235# if defined(_REENTRANT) && defined(SIGCONT)
1236 /*
1237 * Wait for the SIGCONT signal to be handled. It generally happens
1238 * immediately, but somehow not all the time. Do not call pause()
1239 * because there would be race condition which would hang Vim if
1240 * signal happened in between the test of sigcont_received and the
1241 * call to pause(). If signal is not yet received, call sleep(0)
1242 * to just yield CPU. Signal should then be received. If somehow
1243 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1244 * further if signal is not received after 1+2+3+4 ms (not expected
1245 * to happen).
1246 */
1247 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001248 long wait_time;
1249 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001250 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001251 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001252 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253# endif
1254
1255# ifdef FEAT_TITLE
1256 /*
1257 * Set oldtitle to NULL, so the current title is obtained again.
1258 */
1259 vim_free(oldtitle);
1260 oldtitle = NULL;
1261# endif
1262 settmode(TMODE_RAW);
1263 need_check_timestamps = TRUE;
1264 did_check_timestamps = FALSE;
1265#else
1266 suspend_shell();
1267#endif
1268}
1269
1270 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001271mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272{
1273 Columns = 80;
1274 Rows = 24;
1275
1276 out_flush();
1277 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001278
Bram Moolenaar56718732006-03-15 22:53:57 +00001279#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001280 mac_conv_init();
1281#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001282#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1283 win_clip_init();
1284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285}
1286
1287 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001288set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289{
1290#if defined(SIGWINCH)
1291 /*
1292 * WINDOW CHANGE signal is handled with sig_winch().
1293 */
1294 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1295#endif
1296
1297 /*
1298 * We want the STOP signal to work, to make mch_suspend() work.
1299 * For "rvim" the STOP signal is ignored.
1300 */
1301#ifdef SIGTSTP
1302 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1303#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001304#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305 signal(SIGCONT, sigcont_handler);
1306#endif
1307
1308 /*
1309 * We want to ignore breaking of PIPEs.
1310 */
1311#ifdef SIGPIPE
1312 signal(SIGPIPE, SIG_IGN);
1313#endif
1314
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001316 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317#endif
1318
1319 /*
1320 * Ignore alarm signals (Perl's alarm() generates it).
1321 */
1322#ifdef SIGALRM
1323 signal(SIGALRM, SIG_IGN);
1324#endif
1325
1326 /*
1327 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1328 * work will be lost.
1329 */
1330#ifdef SIGPWR
1331 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1332#endif
1333
1334 /*
1335 * Arrange for other signals to gracefully shutdown Vim.
1336 */
1337 catch_signals(deathtrap, SIG_ERR);
1338
1339#if defined(FEAT_GUI) && defined(SIGHUP)
1340 /*
1341 * When the GUI is running, ignore the hangup signal.
1342 */
1343 if (gui.in_use)
1344 signal(SIGHUP, SIG_IGN);
1345#endif
1346}
1347
Bram Moolenaardf177f62005-02-22 08:39:57 +00001348#if defined(SIGINT) || defined(PROTO)
1349/*
1350 * Catch CTRL-C (only works while in Cooked mode).
1351 */
1352 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001353catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001354{
1355 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1356}
1357#endif
1358
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001360reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361{
1362 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001363#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 /* SIGCONT isn't in the list, because its default action is ignore */
1365 signal(SIGCONT, SIG_DFL);
1366#endif
1367}
1368
1369 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001370catch_signals(
1371 RETSIGTYPE (*func_deadly)(),
1372 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373{
1374 int i;
1375
1376 for (i = 0; signal_info[i].sig != -1; i++)
1377 if (signal_info[i].deadly)
1378 {
1379#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1380 struct sigaction sa;
1381
1382 /* Setup to use the alternate stack for the signal function. */
1383 sa.sa_handler = func_deadly;
1384 sigemptyset(&sa.sa_mask);
1385# if defined(__linux__) && defined(_REENTRANT)
1386 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1387 * thread handling in combination with using the alternate stack:
1388 * pthread library functions try to use the stack pointer to
1389 * identify the current thread, causing a SEGV signal, which
1390 * recursively calls deathtrap() and hangs. */
1391 sa.sa_flags = 0;
1392# else
1393 sa.sa_flags = SA_ONSTACK;
1394# endif
1395 sigaction(signal_info[i].sig, &sa, NULL);
1396#else
1397# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1398 struct sigvec sv;
1399
1400 /* Setup to use the alternate stack for the signal function. */
1401 sv.sv_handler = func_deadly;
1402 sv.sv_mask = 0;
1403 sv.sv_flags = SV_ONSTACK;
1404 sigvec(signal_info[i].sig, &sv, NULL);
1405# else
1406 signal(signal_info[i].sig, func_deadly);
1407# endif
1408#endif
1409 }
1410 else if (func_other != SIG_ERR)
1411 signal(signal_info[i].sig, func_other);
1412}
1413
1414/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001415 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001416 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1417 * return TRUE
1418 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1419 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001420 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001421 * Returns TRUE when Vim should exit.
1422 */
1423 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001424vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001425{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001426 static int got_signal = 0;
1427 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001428
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001429 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001430 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001431 case SIGNAL_BLOCK: blocked = TRUE;
1432 break;
1433
1434 case SIGNAL_UNBLOCK: blocked = FALSE;
1435 if (got_signal != 0)
1436 {
1437 kill(getpid(), got_signal);
1438 got_signal = 0;
1439 }
1440 break;
1441
1442 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001443 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001444 got_signal = sig;
1445#ifdef SIGPWR
1446 if (sig != SIGPWR)
1447#endif
1448 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001449 break;
1450 }
1451 return FALSE;
1452}
1453
1454/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 * Check_win checks whether we have an interactive stdout.
1456 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001458mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 if (isatty(1))
1461 return OK;
1462 return FAIL;
1463}
1464
1465/*
1466 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1467 */
1468 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001469mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470{
1471 if (isatty(read_cmd_fd))
1472 return TRUE;
1473 return FALSE;
1474}
1475
1476#ifdef FEAT_X11
1477
1478# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1479 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1480
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001481static void xopen_message(struct timeval *tvp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482
1483/*
1484 * Give a message about the elapsed time for opening the X window.
1485 */
1486 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001487xopen_message(
1488 struct timeval *tvp) /* must contain start time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489{
1490 struct timeval end_tv;
1491
1492 /* Compute elapsed time. */
1493 gettimeofday(&end_tv, NULL);
1494 smsg((char_u *)_("Opening the X display took %ld msec"),
1495 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001496 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497}
1498# endif
1499#endif
1500
1501#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1502/*
1503 * A few functions shared by X11 title and clipboard code.
1504 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001505static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1506static int x_error_check(Display *dpy, XErrorEvent *error_event);
1507static int x_connect_to_server(void);
1508static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509
1510static int got_x_error = FALSE;
1511
1512/*
1513 * X Error handler, otherwise X just exits! (very rude) -- webb
1514 */
1515 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001516x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001517{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001518 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519 STRCAT(IObuff, _("\nVim: Got X error\n"));
1520
1521 /* We cannot print a message and continue, because no X calls are allowed
1522 * here (causes my system to hang). Silently continuing might be an
1523 * alternative... */
1524 preserve_exit(); /* preserve files and exit */
1525
1526 return 0; /* NOTREACHED */
1527}
1528
1529/*
1530 * Another X Error handler, just used to check for errors.
1531 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001533x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534{
1535 got_x_error = TRUE;
1536 return 0;
1537}
1538
1539#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1540# if defined(HAVE_SETJMP_H)
1541/*
1542 * An X IO Error handler, used to catch error while opening the display.
1543 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001544static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001547x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548{
1549 /* This function should not return, it causes exit(). Longjump instead. */
1550 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001551# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001552 return 0; /* avoid the compiler complains about missing return value */
1553# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554}
1555# endif
1556
1557/*
1558 * An X IO Error handler, used to catch terminal errors.
1559 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001560static int x_IOerror_handler(Display *dpy);
1561static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001562static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001565x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566{
1567 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001568 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 x11_window = 0;
1570 x11_display = NULL;
1571 xterm_Shell = (Widget)0;
1572
1573 /* This function should not return, it causes exit(). Longjump instead. */
1574 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001575# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001576 return 0; /* avoid the compiler complains about missing return value */
1577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001579
1580/*
1581 * If the X11 connection was lost try to restore it.
1582 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001583 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001584 */
1585 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001586may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001587{
1588 if (xterm_dpy_was_reset)
1589 {
1590 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001591
1592# ifndef LESSTIF_VERSION
1593 /* This has been reported to avoid Vim getting stuck. */
1594 if (app_context != (XtAppContext)NULL)
1595 {
1596 XtDestroyApplicationContext(app_context);
1597 app_context = (XtAppContext)NULL;
1598 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1599 }
1600# endif
1601
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001602 setup_term_clip();
1603 get_x11_title(FALSE);
1604 }
1605}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606#endif
1607
1608/*
1609 * Return TRUE when connection to the X server is desired.
1610 */
1611 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001612x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614#if defined(FEAT_CLIENTSERVER)
1615 if (x_force_connect)
1616 return TRUE;
1617#endif
1618 if (x_no_connect)
1619 return FALSE;
1620
1621 /* Check for a match with "exclude:" from 'clipboard'. */
1622 if (clip_exclude_prog != NULL)
1623 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001624 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 return FALSE;
1626 }
1627 return TRUE;
1628}
1629
1630/*
1631 * Test if "dpy" and x11_window are valid by getting the window title.
1632 * I don't actually want it yet, so there may be a simpler call to use, but
1633 * this will cause the error handler x_error_check() to be called if anything
1634 * is wrong, such as the window pointer being invalid (as can happen when the
1635 * user changes his DISPLAY, but not his WINDOWID) -- webb
1636 */
1637 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001638test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639{
1640 int (*old_handler)();
1641 XTextProperty text_prop;
1642
1643 old_handler = XSetErrorHandler(x_error_check);
1644 got_x_error = FALSE;
1645 if (XGetWMName(dpy, x11_window, &text_prop))
1646 XFree((void *)text_prop.value);
1647 XSync(dpy, False);
1648 (void)XSetErrorHandler(old_handler);
1649
1650 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001651 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 return (got_x_error ? FAIL : OK);
1654}
1655#endif
1656
1657#ifdef FEAT_TITLE
1658
1659#ifdef FEAT_X11
1660
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001661static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662
1663/*
1664 * try to get x11 window and display
1665 *
1666 * return FAIL for failure, OK otherwise
1667 */
1668 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001669get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670{
1671 char *winid;
1672 static int result = -1;
1673#define XD_NONE 0 /* x11_display not set here */
1674#define XD_HERE 1 /* x11_display opened here */
1675#define XD_GUI 2 /* x11_display used from gui.dpy */
1676#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1677 static int x11_display_from = XD_NONE;
1678 static int did_set_error_handler = FALSE;
1679
1680 if (!did_set_error_handler)
1681 {
1682 /* X just exits if it finds an error otherwise! */
1683 (void)XSetErrorHandler(x_error_handler);
1684 did_set_error_handler = TRUE;
1685 }
1686
Bram Moolenaar9372a112005-12-06 19:59:18 +00001687#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 if (gui.in_use)
1689 {
1690 /*
1691 * If the X11 display was opened here before, for the window where Vim
1692 * was started, close that one now to avoid a memory leak.
1693 */
1694 if (x11_display_from == XD_HERE && x11_display != NULL)
1695 {
1696 XCloseDisplay(x11_display);
1697 x11_display_from = XD_NONE;
1698 }
1699 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1700 {
1701 x11_display_from = XD_GUI;
1702 return OK;
1703 }
1704 x11_display = NULL;
1705 return FAIL;
1706 }
1707 else if (x11_display_from == XD_GUI)
1708 {
1709 /* GUI must have stopped somehow, clear x11_display */
1710 x11_window = 0;
1711 x11_display = NULL;
1712 x11_display_from = XD_NONE;
1713 }
1714#endif
1715
1716 /* When started with the "-X" argument, don't try connecting. */
1717 if (!x_connect_to_server())
1718 return FAIL;
1719
1720 /*
1721 * If WINDOWID not set, should try another method to find out
1722 * what the current window number is. The only code I know for
1723 * this is very complicated.
1724 * We assume that zero is invalid for WINDOWID.
1725 */
1726 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1727 x11_window = (Window)atol(winid);
1728
1729#ifdef FEAT_XCLIPBOARD
1730 if (xterm_dpy != NULL && x11_window != 0)
1731 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001732 /* We may have checked it already, but Gnome terminal can move us to
1733 * another window, so we need to check every time. */
1734 if (x11_display_from != XD_XTERM)
1735 {
1736 /*
1737 * If the X11 display was opened here before, for the window where
1738 * Vim was started, close that one now to avoid a memory leak.
1739 */
1740 if (x11_display_from == XD_HERE && x11_display != NULL)
1741 XCloseDisplay(x11_display);
1742 x11_display = xterm_dpy;
1743 x11_display_from = XD_XTERM;
1744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 if (test_x11_window(x11_display) == FAIL)
1746 {
1747 /* probably bad $WINDOWID */
1748 x11_window = 0;
1749 x11_display = NULL;
1750 x11_display_from = XD_NONE;
1751 return FAIL;
1752 }
1753 return OK;
1754 }
1755#endif
1756
1757 if (x11_window == 0 || x11_display == NULL)
1758 result = -1;
1759
1760 if (result != -1) /* Have already been here and set this */
1761 return result; /* Don't do all these X calls again */
1762
1763 if (x11_window != 0 && x11_display == NULL)
1764 {
1765#ifdef SET_SIG_ALARM
1766 RETSIGTYPE (*sig_save)();
1767#endif
1768#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1769 struct timeval start_tv;
1770
1771 if (p_verbose > 0)
1772 gettimeofday(&start_tv, NULL);
1773#endif
1774
1775#ifdef SET_SIG_ALARM
1776 /*
1777 * Opening the Display may hang if the DISPLAY setting is wrong, or
1778 * the network connection is bad. Set an alarm timer to get out.
1779 */
1780 sig_alarm_called = FALSE;
1781 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1782 (RETSIGTYPE (*)())sig_alarm);
1783 alarm(2);
1784#endif
1785 x11_display = XOpenDisplay(NULL);
1786
1787#ifdef SET_SIG_ALARM
1788 alarm(0);
1789 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1790 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001791 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792#endif
1793 if (x11_display != NULL)
1794 {
1795# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1796 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001797 {
1798 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001800 verbose_leave();
1801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802# endif
1803 if (test_x11_window(x11_display) == FAIL)
1804 {
1805 /* Maybe window id is bad */
1806 x11_window = 0;
1807 XCloseDisplay(x11_display);
1808 x11_display = NULL;
1809 }
1810 else
1811 x11_display_from = XD_HERE;
1812 }
1813 }
1814 if (x11_window == 0 || x11_display == NULL)
1815 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001816
1817# ifdef FEAT_EVAL
1818 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1819# endif
1820
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 return (result = OK);
1822}
1823
1824/*
1825 * Determine original x11 Window Title
1826 */
1827 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001828get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001830 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831}
1832
1833/*
1834 * Determine original x11 Window icon
1835 */
1836 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001837get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838{
1839 int retval = FALSE;
1840
1841 retval = get_x11_thing(FALSE, test_only);
1842
1843 /* could not get old icon, use terminal name */
1844 if (oldicon == NULL && !test_only)
1845 {
1846 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001847 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001849 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 }
1851
1852 return retval;
1853}
1854
1855 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001856get_x11_thing(
1857 int get_title, /* get title string */
1858 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859{
1860 XTextProperty text_prop;
1861 int retval = FALSE;
1862 Status status;
1863
1864 if (get_x11_windis() == OK)
1865 {
1866 /* Get window/icon name if any */
1867 if (get_title)
1868 status = XGetWMName(x11_display, x11_window, &text_prop);
1869 else
1870 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1871
1872 /*
1873 * If terminal is xterm, then x11_window may be a child window of the
1874 * outer xterm window that actually contains the window/icon name, so
1875 * keep traversing up the tree until a window with a title/icon is
1876 * found.
1877 */
1878 /* Previously this was only done for xterm and alikes. I don't see a
1879 * reason why it would fail for other terminal emulators.
1880 * if (term_is_xterm) */
1881 {
1882 Window root;
1883 Window parent;
1884 Window win = x11_window;
1885 Window *children;
1886 unsigned int num_children;
1887
1888 while (!status || text_prop.value == NULL)
1889 {
1890 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1891 &num_children))
1892 break;
1893 if (children)
1894 XFree((void *)children);
1895 if (parent == root || parent == 0)
1896 break;
1897
1898 win = parent;
1899 if (get_title)
1900 status = XGetWMName(x11_display, win, &text_prop);
1901 else
1902 status = XGetWMIconName(x11_display, win, &text_prop);
1903 }
1904 }
1905 if (status && text_prop.value != NULL)
1906 {
1907 retval = TRUE;
1908 if (!test_only)
1909 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001910#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1911 if (text_prop.encoding == XA_STRING
1912# ifdef FEAT_MBYTE
1913 && !has_mbyte
1914# endif
1915 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917#endif
1918 if (get_title)
1919 oldtitle = vim_strsave((char_u *)text_prop.value);
1920 else
1921 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001922#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
1924 else
1925 {
1926 char **cl;
1927 Status transform_status;
1928 int n = 0;
1929
1930 transform_status = XmbTextPropertyToTextList(x11_display,
1931 &text_prop,
1932 &cl, &n);
1933 if (transform_status >= Success && n > 0 && cl[0])
1934 {
1935 if (get_title)
1936 oldtitle = vim_strsave((char_u *) cl[0]);
1937 else
1938 oldicon = vim_strsave((char_u *) cl[0]);
1939 XFreeStringList(cl);
1940 }
1941 else
1942 {
1943 if (get_title)
1944 oldtitle = vim_strsave((char_u *)text_prop.value);
1945 else
1946 oldicon = vim_strsave((char_u *)text_prop.value);
1947 }
1948 }
1949#endif
1950 }
1951 XFree((void *)text_prop.value);
1952 }
1953 }
1954 return retval;
1955}
1956
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001957/* Xutf8 functions are not avaialble on older systems. Note that on some
1958 * systems X_HAVE_UTF8_STRING may be defined in a header file but
1959 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
1960 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001962# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963# define USE_UTF8_STRING
1964# endif
1965#endif
1966
1967/*
1968 * Set x11 Window Title
1969 *
1970 * get_x11_windis() must be called before this and have returned OK
1971 */
1972 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001973set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974{
1975 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1976 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1977 * supported everywhere and STRING doesn't work for multi-byte titles.
1978 */
1979#ifdef USE_UTF8_STRING
1980 if (enc_utf8)
1981 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1982 NULL, NULL, 0, NULL, NULL, NULL);
1983 else
1984#endif
1985 {
1986#if XtSpecificationRelease >= 4
1987# ifdef FEAT_XFONTSET
1988 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1989 NULL, NULL, 0, NULL, NULL, NULL);
1990# else
1991 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001992 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993
1994 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001995 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 XSetWMProperties(x11_display, x11_window, &text_prop,
1997 NULL, NULL, 0, NULL, NULL, NULL);
1998# endif
1999#else
2000 XStoreName(x11_display, x11_window, (char *)title);
2001#endif
2002 }
2003 XFlush(x11_display);
2004}
2005
2006/*
2007 * Set x11 Window icon
2008 *
2009 * get_x11_windis() must be called before this and have returned OK
2010 */
2011 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002012set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013{
2014 /* See above for comments about using X*SetWMProperties(). */
2015#ifdef USE_UTF8_STRING
2016 if (enc_utf8)
2017 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2018 NULL, 0, NULL, NULL, NULL);
2019 else
2020#endif
2021 {
2022#if XtSpecificationRelease >= 4
2023# ifdef FEAT_XFONTSET
2024 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2025 NULL, 0, NULL, NULL, NULL);
2026# else
2027 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002028 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002030 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2032 NULL, 0, NULL, NULL, NULL);
2033# endif
2034#else
2035 XSetIconName(x11_display, x11_window, (char *)icon);
2036#endif
2037 }
2038 XFlush(x11_display);
2039}
2040
2041#else /* FEAT_X11 */
2042
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 static int
2044get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002045 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046{
2047 return FALSE;
2048}
2049
2050 static int
2051get_x11_icon(test_only)
2052 int test_only;
2053{
2054 if (!test_only)
2055 {
2056 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002057 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002059 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
2061 return FALSE;
2062}
2063
2064#endif /* FEAT_X11 */
2065
2066 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002067mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068{
2069 return get_x11_title(TRUE);
2070}
2071
2072 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002073mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074{
2075 return get_x11_icon(TRUE);
2076}
2077
2078/*
2079 * Set the window title and icon.
2080 */
2081 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002082mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083{
2084 int type = 0;
2085 static int recursive = 0;
2086
2087 if (T_NAME == NULL) /* no terminal name (yet) */
2088 return;
2089 if (title == NULL && icon == NULL) /* nothing to do */
2090 return;
2091
2092 /* When one of the X11 functions causes a deadly signal, we get here again
2093 * recursively. Avoid hanging then (something is probably locked). */
2094 if (recursive)
2095 return;
2096 ++recursive;
2097
2098 /*
2099 * if the window ID and the display is known, we may use X11 calls
2100 */
2101#ifdef FEAT_X11
2102 if (get_x11_windis() == OK)
2103 type = 1;
2104#else
2105# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2106 if (gui.in_use)
2107 type = 1;
2108# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109#endif
2110
2111 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002112 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 * than x11 calls, because the x11 calls don't always work
2114 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 if ((type || *T_TS != NUL) && title != NULL)
2116 {
2117 if (oldtitle == NULL
2118#ifdef FEAT_GUI
2119 && !gui.in_use
2120#endif
2121 ) /* first call but not in GUI, save title */
2122 (void)get_x11_title(FALSE);
2123
2124 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2125 term_settitle(title);
2126#ifdef FEAT_X11
2127 else
2128# ifdef FEAT_GUI_GTK
2129 if (!gui.in_use) /* don't do this if GTK+ is running */
2130# endif
2131 set_x11_title(title); /* x11 */
2132#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002133#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002134 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2135 else
2136 gui_mch_settitle(title, icon);
2137#endif
2138 did_set_title = TRUE;
2139 }
2140
2141 if ((type || *T_CIS != NUL) && icon != NULL)
2142 {
2143 if (oldicon == NULL
2144#ifdef FEAT_GUI
2145 && !gui.in_use
2146#endif
2147 ) /* first call, save icon */
2148 get_x11_icon(FALSE);
2149
2150 if (*T_CIS != NUL)
2151 {
2152 out_str(T_CIS); /* set icon start */
2153 out_str_nf(icon);
2154 out_str(T_CIE); /* set icon end */
2155 out_flush();
2156 }
2157#ifdef FEAT_X11
2158 else
2159# ifdef FEAT_GUI_GTK
2160 if (!gui.in_use) /* don't do this if GTK+ is running */
2161# endif
2162 set_x11_icon(icon); /* x11 */
2163#endif
2164 did_set_icon = TRUE;
2165 }
2166 --recursive;
2167}
2168
2169/*
2170 * Restore the window/icon title.
2171 * "which" is one of:
2172 * 1 only restore title
2173 * 2 only restore icon
2174 * 3 restore title and icon
2175 */
2176 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002177mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178{
2179 /* only restore the title or icon when it has been set */
2180 mch_settitle(((which & 1) && did_set_title) ?
2181 (oldtitle ? oldtitle : p_titleold) : NULL,
2182 ((which & 2) && did_set_icon) ? oldicon : NULL);
2183}
2184
2185#endif /* FEAT_TITLE */
2186
2187/*
2188 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002189 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 */
2191 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002192vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193{
2194 if (name == NULL)
2195 return FALSE;
2196 return (STRNICMP(name, "xterm", 5) == 0
2197 || STRNICMP(name, "nxterm", 6) == 0
2198 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002199 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 || STRNICMP(name, "rxvt", 4) == 0
2201 || STRCMP(name, "builtin_xterm") == 0);
2202}
2203
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002204#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2205/*
2206 * Return TRUE if "name" appears to be that of a terminal
2207 * known to support the xterm-style mouse protocol.
2208 * Relies on term_is_xterm having been set to its correct value.
2209 */
2210 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002211use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002212{
2213 return (name != NULL
2214 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2215}
2216#endif
2217
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2219/*
2220 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2221 * Return 1 for "xterm".
2222 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002223 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002224 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 */
2226 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002227use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002229 if (ttym_flags == TTYM_SGR)
2230 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002231 if (ttym_flags == TTYM_URXVT)
2232 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002233 if (ttym_flags == TTYM_XTERM2)
2234 return 2;
2235 if (ttym_flags == TTYM_XTERM)
2236 return 1;
2237 return 0;
2238}
2239#endif
2240
2241 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002242vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243{
2244 if (name == NULL)
2245 return FALSE;
2246 return (STRNICMP(name, "iris-ansi", 9) == 0
2247 || STRCMP(name, "builtin_iris-ansi") == 0);
2248}
2249
2250 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002251vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252{
2253 if (name == NULL)
2254 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002255 /* catch VT100 - VT5xx */
2256 return ((STRNICMP(name, "vt", 2) == 0
2257 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 || STRCMP(name, "builtin_vt320") == 0);
2259}
2260
2261/*
2262 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2263 * This should include all windowed terminal emulators.
2264 */
2265 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002266vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267{
2268 if (name == NULL)
2269 return FALSE;
2270 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2271 return TRUE;
2272 return ( STRNICMP(name, "hpterm", 6) == 0
2273 || STRNICMP(name, "sun-cmd", 7) == 0
2274 || STRNICMP(name, "screen", 6) == 0
2275 || STRNICMP(name, "dtterm", 6) == 0);
2276}
2277
2278/*
2279 * Insert user name in s[len].
2280 * Return OK if a name found.
2281 */
2282 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002283mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284{
2285#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002286 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 return OK;
2288#else
2289 return mch_get_uname(getuid(), s, len);
2290#endif
2291}
2292
2293/*
2294 * Insert user name for "uid" in s[len].
2295 * Return OK if a name found.
2296 */
2297 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002298mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299{
2300#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2301 struct passwd *pw;
2302
2303 if ((pw = getpwuid(uid)) != NULL
2304 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2305 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002306 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 return OK;
2308 }
2309#endif
2310 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2311 return FAIL; /* a number is not a name */
2312}
2313
2314/*
2315 * Insert host name is s[len].
2316 */
2317
2318#ifdef HAVE_SYS_UTSNAME_H
2319 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002320mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
2322 struct utsname vutsname;
2323
2324 if (uname(&vutsname) < 0)
2325 *s = NUL;
2326 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002327 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328}
2329#else /* HAVE_SYS_UTSNAME_H */
2330
2331# ifdef HAVE_SYS_SYSTEMINFO_H
2332# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2333# endif
2334
2335 void
2336mch_get_host_name(s, len)
2337 char_u *s;
2338 int len;
2339{
2340# ifdef VAXC
2341 vaxc$gethostname((char *)s, len);
2342# else
2343 gethostname((char *)s, len);
2344# endif
2345 s[len - 1] = NUL; /* make sure it's terminated */
2346}
2347#endif /* HAVE_SYS_UTSNAME_H */
2348
2349/*
2350 * return process ID
2351 */
2352 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002353mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354{
2355 return (long)getpid();
2356}
2357
2358#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002359static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360
2361 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002362strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363{
2364 extern int sys_nerr;
2365 extern char *sys_errlist[];
2366 static char er[20];
2367
2368 if (err > 0 && err < sys_nerr)
2369 return (sys_errlist[err]);
2370 sprintf(er, "Error %d", err);
2371 return er;
2372}
2373#endif
2374
2375/*
2376 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2377 * Return OK for success, FAIL for failure.
2378 */
2379 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002380mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381{
2382#if defined(USE_GETCWD)
2383 if (getcwd((char *)buf, len) == NULL)
2384 {
2385 STRCPY(buf, strerror(errno));
2386 return FAIL;
2387 }
2388 return OK;
2389#else
2390 return (getwd((char *)buf) != NULL ? OK : FAIL);
2391#endif
2392}
2393
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002395 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 *
2397 * return FAIL for failure, OK for success
2398 */
2399 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002400mch_FullName(
2401 char_u *fname,
2402 char_u *buf,
2403 int len,
2404 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405{
2406 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002407#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 int fd = -1;
2409 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002410#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 char_u olddir[MAXPATHL];
2412 char_u *p;
2413 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002414#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002415 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2416 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002417#endif
2418
Bram Moolenaar38323e42007-03-06 19:22:53 +00002419#ifdef VMS
2420 fname = vms_fixfilename(fname);
2421#endif
2422
Bram Moolenaara2442432007-04-26 14:26:37 +00002423#ifdef __CYGWIN__
2424 /*
2425 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2426 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002427# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002428 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2429 * a forward slash. */
2430 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2431 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002432# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002433 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002434# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002435 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002436#endif
2437
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002438 /* Expand it if forced or not an absolute path.
2439 * Do not do it for "/file", the result is always "/". */
2440 if ((force || !mch_isFullName(fname))
2441 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 {
2443 /*
2444 * If the file name has a path, change to that directory for a moment,
2445 * and then do the getwd() (and get back to where we were).
2446 * This will get the correct path name with "../" things.
2447 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002448 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002450#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 /*
2452 * Use fchdir() if possible, it's said to be faster and more
2453 * reliable. But on SunOS 4 it might not work. Check this by
2454 * doing a fchdir() right now.
2455 */
2456 if (!dont_fchdir)
2457 {
2458 fd = open(".", O_RDONLY | O_EXTRA, 0);
2459 if (fd >= 0 && fchdir(fd) < 0)
2460 {
2461 close(fd);
2462 fd = -1;
2463 dont_fchdir = TRUE; /* don't try again */
2464 }
2465 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002466#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467
2468 /* Only change directory when we are sure we can return to where
2469 * we are now. After doing "su" chdir(".") might not work. */
2470 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002471#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002473#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 (mch_dirname(olddir, MAXPATHL) == FAIL
2475 || mch_chdir((char *)olddir) != 0))
2476 {
2477 p = NULL; /* can't get current dir: don't chdir */
2478 retval = FAIL;
2479 }
2480 else
2481 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 /* The directory is copied into buf[], to be able to remove
2483 * the file name without changing it (could be a string in
2484 * read-only memory) */
2485 if (p - fname >= len)
2486 retval = FAIL;
2487 else
2488 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002489 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 if (mch_chdir((char *)buf))
2491 retval = FAIL;
2492 else
2493 fname = p + 1;
2494 *buf = NUL;
2495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 }
2497 }
2498 if (mch_dirname(buf, len) == FAIL)
2499 {
2500 retval = FAIL;
2501 *buf = NUL;
2502 }
2503 if (p != NULL)
2504 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002505#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506 if (fd >= 0)
2507 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002508 if (p_verbose >= 5)
2509 {
2510 verbose_enter();
2511 MSG("fchdir() to previous dir");
2512 verbose_leave();
2513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 l = fchdir(fd);
2515 close(fd);
2516 }
2517 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 l = mch_chdir((char *)olddir);
2520 if (l != 0)
2521 EMSG(_(e_prev_dir));
2522 }
2523
2524 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002525 if (l >= len - 1)
2526 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002527#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002528 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002530 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002533
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002535 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 return FAIL;
2537
2538 /* Do not append ".", "/dir/." is equal to "/dir". */
2539 if (STRCMP(fname, ".") != 0)
2540 STRCAT(buf, fname);
2541
2542 return OK;
2543}
2544
2545/*
2546 * Return TRUE if "fname" does not depend on the current directory.
2547 */
2548 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002549mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550{
2551#ifdef __EMX__
2552 return _fnisabs(fname);
2553#else
2554# ifdef VMS
2555 return ( fname[0] == '/' || fname[0] == '.' ||
2556 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2557 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2558 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2559# else
2560 return (*fname == '/' || *fname == '~');
2561# endif
2562#endif
2563}
2564
Bram Moolenaar24552be2005-12-10 20:17:30 +00002565#if defined(USE_FNAME_CASE) || defined(PROTO)
2566/*
2567 * Set the case of the file name, if it already exists. This will cause the
2568 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002569 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002570 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002571 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002572fname_case(
2573 char_u *name,
2574 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002575{
2576 struct stat st;
2577 char_u *slash, *tail;
2578 DIR *dirp;
2579 struct dirent *dp;
2580
2581 if (lstat((char *)name, &st) >= 0)
2582 {
2583 /* Open the directory where the file is located. */
2584 slash = vim_strrchr(name, '/');
2585 if (slash == NULL)
2586 {
2587 dirp = opendir(".");
2588 tail = name;
2589 }
2590 else
2591 {
2592 *slash = NUL;
2593 dirp = opendir((char *)name);
2594 *slash = '/';
2595 tail = slash + 1;
2596 }
2597
2598 if (dirp != NULL)
2599 {
2600 while ((dp = readdir(dirp)) != NULL)
2601 {
2602 /* Only accept names that differ in case and are the same byte
2603 * length. TODO: accept different length name. */
2604 if (STRICMP(tail, dp->d_name) == 0
2605 && STRLEN(tail) == STRLEN(dp->d_name))
2606 {
2607 char_u newname[MAXPATHL + 1];
2608 struct stat st2;
2609
2610 /* Verify the inode is equal. */
2611 vim_strncpy(newname, name, MAXPATHL);
2612 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2613 MAXPATHL - (tail - name));
2614 if (lstat((char *)newname, &st2) >= 0
2615 && st.st_ino == st2.st_ino
2616 && st.st_dev == st2.st_dev)
2617 {
2618 STRCPY(tail, dp->d_name);
2619 break;
2620 }
2621 }
2622 }
2623
2624 closedir(dirp);
2625 }
2626 }
2627}
2628#endif
2629
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630/*
2631 * Get file permissions for 'name'.
2632 * Returns -1 when it doesn't exist.
2633 */
2634 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002635mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636{
2637 struct stat statb;
2638
2639 /* Keep the #ifdef outside of stat(), it may be a macro. */
2640#ifdef VMS
2641 if (stat((char *)vms_fixfilename(name), &statb))
2642#else
2643 if (stat((char *)name, &statb))
2644#endif
2645 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002646#ifdef __INTERIX
2647 /* The top bit makes the value negative, which means the file doesn't
2648 * exist. Remove the bit, we don't use it. */
2649 return statb.st_mode & ~S_ADDACE;
2650#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002652#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653}
2654
2655/*
2656 * set file permission for 'name' to 'perm'
2657 *
2658 * return FAIL for failure, OK otherwise
2659 */
2660 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002661mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662{
2663 return (chmod((char *)
2664#ifdef VMS
2665 vms_fixfilename(name),
2666#else
2667 name,
2668#endif
2669 (mode_t)perm) == 0 ? OK : FAIL);
2670}
2671
2672#if defined(HAVE_ACL) || defined(PROTO)
2673# ifdef HAVE_SYS_ACL_H
2674# include <sys/acl.h>
2675# endif
2676# ifdef HAVE_SYS_ACCESS_H
2677# include <sys/access.h>
2678# endif
2679
2680# ifdef HAVE_SOLARIS_ACL
2681typedef struct vim_acl_solaris_T {
2682 int acl_cnt;
2683 aclent_t *acl_entry;
2684} vim_acl_solaris_T;
2685# endif
2686
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002687#if defined(HAVE_SELINUX) || defined(PROTO)
2688/*
2689 * Copy security info from "from_file" to "to_file".
2690 */
2691 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002692mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002693{
2694 if (from_file == NULL)
2695 return;
2696
2697 if (selinux_enabled == -1)
2698 selinux_enabled = is_selinux_enabled();
2699
2700 if (selinux_enabled > 0)
2701 {
2702 security_context_t from_context = NULL;
2703 security_context_t to_context = NULL;
2704
2705 if (getfilecon((char *)from_file, &from_context) < 0)
2706 {
2707 /* If the filesystem doesn't support extended attributes,
2708 the original had no special security context and the
2709 target cannot have one either. */
2710 if (errno == EOPNOTSUPP)
2711 return;
2712
2713 MSG_PUTS(_("\nCould not get security context for "));
2714 msg_outtrans(from_file);
2715 msg_putchar('\n');
2716 return;
2717 }
2718 if (getfilecon((char *)to_file, &to_context) < 0)
2719 {
2720 MSG_PUTS(_("\nCould not get security context for "));
2721 msg_outtrans(to_file);
2722 msg_putchar('\n');
2723 freecon (from_context);
2724 return ;
2725 }
2726 if (strcmp(from_context, to_context) != 0)
2727 {
2728 if (setfilecon((char *)to_file, from_context) < 0)
2729 {
2730 MSG_PUTS(_("\nCould not set security context for "));
2731 msg_outtrans(to_file);
2732 msg_putchar('\n');
2733 }
2734 }
2735 freecon(to_context);
2736 freecon(from_context);
2737 }
2738}
2739#endif /* HAVE_SELINUX */
2740
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002741#if defined(HAVE_SMACK) && !defined(PROTO)
2742/*
2743 * Copy security info from "from_file" to "to_file".
2744 */
2745 void
2746mch_copy_sec(from_file, to_file)
2747 char_u *from_file;
2748 char_u *to_file;
2749{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002750 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002751 {
2752 XATTR_NAME_SMACK,
2753 XATTR_NAME_SMACKEXEC,
2754 XATTR_NAME_SMACKMMAP
2755 };
2756
2757 char buffer[SMACK_LABEL_LEN];
2758 const char *name;
2759 int index;
2760 int ret;
2761 ssize_t size;
2762
2763 if (from_file == NULL)
2764 return;
2765
2766 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2767 / sizeof(smack_copied_attributes)[0]) ; index++)
2768 {
2769 /* get the name of the attribute to copy */
2770 name = smack_copied_attributes[index];
2771
2772 /* get the value of the attribute in buffer */
2773 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2774 if (size >= 0)
2775 {
2776 /* copy the attribute value of buffer */
2777 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2778 if (ret < 0)
2779 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002780 vim_snprintf((char *)IObuff, IOSIZE,
2781 _("Could not set security context %s for %s"),
2782 name, to_file);
2783 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002784 msg_putchar('\n');
2785 }
2786 }
2787 else
2788 {
2789 /* what reason of not having the attribute value? */
2790 switch (errno)
2791 {
2792 case ENOTSUP:
2793 /* extended attributes aren't supported or enabled */
2794 /* should a message be echoed? not sure... */
2795 return; /* leave because it isn't usefull to continue */
2796
2797 case ERANGE:
2798 default:
2799 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002800 vim_snprintf((char *)IObuff, IOSIZE,
2801 _("Could not get security context %s for %s. Removing it!"),
2802 name, from_file);
2803 msg_puts(IObuff);
2804 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002805 /* FALLTHROUGH to remove the attribute */
2806
2807 case ENODATA:
2808 /* no attribute of this name */
2809 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002810 /* Silently ignore errors, apparently this happens when
2811 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002812 break;
2813 }
2814 }
2815 }
2816}
2817#endif /* HAVE_SMACK */
2818
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819/*
2820 * Return a pointer to the ACL of file "fname" in allocated memory.
2821 * Return NULL if the ACL is not available for whatever reason.
2822 */
2823 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002824mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825{
2826 vim_acl_T ret = NULL;
2827#ifdef HAVE_POSIX_ACL
2828 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2829#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002830#ifdef HAVE_SOLARIS_ZFS_ACL
2831 acl_t *aclent;
2832
2833 if (acl_get((char *)fname, 0, &aclent) < 0)
2834 return NULL;
2835 ret = (vim_acl_T)aclent;
2836#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837#ifdef HAVE_SOLARIS_ACL
2838 vim_acl_solaris_T *aclent;
2839
2840 aclent = malloc(sizeof(vim_acl_solaris_T));
2841 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2842 {
2843 free(aclent);
2844 return NULL;
2845 }
2846 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2847 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2848 {
2849 free(aclent->acl_entry);
2850 free(aclent);
2851 return NULL;
2852 }
2853 ret = (vim_acl_T)aclent;
2854#else
2855#if defined(HAVE_AIX_ACL)
2856 int aclsize;
2857 struct acl *aclent;
2858
2859 aclsize = sizeof(struct acl);
2860 aclent = malloc(aclsize);
2861 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2862 {
2863 if (errno == ENOSPC)
2864 {
2865 aclsize = aclent->acl_len;
2866 aclent = realloc(aclent, aclsize);
2867 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2868 {
2869 free(aclent);
2870 return NULL;
2871 }
2872 }
2873 else
2874 {
2875 free(aclent);
2876 return NULL;
2877 }
2878 }
2879 ret = (vim_acl_T)aclent;
2880#endif /* HAVE_AIX_ACL */
2881#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002882#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883#endif /* HAVE_POSIX_ACL */
2884 return ret;
2885}
2886
2887/*
2888 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2889 */
2890 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002891mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892{
2893 if (aclent == NULL)
2894 return;
2895#ifdef HAVE_POSIX_ACL
2896 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2897#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002898#ifdef HAVE_SOLARIS_ZFS_ACL
2899 acl_set((char *)fname, (acl_t *)aclent);
2900#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901#ifdef HAVE_SOLARIS_ACL
2902 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2903 ((vim_acl_solaris_T *)aclent)->acl_entry);
2904#else
2905#ifdef HAVE_AIX_ACL
2906 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2907#endif /* HAVE_AIX_ACL */
2908#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002909#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910#endif /* HAVE_POSIX_ACL */
2911}
2912
2913 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002914mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915{
2916 if (aclent == NULL)
2917 return;
2918#ifdef HAVE_POSIX_ACL
2919 acl_free((acl_t)aclent);
2920#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002921#ifdef HAVE_SOLARIS_ZFS_ACL
2922 acl_free((acl_t *)aclent);
2923#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924#ifdef HAVE_SOLARIS_ACL
2925 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2926 free(aclent);
2927#else
2928#ifdef HAVE_AIX_ACL
2929 free(aclent);
2930#endif /* HAVE_AIX_ACL */
2931#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002932#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933#endif /* HAVE_POSIX_ACL */
2934}
2935#endif
2936
2937/*
2938 * Set hidden flag for "name".
2939 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002941mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942{
2943 /* can't hide a file */
2944}
2945
2946/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002947 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 * return FALSE if "name" is not a directory
2949 * return FALSE for error
2950 */
2951 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002952mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953{
2954 struct stat statb;
2955
2956 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2957 return FALSE;
2958 if (stat((char *)name, &statb))
2959 return FALSE;
2960#ifdef _POSIX_SOURCE
2961 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2962#else
2963 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2964#endif
2965}
2966
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002967/*
2968 * return TRUE if "name" is a directory, NOT a symlink to a directory
2969 * return FALSE if "name" is not a directory
2970 * return FALSE for error
2971 */
2972 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002973mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01002974{
2975 struct stat statb;
2976
2977 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2978 return FALSE;
2979 if (lstat((char *)name, &statb))
2980 return FALSE;
2981#ifdef _POSIX_SOURCE
2982 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2983#else
2984 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2985#endif
2986}
2987
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002988static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989
2990/*
2991 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2992 */
2993 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01002994executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995{
2996 struct stat st;
2997
2998 if (stat((char *)name, &st))
2999 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003000#ifdef VMS
3001 /* Like on Unix system file can have executable rights but not necessarily
3002 * be an executable, but on Unix is not a default for an ordianry file to
3003 * have an executable flag - on VMS it is in most cases.
3004 * Therefore, this check does not have any sense - let keep us to the
3005 * conventions instead:
3006 * *.COM and *.EXE files are the executables - the rest are not. This is
3007 * not ideal but better then it was.
3008 */
3009 int vms_executable = 0;
3010 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3011 {
3012 if (strstr(vms_tolower((char*)name),".exe") != NULL
3013 || strstr(vms_tolower((char*)name),".com")!= NULL)
3014 vms_executable = 1;
3015 }
3016 return vms_executable;
3017#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003019#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020}
3021
3022/*
3023 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003024 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 * Return -1 if unknown.
3026 */
3027 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003028mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029{
3030 char_u *buf;
3031 char_u *p, *e;
3032 int retval;
3033
Bram Moolenaarb5971142015-03-21 17:32:19 +01003034 /* When "use_path" is false and if it's an absolute or relative path don't
3035 * need to use $PATH. */
3036 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3037 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003038 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003039 /* There must be a path separator, files in the current directory
3040 * can't be executed. */
3041 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003042 {
3043 if (path != NULL)
3044 {
3045 if (name[0] == '.')
3046 *path = FullName_save(name, TRUE);
3047 else
3048 *path = vim_strsave(name);
3049 }
3050 return TRUE;
3051 }
3052 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003053 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
3055 p = (char_u *)getenv("PATH");
3056 if (p == NULL || *p == NUL)
3057 return -1;
3058 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3059 if (buf == NULL)
3060 return -1;
3061
3062 /*
3063 * Walk through all entries in $PATH to check if "name" exists there and
3064 * is an executable file.
3065 */
3066 for (;;)
3067 {
3068 e = (char_u *)strchr((char *)p, ':');
3069 if (e == NULL)
3070 e = p + STRLEN(p);
3071 if (e - p <= 1) /* empty entry means current dir */
3072 STRCPY(buf, "./");
3073 else
3074 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003075 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076 add_pathsep(buf);
3077 }
3078 STRCAT(buf, name);
3079 retval = executable_file(buf);
3080 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003081 {
3082 if (path != NULL)
3083 {
3084 if (buf[0] == '.')
3085 *path = FullName_save(buf, TRUE);
3086 else
3087 *path = vim_strsave(buf);
3088 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
3092 if (*e != ':')
3093 break;
3094 p = e + 1;
3095 }
3096
3097 vim_free(buf);
3098 return retval;
3099}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100
3101/*
3102 * Check what "name" is:
3103 * NODE_NORMAL: file or directory (or doesn't exist)
3104 * NODE_WRITABLE: writable device, socket, fifo, etc.
3105 * NODE_OTHER: non-writable things
3106 */
3107 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003108mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109{
3110 struct stat st;
3111
3112 if (stat((char *)name, &st))
3113 return NODE_NORMAL;
3114 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3115 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3117 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 /* Everything else is writable? */
3119 return NODE_WRITABLE;
3120}
3121
3122 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003123mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124{
3125#ifdef HAVE_CHECK_STACK_GROWTH
3126 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 check_stack_growth((char *)&i);
3129
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003130# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 get_stack_limit();
3132# endif
3133
3134#endif
3135
3136 /*
3137 * Setup an alternative stack for signals. Helps to catch signals when
3138 * running out of stack space.
3139 * Use of sigaltstack() is preferred, it's more portable.
3140 * Ignore any errors.
3141 */
3142#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003143 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 init_signal_stack();
3145#endif
3146}
3147
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003148#if defined(EXITFREE) || defined(PROTO)
3149 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003150mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003151{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003152# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3153 if (clip_star.owned)
3154 clip_lose_selection(&clip_star);
3155 if (clip_plus.owned)
3156 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003157# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003158# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003159 if (xterm_Shell != (Widget)0)
3160 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003161# ifndef LESSTIF_VERSION
3162 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003163 if (xterm_dpy != NULL)
3164 XtCloseDisplay(xterm_dpy);
3165 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003166 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003167 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003168# ifdef FEAT_X11
3169 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3170# endif
3171 }
3172# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003173# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003174# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003175 if (x11_display != NULL
3176# ifdef FEAT_XCLIPBOARD
3177 && x11_display != xterm_dpy
3178# endif
3179 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003180 XCloseDisplay(x11_display);
3181# endif
3182# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3183 vim_free(signal_stack);
3184 signal_stack = NULL;
3185# endif
3186# ifdef FEAT_TITLE
3187 vim_free(oldtitle);
3188 vim_free(oldicon);
3189# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003190}
3191#endif
3192
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003193static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194
3195/*
3196 * Output a newline when exiting.
3197 * Make sure the newline goes to the same stream as the text.
3198 */
3199 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003200exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003202 if (silent_mode)
3203 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 if (newline_on_exit || msg_didout)
3205 {
3206 if (msg_use_printf())
3207 {
3208 if (info_message)
3209 mch_msg("\n");
3210 else
3211 mch_errmsg("\r\n");
3212 }
3213 else
3214 out_char('\n');
3215 }
3216 else
3217 {
3218 restore_cterm_colors(); /* get original colors back */
3219 msg_clr_eos_force(); /* clear the rest of the display */
3220 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3221 }
3222}
3223
3224 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003225mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226{
3227 exiting = TRUE;
3228
3229#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3230 x11_export_final_selection();
3231#endif
3232
3233#ifdef FEAT_GUI
3234 if (!gui.in_use)
3235#endif
3236 {
3237 settmode(TMODE_COOK);
3238#ifdef FEAT_TITLE
3239 mch_restore_title(3); /* restore xterm title and icon name */
3240#endif
3241 /*
3242 * When t_ti is not empty but it doesn't cause swapping terminal
3243 * pages, need to output a newline when msg_didout is set. But when
3244 * t_ti does swap pages it should not go to the shell page. Do this
3245 * before stoptermcap().
3246 */
3247 if (swapping_screen() && !newline_on_exit)
3248 exit_scroll();
3249
3250 /* Stop termcap: May need to check for T_CRV response, which
3251 * requires RAW mode. */
3252 stoptermcap();
3253
3254 /*
3255 * A newline is only required after a message in the alternate screen.
3256 * This is set to TRUE by wait_return().
3257 */
3258 if (!swapping_screen() || newline_on_exit)
3259 exit_scroll();
3260
3261 /* Cursor may have been switched off without calling starttermcap()
3262 * when doing "vim -u vimrc" and vimrc contains ":q". */
3263 if (full_screen)
3264 cursor_on();
3265 }
3266 out_flush();
3267 ml_close_all(TRUE); /* remove all memfiles */
3268 may_core_dump();
3269#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003270 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 gui_exit(r);
3272#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003273
Bram Moolenaar56718732006-03-15 22:53:57 +00003274#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003275 mac_conv_cleanup();
3276#endif
3277
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278#ifdef __QNX__
3279 /* A core dump won't be created if the signal handler
3280 * doesn't return, so we can't call exit() */
3281 if (deadly_signal != 0)
3282 return;
3283#endif
3284
Bram Moolenaar009b2592004-10-24 19:18:58 +00003285#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003286 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003287#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003288
3289#ifdef EXITFREE
3290 free_all_mem();
3291#endif
3292
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 exit(r);
3294}
3295
3296 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003297may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298{
3299 if (deadly_signal != 0)
3300 {
3301 signal(deadly_signal, SIG_DFL);
3302 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3303 }
3304}
3305
3306#ifndef VMS
3307
3308 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003309mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310{
3311 static int first = TRUE;
3312
3313 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3314#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3315 /*
3316 * for "new" tty systems
3317 */
3318# ifdef HAVE_TERMIOS_H
3319 static struct termios told;
3320 struct termios tnew;
3321# else
3322 static struct termio told;
3323 struct termio tnew;
3324# endif
3325
3326 if (first)
3327 {
3328 first = FALSE;
3329# if defined(HAVE_TERMIOS_H)
3330 tcgetattr(read_cmd_fd, &told);
3331# else
3332 ioctl(read_cmd_fd, TCGETA, &told);
3333# endif
3334 }
3335
3336 tnew = told;
3337 if (tmode == TMODE_RAW)
3338 {
3339 /*
3340 * ~ICRNL enables typing ^V^M
3341 */
3342 tnew.c_iflag &= ~ICRNL;
3343 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3344# if defined(IEXTEN) && !defined(__MINT__)
3345 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3346 /* but it breaks function keys on MINT */
3347# endif
3348 );
3349# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3350 tnew.c_oflag &= ~ONLCR;
3351# endif
3352 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3353 tnew.c_cc[VTIME] = 0; /* don't wait */
3354 }
3355 else if (tmode == TMODE_SLEEP)
3356 tnew.c_lflag &= ~(ECHO);
3357
3358# if defined(HAVE_TERMIOS_H)
3359 {
3360 int n = 10;
3361
3362 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3363 * few times. */
3364 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3365 && errno == EINTR && n > 0)
3366 --n;
3367 }
3368# else
3369 ioctl(read_cmd_fd, TCSETA, &tnew);
3370# endif
3371
3372#else
3373
3374 /*
3375 * for "old" tty systems
3376 */
3377# ifndef TIOCSETN
3378# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3379# endif
3380 static struct sgttyb ttybold;
3381 struct sgttyb ttybnew;
3382
3383 if (first)
3384 {
3385 first = FALSE;
3386 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3387 }
3388
3389 ttybnew = ttybold;
3390 if (tmode == TMODE_RAW)
3391 {
3392 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3393 ttybnew.sg_flags |= RAW;
3394 }
3395 else if (tmode == TMODE_SLEEP)
3396 ttybnew.sg_flags &= ~(ECHO);
3397 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3398#endif
3399 curr_tmode = tmode;
3400}
3401
3402/*
3403 * Try to get the code for "t_kb" from the stty setting
3404 *
3405 * Even if termcap claims a backspace key, the user's setting *should*
3406 * prevail. stty knows more about reality than termcap does, and if
3407 * somebody's usual erase key is DEL (which, for most BSD users, it will
3408 * be), they're going to get really annoyed if their erase key starts
3409 * doing forward deletes for no reason. (Eric Fischer)
3410 */
3411 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003412get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413{
3414 char_u buf[2];
3415 char_u *p;
3416
3417 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3418#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3419 /* for "new" tty systems */
3420# ifdef HAVE_TERMIOS_H
3421 struct termios keys;
3422# else
3423 struct termio keys;
3424# endif
3425
3426# if defined(HAVE_TERMIOS_H)
3427 if (tcgetattr(read_cmd_fd, &keys) != -1)
3428# else
3429 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3430# endif
3431 {
3432 buf[0] = keys.c_cc[VERASE];
3433 intr_char = keys.c_cc[VINTR];
3434#else
3435 /* for "old" tty systems */
3436 struct sgttyb keys;
3437
3438 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3439 {
3440 buf[0] = keys.sg_erase;
3441 intr_char = keys.sg_kill;
3442#endif
3443 buf[1] = NUL;
3444 add_termcode((char_u *)"kb", buf, FALSE);
3445
3446 /*
3447 * If <BS> and <DEL> are now the same, redefine <DEL>.
3448 */
3449 p = find_termcode((char_u *)"kD");
3450 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3451 do_fixdel(NULL);
3452 }
3453#if 0
3454 } /* to keep cindent happy */
3455#endif
3456}
3457
3458#endif /* VMS */
3459
3460#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3461/*
3462 * Set mouse clicks on or off.
3463 */
3464 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003465mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466{
3467 static int ison = FALSE;
3468 int xterm_mouse_vers;
3469
3470 if (on == ison) /* return quickly if nothing to do */
3471 return;
3472
3473 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003474
3475# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003476 if (ttym_flags == TTYM_URXVT)
3477 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003478 out_str_nf((char_u *)
3479 (on
3480 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3481 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3482 ison = on;
3483 }
3484# endif
3485
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003486# ifdef FEAT_MOUSE_SGR
3487 if (ttym_flags == TTYM_SGR)
3488 {
3489 out_str_nf((char_u *)
3490 (on
3491 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3492 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3493 ison = on;
3494 }
3495# endif
3496
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497 if (xterm_mouse_vers > 0)
3498 {
3499 if (on) /* enable mouse events, use mouse tracking if available */
3500 out_str_nf((char_u *)
3501 (xterm_mouse_vers > 1
3502 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3503 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3504 else /* disable mouse events, could probably always send the same */
3505 out_str_nf((char_u *)
3506 (xterm_mouse_vers > 1
3507 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3508 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3509 ison = on;
3510 }
3511
3512# ifdef FEAT_MOUSE_DEC
3513 else if (ttym_flags == TTYM_DEC)
3514 {
3515 if (on) /* enable mouse events */
3516 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3517 else /* disable mouse events */
3518 out_str_nf((char_u *)"\033['z");
3519 ison = on;
3520 }
3521# endif
3522
3523# ifdef FEAT_MOUSE_GPM
3524 else
3525 {
3526 if (on)
3527 {
3528 if (gpm_open())
3529 ison = TRUE;
3530 }
3531 else
3532 {
3533 gpm_close();
3534 ison = FALSE;
3535 }
3536 }
3537# endif
3538
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003539# ifdef FEAT_SYSMOUSE
3540 else
3541 {
3542 if (on)
3543 {
3544 if (sysmouse_open() == OK)
3545 ison = TRUE;
3546 }
3547 else
3548 {
3549 sysmouse_close();
3550 ison = FALSE;
3551 }
3552 }
3553# endif
3554
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555# ifdef FEAT_MOUSE_JSB
3556 else
3557 {
3558 if (on)
3559 {
3560 /* D - Enable Mouse up/down messages
3561 * L - Enable Left Button Reporting
3562 * M - Enable Middle Button Reporting
3563 * R - Enable Right Button Reporting
3564 * K - Enable SHIFT and CTRL key Reporting
3565 * + - Enable Advanced messaging of mouse moves and up/down messages
3566 * Q - Quiet No Ack
3567 * # - Numeric value of mouse pointer required
3568 * 0 = Multiview 2000 cursor, used as standard
3569 * 1 = Windows Arrow
3570 * 2 = Windows I Beam
3571 * 3 = Windows Hour Glass
3572 * 4 = Windows Cross Hair
3573 * 5 = Windows UP Arrow
3574 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003575# ifdef JSBTERM_MOUSE_NONADVANCED
3576 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3578 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003579# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3581 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003582# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 ison = TRUE;
3584 }
3585 else
3586 {
3587 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3588 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3589 ison = FALSE;
3590 }
3591 }
3592# endif
3593# ifdef FEAT_MOUSE_PTERM
3594 else
3595 {
3596 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3597 if (on)
3598 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3599 else
3600 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3601 ison = on;
3602 }
3603# endif
3604}
3605
3606/*
3607 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3608 */
3609 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003610check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611{
3612# ifdef FEAT_MOUSE_XTERM
3613 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003614# ifdef FEAT_MOUSE_URXVT
3615 && use_xterm_mouse() != 3
3616# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617# ifdef FEAT_GUI
3618 && !gui.in_use
3619# endif
3620 )
3621 {
3622 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003623 ? IF_EB("\233M", CSI_STR "M")
3624 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 if (*p_mouse != NUL)
3626 {
3627 /* force mouse off and maybe on to send possibly new mouse
3628 * activation sequence to the xterm, with(out) drag tracing. */
3629 mch_setmouse(FALSE);
3630 setmouse();
3631 }
3632 }
3633 else
3634 del_mouse_termcode(KS_MOUSE);
3635# endif
3636
3637# ifdef FEAT_MOUSE_GPM
3638 if (!use_xterm_mouse()
3639# ifdef FEAT_GUI
3640 && !gui.in_use
3641# endif
3642 )
3643 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3644# endif
3645
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003646# ifdef FEAT_SYSMOUSE
3647 if (!use_xterm_mouse()
3648# ifdef FEAT_GUI
3649 && !gui.in_use
3650# endif
3651 )
3652 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3653# endif
3654
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003656 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657 if (!use_xterm_mouse()
3658# ifdef FEAT_GUI
3659 && !gui.in_use
3660# endif
3661 )
3662 set_mouse_termcode(KS_JSBTERM_MOUSE,
3663 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3664 else
3665 del_mouse_termcode(KS_JSBTERM_MOUSE);
3666# endif
3667
3668# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003669 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 * define it in the GUI or when using an xterm. */
3671 if (!use_xterm_mouse()
3672# ifdef FEAT_GUI
3673 && !gui.in_use
3674# endif
3675 )
3676 set_mouse_termcode(KS_NETTERM_MOUSE,
3677 (char_u *)IF_EB("\033}", ESC_STR "}"));
3678 else
3679 del_mouse_termcode(KS_NETTERM_MOUSE);
3680# endif
3681
3682# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003683 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003684 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685# ifdef FEAT_GUI
3686 && !gui.in_use
3687# endif
3688 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003689 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3690 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 else
3692 del_mouse_termcode(KS_DEC_MOUSE);
3693# endif
3694# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003695 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003696 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697# ifdef FEAT_GUI
3698 && !gui.in_use
3699# endif
3700 )
3701 set_mouse_termcode(KS_PTERM_MOUSE,
3702 (char_u *) IF_EB("\033[", ESC_STR "["));
3703 else
3704 del_mouse_termcode(KS_PTERM_MOUSE);
3705# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003706# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003707 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003708 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003709# ifdef FEAT_GUI
3710 && !gui.in_use
3711# endif
3712 )
3713 {
3714 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3715 ? IF_EB("\233", CSI_STR)
3716 : IF_EB("\033[", ESC_STR "[")));
3717
3718 if (*p_mouse != NUL)
3719 {
3720 mch_setmouse(FALSE);
3721 setmouse();
3722 }
3723 }
3724 else
3725 del_mouse_termcode(KS_URXVT_MOUSE);
3726# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003727# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003728 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003729 if (use_xterm_mouse() == 4
3730# ifdef FEAT_GUI
3731 && !gui.in_use
3732# endif
3733 )
3734 {
3735 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3736 ? IF_EB("\233<", CSI_STR "<")
3737 : IF_EB("\033[<", ESC_STR "[<")));
3738
3739 if (*p_mouse != NUL)
3740 {
3741 mch_setmouse(FALSE);
3742 setmouse();
3743 }
3744 }
3745 else
3746 del_mouse_termcode(KS_SGR_MOUSE);
3747# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748}
3749#endif
3750
3751/*
3752 * set screen mode, always fails.
3753 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003755mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756{
3757 EMSG(_(e_screenmode));
3758 return FAIL;
3759}
3760
3761#ifndef VMS
3762
3763/*
3764 * Try to get the current window size:
3765 * 1. with an ioctl(), most accurate method
3766 * 2. from the environment variables LINES and COLUMNS
3767 * 3. from the termcap
3768 * 4. keep using the old values
3769 * Return OK when size could be determined, FAIL otherwise.
3770 */
3771 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003772mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773{
3774 long rows = 0;
3775 long columns = 0;
3776 char_u *p;
3777
3778 /*
3779 * For OS/2 use _scrsize().
3780 */
3781# ifdef __EMX__
3782 {
3783 int s[2];
3784
3785 _scrsize(s);
3786 columns = s[0];
3787 rows = s[1];
3788 }
3789# endif
3790
3791 /*
3792 * 1. try using an ioctl. It is the most accurate method.
3793 *
3794 * Try using TIOCGWINSZ first, some systems that have it also define
3795 * TIOCGSIZE but don't have a struct ttysize.
3796 */
3797# ifdef TIOCGWINSZ
3798 {
3799 struct winsize ws;
3800 int fd = 1;
3801
3802 /* When stdout is not a tty, use stdin for the ioctl(). */
3803 if (!isatty(fd) && isatty(read_cmd_fd))
3804 fd = read_cmd_fd;
3805 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3806 {
3807 columns = ws.ws_col;
3808 rows = ws.ws_row;
3809 }
3810 }
3811# else /* TIOCGWINSZ */
3812# ifdef TIOCGSIZE
3813 {
3814 struct ttysize ts;
3815 int fd = 1;
3816
3817 /* When stdout is not a tty, use stdin for the ioctl(). */
3818 if (!isatty(fd) && isatty(read_cmd_fd))
3819 fd = read_cmd_fd;
3820 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3821 {
3822 columns = ts.ts_cols;
3823 rows = ts.ts_lines;
3824 }
3825 }
3826# endif /* TIOCGSIZE */
3827# endif /* TIOCGWINSZ */
3828
3829 /*
3830 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003831 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3832 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003834 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 {
3836 if ((p = (char_u *)getenv("LINES")))
3837 rows = atoi((char *)p);
3838 if ((p = (char_u *)getenv("COLUMNS")))
3839 columns = atoi((char *)p);
3840 }
3841
3842#ifdef HAVE_TGETENT
3843 /*
3844 * 3. try reading "co" and "li" entries from termcap
3845 */
3846 if (columns == 0 || rows == 0)
3847 getlinecol(&columns, &rows);
3848#endif
3849
3850 /*
3851 * 4. If everything fails, use the old values
3852 */
3853 if (columns <= 0 || rows <= 0)
3854 return FAIL;
3855
3856 Rows = rows;
3857 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003858 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 return OK;
3860}
3861
3862/*
3863 * Try to set the window size to Rows and Columns.
3864 */
3865 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003866mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867{
3868 if (*T_CWS)
3869 {
3870 /*
3871 * NOTE: if you get an error here that term_set_winsize() is
3872 * undefined, check the output of configure. It could probably not
3873 * find a ncurses, termcap or termlib library.
3874 */
3875 term_set_winsize((int)Rows, (int)Columns);
3876 out_flush();
3877 screen_start(); /* don't know where cursor is now */
3878 }
3879}
3880
3881#endif /* VMS */
3882
3883/*
3884 * Rows and/or Columns has changed.
3885 */
3886 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003887mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888{
3889 /* Nothing to do. */
3890}
3891
Bram Moolenaar205b8862011-09-07 15:04:31 +02003892/*
3893 * Wait for process "child" to end.
3894 * Return "child" if it exited properly, <= 0 on error.
3895 */
3896 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01003897wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02003898{
3899 pid_t wait_pid = 0;
3900
3901 while (wait_pid != child)
3902 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003903 /* When compiled with Python threads are probably used, in which case
3904 * wait() sometimes hangs for no obvious reason. Use waitpid()
3905 * instead and loop (like the GUI). Also needed for other interfaces,
3906 * they might call system(). */
3907# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003908 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003909# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003910 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003911# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003912 if (wait_pid == 0)
3913 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003914 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003915 mch_delay(10L, TRUE);
3916 continue;
3917 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003918 if (wait_pid <= 0
3919# ifdef ECHILD
3920 && errno == ECHILD
3921# endif
3922 )
3923 break;
3924 }
3925 return wait_pid;
3926}
3927
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003929mch_call_shell(
3930 char_u *cmd,
3931 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932{
3933#ifdef VMS
3934 char *ifn = NULL;
3935 char *ofn = NULL;
3936#endif
3937 int tmode = cur_tmode;
3938#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3939 int x;
3940# ifndef __EMX__
3941 char_u *newcmd; /* only needed for unix */
3942# else
3943 /*
3944 * Set the preferred shell in the EMXSHELL environment variable (but
3945 * only if it is different from what is already in the environment).
3946 * Emx then takes care of whether to use "/c" or "-c" in an
3947 * intelligent way. Simply pass the whole thing to emx's system() call.
3948 * Emx also starts an interactive shell if system() is passed an empty
3949 * string.
3950 */
3951 char_u *p, *old;
3952
3953 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3954 {
3955 /* should check HAVE_SETENV, but I know we don't have it. */
3956 p = alloc(10 + strlen(p_sh));
3957 if (p)
3958 {
3959 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3960 putenv((char *)p); /* don't free the pointer! */
3961 }
3962 }
3963# endif
3964
3965 out_flush();
3966
3967 if (options & SHELL_COOKED)
3968 settmode(TMODE_COOK); /* set to normal mode */
3969
Bram Moolenaar62b42182010-09-21 22:09:37 +02003970# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003971 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02003972 loose_clipboard();
3973# endif
3974
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975# ifdef __EMX__
3976 if (cmd == NULL)
3977 x = system(""); /* this starts an interactive shell in emx */
3978 else
3979 x = system((char *)cmd);
3980 /* system() returns -1 when error occurs in starting shell */
3981 if (x == -1 && !emsg_silent)
3982 {
3983 MSG_PUTS(_("\nCannot execute shell "));
3984 msg_outtrans(p_sh);
3985 msg_putchar('\n');
3986 }
3987# else /* not __EMX__ */
3988 if (cmd == NULL)
3989 x = system((char *)p_sh);
3990 else
3991 {
3992# ifdef VMS
3993 if (ofn = strchr((char *)cmd, '>'))
3994 *ofn++ = '\0';
3995 if (ifn = strchr((char *)cmd, '<'))
3996 {
3997 char *p;
3998
3999 *ifn++ = '\0';
4000 p = strchr(ifn,' '); /* chop off any trailing spaces */
4001 if (p)
4002 *p = '\0';
4003 }
4004 if (ofn)
4005 x = vms_sys((char *)cmd, ofn, ifn);
4006 else
4007 x = system((char *)cmd);
4008# else
4009 newcmd = lalloc(STRLEN(p_sh)
4010 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4011 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4012 if (newcmd == NULL)
4013 x = 0;
4014 else
4015 {
4016 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4017 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4018 (char *)p_shcf,
4019 (char *)cmd);
4020 x = system((char *)newcmd);
4021 vim_free(newcmd);
4022 }
4023# endif
4024 }
4025# ifdef VMS
4026 x = vms_sys_status(x);
4027# endif
4028 if (emsg_silent)
4029 ;
4030 else if (x == 127)
4031 MSG_PUTS(_("\nCannot execute shell sh\n"));
4032# endif /* __EMX__ */
4033 else if (x && !(options & SHELL_SILENT))
4034 {
4035 MSG_PUTS(_("\nshell returned "));
4036 msg_outnum((long)x);
4037 msg_putchar('\n');
4038 }
4039
4040 if (tmode == TMODE_RAW)
4041 settmode(TMODE_RAW); /* set to raw mode */
4042# ifdef FEAT_TITLE
4043 resettitle();
4044# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004045# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4046 restore_clipboard();
4047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048 return x;
4049
4050#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4051
Bram Moolenaardf177f62005-02-22 08:39:57 +00004052# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4053 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
4055 char_u *newcmd = NULL;
4056 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004057 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 pid_t wait_pid = 0;
4059# ifdef HAVE_UNION_WAIT
4060 union wait status;
4061# else
4062 int status = -1;
4063# endif
4064 int retval = -1;
4065 char **argv = NULL;
4066 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004067 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 int i;
4069 char_u *p;
4070 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004072# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 int pty_slave_fd = -1;
4074 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004075# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004076 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 int fd_fromshell[2];
4078 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004079# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004081# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004082 static char envbuf_Rows[20];
4083 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004085 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086
Bram Moolenaar62b42182010-09-21 22:09:37 +02004087 newcmd = vim_strsave(p_sh);
4088 if (newcmd == NULL) /* out of memory */
4089 goto error;
4090
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 out_flush();
4092 if (options & SHELL_COOKED)
4093 settmode(TMODE_COOK); /* set to normal mode */
4094
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004095 /*
4096 * Do this loop twice:
4097 * 1: find number of arguments
4098 * 2: separate them and build argv[]
4099 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 for (i = 0; i < 2; ++i)
4101 {
4102 p = newcmd;
4103 inquote = FALSE;
4104 argc = 0;
4105 for (;;)
4106 {
4107 if (i == 1)
4108 argv[argc] = (char *)p;
4109 ++argc;
4110 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4111 {
4112 if (*p == '"')
4113 inquote = !inquote;
4114 ++p;
4115 }
4116 if (*p == NUL)
4117 break;
4118 if (i == 1)
4119 *p++ = NUL;
4120 p = skipwhite(p);
4121 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004122 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004124 /*
4125 * Account for possible multiple args in p_shcf.
4126 */
4127 p = p_shcf;
4128 for (;;)
4129 {
4130 p = skiptowhite(p);
4131 if (*p == NUL)
4132 break;
4133 ++argc;
4134 p = skipwhite(p);
4135 }
4136
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4138 if (argv == NULL) /* out of memory */
4139 goto error;
4140 }
4141 }
4142 if (cmd != NULL)
4143 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004144 char_u *s;
4145
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 if (extra_shell_arg != NULL)
4147 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004148
4149 /* Break 'shellcmdflag' into white separated parts. This doesn't
4150 * handle quoted strings, they are very unlikely to appear. */
4151 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4152 if (p_shcf_copy == NULL) /* out of memory */
4153 goto error;
4154 s = p_shcf_copy;
4155 p = p_shcf;
4156 while (*p != NUL)
4157 {
4158 argv[argc++] = (char *)s;
4159 while (*p && *p != ' ' && *p != TAB)
4160 *s++ = *p++;
4161 *s++ = NUL;
4162 p = skipwhite(p);
4163 }
4164
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 argv[argc++] = (char *)cmd;
4166 }
4167 argv[argc] = NULL;
4168
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004170 * For the GUI, when writing the output into the buffer and when reading
4171 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4172 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004174 if ((options & (SHELL_READ|SHELL_WRITE))
4175# ifdef FEAT_GUI
4176 || (gui.in_use && show_shell_mess)
4177# endif
4178 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004180# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 /*
4182 * Try to open a master pty.
4183 * If this works, open the slave pty.
4184 * If the slave can't be opened, close the master pty.
4185 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004186 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 {
4188 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004189 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004191 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4192 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4193 * adding O_NOCTTY always works when defined. */
4194#ifdef O_NOCTTY
4195 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4196#else
4197 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4198#endif
4199 if (pty_slave_fd < 0)
4200 {
4201 close(pty_master_fd);
4202 pty_master_fd = -1;
4203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004204 }
4205 }
4206 /*
4207 * If not opening a pty or it didn't work, try using pipes.
4208 */
4209 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004210# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 {
4212 pipe_error = (pipe(fd_toshell) < 0);
4213 if (!pipe_error) /* pipe create OK */
4214 {
4215 pipe_error = (pipe(fd_fromshell) < 0);
4216 if (pipe_error) /* pipe create failed */
4217 {
4218 close(fd_toshell[0]);
4219 close(fd_toshell[1]);
4220 }
4221 }
4222 if (pipe_error)
4223 {
4224 MSG_PUTS(_("\nCannot create pipes\n"));
4225 out_flush();
4226 }
4227 }
4228 }
4229
4230 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 {
4232# ifdef __BEOS__
4233 beos_cleanup_read_thread();
4234# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004235
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4237 {
4238 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004239 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004241 || (gui.in_use && show_shell_mess)
4242# endif
4243 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004245# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246 if (pty_master_fd >= 0) /* close the pseudo tty */
4247 {
4248 close(pty_master_fd);
4249 close(pty_slave_fd);
4250 }
4251 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004252# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 {
4254 close(fd_toshell[0]);
4255 close(fd_toshell[1]);
4256 close(fd_fromshell[0]);
4257 close(fd_fromshell[1]);
4258 }
4259 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 }
4261 else if (pid == 0) /* child */
4262 {
4263 reset_signals(); /* handle signals normally */
4264
4265 if (!show_shell_mess || (options & SHELL_EXPAND))
4266 {
4267 int fd;
4268
4269 /*
4270 * Don't want to show any message from the shell. Can't just
4271 * close stdout and stderr though, because some systems will
4272 * break if you try to write to them after that, so we must
4273 * use dup() to replace them with something else -- webb
4274 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4275 * waiting for input.
4276 */
4277 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4278 fclose(stdin);
4279 fclose(stdout);
4280 fclose(stderr);
4281
4282 /*
4283 * If any of these open()'s and dup()'s fail, we just continue
4284 * anyway. It's not fatal, and on most systems it will make
4285 * no difference at all. On a few it will cause the execvp()
4286 * to exit with a non-zero status even when the completion
4287 * could be done, which is nothing too serious. If the open()
4288 * or dup() failed we'd just do the same thing ourselves
4289 * anyway -- webb
4290 */
4291 if (fd >= 0)
4292 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004293 ignored = dup(fd); /* To replace stdin (fd 0) */
4294 ignored = dup(fd); /* To replace stdout (fd 1) */
4295 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296
4297 /* Don't need this now that we've duplicated it */
4298 close(fd);
4299 }
4300 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004301 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004303 || gui.in_use
4304# endif
4305 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 {
4307
Bram Moolenaardf177f62005-02-22 08:39:57 +00004308# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004309 /* Create our own process group, so that the child and all its
4310 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004311 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004312 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004313 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004314 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004315# if defined(SIGHUP)
4316 /* When doing "!xterm&" and 'shell' is bash: the shell
4317 * will exit and send SIGHUP to all processes in its
4318 * group, killing the just started process. Ignore SIGHUP
4319 * to avoid that. (suggested by Simon Schubert)
4320 */
4321 signal(SIGHUP, SIG_IGN);
4322# endif
4323 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004324# endif
4325# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004326 if (pty_slave_fd >= 0)
4327 {
4328 /* push stream discipline modules */
4329 if (options & SHELL_COOKED)
4330 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004332 /* Try to become controlling tty (probably doesn't work,
4333 * unless run by root) */
4334 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004336 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004337# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004339# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 setenv("TERM", "dumb", 1);
4341 sprintf((char *)envbuf, "%ld", Rows);
4342 setenv("ROWS", (char *)envbuf, 1);
4343 sprintf((char *)envbuf, "%ld", Rows);
4344 setenv("LINES", (char *)envbuf, 1);
4345 sprintf((char *)envbuf, "%ld", Columns);
4346 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004347# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 /*
4349 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004350 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 */
4352 putenv("TERM=dumb");
4353 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4354 putenv(envbuf_Rows);
4355 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4356 putenv(envbuf_Rows);
4357 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4358 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004359# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360
Bram Moolenaara5792f52005-11-23 21:25:05 +00004361 /*
4362 * stderr is only redirected when using the GUI, so that a
4363 * program like gpg can still access the terminal to get a
4364 * passphrase using stderr.
4365 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004366# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 if (pty_master_fd >= 0)
4368 {
4369 close(pty_master_fd); /* close master side of pty */
4370
4371 /* set up stdin/stdout/stderr for the child */
4372 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004373 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004375 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004376 if (gui.in_use)
4377 {
4378 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004379 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004380 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381
4382 close(pty_slave_fd); /* has been dupped, close it now */
4383 }
4384 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004385# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 {
4387 /* set up stdin for the child */
4388 close(fd_toshell[1]);
4389 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004390 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391 close(fd_toshell[0]);
4392
4393 /* set up stdout for the child */
4394 close(fd_fromshell[0]);
4395 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004396 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397 close(fd_fromshell[1]);
4398
Bram Moolenaara5792f52005-11-23 21:25:05 +00004399# ifdef FEAT_GUI
4400 if (gui.in_use)
4401 {
4402 /* set up stderr for the child */
4403 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004404 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004405 }
4406# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 }
4408 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004409
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 /*
4411 * There is no type cast for the argv, because the type may be
4412 * different on different machines. This may cause a warning
4413 * message with strict compilers, don't worry about it.
4414 * Call _exit() instead of exit() to avoid closing the connection
4415 * to the X server (esp. with GTK, which uses atexit()).
4416 */
4417 execvp(argv[0], argv);
4418 _exit(EXEC_FAILED); /* exec failed, return failure code */
4419 }
4420 else /* parent */
4421 {
4422 /*
4423 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004424 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004425 */
4426 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004427 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428
4429 /*
4430 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004431 * This is also used to pipe stdin/stdout to/from the external
4432 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004434 if ((options & (SHELL_READ|SHELL_WRITE))
4435# ifdef FEAT_GUI
4436 || (gui.in_use && show_shell_mess)
4437# endif
4438 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004440# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004442# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004444# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4446 int ta_len = 0; /* valid bytes in ta_buf[] */
4447 int len;
4448 int p_more_save;
4449 int old_State;
4450 int c;
4451 int toshell_fd;
4452 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004453 garray_T ga;
4454 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004455# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4456 struct timeval start_tv;
4457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458
Bram Moolenaardf177f62005-02-22 08:39:57 +00004459# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460 if (pty_master_fd >= 0)
4461 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462 fromshell_fd = pty_master_fd;
4463 toshell_fd = dup(pty_master_fd);
4464 }
4465 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 {
4468 close(fd_toshell[0]);
4469 close(fd_fromshell[1]);
4470 toshell_fd = fd_toshell[1];
4471 fromshell_fd = fd_fromshell[0];
4472 }
4473
4474 /*
4475 * Write to the child if there are typed characters.
4476 * Read from the child if there are characters available.
4477 * Repeat the reading a few times if more characters are
4478 * available. Need to check for typed keys now and then, but
4479 * not too often (delays when no chars are available).
4480 * This loop is quit if no characters can be read from the pty
4481 * (WaitForChar detected special condition), or there are no
4482 * characters available and the child has exited.
4483 * Only check if the child has exited when there is no more
4484 * output. The child may exit before all the output has
4485 * been printed.
4486 *
4487 * Currently this busy loops!
4488 * This can probably dead-lock when the write blocks!
4489 */
4490 p_more_save = p_more;
4491 p_more = FALSE;
4492 old_State = State;
4493 State = EXTERNCMD; /* don't redraw at window resize */
4494
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004495 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004496 {
4497 /* Fork a process that will write the lines to the
4498 * external program. */
4499 if ((wpid = fork()) == -1)
4500 {
4501 MSG_PUTS(_("\nCannot fork\n"));
4502 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004503 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004504 {
4505 linenr_T lnum = curbuf->b_op_start.lnum;
4506 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004507 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004508 size_t l;
4509
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004510 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004511 for (;;)
4512 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004513 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004514 if (l == 0)
4515 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004516 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004517 /* NL -> NUL translation */
4518 len = write(toshell_fd, "", (size_t)1);
4519 else
4520 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004521 char_u *s = vim_strchr(lp + written, NL);
4522
Bram Moolenaar89d40322006-08-29 15:30:07 +00004523 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004524 s == NULL ? l
4525 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004526 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004527 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004528 {
4529 /* Finished a line, add a NL, unless this line
4530 * should not have one. */
4531 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004532 || (!curbuf->b_p_bin
4533 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004534 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004535 && (lnum !=
4536 curbuf->b_ml.ml_line_count
4537 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004538 ignored = write(toshell_fd, "\n",
4539 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004540 ++lnum;
4541 if (lnum > curbuf->b_op_end.lnum)
4542 {
4543 /* finished all the lines, close pipe */
4544 close(toshell_fd);
4545 toshell_fd = -1;
4546 break;
4547 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004548 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004549 written = 0;
4550 }
4551 else if (len > 0)
4552 written += len;
4553 }
4554 _exit(0);
4555 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004556 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004557 {
4558 close(toshell_fd);
4559 toshell_fd = -1;
4560 }
4561 }
4562
4563 if (options & SHELL_READ)
4564 ga_init2(&ga, 1, BUFLEN);
4565
4566 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004567# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4568 gettimeofday(&start_tv, NULL);
4569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 for (;;)
4571 {
4572 /*
4573 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004574 * if there are any.
4575 * Don't do this if we are expanding wild cards (would eat
4576 * typeahead).
4577 * Don't do this when filtering and terminal is in cooked
4578 * mode, the shell command will handle the I/O. Avoids
4579 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004580 * Don't get characters when the child has already
4581 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004582 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004583 * while (noread_cnt > 4), avoids that ":r !ls" eats
4584 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 */
4586 len = 0;
4587 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004588 && ((options &
4589 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4590 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004591# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004592 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004593# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004594 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004595 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004596 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004598 if (ta_len == 0)
4599 {
4600 /* Get extra characters when we don't have any.
4601 * Reset the counter and timer. */
4602 noread_cnt = 0;
4603# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4604 gettimeofday(&start_tv, NULL);
4605# endif
4606 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4607 }
4608 if (ta_len > 0 || len > 0)
4609 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610 /*
4611 * For pipes:
4612 * Check for CTRL-C: send interrupt signal to child.
4613 * Check for CTRL-D: EOF, close pipe to child.
4614 */
4615 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4616 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004617# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 /*
4619 * Send SIGINT to the child's group or all
4620 * processes in our group.
4621 */
4622 if (ta_buf[ta_len] == Ctrl_C
4623 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004624 {
4625# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004627# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004630 if (wpid > 0)
4631 kill(wpid, SIGINT);
4632 }
4633# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 if (pty_master_fd < 0 && toshell_fd >= 0
4635 && ta_buf[ta_len] == Ctrl_D)
4636 {
4637 close(toshell_fd);
4638 toshell_fd = -1;
4639 }
4640 }
4641
4642 /* replace K_BS by <BS> and K_DEL by <DEL> */
4643 for (i = ta_len; i < ta_len + len; ++i)
4644 {
4645 if (ta_buf[i] == CSI && len - i > 2)
4646 {
4647 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4648 if (c == K_DEL || c == K_KDEL || c == K_BS)
4649 {
4650 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4651 (size_t)(len - i - 2));
4652 if (c == K_DEL || c == K_KDEL)
4653 ta_buf[i] = DEL;
4654 else
4655 ta_buf[i] = Ctrl_H;
4656 len -= 2;
4657 }
4658 }
4659 else if (ta_buf[i] == '\r')
4660 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004661# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004662 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004663 i += (*mb_ptr2len_len)(ta_buf + i,
4664 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004665# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004666 }
4667
4668 /*
4669 * For pipes: echo the typed characters.
4670 * For a pty this does not seem to work.
4671 */
4672 if (pty_master_fd < 0)
4673 {
4674 for (i = ta_len; i < ta_len + len; ++i)
4675 {
4676 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4677 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004678# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679 else if (has_mbyte)
4680 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004681 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004682
4683 msg_outtrans_len(ta_buf + i, l);
4684 i += l - 1;
4685 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 else
4688 msg_outtrans_len(ta_buf + i, 1);
4689 }
4690 windgoto(msg_row, msg_col);
4691 out_flush();
4692 }
4693
4694 ta_len += len;
4695
4696 /*
4697 * Write the characters to the child, unless EOF has
4698 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004699 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004700 * When writing buffer lines, drop the typed
4701 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004703 if (options & SHELL_WRITE)
4704 ta_len = 0;
4705 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706 {
4707 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4708 if (len > 0)
4709 {
4710 ta_len -= len;
4711 mch_memmove(ta_buf, ta_buf + len, ta_len);
4712 }
4713 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 }
4716
Bram Moolenaardf177f62005-02-22 08:39:57 +00004717 if (got_int)
4718 {
4719 /* CTRL-C sends a signal to the child, we ignore it
4720 * ourselves */
4721# ifdef HAVE_SETSID
4722 kill(-pid, SIGINT);
4723# else
4724 kill(0, SIGINT);
4725# endif
4726 if (wpid > 0)
4727 kill(wpid, SIGINT);
4728 got_int = FALSE;
4729 }
4730
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 /*
4732 * Check if the child has any characters to be printed.
4733 * Read them and write them to our window. Repeat this as
4734 * long as there is something to do, avoid the 10ms wait
4735 * for mch_inchar(), or sending typeahead characters to
4736 * the external process.
4737 * TODO: This should handle escape sequences, compatible
4738 * to some terminal (vt52?).
4739 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004740 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4742 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004743 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004744# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004746# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 );
4750 if (len <= 0) /* end of file or error */
4751 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004752
4753 noread_cnt = 0;
4754 if (options & SHELL_READ)
4755 {
4756 /* Do NUL -> NL translation, append NL separated
4757 * lines to the current buffer. */
4758 for (i = 0; i < len; ++i)
4759 {
4760 if (buffer[i] == NL)
4761 append_ga_line(&ga);
4762 else if (buffer[i] == NUL)
4763 ga_append(&ga, NL);
4764 else
4765 ga_append(&ga, buffer[i]);
4766 }
4767 }
4768# ifdef FEAT_MBYTE
4769 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 {
4771 int l;
4772
Bram Moolenaardf177f62005-02-22 08:39:57 +00004773 len += buffer_off;
4774 buffer[len] = NUL;
4775
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776 /* Check if the last character in buffer[] is
4777 * incomplete, keep these bytes for the next
4778 * round. */
4779 for (p = buffer; p < buffer + len; p += l)
4780 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004781 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 if (l == 0)
4783 l = 1; /* NUL byte? */
4784 else if (MB_BYTE2LEN(*p) != l)
4785 break;
4786 }
4787 if (p == buffer) /* no complete character */
4788 {
4789 /* avoid getting stuck at an illegal byte */
4790 if (len >= 12)
4791 ++p;
4792 else
4793 {
4794 buffer_off = len;
4795 continue;
4796 }
4797 }
4798 c = *p;
4799 *p = NUL;
4800 msg_puts(buffer);
4801 if (p < buffer + len)
4802 {
4803 *p = c;
4804 buffer_off = (buffer + len) - p;
4805 mch_memmove(buffer, p, buffer_off);
4806 continue;
4807 }
4808 buffer_off = 0;
4809 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004810# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 {
4813 buffer[len] = NUL;
4814 msg_puts(buffer);
4815 }
4816
4817 windgoto(msg_row, msg_col);
4818 cursor_on();
4819 out_flush();
4820 if (got_int)
4821 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004822
4823# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4824 {
4825 struct timeval now_tv;
4826 long msec;
4827
4828 /* Avoid that we keep looping here without
4829 * checking for a CTRL-C for a long time. Don't
4830 * break out too often to avoid losing typeahead. */
4831 gettimeofday(&now_tv, NULL);
4832 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4833 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4834 if (msec > 2000)
4835 {
4836 noread_cnt = 5;
4837 break;
4838 }
4839 }
4840# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 }
4842
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004843 /* If we already detected the child has finished break the
4844 * loop now. */
4845 if (wait_pid == pid)
4846 break;
4847
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 /*
4849 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004850 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004852# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004853 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004854# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004856# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4858 || (wait_pid == pid && WIFEXITED(status)))
4859 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004860 /* Don't break the loop yet, try reading more
4861 * characters from "fromshell_fd" first. When using
4862 * pipes there might still be something to read and
4863 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004866 else
4867 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004868
Bram Moolenaar95a51352013-03-21 22:53:50 +01004869# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004870 /* Handle any X events, e.g. serving the clipboard. */
4871 clip_update();
4872# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
4874finished:
4875 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004876 if (options & SHELL_READ)
4877 {
4878 if (ga.ga_len > 0)
4879 {
4880 append_ga_line(&ga);
4881 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004882 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004883 }
4884 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004885 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004886 ga_clear(&ga);
4887 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 /*
4890 * Give all typeahead that wasn't used back to ui_inchar().
4891 */
4892 if (ta_len)
4893 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 State = old_State;
4895 if (toshell_fd >= 0)
4896 close(toshell_fd);
4897 close(fromshell_fd);
4898 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004899# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004900 else
4901 {
4902 /*
4903 * Similar to the loop above, but only handle X events, no
4904 * I/O.
4905 */
4906 for (;;)
4907 {
4908 if (got_int)
4909 {
4910 /* CTRL-C sends a signal to the child, we ignore it
4911 * ourselves */
4912# ifdef HAVE_SETSID
4913 kill(-pid, SIGINT);
4914# else
4915 kill(0, SIGINT);
4916# endif
4917 got_int = FALSE;
4918 }
4919# ifdef __NeXT__
4920 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4921# else
4922 wait_pid = waitpid(pid, &status, WNOHANG);
4923# endif
4924 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4925 || (wait_pid == pid && WIFEXITED(status)))
4926 {
4927 wait_pid = pid;
4928 break;
4929 }
4930
4931 /* Handle any X events, e.g. serving the clipboard. */
4932 clip_update();
4933
4934 mch_delay(10L, TRUE);
4935 }
4936 }
4937# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938
4939 /*
4940 * Wait until our child has exited.
4941 * Ignore wait() returning pids of other children and returning
4942 * because of some signal like SIGWINCH.
4943 * Don't wait if wait_pid was already set above, indicating the
4944 * child already exited.
4945 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004946 if (wait_pid != pid)
4947 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948
Bram Moolenaar624891f2010-10-13 16:22:09 +02004949# ifdef FEAT_GUI
4950 /* Close slave side of pty. Only do this after the child has
4951 * exited, otherwise the child may hang when it tries to write on
4952 * the pty. */
4953 if (pty_master_fd >= 0)
4954 close(pty_slave_fd);
4955# endif
4956
Bram Moolenaardf177f62005-02-22 08:39:57 +00004957 /* Make sure the child that writes to the external program is
4958 * dead. */
4959 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004960 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004961 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004962 wait4pid(wpid, NULL);
4963 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004964
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 /*
4966 * Set to raw mode right now, otherwise a CTRL-C after
4967 * catch_signals() will kill Vim.
4968 */
4969 if (tmode == TMODE_RAW)
4970 settmode(TMODE_RAW);
4971 did_settmode = TRUE;
4972 set_signals();
4973
4974 if (WIFEXITED(status))
4975 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004976 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01004978 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 {
4980 if (retval == EXEC_FAILED)
4981 {
4982 MSG_PUTS(_("\nCannot execute shell "));
4983 msg_outtrans(p_sh);
4984 msg_putchar('\n');
4985 }
4986 else if (!(options & SHELL_SILENT))
4987 {
4988 MSG_PUTS(_("\nshell returned "));
4989 msg_outnum((long)retval);
4990 msg_putchar('\n');
4991 }
4992 }
4993 }
4994 else
4995 MSG_PUTS(_("\nCommand terminated\n"));
4996 }
4997 }
4998 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004999 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000
5001error:
5002 if (!did_settmode)
5003 if (tmode == TMODE_RAW)
5004 settmode(TMODE_RAW); /* set to raw mode */
5005# ifdef FEAT_TITLE
5006 resettitle();
5007# endif
5008 vim_free(newcmd);
5009
5010 return retval;
5011
5012#endif /* USE_SYSTEM */
5013}
5014
5015/*
5016 * Check for CTRL-C typed by reading all available characters.
5017 * In cooked mode we should get SIGINT, no need to check.
5018 */
5019 void
Bram Moolenaar05540972016-01-30 20:31:25 +01005020mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021{
5022 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
5023 fill_input_buf(FALSE);
5024}
5025
5026/*
5027 * Wait "msec" msec until a character is available from the keyboard or from
5028 * inbuf[]. msec == -1 will block forever.
5029 * When a GUI is being used, this will never get called -- webb
5030 */
5031 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01005032WaitForChar(long msec)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033{
5034#ifdef FEAT_MOUSE_GPM
5035 int gpm_process_wanted;
5036#endif
5037#ifdef FEAT_XCLIPBOARD
5038 int rest;
5039#endif
5040 int avail;
5041
5042 if (input_available()) /* something in inbuf[] */
5043 return 1;
5044
5045#if defined(FEAT_MOUSE_DEC)
5046 /* May need to query the mouse position. */
5047 if (WantQueryMouse)
5048 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005049 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5051 }
5052#endif
5053
5054 /*
5055 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5056 * events. This is a bit complicated, because they might both be defined.
5057 */
5058#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5059# ifdef FEAT_XCLIPBOARD
5060 rest = 0;
5061 if (do_xterm_trace())
5062 rest = msec;
5063# endif
5064 do
5065 {
5066# ifdef FEAT_XCLIPBOARD
5067 if (rest != 0)
5068 {
5069 msec = XT_TRACE_DELAY;
5070 if (rest >= 0 && rest < XT_TRACE_DELAY)
5071 msec = rest;
5072 if (rest >= 0)
5073 rest -= msec;
5074 }
5075# endif
5076# ifdef FEAT_MOUSE_GPM
5077 gpm_process_wanted = 0;
5078 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5079# else
5080 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5081# endif
5082 if (!avail)
5083 {
5084 if (input_available())
5085 return 1;
5086# ifdef FEAT_XCLIPBOARD
5087 if (rest == 0 || !do_xterm_trace())
5088# endif
5089 break;
5090 }
5091 }
5092 while (FALSE
5093# ifdef FEAT_MOUSE_GPM
5094 || (gpm_process_wanted && mch_gpm_process() == 0)
5095# endif
5096# ifdef FEAT_XCLIPBOARD
5097 || (!avail && rest != 0)
5098# endif
5099 );
5100
5101#else
5102 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5103#endif
5104 return avail;
5105}
5106
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005107#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005108/*
5109 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005110 * "msec" == 0 will check for characters once.
5111 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005112 * When a GUI is being used, this will not be used for input -- webb
5113 * Returns also, when a request from Sniff is waiting -- toni.
5114 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005115 * Or when a clientserver message is on the queue.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005117#if defined(__BEOS__)
5118 int
5119#else
5120 static int
5121#endif
Bram Moolenaar05540972016-01-30 20:31:25 +01005122RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005123{
5124 int ret;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005125#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005126 static int busy = FALSE;
5127
5128 /* May retry getting characters after an event was handled. */
5129# define MAY_LOOP
5130
5131# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5132 /* Remember at what time we started, so that we know how much longer we
5133 * should wait after being interrupted. */
5134# define USE_START_TV
5135 struct timeval start_tv;
5136
5137 if (msec > 0 && (
5138# ifdef FEAT_XCLIPBOARD
5139 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005140# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 ||
5142# endif
5143# endif
5144# ifdef USE_XSMP
5145 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005146# ifdef FEAT_MZSCHEME
5147 ||
5148# endif
5149# endif
5150# ifdef FEAT_MZSCHEME
5151 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005152# endif
5153 ))
5154 gettimeofday(&start_tv, NULL);
5155# endif
5156
5157 /* Handle being called recursively. This may happen for the session
5158 * manager stuff, it may save the file, which does a breakcheck. */
5159 if (busy)
5160 return 0;
5161#endif
5162
5163#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005164 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165#endif
5166 {
5167#ifdef MAY_LOOP
5168 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005169# ifdef FEAT_MZSCHEME
5170 int mzquantum_used = FALSE;
5171# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172#endif
5173#ifndef HAVE_SELECT
Bram Moolenaare0874f82016-01-24 20:36:41 +01005174 struct pollfd fds[6 + MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 int nfd;
5176# ifdef FEAT_XCLIPBOARD
5177 int xterm_idx = -1;
5178# endif
5179# ifdef FEAT_MOUSE_GPM
5180 int gpm_idx = -1;
5181# endif
5182# ifdef USE_XSMP
5183 int xsmp_idx = -1;
5184# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005185 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005187# ifdef FEAT_MZSCHEME
5188 mzvim_check_threads();
5189 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5190 {
5191 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5192 mzquantum_used = TRUE;
5193 }
5194# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 fds[0].fd = fd;
5196 fds[0].events = POLLIN;
5197 nfd = 1;
5198
5199# ifdef FEAT_SNIFF
5200# define SNIFF_IDX 1
5201 if (want_sniff_request)
5202 {
5203 fds[SNIFF_IDX].fd = fd_from_sniff;
5204 fds[SNIFF_IDX].events = POLLIN;
5205 nfd++;
5206 }
5207# endif
5208# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005209 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 if (xterm_Shell != (Widget)0)
5211 {
5212 xterm_idx = nfd;
5213 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5214 fds[nfd].events = POLLIN;
5215 nfd++;
5216 }
5217# endif
5218# ifdef FEAT_MOUSE_GPM
5219 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5220 {
5221 gpm_idx = nfd;
5222 fds[nfd].fd = gpm_fd;
5223 fds[nfd].events = POLLIN;
5224 nfd++;
5225 }
5226# endif
5227# ifdef USE_XSMP
5228 if (xsmp_icefd != -1)
5229 {
5230 xsmp_idx = nfd;
5231 fds[nfd].fd = xsmp_icefd;
5232 fds[nfd].events = POLLIN;
5233 nfd++;
5234 }
5235# endif
Bram Moolenaare0874f82016-01-24 20:36:41 +01005236#ifdef FEAT_CHANNEL
5237 nfd = channel_poll_setup(nfd, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005238#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005240 ret = poll(fds, nfd, towait);
5241# ifdef FEAT_MZSCHEME
5242 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005243 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005244 finished = FALSE;
5245# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246
5247# ifdef FEAT_SNIFF
5248 if (ret < 0)
5249 sniff_disconnect(1);
5250 else if (want_sniff_request)
5251 {
5252 if (fds[SNIFF_IDX].revents & POLLHUP)
5253 sniff_disconnect(1);
5254 if (fds[SNIFF_IDX].revents & POLLIN)
5255 sniff_request_waiting = 1;
5256 }
5257# endif
5258# ifdef FEAT_XCLIPBOARD
5259 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5260 {
5261 xterm_update(); /* Maybe we should hand out clipboard */
5262 if (--ret == 0 && !input_available())
5263 /* Try again */
5264 finished = FALSE;
5265 }
5266# endif
5267# ifdef FEAT_MOUSE_GPM
5268 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5269 {
5270 *check_for_gpm = 1;
5271 }
5272# endif
5273# ifdef USE_XSMP
5274 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5275 {
5276 if (fds[xsmp_idx].revents & POLLIN)
5277 {
5278 busy = TRUE;
5279 xsmp_handle_requests();
5280 busy = FALSE;
5281 }
5282 else if (fds[xsmp_idx].revents & POLLHUP)
5283 {
5284 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005285 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286 xsmp_close();
5287 }
5288 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005289 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005290 }
5291# endif
Bram Moolenaare0874f82016-01-24 20:36:41 +01005292#ifdef FEAT_CHANNEL
5293 if (ret > 0)
5294 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005295#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296
5297
5298#else /* HAVE_SELECT */
5299
5300 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005301 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005302 fd_set rfds, efds;
5303 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005304 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005306# ifdef FEAT_MZSCHEME
5307 mzvim_check_threads();
5308 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5309 {
5310 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5311 mzquantum_used = TRUE;
5312 }
5313# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314# ifdef __EMX__
5315 /* don't check for incoming chars if not in raw mode, because select()
5316 * always returns TRUE then (in some version of emx.dll) */
5317 if (curr_tmode != TMODE_RAW)
5318 return 0;
5319# endif
5320
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005321 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005323 tv.tv_sec = towait / 1000;
5324 tv.tv_usec = (towait % 1000) * (1000000/1000);
5325 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005327 else
5328 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329
5330 /*
5331 * Select on ready for reading and exceptional condition (end of file).
5332 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005333select_eintr:
5334 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335 FD_ZERO(&efds);
5336 FD_SET(fd, &rfds);
5337# if !defined(__QNX__) && !defined(__CYGWIN32__)
5338 /* For QNX select() always returns 1 if this is set. Why? */
5339 FD_SET(fd, &efds);
5340# endif
5341 maxfd = fd;
5342
5343# ifdef FEAT_SNIFF
5344 if (want_sniff_request)
5345 {
5346 FD_SET(fd_from_sniff, &rfds);
5347 FD_SET(fd_from_sniff, &efds);
5348 if (maxfd < fd_from_sniff)
5349 maxfd = fd_from_sniff;
5350 }
5351# endif
5352# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01005353 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005354 if (xterm_Shell != (Widget)0)
5355 {
5356 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5357 if (maxfd < ConnectionNumber(xterm_dpy))
5358 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005359
5360 /* An event may have already been read but not handled. In
5361 * particulary, XFlush may cause this. */
5362 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 }
5364# endif
5365# ifdef FEAT_MOUSE_GPM
5366 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5367 {
5368 FD_SET(gpm_fd, &rfds);
5369 FD_SET(gpm_fd, &efds);
5370 if (maxfd < gpm_fd)
5371 maxfd = gpm_fd;
5372 }
5373# endif
5374# ifdef USE_XSMP
5375 if (xsmp_icefd != -1)
5376 {
5377 FD_SET(xsmp_icefd, &rfds);
5378 FD_SET(xsmp_icefd, &efds);
5379 if (maxfd < xsmp_icefd)
5380 maxfd = xsmp_icefd;
5381 }
5382# endif
Bram Moolenaare0874f82016-01-24 20:36:41 +01005383# ifdef FEAT_CHANNEL
5384 maxfd = channel_select_setup(maxfd, &rfds);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005385# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005387 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005388# ifdef EINTR
5389 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005390 {
5391 /* Check whether window has been resized, EINTR may be caused by
5392 * SIGWINCH. */
5393 if (do_resize)
5394 handle_resize();
5395
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005396 /* Interrupted by a signal, need to try again. We ignore msec
5397 * here, because we do want to check even after a timeout if
5398 * characters are available. Needed for reading output of an
5399 * external command after the process has finished. */
5400 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005401 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005402# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005403# ifdef __TANDEM
5404 if (ret == -1 && errno == ENOTSUP)
5405 {
5406 FD_ZERO(&rfds);
5407 FD_ZERO(&efds);
5408 ret = 0;
5409 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005410# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005411# ifdef FEAT_MZSCHEME
5412 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005413 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005414 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415# endif
5416
5417# ifdef FEAT_SNIFF
5418 if (ret < 0 )
5419 sniff_disconnect(1);
5420 else if (ret > 0 && want_sniff_request)
5421 {
5422 if (FD_ISSET(fd_from_sniff, &efds))
5423 sniff_disconnect(1);
5424 if (FD_ISSET(fd_from_sniff, &rfds))
5425 sniff_request_waiting = 1;
5426 }
5427# endif
5428# ifdef FEAT_XCLIPBOARD
5429 if (ret > 0 && xterm_Shell != (Widget)0
5430 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5431 {
5432 xterm_update(); /* Maybe we should hand out clipboard */
5433 /* continue looping when we only got the X event and the input
5434 * buffer is empty */
5435 if (--ret == 0 && !input_available())
5436 {
5437 /* Try again */
5438 finished = FALSE;
5439 }
5440 }
5441# endif
5442# ifdef FEAT_MOUSE_GPM
5443 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5444 {
5445 if (FD_ISSET(gpm_fd, &efds))
5446 gpm_close();
5447 else if (FD_ISSET(gpm_fd, &rfds))
5448 *check_for_gpm = 1;
5449 }
5450# endif
5451# ifdef USE_XSMP
5452 if (ret > 0 && xsmp_icefd != -1)
5453 {
5454 if (FD_ISSET(xsmp_icefd, &efds))
5455 {
5456 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005457 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458 xsmp_close();
5459 if (--ret == 0)
5460 finished = FALSE; /* keep going if event was only one */
5461 }
5462 else if (FD_ISSET(xsmp_icefd, &rfds))
5463 {
5464 busy = TRUE;
5465 xsmp_handle_requests();
5466 busy = FALSE;
5467 if (--ret == 0)
5468 finished = FALSE; /* keep going if event was only one */
5469 }
5470 }
5471# endif
Bram Moolenaare0874f82016-01-24 20:36:41 +01005472#ifdef FEAT_CHANNEL
5473 if (ret > 0)
5474 ret = channel_select_check(ret, &rfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02005475#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476
5477#endif /* HAVE_SELECT */
5478
5479#ifdef MAY_LOOP
5480 if (finished || msec == 0)
5481 break;
5482
Bram Moolenaar93c88e02015-09-15 14:12:05 +02005483# ifdef FEAT_CLIENTSERVER
5484 if (server_waiting())
5485 break;
5486# endif
5487
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 /* We're going to loop around again, find out for how long */
5489 if (msec > 0)
5490 {
5491# ifdef USE_START_TV
5492 struct timeval mtv;
5493
5494 /* Compute remaining wait time. */
5495 gettimeofday(&mtv, NULL);
5496 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5497 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5498# else
5499 /* Guess we got interrupted halfway. */
5500 msec = msec / 2;
5501# endif
5502 if (msec <= 0)
5503 break; /* waited long enough */
5504 }
5505#endif
5506 }
5507
5508 return (ret > 0);
5509}
5510
Bram Moolenaar071d4272004-06-13 20:20:40 +00005511#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005513 * Expand a path into all matching files and/or directories. Handles "*",
5514 * "?", "[a-z]", "**", etc.
5515 * "path" has backslashes before chars that are not to be expanded.
5516 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517 */
5518 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005519mch_expandpath(
5520 garray_T *gap,
5521 char_u *path,
5522 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523{
Bram Moolenaar02743632005-07-25 20:42:36 +00005524 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005525}
5526#endif
5527
5528/*
5529 * mch_expand_wildcards() - this code does wild-card pattern matching using
5530 * the shell
5531 *
5532 * return OK for success, FAIL for error (you may lose some memory) and put
5533 * an error message in *file.
5534 *
5535 * num_pat is number of input patterns
5536 * pat is array of pointers to input patterns
5537 * num_file is pointer to number of matched file names
5538 * file is pointer to array of pointers to matched file names
5539 */
5540
5541#ifndef SEEK_SET
5542# define SEEK_SET 0
5543#endif
5544#ifndef SEEK_END
5545# define SEEK_END 2
5546#endif
5547
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005548#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005549
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 int
Bram Moolenaar05540972016-01-30 20:31:25 +01005551mch_expand_wildcards(
5552 int num_pat,
5553 char_u **pat,
5554 int *num_file,
5555 char_u ***file,
5556 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557{
5558 int i;
5559 size_t len;
5560 char_u *p;
5561 int dir;
5562#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005563 /*
5564 * This is the OS/2 implementation.
5565 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566# define EXPL_ALLOC_INC 16
5567 char_u **expl_files;
5568 size_t files_alloced, files_free;
5569 char_u *buf;
5570 int has_wildcard;
5571
5572 *num_file = 0; /* default: no files found */
5573 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5574 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5575 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5576 if (*file == NULL)
5577 return FAIL;
5578
5579 for (; num_pat > 0; num_pat--, pat++)
5580 {
5581 expl_files = NULL;
5582 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5583 /* expand environment var or home dir */
5584 buf = expand_env_save(*pat);
5585 else
5586 buf = vim_strsave(*pat);
5587 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005588 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 if (has_wildcard) /* yes, so expand them */
5590 expl_files = (char_u **)_fnexplode(buf);
5591
5592 /*
5593 * return value of buf if no wildcards left,
5594 * OR if no match AND EW_NOTFOUND is set.
5595 */
5596 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5597 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5598 { /* simply save the current contents of *buf */
5599 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5600 if (expl_files != NULL)
5601 {
5602 expl_files[0] = vim_strsave(buf);
5603 expl_files[1] = NULL;
5604 }
5605 }
5606 vim_free(buf);
5607
5608 /*
5609 * Count number of names resulting from expansion,
5610 * At the same time add a backslash to the end of names that happen to
5611 * be directories, and replace slashes with backslashes.
5612 */
5613 if (expl_files)
5614 {
5615 for (i = 0; (p = expl_files[i]) != NULL; i++)
5616 {
5617 dir = mch_isdir(p);
5618 /* If we don't want dirs and this is one, skip it */
5619 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5620 continue;
5621
Bram Moolenaara2031822006-03-07 22:29:51 +00005622 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01005623 if (!dir && (flags & EW_EXEC)
5624 && !mch_can_exe(p, NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00005625 continue;
5626
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 if (--files_free == 0)
5628 {
5629 /* need more room in table of pointers */
5630 files_alloced += EXPL_ALLOC_INC;
5631 *file = (char_u **)vim_realloc(*file,
5632 sizeof(char_u **) * files_alloced);
5633 if (*file == NULL)
5634 {
5635 EMSG(_(e_outofmem));
5636 *num_file = 0;
5637 return FAIL;
5638 }
5639 files_free = EXPL_ALLOC_INC;
5640 }
5641 slash_adjust(p);
5642 if (dir)
5643 {
5644 /* For a directory we add a '/', unless it's already
5645 * there. */
5646 len = STRLEN(p);
5647 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5648 {
5649 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005650 if (!after_pathsep((*file)[*num_file],
5651 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 {
5653 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005654 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 }
5656 }
5657 }
5658 else
5659 {
5660 (*file)[*num_file] = vim_strsave(p);
5661 }
5662
5663 /*
5664 * Error message already given by either alloc or vim_strsave.
5665 * Should return FAIL, but returning OK works also.
5666 */
5667 if ((*file)[*num_file] == NULL)
5668 break;
5669 (*num_file)++;
5670 }
5671 _fnexplodefree((char **)expl_files);
5672 }
5673 }
5674 return OK;
5675
5676#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005677 /*
5678 * This is the non-OS/2 implementation (really Unix).
5679 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 int j;
5681 char_u *tempname;
5682 char_u *command;
5683 FILE *fd;
5684 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005685#define STYLE_ECHO 0 /* use "echo", the default */
5686#define STYLE_GLOB 1 /* use "glob", for csh */
5687#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5688#define STYLE_PRINT 3 /* use "print -N", for zsh */
5689#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5690 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 int shell_style = STYLE_ECHO;
5692 int check_spaces;
5693 static int did_find_nul = FALSE;
5694 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005695 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005696 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697
5698 *num_file = 0; /* default: no files found */
5699 *file = NULL;
5700
5701 /*
5702 * If there are no wildcards, just copy the names to allocated memory.
5703 * Saves a lot of time, because we don't have to start a new shell.
5704 */
5705 if (!have_wildcard(num_pat, pat))
5706 return save_patterns(num_pat, pat, num_file, file);
5707
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005708# ifdef HAVE_SANDBOX
5709 /* Don't allow any shell command in the sandbox. */
5710 if (sandbox != 0 && check_secure())
5711 return FAIL;
5712# endif
5713
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 /*
5715 * Don't allow the use of backticks in secure and restricted mode.
5716 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005717 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 for (i = 0; i < num_pat; ++i)
5719 if (vim_strchr(pat[i], '`') != NULL
5720 && (check_restricted() || check_secure()))
5721 return FAIL;
5722
5723 /*
5724 * get a name for the temp file
5725 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02005726 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727 {
5728 EMSG(_(e_notmp));
5729 return FAIL;
5730 }
5731
5732 /*
5733 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005734 * file.
5735 * STYLE_BT: NL separated
5736 * If expanding `cmd` execute it directly.
5737 * STYLE_GLOB: NUL separated
5738 * If we use *csh, "glob" will work better than "echo".
5739 * STYLE_PRINT: NL or NUL separated
5740 * If we use *zsh, "print -N" will work better than "glob".
5741 * STYLE_VIMGLOB: NL separated
5742 * If we use *sh*, we define "vimglob()".
5743 * STYLE_ECHO: space separated.
5744 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 */
5746 if (num_pat == 1 && *pat[0] == '`'
5747 && (len = STRLEN(pat[0])) > 2
5748 && *(pat[0] + len - 1) == '`')
5749 shell_style = STYLE_BT;
5750 else if ((len = STRLEN(p_sh)) >= 3)
5751 {
5752 if (STRCMP(p_sh + len - 3, "csh") == 0)
5753 shell_style = STYLE_GLOB;
5754 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5755 shell_style = STYLE_PRINT;
5756 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005757 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5758 "sh") != NULL)
5759 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760
Bram Moolenaarc7247912008-01-13 12:54:11 +00005761 /* Compute the length of the command. We need 2 extra bytes: for the
5762 * optional '&' and for the NUL.
5763 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005765 if (shell_style == STYLE_VIMGLOB)
5766 len += STRLEN(sh_vimglob_func);
5767
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005768 for (i = 0; i < num_pat; ++i)
5769 {
5770 /* Count the length of the patterns in the same way as they are put in
5771 * "command" below. */
5772#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005774#else
5775 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005776 for (j = 0; pat[i][j] != NUL; ++j)
5777 {
5778 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5779 ++len; /* may add a backslash */
5780 ++len;
5781 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005782#endif
5783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 command = alloc(len);
5785 if (command == NULL)
5786 {
5787 /* out of memory */
5788 vim_free(tempname);
5789 return FAIL;
5790 }
5791
5792 /*
5793 * Build the shell command:
5794 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5795 * recognizes this).
5796 * - Add the shell command to print the expanded names.
5797 * - Add the temp file name.
5798 * - Add the file name patterns.
5799 */
5800 if (shell_style == STYLE_BT)
5801 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005802 /* change `command; command& ` to (command; command ) */
5803 STRCPY(command, "(");
5804 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005806 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 while (p > command && vim_iswhite(*p))
5808 --p;
5809 if (*p == '&') /* remove trailing '&' */
5810 {
5811 ampersent = TRUE;
5812 *p = ' ';
5813 }
5814 STRCAT(command, ">");
5815 }
5816 else
5817 {
5818 if (flags & EW_NOTFOUND)
5819 STRCPY(command, "set nonomatch; ");
5820 else
5821 STRCPY(command, "unset nonomatch; ");
5822 if (shell_style == STYLE_GLOB)
5823 STRCAT(command, "glob >");
5824 else if (shell_style == STYLE_PRINT)
5825 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005826 else if (shell_style == STYLE_VIMGLOB)
5827 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 else
5829 STRCAT(command, "echo >");
5830 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005831
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005833
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834 if (shell_style != STYLE_BT)
5835 for (i = 0; i < num_pat; ++i)
5836 {
5837 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005838 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005839 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840#ifdef USE_SYSTEM
5841 STRCAT(command, " \"");
5842 STRCAT(command, pat[i]);
5843 STRCAT(command, "\"");
5844#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005845 int intick = FALSE;
5846
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 p = command + STRLEN(command);
5848 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005849 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005850 {
5851 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005852 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005853 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5854 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005855 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005856 * backslash inside backticks, before a special character
5857 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005858 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005859 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5860 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005861 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005862 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005863 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02005864 else if (!intick
5865 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
5866 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005867 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02005868 * when inside ``. And not for $var when EW_KEEPDOLLAR is
5869 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005870 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005871
5872 /* Copy one character. */
5873 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005874 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 *p = NUL;
5876#endif
5877 }
5878 if (flags & EW_SILENT)
5879 show_shell_mess = FALSE;
5880 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005881 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882
5883 /*
5884 * Using zsh -G: If a pattern has no matches, it is just deleted from
5885 * the argument list, otherwise zsh gives an error message and doesn't
5886 * expand any other pattern.
5887 */
5888 if (shell_style == STYLE_PRINT)
5889 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5890
5891 /*
5892 * If we use -f then shell variables set in .cshrc won't get expanded.
5893 * vi can do it, so we will too, but it is only necessary if there is a "$"
5894 * in one of the patterns, otherwise we can still use the fast option.
5895 */
5896 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5897 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5898
5899 /*
5900 * execute the shell command
5901 */
5902 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5903
5904 /* When running in the background, give it some time to create the temp
5905 * file, but don't wait for it to finish. */
5906 if (ampersent)
5907 mch_delay(10L, TRUE);
5908
5909 extra_shell_arg = NULL; /* cleanup */
5910 show_shell_mess = TRUE;
5911 vim_free(command);
5912
Bram Moolenaarc7247912008-01-13 12:54:11 +00005913 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 {
5915 mch_remove(tempname);
5916 vim_free(tempname);
5917 /*
5918 * With interactive completion, the error message is not printed.
5919 * However with USE_SYSTEM, I don't know how to turn off error messages
5920 * from the shell, so screen may still get messed up -- webb.
5921 */
5922#ifndef USE_SYSTEM
5923 if (!(flags & EW_SILENT))
5924#endif
5925 {
5926 redraw_later_clear(); /* probably messed up screen */
5927 msg_putchar('\n'); /* clear bottom line quickly */
5928 cmdline_row = Rows - 1; /* continue on last line */
5929#ifdef USE_SYSTEM
5930 if (!(flags & EW_SILENT))
5931#endif
5932 {
5933 MSG(_(e_wildexpand));
5934 msg_start(); /* don't overwrite this message */
5935 }
5936 }
5937 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5938 * EW_NOTFOUND is given */
5939 if (shell_style == STYLE_BT)
5940 return FAIL;
5941 goto notfound;
5942 }
5943
5944 /*
5945 * read the names from the file into memory
5946 */
5947 fd = fopen((char *)tempname, READBIN);
5948 if (fd == NULL)
5949 {
5950 /* Something went wrong, perhaps a file name with a special char. */
5951 if (!(flags & EW_SILENT))
5952 {
5953 MSG(_(e_wildexpand));
5954 msg_start(); /* don't overwrite this message */
5955 }
5956 vim_free(tempname);
5957 goto notfound;
5958 }
5959 fseek(fd, 0L, SEEK_END);
5960 len = ftell(fd); /* get size of temp file */
5961 fseek(fd, 0L, SEEK_SET);
5962 buffer = alloc(len + 1);
5963 if (buffer == NULL)
5964 {
5965 /* out of memory */
5966 mch_remove(tempname);
5967 vim_free(tempname);
5968 fclose(fd);
5969 return FAIL;
5970 }
5971 i = fread((char *)buffer, 1, len, fd);
5972 fclose(fd);
5973 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005974 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975 {
5976 /* unexpected read error */
5977 EMSG2(_(e_notread), tempname);
5978 vim_free(tempname);
5979 vim_free(buffer);
5980 return FAIL;
5981 }
5982 vim_free(tempname);
5983
Bram Moolenaarc7247912008-01-13 12:54:11 +00005984# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5986 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02005987 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5989 *p++ = buffer[i];
5990 len = p - buffer;
5991# endif
5992
5993
5994 /* file names are separated with Space */
5995 if (shell_style == STYLE_ECHO)
5996 {
5997 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5998 p = buffer;
5999 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6000 {
6001 while (*p != ' ' && *p != '\n')
6002 ++p;
6003 p = skipwhite(p); /* skip to next entry */
6004 }
6005 }
6006 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006007 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 {
6009 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6010 p = buffer;
6011 for (i = 0; *p != NUL; ++i) /* count number of entries */
6012 {
6013 while (*p != '\n' && *p != NUL)
6014 ++p;
6015 if (*p != NUL)
6016 ++p;
6017 p = skipwhite(p); /* skip leading white space */
6018 }
6019 }
6020 /* file names are separated with NUL */
6021 else
6022 {
6023 /*
6024 * Some versions of zsh use spaces instead of NULs to separate
6025 * results. Only do this when there is no NUL before the end of the
6026 * buffer, otherwise we would never be able to use file names with
6027 * embedded spaces when zsh does use NULs.
6028 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6029 * don't check for spaces again.
6030 */
6031 check_spaces = FALSE;
6032 if (shell_style == STYLE_PRINT && !did_find_nul)
6033 {
6034 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006035 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006036 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 did_find_nul = TRUE;
6038 else
6039 check_spaces = TRUE;
6040 }
6041
6042 /*
6043 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6044 * already is one, for STYLE_GLOB it needs to be added.
6045 */
6046 if (len && buffer[len - 1] == NUL)
6047 --len;
6048 else
6049 buffer[len] = NUL;
6050 i = 0;
6051 for (p = buffer; p < buffer + len; ++p)
6052 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6053 {
6054 ++i;
6055 *p = NUL;
6056 }
6057 if (len)
6058 ++i; /* count last entry */
6059 }
6060 if (i == 0)
6061 {
6062 /*
6063 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6064 * /bin/sh will happily expand it to nothing rather than returning an
6065 * error; and hey, it's good to check anyway -- webb.
6066 */
6067 vim_free(buffer);
6068 goto notfound;
6069 }
6070 *num_file = i;
6071 *file = (char_u **)alloc(sizeof(char_u *) * i);
6072 if (*file == NULL)
6073 {
6074 /* out of memory */
6075 vim_free(buffer);
6076 return FAIL;
6077 }
6078
6079 /*
6080 * Isolate the individual file names.
6081 */
6082 p = buffer;
6083 for (i = 0; i < *num_file; ++i)
6084 {
6085 (*file)[i] = p;
6086 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006087 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6088 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006090 while (!(shell_style == STYLE_ECHO && *p == ' ')
6091 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 ++p;
6093 if (p == buffer + len) /* last entry */
6094 *p = NUL;
6095 else
6096 {
6097 *p++ = NUL;
6098 p = skipwhite(p); /* skip to next entry */
6099 }
6100 }
6101 else /* NUL separates */
6102 {
6103 while (*p && p < buffer + len) /* skip entry */
6104 ++p;
6105 ++p; /* skip NUL */
6106 }
6107 }
6108
6109 /*
6110 * Move the file names to allocated memory.
6111 */
6112 for (j = 0, i = 0; i < *num_file; ++i)
6113 {
6114 /* Require the files to exist. Helps when using /bin/sh */
6115 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6116 continue;
6117
6118 /* check if this entry should be included */
6119 dir = (mch_isdir((*file)[i]));
6120 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6121 continue;
6122
Bram Moolenaara2031822006-03-07 22:29:51 +00006123 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006124 if (!dir && (flags & EW_EXEC)
6125 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006126 continue;
6127
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6129 if (p)
6130 {
6131 STRCPY(p, (*file)[i]);
6132 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006133 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134 (*file)[j++] = p;
6135 }
6136 }
6137 vim_free(buffer);
6138 *num_file = j;
6139
6140 if (*num_file == 0) /* rejected all entries */
6141 {
6142 vim_free(*file);
6143 *file = NULL;
6144 goto notfound;
6145 }
6146
6147 return OK;
6148
6149notfound:
6150 if (flags & EW_NOTFOUND)
6151 return save_patterns(num_pat, pat, num_file, file);
6152 return FAIL;
6153
6154#endif /* __EMX__ */
6155}
6156
6157#endif /* VMS */
6158
6159#ifndef __EMX__
6160 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006161save_patterns(
6162 int num_pat,
6163 char_u **pat,
6164 int *num_file,
6165 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166{
6167 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006168 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169
6170 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6171 if (*file == NULL)
6172 return FAIL;
6173 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006174 {
6175 s = vim_strsave(pat[i]);
6176 if (s != NULL)
6177 /* Be compatible with expand_filename(): halve the number of
6178 * backslashes. */
6179 backslash_halve(s);
6180 (*file)[i] = s;
6181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182 *num_file = num_pat;
6183 return OK;
6184}
6185#endif
6186
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187/*
6188 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6189 * expand.
6190 */
6191 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006192mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006194 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196 if (*p == '\\' && p[1] != NUL)
6197 ++p;
6198 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006199 if (vim_strchr((char_u *)
6200#ifdef VMS
6201 "*?%"
6202#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204#endif
6205 , *p) != NULL)
6206 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207 }
6208 return FALSE;
6209}
6210
6211/*
6212 * Return TRUE if the string "p" contains a wildcard.
6213 * Don't recognize '~' at the end as a wildcard.
6214 */
6215 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006216mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006218 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 if (*p == '\\' && p[1] != NUL)
6221 ++p;
6222 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 if (vim_strchr((char_u *)
6224#ifdef VMS
6225 "*?%$"
6226#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228#endif
6229 , *p) != NULL
6230 || (*p == '~' && p[1] != NUL))
6231 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 }
6233 return FALSE;
6234}
6235
6236#ifndef __EMX__
6237 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006238have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239{
6240 int i;
6241
6242 for (i = 0; i < num; i++)
6243 if (mch_has_wildcard(file[i]))
6244 return 1;
6245 return 0;
6246}
6247
6248 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006249have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250{
6251 int i;
6252
6253 for (i = 0; i < num; i++)
6254 if (vim_strchr(file[i], '$') != NULL)
6255 return TRUE;
6256 return FALSE;
6257}
6258#endif /* ifndef __EMX__ */
6259
6260#ifndef HAVE_RENAME
6261/*
6262 * Scaled-down version of rename(), which is missing in Xenix.
6263 * This version can only move regular files and will fail if the
6264 * destination exists.
6265 */
6266 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006267mch_rename(const char *src, *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268{
6269 struct stat st;
6270
6271 if (stat(dest, &st) >= 0) /* fail if destination exists */
6272 return -1;
6273 if (link(src, dest) != 0) /* link file to new name */
6274 return -1;
6275 if (mch_remove(src) == 0) /* delete link to old name */
6276 return 0;
6277 return -1;
6278}
6279#endif /* !HAVE_RENAME */
6280
6281#ifdef FEAT_MOUSE_GPM
6282/*
6283 * Initializes connection with gpm (if it isn't already opened)
6284 * Return 1 if succeeded (or connection already opened), 0 if failed
6285 */
6286 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006287gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288{
6289 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6290
6291 if (!gpm_flag)
6292 {
6293 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6294 gpm_connect.defaultMask = ~GPM_HARD;
6295 /* Default handling for mouse move*/
6296 gpm_connect.minMod = 0; /* Handle any modifier keys */
6297 gpm_connect.maxMod = 0xffff;
6298 if (Gpm_Open(&gpm_connect, 0) > 0)
6299 {
6300 /* gpm library tries to handling TSTP causes
6301 * problems. Anyways, we close connection to Gpm whenever
6302 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006303 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006305# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006307# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 return 1; /* succeed */
6309 }
6310 if (gpm_fd == -2)
6311 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6312 return 0;
6313 }
6314 return 1; /* already open */
6315}
6316
6317/*
6318 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 */
6320 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006321gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322{
6323 if (gpm_flag && gpm_fd >= 0) /* if Open */
6324 Gpm_Close();
6325}
6326
6327/* Reads gpm event and adds special keys to input buf. Returns length of
6328 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006329 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 */
6331 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006332mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333{
6334 int button;
6335 static Gpm_Event gpm_event;
6336 char_u string[6];
6337 int_u vim_modifiers;
6338 int row,col;
6339 unsigned char buttons_mask;
6340 unsigned char gpm_modifiers;
6341 static unsigned char old_buttons = 0;
6342
6343 Gpm_GetEvent(&gpm_event);
6344
6345#ifdef FEAT_GUI
6346 /* Don't put events in the input queue now. */
6347 if (hold_gui_events)
6348 return 0;
6349#endif
6350
6351 row = gpm_event.y - 1;
6352 col = gpm_event.x - 1;
6353
6354 string[0] = ESC; /* Our termcode */
6355 string[1] = 'M';
6356 string[2] = 'G';
6357 switch (GPM_BARE_EVENTS(gpm_event.type))
6358 {
6359 case GPM_DRAG:
6360 string[3] = MOUSE_DRAG;
6361 break;
6362 case GPM_DOWN:
6363 buttons_mask = gpm_event.buttons & ~old_buttons;
6364 old_buttons = gpm_event.buttons;
6365 switch (buttons_mask)
6366 {
6367 case GPM_B_LEFT:
6368 button = MOUSE_LEFT;
6369 break;
6370 case GPM_B_MIDDLE:
6371 button = MOUSE_MIDDLE;
6372 break;
6373 case GPM_B_RIGHT:
6374 button = MOUSE_RIGHT;
6375 break;
6376 default:
6377 return 0;
6378 /*Don't know what to do. Can more than one button be
6379 * reported in one event? */
6380 }
6381 string[3] = (char_u)(button | 0x20);
6382 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6383 break;
6384 case GPM_UP:
6385 string[3] = MOUSE_RELEASE;
6386 old_buttons &= ~gpm_event.buttons;
6387 break;
6388 default:
6389 return 0;
6390 }
6391 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6392 gpm_modifiers = gpm_event.modifiers;
6393 vim_modifiers = 0x0;
6394 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6395 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6396 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6397 */
6398 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6399 vim_modifiers |= MOUSE_SHIFT;
6400
6401 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6402 vim_modifiers |= MOUSE_CTRL;
6403 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6404 vim_modifiers |= MOUSE_ALT;
6405 string[3] |= vim_modifiers;
6406 string[4] = (char_u)(col + ' ' + 1);
6407 string[5] = (char_u)(row + ' ' + 1);
6408 add_to_input_buf(string, 6);
6409 return 6;
6410}
6411#endif /* FEAT_MOUSE_GPM */
6412
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006413#ifdef FEAT_SYSMOUSE
6414/*
6415 * Initialize connection with sysmouse.
6416 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6417 * output, any sysmouse output than will be processed via sig_sysmouse().
6418 * Return OK if succeeded, FAIL if failed.
6419 */
6420 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006421sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006422{
6423 struct mouse_info mouse;
6424
6425 mouse.operation = MOUSE_MODE;
6426 mouse.u.mode.mode = 0;
6427 mouse.u.mode.signal = SIGUSR2;
6428 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6429 {
6430 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6431 mouse.operation = MOUSE_SHOW;
6432 ioctl(1, CONS_MOUSECTL, &mouse);
6433 return OK;
6434 }
6435 return FAIL;
6436}
6437
6438/*
6439 * Stop processing SIGUSR2 signals, and also make sure that
6440 * virtual console do not send us any sysmouse related signal.
6441 */
6442 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006443sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006444{
6445 struct mouse_info mouse;
6446
6447 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6448 mouse.operation = MOUSE_MODE;
6449 mouse.u.mode.mode = 0;
6450 mouse.u.mode.signal = 0;
6451 ioctl(1, CONS_MOUSECTL, &mouse);
6452}
6453
6454/*
6455 * Gets info from sysmouse and adds special keys to input buf.
6456 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006457 static RETSIGTYPE
6458sig_sysmouse SIGDEFARG(sigarg)
6459{
6460 struct mouse_info mouse;
6461 struct video_info video;
6462 char_u string[6];
6463 int row, col;
6464 int button;
6465 int buttons;
6466 static int oldbuttons = 0;
6467
6468#ifdef FEAT_GUI
6469 /* Don't put events in the input queue now. */
6470 if (hold_gui_events)
6471 return;
6472#endif
6473
6474 mouse.operation = MOUSE_GETINFO;
6475 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6476 && ioctl(1, FBIO_MODEINFO, &video) != -1
6477 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6478 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6479 {
6480 row = mouse.u.data.y / video.vi_cheight;
6481 col = mouse.u.data.x / video.vi_cwidth;
6482 buttons = mouse.u.data.buttons;
6483 string[0] = ESC; /* Our termcode */
6484 string[1] = 'M';
6485 string[2] = 'S';
6486 if (oldbuttons == buttons && buttons != 0)
6487 {
6488 button = MOUSE_DRAG;
6489 }
6490 else
6491 {
6492 switch (buttons)
6493 {
6494 case 0:
6495 button = MOUSE_RELEASE;
6496 break;
6497 case 1:
6498 button = MOUSE_LEFT;
6499 break;
6500 case 2:
6501 button = MOUSE_MIDDLE;
6502 break;
6503 case 4:
6504 button = MOUSE_RIGHT;
6505 break;
6506 default:
6507 return;
6508 }
6509 oldbuttons = buttons;
6510 }
6511 string[3] = (char_u)(button);
6512 string[4] = (char_u)(col + ' ' + 1);
6513 string[5] = (char_u)(row + ' ' + 1);
6514 add_to_input_buf(string, 6);
6515 }
6516 return;
6517}
6518#endif /* FEAT_SYSMOUSE */
6519
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01006521typedef char_u * (*STRPROCSTR)(char_u *);
6522typedef char_u * (*INTPROCSTR)(int);
6523typedef int (*STRPROCINT)(char_u *);
6524typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525
6526/*
6527 * Call a DLL routine which takes either a string or int param
6528 * and returns an allocated string.
6529 */
6530 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006531mch_libcall(
6532 char_u *libname,
6533 char_u *funcname,
6534 char_u *argstring, /* NULL when using a argint */
6535 int argint,
6536 char_u **string_result,/* NULL when using number_result */
6537 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538{
6539# if defined(USE_DLOPEN)
6540 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006541 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542# else
6543 shl_t hinstLib;
6544# endif
6545 STRPROCSTR ProcAdd;
6546 INTPROCSTR ProcAddI;
6547 char_u *retval_str = NULL;
6548 int retval_int = 0;
6549 int success = FALSE;
6550
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006551 /*
6552 * Get a handle to the DLL module.
6553 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006555 /* First clear any error, it's not cleared by the dlopen() call. */
6556 (void)dlerror();
6557
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558 hinstLib = dlopen((char *)libname, RTLD_LAZY
6559# ifdef RTLD_LOCAL
6560 | RTLD_LOCAL
6561# endif
6562 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006563 if (hinstLib == NULL)
6564 {
6565 /* "dlerr" must be used before dlclose() */
6566 dlerr = (char *)dlerror();
6567 if (dlerr != NULL)
6568 EMSG2(_("dlerror = \"%s\""), dlerr);
6569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570# else
6571 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6572# endif
6573
6574 /* If the handle is valid, try to get the function address. */
6575 if (hinstLib != NULL)
6576 {
6577# ifdef HAVE_SETJMP_H
6578 /*
6579 * Catch a crash when calling the library function. For example when
6580 * using a number where a string pointer is expected.
6581 */
6582 mch_startjmp();
6583 if (SETJMP(lc_jump_env) != 0)
6584 {
6585 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006586# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006587 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006588# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 mch_didjmp();
6590 }
6591 else
6592# endif
6593 {
6594 retval_str = NULL;
6595 retval_int = 0;
6596
6597 if (argstring != NULL)
6598 {
6599# if defined(USE_DLOPEN)
6600 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006601 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602# else
6603 if (shl_findsym(&hinstLib, (const char *)funcname,
6604 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6605 ProcAdd = NULL;
6606# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006607 if ((success = (ProcAdd != NULL
6608# if defined(USE_DLOPEN)
6609 && dlerr == NULL
6610# endif
6611 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 {
6613 if (string_result == NULL)
6614 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6615 else
6616 retval_str = (ProcAdd)(argstring);
6617 }
6618 }
6619 else
6620 {
6621# if defined(USE_DLOPEN)
6622 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006623 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624# else
6625 if (shl_findsym(&hinstLib, (const char *)funcname,
6626 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6627 ProcAddI = NULL;
6628# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006629 if ((success = (ProcAddI != NULL
6630# if defined(USE_DLOPEN)
6631 && dlerr == NULL
6632# endif
6633 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 {
6635 if (string_result == NULL)
6636 retval_int = ((INTPROCINT)ProcAddI)(argint);
6637 else
6638 retval_str = (ProcAddI)(argint);
6639 }
6640 }
6641
6642 /* Save the string before we free the library. */
6643 /* Assume that a "1" or "-1" result is an illegal pointer. */
6644 if (string_result == NULL)
6645 *number_result = retval_int;
6646 else if (retval_str != NULL
6647 && retval_str != (char_u *)1
6648 && retval_str != (char_u *)-1)
6649 *string_result = vim_strsave(retval_str);
6650 }
6651
6652# ifdef HAVE_SETJMP_H
6653 mch_endjmp();
6654# ifdef SIGHASARG
6655 if (lc_signal != 0)
6656 {
6657 int i;
6658
6659 /* try to find the name of this signal */
6660 for (i = 0; signal_info[i].sig != -1; i++)
6661 if (lc_signal == signal_info[i].sig)
6662 break;
6663 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6664 }
6665# endif
6666# endif
6667
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006669 /* "dlerr" must be used before dlclose() */
6670 if (dlerr != NULL)
6671 EMSG2(_("dlerror = \"%s\""), dlerr);
6672
6673 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 (void)dlclose(hinstLib);
6675# else
6676 (void)shl_unload(hinstLib);
6677# endif
6678 }
6679
6680 if (!success)
6681 {
6682 EMSG2(_(e_libcall), funcname);
6683 return FAIL;
6684 }
6685
6686 return OK;
6687}
6688#endif
6689
6690#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6691static int xterm_trace = -1; /* default: disabled */
6692static int xterm_button;
6693
6694/*
6695 * Setup a dummy window for X selections in a terminal.
6696 */
6697 void
Bram Moolenaar05540972016-01-30 20:31:25 +01006698setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699{
6700 int z = 0;
6701 char *strp = "";
6702 Widget AppShell;
6703
6704 if (!x_connect_to_server())
6705 return;
6706
6707 open_app_context();
6708 if (app_context != NULL && xterm_Shell == (Widget)0)
6709 {
6710 int (*oldhandler)();
6711#if defined(HAVE_SETJMP_H)
6712 int (*oldIOhandler)();
6713#endif
6714# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6715 struct timeval start_tv;
6716
6717 if (p_verbose > 0)
6718 gettimeofday(&start_tv, NULL);
6719# endif
6720
6721 /* Ignore X errors while opening the display */
6722 oldhandler = XSetErrorHandler(x_error_check);
6723
6724#if defined(HAVE_SETJMP_H)
6725 /* Ignore X IO errors while opening the display */
6726 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6727 mch_startjmp();
6728 if (SETJMP(lc_jump_env) != 0)
6729 {
6730 mch_didjmp();
6731 xterm_dpy = NULL;
6732 }
6733 else
6734#endif
6735 {
6736 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6737 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6738#if defined(HAVE_SETJMP_H)
6739 mch_endjmp();
6740#endif
6741 }
6742
6743#if defined(HAVE_SETJMP_H)
6744 /* Now handle X IO errors normally. */
6745 (void)XSetIOErrorHandler(oldIOhandler);
6746#endif
6747 /* Now handle X errors normally. */
6748 (void)XSetErrorHandler(oldhandler);
6749
6750 if (xterm_dpy == NULL)
6751 {
6752 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006753 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 return;
6755 }
6756
6757 /* Catch terminating error of the X server connection. */
6758 (void)XSetIOErrorHandler(x_IOerror_handler);
6759
6760# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6761 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006762 {
6763 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006765 verbose_leave();
6766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767# endif
6768
6769 /* Create a Shell to make converters work. */
6770 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6771 applicationShellWidgetClass, xterm_dpy,
6772 NULL);
6773 if (AppShell == (Widget)0)
6774 return;
6775 xterm_Shell = XtVaCreatePopupShell("VIM",
6776 topLevelShellWidgetClass, AppShell,
6777 XtNmappedWhenManaged, 0,
6778 XtNwidth, 1,
6779 XtNheight, 1,
6780 NULL);
6781 if (xterm_Shell == (Widget)0)
6782 return;
6783
6784 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006785 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 if (x11_display == NULL)
6787 x11_display = xterm_dpy;
6788
6789 XtRealizeWidget(xterm_Shell);
6790 XSync(xterm_dpy, False);
6791 xterm_update();
6792 }
6793 if (xterm_Shell != (Widget)0)
6794 {
6795 clip_init(TRUE);
6796 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6797 x11_window = (Window)atol(strp);
6798 /* Check if $WINDOWID is valid. */
6799 if (test_x11_window(xterm_dpy) == FAIL)
6800 x11_window = 0;
6801 if (x11_window != 0)
6802 xterm_trace = 0;
6803 }
6804}
6805
6806 void
Bram Moolenaar05540972016-01-30 20:31:25 +01006807start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808{
6809 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6810 return;
6811 xterm_trace = 1;
6812 xterm_button = button;
6813 do_xterm_trace();
6814}
6815
6816
6817 void
Bram Moolenaar05540972016-01-30 20:31:25 +01006818stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819{
6820 if (xterm_trace < 0)
6821 return;
6822 xterm_trace = 0;
6823}
6824
6825/*
6826 * Query the xterm pointer and generate mouse termcodes if necessary
6827 * return TRUE if dragging is active, else FALSE
6828 */
6829 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006830do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831{
6832 Window root, child;
6833 int root_x, root_y;
6834 int win_x, win_y;
6835 int row, col;
6836 int_u mask_return;
6837 char_u buf[50];
6838 char_u *strp;
6839 long got_hints;
6840 static char_u *mouse_code;
6841 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6842 static int prev_row = 0, prev_col = 0;
6843 static XSizeHints xterm_hints;
6844
6845 if (xterm_trace <= 0)
6846 return FALSE;
6847
6848 if (xterm_trace == 1)
6849 {
6850 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006851 * have changed recently. */
6852 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6853 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 || xterm_hints.width_inc <= 1
6855 || xterm_hints.height_inc <= 1)
6856 {
6857 xterm_trace = -1; /* Not enough data -- disable tracing */
6858 return FALSE;
6859 }
6860
6861 /* Rely on the same mouse code for the duration of this */
6862 mouse_code = find_termcode(mouse_name);
6863 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02006864 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865 xterm_trace = 2;
6866
6867 /* Find the offset of the chars, there might be a scrollbar on the
6868 * left of the window and/or a menu on the top (eterm etc.) */
6869 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6870 &win_x, &win_y, &mask_return);
6871 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6872 - (xterm_hints.height_inc / 2);
6873 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6874 xterm_hints.y = 2;
6875 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6876 - (xterm_hints.width_inc / 2);
6877 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6878 xterm_hints.x = 2;
6879 return TRUE;
6880 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006881 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 {
6883 xterm_trace = 0;
6884 return FALSE;
6885 }
6886
6887 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6888 &win_x, &win_y, &mask_return);
6889
6890 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6891 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6892 if (row == prev_row && col == prev_col)
6893 return TRUE;
6894
6895 STRCPY(buf, mouse_code);
6896 strp = buf + STRLEN(buf);
6897 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6898 *strp++ = (char_u)(col + ' ' + 1);
6899 *strp++ = (char_u)(row + ' ' + 1);
6900 *strp = 0;
6901 add_to_input_buf(buf, STRLEN(buf));
6902
6903 prev_row = row;
6904 prev_col = col;
6905 return TRUE;
6906}
6907
6908# if defined(FEAT_GUI) || defined(PROTO)
6909/*
6910 * Destroy the display, window and app_context. Required for GTK.
6911 */
6912 void
Bram Moolenaar05540972016-01-30 20:31:25 +01006913clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914{
6915 if (xterm_Shell != (Widget)0)
6916 {
6917 XtDestroyWidget(xterm_Shell);
6918 xterm_Shell = (Widget)0;
6919 }
6920 if (xterm_dpy != NULL)
6921 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006922# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 /* Lesstif and Solaris crash here, lose some memory */
6924 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006925# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 if (x11_display == xterm_dpy)
6927 x11_display = NULL;
6928 xterm_dpy = NULL;
6929 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006930# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 if (app_context != (XtAppContext)NULL)
6932 {
6933 /* Lesstif and Solaris crash here, lose some memory */
6934 XtDestroyApplicationContext(app_context);
6935 app_context = (XtAppContext)NULL;
6936 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006937# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938}
6939# endif
6940
6941/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01006942 * Catch up with GUI or X events.
6943 */
6944 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006945clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01006946{
6947# ifdef FEAT_GUI
6948 if (gui.in_use)
6949 gui_mch_update();
6950 else
6951# endif
6952 if (xterm_Shell != (Widget)0)
6953 xterm_update();
6954}
6955
6956/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 * Catch up with any queued X events. This may put keyboard input into the
6958 * input buffer, call resize call-backs, trigger timers etc. If there is
6959 * nothing in the X event queue (& no timers pending), then we return
6960 * immediately.
6961 */
6962 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01006963xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964{
6965 XEvent event;
6966
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006967 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006969 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006971 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006972 break;
6973
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006974 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006975 {
6976 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006977 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006978#ifdef FEAT_CLIENTSERVER
6979 {
6980 XPropertyEvent *e = (XPropertyEvent *)&event;
6981
6982 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006984 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006985 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006987 XtDispatchEvent(&event);
6988 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01006989 else
6990 {
6991 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006992 XtAppProcessEvent(app_context, mask);
6993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 }
6995}
6996
6997 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006998clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999{
7000 if (xterm_Shell != (Widget)0)
7001 return clip_x11_own_selection(xterm_Shell, cbd);
7002 return FAIL;
7003}
7004
7005 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007006clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007{
7008 if (xterm_Shell != (Widget)0)
7009 clip_x11_lose_selection(xterm_Shell, cbd);
7010}
7011
7012 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007013clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014{
7015 if (xterm_Shell != (Widget)0)
7016 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7017}
7018
7019 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007020clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021{
7022 clip_x11_set_selection(cbd);
7023}
7024#endif
7025
7026
7027#if defined(USE_XSMP) || defined(PROTO)
7028/*
7029 * Code for X Session Management Protocol.
7030 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007031static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7032static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7033static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7034static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7035static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036
7037
7038# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007039static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007040
7041/*
7042 * This is our chance to ask the user if they want to save,
7043 * or abort the logout
7044 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007046xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047{
7048 cmdmod_T save_cmdmod;
7049 int cancel_shutdown = False;
7050
7051 save_cmdmod = cmdmod;
7052 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007053 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 /* Mustn't logout */
7055 cancel_shutdown = True;
7056 cmdmod = save_cmdmod;
7057 setcursor(); /* position cursor */
7058 out_flush();
7059
7060 /* Done interaction */
7061 SmcInteractDone(smc_conn, cancel_shutdown);
7062
7063 /* Finish off
7064 * Only end save-yourself here if we're not cancelling shutdown;
7065 * we'll get a cancelled callback later in which we'll end it.
7066 * Hopefully get around glitchy SMs (like GNOME-1)
7067 */
7068 if (!cancel_shutdown)
7069 {
7070 xsmp.save_yourself = False;
7071 SmcSaveYourselfDone(smc_conn, True);
7072 }
7073}
7074# endif
7075
7076/*
7077 * Callback that starts save-yourself.
7078 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007080xsmp_handle_save_yourself(
7081 SmcConn smc_conn,
7082 SmPointer client_data UNUSED,
7083 int save_type UNUSED,
7084 Bool shutdown,
7085 int interact_style UNUSED,
7086 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087{
7088 /* Handle already being in saveyourself */
7089 if (xsmp.save_yourself)
7090 SmcSaveYourselfDone(smc_conn, True);
7091 xsmp.save_yourself = True;
7092 xsmp.shutdown = shutdown;
7093
7094 /* First up, preserve all files */
7095 out_flush();
7096 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7097
7098 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007099 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100
7101# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7102 /* Now see if we can ask about unsaved files */
7103 if (shutdown && !fast && gui.in_use)
7104 /* Need to interact with user, but need SM's permission */
7105 SmcInteractRequest(smc_conn, SmDialogError,
7106 xsmp_handle_interaction, client_data);
7107 else
7108# endif
7109 {
7110 /* Can stop the cycle here */
7111 SmcSaveYourselfDone(smc_conn, True);
7112 xsmp.save_yourself = False;
7113 }
7114}
7115
7116
7117/*
7118 * Callback to warn us of imminent death.
7119 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007121xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122{
7123 xsmp_close();
7124
7125 /* quit quickly leaving swapfiles for modified buffers behind */
7126 getout_preserve_modified(0);
7127}
7128
7129
7130/*
7131 * Callback to tell us that save-yourself has completed.
7132 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007134xsmp_save_complete(
7135 SmcConn smc_conn UNUSED,
7136 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137{
7138 xsmp.save_yourself = False;
7139}
7140
7141
7142/*
7143 * Callback to tell us that an instigated shutdown was cancelled
7144 * (maybe even by us)
7145 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007147xsmp_shutdown_cancelled(
7148 SmcConn smc_conn,
7149 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150{
7151 if (xsmp.save_yourself)
7152 SmcSaveYourselfDone(smc_conn, True);
7153 xsmp.save_yourself = False;
7154 xsmp.shutdown = False;
7155}
7156
7157
7158/*
7159 * Callback to tell us that a new ICE connection has been established.
7160 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007162xsmp_ice_connection(
7163 IceConn iceConn,
7164 IcePointer clientData UNUSED,
7165 Bool opening,
7166 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007167{
7168 /* Intercept creation of ICE connection fd */
7169 if (opening)
7170 {
7171 xsmp_icefd = IceConnectionNumber(iceConn);
7172 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7173 }
7174}
7175
7176
7177/* Handle any ICE processing that's required; return FAIL if SM lost */
7178 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007179xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180{
7181 Bool rep;
7182
7183 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7184 == IceProcessMessagesIOError)
7185 {
7186 /* Lost ICE */
7187 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007188 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189 xsmp_close();
7190 return FAIL;
7191 }
7192 else
7193 return OK;
7194}
7195
7196static int dummy;
7197
7198/* Set up X Session Management Protocol */
7199 void
7200xsmp_init(void)
7201{
7202 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 SmcCallbacks smcallbacks;
7204#if 0
7205 SmPropValue smname;
7206 SmProp smnameprop;
7207 SmProp *smprops[1];
7208#endif
7209
7210 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007211 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212
7213 xsmp.save_yourself = xsmp.shutdown = False;
7214
7215 /* Set up SM callbacks - must have all, even if they're not used */
7216 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7217 smcallbacks.save_yourself.client_data = NULL;
7218 smcallbacks.die.callback = xsmp_die;
7219 smcallbacks.die.client_data = NULL;
7220 smcallbacks.save_complete.callback = xsmp_save_complete;
7221 smcallbacks.save_complete.client_data = NULL;
7222 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7223 smcallbacks.shutdown_cancelled.client_data = NULL;
7224
7225 /* Set up a watch on ICE connection creations. The "dummy" argument is
7226 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7227 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7228 {
7229 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007230 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 return;
7232 }
7233
7234 /* Create an SM connection */
7235 xsmp.smcconn = SmcOpenConnection(
7236 NULL,
7237 NULL,
7238 SmProtoMajor,
7239 SmProtoMinor,
7240 SmcSaveYourselfProcMask | SmcDieProcMask
7241 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7242 &smcallbacks,
7243 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007244 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 sizeof(errorstring),
7246 errorstring);
7247 if (xsmp.smcconn == NULL)
7248 {
7249 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007250
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007252 {
7253 vim_snprintf(errorreport, sizeof(errorreport),
7254 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7255 verb_msg((char_u *)errorreport);
7256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 return;
7258 }
7259 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7260
7261#if 0
7262 /* ID ourselves */
7263 smname.value = "vim";
7264 smname.length = 3;
7265 smnameprop.name = "SmProgram";
7266 smnameprop.type = "SmARRAY8";
7267 smnameprop.num_vals = 1;
7268 smnameprop.vals = &smname;
7269
7270 smprops[0] = &smnameprop;
7271 SmcSetProperties(xsmp.smcconn, 1, smprops);
7272#endif
7273}
7274
7275
7276/* Shut down XSMP comms. */
7277 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007278xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007279{
7280 if (xsmp_icefd != -1)
7281 {
7282 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007283 if (xsmp.clientid != NULL)
7284 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007285 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007286 xsmp_icefd = -1;
7287 }
7288}
7289#endif /* USE_XSMP */
7290
7291
7292#ifdef EBCDIC
7293/* Translate character to its CTRL- value */
7294char CtrlTable[] =
7295{
7296/* 00 - 5E */
7297 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7298 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7299 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7300 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7301 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7302 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7303/* ^ */ 0x1E,
7304/* - */ 0x1F,
7305/* 61 - 6C */
7306 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7307/* _ */ 0x1F,
7308/* 6E - 80 */
7309 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7310/* a */ 0x01,
7311/* b */ 0x02,
7312/* c */ 0x03,
7313/* d */ 0x37,
7314/* e */ 0x2D,
7315/* f */ 0x2E,
7316/* g */ 0x2F,
7317/* h */ 0x16,
7318/* i */ 0x05,
7319/* 8A - 90 */
7320 0, 0, 0, 0, 0, 0, 0,
7321/* j */ 0x15,
7322/* k */ 0x0B,
7323/* l */ 0x0C,
7324/* m */ 0x0D,
7325/* n */ 0x0E,
7326/* o */ 0x0F,
7327/* p */ 0x10,
7328/* q */ 0x11,
7329/* r */ 0x12,
7330/* 9A - A1 */
7331 0, 0, 0, 0, 0, 0, 0, 0,
7332/* s */ 0x13,
7333/* t */ 0x3C,
7334/* u */ 0x3D,
7335/* v */ 0x32,
7336/* w */ 0x26,
7337/* x */ 0x18,
7338/* y */ 0x19,
7339/* z */ 0x3F,
7340/* AA - AC */
7341 0, 0, 0,
7342/* [ */ 0x27,
7343/* AE - BC */
7344 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7345/* ] */ 0x1D,
7346/* BE - C0 */ 0, 0, 0,
7347/* A */ 0x01,
7348/* B */ 0x02,
7349/* C */ 0x03,
7350/* D */ 0x37,
7351/* E */ 0x2D,
7352/* F */ 0x2E,
7353/* G */ 0x2F,
7354/* H */ 0x16,
7355/* I */ 0x05,
7356/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7357/* J */ 0x15,
7358/* K */ 0x0B,
7359/* L */ 0x0C,
7360/* M */ 0x0D,
7361/* N */ 0x0E,
7362/* O */ 0x0F,
7363/* P */ 0x10,
7364/* Q */ 0x11,
7365/* R */ 0x12,
7366/* DA - DF */ 0, 0, 0, 0, 0, 0,
7367/* \ */ 0x1C,
7368/* E1 */ 0,
7369/* S */ 0x13,
7370/* T */ 0x3C,
7371/* U */ 0x3D,
7372/* V */ 0x32,
7373/* W */ 0x26,
7374/* X */ 0x18,
7375/* Y */ 0x19,
7376/* Z */ 0x3F,
7377/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7378 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7379};
7380
7381char MetaCharTable[]=
7382{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7383 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7384 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7385 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7386 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7387};
7388
7389
7390/* TODO: Use characters NOT numbers!!! */
7391char CtrlCharTable[]=
7392{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7393 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7394 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7395 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7396 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7397};
7398
7399
7400#endif