blob: 784c5a3b1427833d4c7793b601502c2e50145414 [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 Moolenaar071d4272004-06-13 20:20:40 +000049/*
50 * Use this prototype for select, some include files have a wrong prototype
51 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000052#ifndef __TANDEM
53# undef select
54# ifdef __BEOS__
55# define select beos_select
56# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
Bram Moolenaara2442432007-04-26 14:26:37 +000059#ifdef __CYGWIN__
60# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000061# include <cygwin/version.h>
62# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
63 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010064# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
65# define WIN32_LEAN_AND_MEAN
66# include <windows.h>
67# include "winclip.pro"
68# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000069# endif
70#endif
71
Bram Moolenaar071d4272004-06-13 20:20:40 +000072#if defined(HAVE_SELECT)
73extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
74#endif
75
76#ifdef FEAT_MOUSE_GPM
77# include <gpm.h>
78/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
79 * I just copied relevant defines here. A cleaner solution would be to put gpm
80 * code into separate file and include there linux/keyboard.h
81 */
82/* #include <linux/keyboard.h> */
83# define KG_SHIFT 0
84# define KG_CTRL 2
85# define KG_ALT 3
86# define KG_ALTGR 1
87# define KG_SHIFTL 4
88# define KG_SHIFTR 5
89# define KG_CTRLL 6
90# define KG_CTRLR 7
91# define KG_CAPSSHIFT 8
92
93static void gpm_close __ARGS((void));
94static int gpm_open __ARGS((void));
95static int mch_gpm_process __ARGS((void));
96#endif
97
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000098#ifdef FEAT_SYSMOUSE
99# include <sys/consio.h>
100# include <sys/fbio.h>
101
102static int sysmouse_open __ARGS((void));
103static void sysmouse_close __ARGS((void));
104static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG);
105#endif
106
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107/*
108 * end of autoconf section. To be extended...
109 */
110
111/* Are the following #ifdefs still required? And why? Is that for X11? */
112
113#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
114# ifdef SIGWINCH
115# undef SIGWINCH
116# endif
117# ifdef TIOCGWINSZ
118# undef TIOCGWINSZ
119# endif
120#endif
121
122#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
123# define SIGWINCH SIGWINDOW
124#endif
125
126#ifdef FEAT_X11
127# include <X11/Xlib.h>
128# include <X11/Xutil.h>
129# include <X11/Xatom.h>
130# ifdef FEAT_XCLIPBOARD
131# include <X11/Intrinsic.h>
132# include <X11/Shell.h>
133# include <X11/StringDefs.h>
134static Widget xterm_Shell = (Widget)0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +0100135static void clip_update __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136static void xterm_update __ARGS((void));
137# endif
138
139# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
140Window x11_window = 0;
141# endif
142Display *x11_display = NULL;
143
144# ifdef FEAT_TITLE
145static int get_x11_windis __ARGS((void));
146static void set_x11_title __ARGS((char_u *));
147static void set_x11_icon __ARGS((char_u *));
148# endif
149#endif
150
151#ifdef FEAT_TITLE
152static int get_x11_title __ARGS((int));
153static int get_x11_icon __ARGS((int));
154
155static char_u *oldtitle = NULL;
156static int did_set_title = FALSE;
157static char_u *oldicon = NULL;
158static int did_set_icon = FALSE;
159#endif
160
161static void may_core_dump __ARGS((void));
162
Bram Moolenaar205b8862011-09-07 15:04:31 +0200163#ifdef HAVE_UNION_WAIT
164typedef union wait waitstatus;
165#else
166typedef int waitstatus;
167#endif
Bram Moolenaar9f118812011-09-08 23:24:14 +0200168static pid_t wait4pid __ARGS((pid_t, waitstatus *));
Bram Moolenaar205b8862011-09-07 15:04:31 +0200169
Bram Moolenaar071d4272004-06-13 20:20:40 +0000170static int WaitForChar __ARGS((long));
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100171#if defined(__BEOS__) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172int RealWaitForChar __ARGS((int, long, int *));
173#else
174static int RealWaitForChar __ARGS((int, long, int *));
175#endif
176
177#ifdef FEAT_XCLIPBOARD
178static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000179# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180#endif
181
182static void handle_resize __ARGS((void));
183
184#if defined(SIGWINCH)
185static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
186#endif
187#if defined(SIGINT)
188static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
189#endif
190#if defined(SIGPWR)
191static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
192#endif
193#if defined(SIGALRM) && defined(FEAT_X11) \
194 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
195# define SET_SIG_ALARM
196static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000197/* volatile because it is used in signal handler sig_alarm(). */
198static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199#endif
200static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
201
Bram Moolenaardf177f62005-02-22 08:39:57 +0000202static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203static void set_signals __ARGS((void));
204static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
205#ifndef __EMX__
206static int have_wildcard __ARGS((int, char_u **));
207static int have_dollars __ARGS((int, char_u **));
208#endif
209
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210#ifndef __EMX__
211static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
212#endif
213
214#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000215# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216#endif
217
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000218/* volatile because it is used in signal handler sig_winch(). */
219static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220#ifndef __EMX__
221static char_u *extra_shell_arg = NULL;
222static int show_shell_mess = TRUE;
223#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000224/* volatile because it is used in signal handler deathtrap(). */
225static volatile int deadly_signal = 0; /* The signal we caught */
226/* volatile because it is used in signal handler deathtrap(). */
227static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228
229static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
230
231#ifdef USE_XSMP
232typedef struct
233{
234 SmcConn smcconn; /* The SM connection ID */
235 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200236 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237 Bool save_yourself; /* If we're in the middle of a save_yourself */
238 Bool shutdown; /* If we're in shutdown mode */
239} xsmp_config_T;
240
241static xsmp_config_T xsmp;
242#endif
243
244#ifdef SYS_SIGLIST_DECLARED
245/*
246 * I have seen
247 * extern char *_sys_siglist[NSIG];
248 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
249 * that describe the signals. That is nearly what we want here. But
250 * autoconf does only check for sys_siglist (without the underscore), I
251 * do not want to change everything today.... jw.
252 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
253 */
254#endif
255
256static struct signalinfo
257{
258 int sig; /* Signal number, eg. SIGSEGV etc */
259 char *name; /* Signal name (not char_u!). */
260 char deadly; /* Catch as a deadly signal? */
261} signal_info[] =
262{
263#ifdef SIGHUP
264 {SIGHUP, "HUP", TRUE},
265#endif
266#ifdef SIGQUIT
267 {SIGQUIT, "QUIT", TRUE},
268#endif
269#ifdef SIGILL
270 {SIGILL, "ILL", TRUE},
271#endif
272#ifdef SIGTRAP
273 {SIGTRAP, "TRAP", TRUE},
274#endif
275#ifdef SIGABRT
276 {SIGABRT, "ABRT", TRUE},
277#endif
278#ifdef SIGEMT
279 {SIGEMT, "EMT", TRUE},
280#endif
281#ifdef SIGFPE
282 {SIGFPE, "FPE", TRUE},
283#endif
284#ifdef SIGBUS
285 {SIGBUS, "BUS", TRUE},
286#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100287#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
288 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000289 {SIGSEGV, "SEGV", TRUE},
290#endif
291#ifdef SIGSYS
292 {SIGSYS, "SYS", TRUE},
293#endif
294#ifdef SIGALRM
295 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
296#endif
297#ifdef SIGTERM
298 {SIGTERM, "TERM", TRUE},
299#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100300#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000301 {SIGVTALRM, "VTALRM", TRUE},
302#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000303#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
304 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
305 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306 {SIGPROF, "PROF", TRUE},
307#endif
308#ifdef SIGXCPU
309 {SIGXCPU, "XCPU", TRUE},
310#endif
311#ifdef SIGXFSZ
312 {SIGXFSZ, "XFSZ", TRUE},
313#endif
314#ifdef SIGUSR1
315 {SIGUSR1, "USR1", TRUE},
316#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000317#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
318 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000319 {SIGUSR2, "USR2", TRUE},
320#endif
321#ifdef SIGINT
322 {SIGINT, "INT", FALSE},
323#endif
324#ifdef SIGWINCH
325 {SIGWINCH, "WINCH", FALSE},
326#endif
327#ifdef SIGTSTP
328 {SIGTSTP, "TSTP", FALSE},
329#endif
330#ifdef SIGPIPE
331 {SIGPIPE, "PIPE", FALSE},
332#endif
333 {-1, "Unknown!", FALSE}
334};
335
Bram Moolenaar25724922009-07-14 15:38:41 +0000336 int
337mch_chdir(path)
338 char *path;
339{
340 if (p_verbose >= 5)
341 {
342 verbose_enter();
343 smsg((char_u *)"chdir(%s)", path);
344 verbose_leave();
345 }
346# ifdef VMS
347 return chdir(vms_fixfilename(path));
348# else
349 return chdir(path);
350# endif
351}
352
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000353/*
354 * Write s[len] to the screen.
355 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356 void
357mch_write(s, len)
358 char_u *s;
359 int len;
360{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000361 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362 if (p_wd) /* Unix is too fast, slow down a bit more */
363 RealWaitForChar(read_cmd_fd, p_wd, NULL);
364}
365
366/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000367 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368 * Get a characters from the keyboard.
369 * Return the number of characters that are available.
370 * If wtime == 0 do not wait for characters.
371 * If wtime == n wait a short time for characters.
372 * If wtime == -1 wait forever for characters.
373 */
374 int
375mch_inchar(buf, maxlen, wtime, tb_change_cnt)
376 char_u *buf;
377 int maxlen;
378 long wtime; /* don't use "time", MIPS cannot handle it */
379 int tb_change_cnt;
380{
381 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000382
Bram Moolenaar67c53842010-05-22 18:28:27 +0200383#ifdef FEAT_NETBEANS_INTG
384 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200385 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200386#endif
387
Bram Moolenaar071d4272004-06-13 20:20:40 +0000388 /* Check if window changed size while we were busy, perhaps the ":set
389 * columns=99" command was used. */
390 while (do_resize)
391 handle_resize();
392
393 if (wtime >= 0)
394 {
395 while (WaitForChar(wtime) == 0) /* no character available */
396 {
397 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200400#ifdef FEAT_NETBEANS_INTG
401 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200402 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200403#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 }
405 }
406 else /* wtime == -1 */
407 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000408 /*
409 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000410 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 * Also done when interrupted by SIGWINCH.
412 */
413 if (WaitForChar(p_ut) == 0)
414 {
415#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000416 if (trigger_cursorhold() && maxlen >= 3
417 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000419 buf[0] = K_SPECIAL;
420 buf[1] = KS_EXTRA;
421 buf[2] = (int)KE_CURSORHOLD;
422 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000425 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 }
427 }
428
429 for (;;) /* repeat until we got a character */
430 {
431 while (do_resize) /* window changed size */
432 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200433
434#ifdef FEAT_NETBEANS_INTG
435 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200436 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200437#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000438 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200439 * We want to be interrupted by the winch signal
440 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200442 if (WaitForChar(-1L) == 0)
443 {
444 if (do_resize) /* interrupted by SIGWINCH signal */
445 handle_resize();
446 return 0;
447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448
449 /* If input was put directly in typeahead buffer bail out here. */
450 if (typebuf_changed(tb_change_cnt))
451 return 0;
452
453 /*
454 * For some terminals we only get one character at a time.
455 * We want the get all available characters, so we could keep on
456 * trying until none is available
457 * For some other terminals this is quite slow, that's why we don't do
458 * it.
459 */
460 len = read_from_input_buf(buf, (long)maxlen);
461 if (len > 0)
462 {
463#ifdef OS2
464 int i;
465
466 for (i = 0; i < len; i++)
467 if (buf[i] == 0)
468 buf[i] = K_NUL;
469#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 return len;
471 }
472 }
473}
474
475 static void
476handle_resize()
477{
478 do_resize = FALSE;
479 shell_resized();
480}
481
482/*
483 * return non-zero if a character is available
484 */
485 int
486mch_char_avail()
487{
488 return WaitForChar(0L);
489}
490
491#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
492# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000493# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494# endif
495# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
496# include <sys/sysctl.h>
497# endif
498# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
499# include <sys/sysinfo.h>
500# endif
501
502/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000503 * Return total amount of memory available in Kbyte.
504 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 long_u
507mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000508 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
600mch_delay(msec, ignoreinput)
601 long msec;
602 int ignoreinput;
603{
604 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000605#ifdef FEAT_MZSCHEME
606 long total = msec; /* remember original value */
607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608
609 if (ignoreinput)
610 {
611 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000612 * here. But we don't want QUIT to kill us (CTRL-\ used in a
613 * shell may produce SIGQUIT). */
614 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 old_tmode = curr_tmode;
616 if (curr_tmode == TMODE_RAW)
617 settmode(TMODE_SLEEP);
618
619 /*
620 * Everybody sleeps in a different way...
621 * Prefer nanosleep(), some versions of usleep() can only sleep up to
622 * one second.
623 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000624#ifdef FEAT_MZSCHEME
625 do
626 {
627 /* if total is large enough, wait by portions in p_mzq */
628 if (total > p_mzq)
629 msec = p_mzq;
630 else
631 msec = total;
632 total -= msec;
633#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634#ifdef HAVE_NANOSLEEP
635 {
636 struct timespec ts;
637
638 ts.tv_sec = msec / 1000;
639 ts.tv_nsec = (msec % 1000) * 1000000;
640 (void)nanosleep(&ts, NULL);
641 }
642#else
643# ifdef HAVE_USLEEP
644 while (msec >= 1000)
645 {
646 usleep((unsigned int)(999 * 1000));
647 msec -= 999;
648 }
649 usleep((unsigned int)(msec * 1000));
650# else
651# ifndef HAVE_SELECT
652 poll(NULL, 0, (int)msec);
653# else
654# ifdef __EMX__
655 _sleep2(msec);
656# else
657 {
658 struct timeval tv;
659
660 tv.tv_sec = msec / 1000;
661 tv.tv_usec = (msec % 1000) * 1000;
662 /*
663 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
664 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
665 */
666 select(0, NULL, NULL, NULL, &tv);
667 }
668# endif /* __EMX__ */
669# endif /* HAVE_SELECT */
670# endif /* HAVE_NANOSLEEP */
671#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000672#ifdef FEAT_MZSCHEME
673 }
674 while (total > 0);
675#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676
677 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000678 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 }
680 else
681 WaitForChar(msec);
682}
683
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000684#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
686# define HAVE_CHECK_STACK_GROWTH
687/*
688 * Support for checking for an almost-out-of-stack-space situation.
689 */
690
691/*
692 * Return a pointer to an item on the stack. Used to find out if the stack
693 * grows up or down.
694 */
695static void check_stack_growth __ARGS((char *p));
696static int stack_grows_downwards;
697
698/*
699 * Find out if the stack grows upwards or downwards.
700 * "p" points to a variable on the stack of the caller.
701 */
702 static void
703check_stack_growth(p)
704 char *p;
705{
706 int i;
707
708 stack_grows_downwards = (p > (char *)&i);
709}
710#endif
711
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000712#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713static char *stack_limit = NULL;
714
715#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
716# include <pthread.h>
717# include <pthread_np.h>
718#endif
719
720/*
721 * Find out until how var the stack can grow without getting into trouble.
722 * Called when starting up and when switching to the signal stack in
723 * deathtrap().
724 */
725 static void
726get_stack_limit()
727{
728 struct rlimit rlp;
729 int i;
730 long lim;
731
732 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
733 * limit doesn't fit in a long (rlim_cur might be "long long"). */
734 if (getrlimit(RLIMIT_STACK, &rlp) == 0
735 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
736# ifdef RLIM_INFINITY
737 && rlp.rlim_cur != RLIM_INFINITY
738# endif
739 )
740 {
741 lim = (long)rlp.rlim_cur;
742#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
743 {
744 pthread_attr_t attr;
745 size_t size;
746
747 /* On FreeBSD the initial thread always has a fixed stack size, no
748 * matter what the limits are set to. Normally it's 1 Mbyte. */
749 pthread_attr_init(&attr);
750 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
751 {
752 pthread_attr_getstacksize(&attr, &size);
753 if (lim > (long)size)
754 lim = (long)size;
755 }
756 pthread_attr_destroy(&attr);
757 }
758#endif
759 if (stack_grows_downwards)
760 {
761 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
762 if (stack_limit >= (char *)&i)
763 /* overflow, set to 1/16 of current stack position */
764 stack_limit = (char *)((long)&i / 16L);
765 }
766 else
767 {
768 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
769 if (stack_limit <= (char *)&i)
770 stack_limit = NULL; /* overflow */
771 }
772 }
773}
774
775/*
776 * Return FAIL when running out of stack space.
777 * "p" must point to any variable local to the caller that's on the stack.
778 */
779 int
780mch_stackcheck(p)
781 char *p;
782{
783 if (stack_limit != NULL)
784 {
785 if (stack_grows_downwards)
786 {
787 if (p < stack_limit)
788 return FAIL;
789 }
790 else if (p > stack_limit)
791 return FAIL;
792 }
793 return OK;
794}
795#endif
796
797#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
798/*
799 * Support for using the signal stack.
800 * This helps when we run out of stack space, which causes a SIGSEGV. The
801 * signal handler then must run on another stack, since the normal stack is
802 * completely full.
803 */
804
Bram Moolenaar39766a72013-11-03 00:41:00 +0100805#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100806# include <AvailabilityMacros.h>
807#endif
808
Bram Moolenaar071d4272004-06-13 20:20:40 +0000809#ifndef SIGSTKSZ
810# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
811#endif
812
813# ifdef HAVE_SIGALTSTACK
814static stack_t sigstk; /* for sigaltstack() */
815# else
816static struct sigstack sigstk; /* for sigstack() */
817# endif
818
819static void init_signal_stack __ARGS((void));
820static char *signal_stack;
821
822 static void
823init_signal_stack()
824{
825 if (signal_stack != NULL)
826 {
827# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000828# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
829 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
831 * "struct sigaltstack" needs to be declared. */
832 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
833# endif
834
835# ifdef HAVE_SS_BASE
836 sigstk.ss_base = signal_stack;
837# else
838 sigstk.ss_sp = signal_stack;
839# endif
840 sigstk.ss_size = SIGSTKSZ;
841 sigstk.ss_flags = 0;
842 (void)sigaltstack(&sigstk, NULL);
843# else
844 sigstk.ss_sp = signal_stack;
845 if (stack_grows_downwards)
846 sigstk.ss_sp += SIGSTKSZ - 1;
847 sigstk.ss_onstack = 0;
848 (void)sigstack(&sigstk, NULL);
849# endif
850 }
851}
852#endif
853
854/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000855 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 * will barf when the second argument to signal() is ``wrong''.
857 * Let me try it with a few tricky defines from my own osdef.h (jw).
858 */
859#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 static RETSIGTYPE
861sig_winch SIGDEFARG(sigarg)
862{
863 /* this is not required on all systems, but it doesn't hurt anybody */
864 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
865 do_resize = TRUE;
866 SIGRETURN;
867}
868#endif
869
870#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871 static RETSIGTYPE
872catch_sigint SIGDEFARG(sigarg)
873{
874 /* this is not required on all systems, but it doesn't hurt anybody */
875 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
876 got_int = TRUE;
877 SIGRETURN;
878}
879#endif
880
881#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882 static RETSIGTYPE
883catch_sigpwr SIGDEFARG(sigarg)
884{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000885 /* this is not required on all systems, but it doesn't hurt anybody */
886 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 /*
888 * I'm not sure we get the SIGPWR signal when the system is really going
889 * down or when the batteries are almost empty. Just preserve the swap
890 * files and don't exit, that can't do any harm.
891 */
892 ml_sync_all(FALSE, FALSE);
893 SIGRETURN;
894}
895#endif
896
897#ifdef SET_SIG_ALARM
898/*
899 * signal function for alarm().
900 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 static RETSIGTYPE
902sig_alarm SIGDEFARG(sigarg)
903{
904 /* doesn't do anything, just to break a system call */
905 sig_alarm_called = TRUE;
906 SIGRETURN;
907}
908#endif
909
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000910#if (defined(HAVE_SETJMP_H) \
911 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
912 || defined(FEAT_LIBCALL))) \
913 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914/*
915 * A simplistic version of setjmp() that only allows one level of using.
916 * Don't call twice before calling mch_endjmp()!.
917 * Usage:
918 * mch_startjmp();
919 * if (SETJMP(lc_jump_env) != 0)
920 * {
921 * mch_didjmp();
922 * EMSG("crash!");
923 * }
924 * else
925 * {
926 * do_the_work;
927 * mch_endjmp();
928 * }
929 * Note: Can't move SETJMP() here, because a function calling setjmp() must
930 * not return before the saved environment is used.
931 * Returns OK for normal return, FAIL when the protected code caused a
932 * problem and LONGJMP() was used.
933 */
934 void
935mch_startjmp()
936{
937#ifdef SIGHASARG
938 lc_signal = 0;
939#endif
940 lc_active = TRUE;
941}
942
943 void
944mch_endjmp()
945{
946 lc_active = FALSE;
947}
948
949 void
950mch_didjmp()
951{
952# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
953 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
954 * otherwise catching the signal only works once. */
955 init_signal_stack();
956# endif
957}
958#endif
959
960/*
961 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200962 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200964 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
965 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 */
967 static RETSIGTYPE
968deathtrap SIGDEFARG(sigarg)
969{
970 static int entered = 0; /* count the number of times we got here.
971 Note: when memory has been corrupted
972 this may get an arbitrary value! */
973#ifdef SIGHASARG
974 int i;
975#endif
976
977#if defined(HAVE_SETJMP_H)
978 /*
979 * Catch a crash in protected code.
980 * Restores the environment saved in lc_jump_env, which looks like
981 * SETJMP() returns 1.
982 */
983 if (lc_active)
984 {
985# if defined(SIGHASARG)
986 lc_signal = sigarg;
987# endif
988 lc_active = FALSE; /* don't jump again */
989 LONGJMP(lc_jump_env, 1);
990 /* NOTREACHED */
991 }
992#endif
993
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000994#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000995# ifdef SIGQUIT
996 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
997 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
998 * pressing CTRL-\, but we don't want Vim to exit then. */
999 if (in_mch_delay && sigarg == SIGQUIT)
1000 SIGRETURN;
1001# endif
1002
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001003 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1004 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1005 * free(). Calling free() again may then cause a crash. */
1006 if (entered == 0
1007 && (0
1008# ifdef SIGHUP
1009 || sigarg == SIGHUP
1010# endif
1011# ifdef SIGQUIT
1012 || sigarg == SIGQUIT
1013# endif
1014# ifdef SIGTERM
1015 || sigarg == SIGTERM
1016# endif
1017# ifdef SIGPWR
1018 || sigarg == SIGPWR
1019# endif
1020# ifdef SIGUSR1
1021 || sigarg == SIGUSR1
1022# endif
1023# ifdef SIGUSR2
1024 || sigarg == SIGUSR2
1025# endif
1026 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001027 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001028 SIGRETURN;
1029#endif
1030
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 /* Remember how often we have been called. */
1032 ++entered;
1033
1034#ifdef FEAT_EVAL
1035 /* Set the v:dying variable. */
1036 set_vim_var_nr(VV_DYING, (long)entered);
1037#endif
1038
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001039#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040 /* Since we are now using the signal stack, need to reset the stack
1041 * limit. Otherwise using a regexp will fail. */
1042 get_stack_limit();
1043#endif
1044
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001045#if 0
1046 /* This is for opening gdb the moment Vim crashes.
1047 * You need to manually adjust the file name and Vim executable name.
1048 * Suggested by SungHyun Nam. */
1049 {
1050# define VI_GDB_FILE "/tmp/vimgdb"
1051# define VIM_NAME "/usr/bin/vim"
1052 FILE *fp = fopen(VI_GDB_FILE, "w");
1053 if (fp)
1054 {
1055 fprintf(fp,
1056 "file %s\n"
1057 "attach %d\n"
1058 "set height 1000\n"
1059 "bt full\n"
1060 , VIM_NAME, getpid());
1061 fclose(fp);
1062 system("xterm -e gdb -x "VI_GDB_FILE);
1063 unlink(VI_GDB_FILE);
1064 }
1065 }
1066#endif
1067
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068#ifdef SIGHASARG
1069 /* try to find the name of this signal */
1070 for (i = 0; signal_info[i].sig != -1; i++)
1071 if (sigarg == signal_info[i].sig)
1072 break;
1073 deadly_signal = sigarg;
1074#endif
1075
1076 full_screen = FALSE; /* don't write message to the GUI, it might be
1077 * part of the problem... */
1078 /*
1079 * If something goes wrong after entering here, we may get here again.
1080 * When this happens, give a message and try to exit nicely (resetting the
1081 * terminal mode, etc.)
1082 * When this happens twice, just exit, don't even try to give a message,
1083 * stack may be corrupt or something weird.
1084 * When this still happens again (or memory was corrupted in such a way
1085 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1086 */
1087 if (entered >= 3)
1088 {
1089 reset_signals(); /* don't catch any signals anymore */
1090 may_core_dump();
1091 if (entered >= 4)
1092 _exit(8);
1093 exit(7);
1094 }
1095 if (entered == 2)
1096 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001097 /* No translation, it may call malloc(). */
1098 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 out_flush();
1100 getout(1);
1101 }
1102
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001103 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001105 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 signal_info[i].name);
1107#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001108 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001110
1111 /* Preserve files and exit. This sets the really_exiting flag to prevent
1112 * calling free(). */
1113 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114
Bram Moolenaar009b2592004-10-24 19:18:58 +00001115#ifdef NBDEBUG
1116 reset_signals();
1117 may_core_dump();
1118 abort();
1119#endif
1120
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 SIGRETURN;
1122}
1123
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001124#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125/*
1126 * On Solaris with multi-threading, suspending might not work immediately.
1127 * Catch the SIGCONT signal, which will be used as an indication whether the
1128 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001129 *
1130 * On Linux, signal is not always handled immediately either.
1131 * See https://bugs.launchpad.net/bugs/291373
1132 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001133 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001135static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1137
1138/*
1139 * signal handler for SIGCONT
1140 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141 static RETSIGTYPE
1142sigcont_handler SIGDEFARG(sigarg)
1143{
1144 sigcont_received = TRUE;
1145 SIGRETURN;
1146}
1147#endif
1148
Bram Moolenaar62b42182010-09-21 22:09:37 +02001149# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1150static void loose_clipboard __ARGS((void));
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001151# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001152static void save_clipboard __ARGS((void));
1153static void restore_clipboard __ARGS((void));
1154
1155static void *clip_star_save = NULL;
1156static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001157# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001158
1159/*
1160 * Called when Vim is going to sleep or execute a shell command.
1161 * We can't respond to requests for the X selections. Lose them, otherwise
1162 * other applications will hang. But first copy the text to cut buffer 0.
1163 */
1164 static void
1165loose_clipboard()
1166{
1167 if (clip_star.owned || clip_plus.owned)
1168 {
1169 x11_export_final_selection();
1170 if (clip_star.owned)
1171 clip_lose_selection(&clip_star);
1172 if (clip_plus.owned)
1173 clip_lose_selection(&clip_plus);
1174 if (x11_display != NULL)
1175 XFlush(x11_display);
1176 }
1177}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001178
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001179# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001180/*
1181 * Save clipboard text to restore later.
1182 */
1183 static void
1184save_clipboard()
1185{
1186 if (clip_star.owned)
1187 clip_star_save = get_register('*', TRUE);
1188 if (clip_plus.owned)
1189 clip_plus_save = get_register('+', TRUE);
1190}
1191
1192/*
1193 * Restore clipboard text if no one own the X selection.
1194 */
1195 static void
1196restore_clipboard()
1197{
1198 if (clip_star_save != NULL)
1199 {
1200 if (!clip_gen_owner_exists(&clip_star))
1201 put_register('*', clip_star_save);
1202 else
1203 free_register(clip_star_save);
1204 clip_star_save = NULL;
1205 }
1206 if (clip_plus_save != NULL)
1207 {
1208 if (!clip_gen_owner_exists(&clip_plus))
1209 put_register('+', clip_plus_save);
1210 else
1211 free_register(clip_plus_save);
1212 clip_plus_save = NULL;
1213 }
1214}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001215# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001216#endif
1217
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218/*
1219 * If the machine has job control, use it to suspend the program,
1220 * otherwise fake it by starting a new shell.
1221 */
1222 void
1223mch_suspend()
1224{
1225 /* BeOS does have SIGTSTP, but it doesn't work. */
1226#if defined(SIGTSTP) && !defined(__BEOS__)
1227 out_flush(); /* needed to make cursor visible on some systems */
1228 settmode(TMODE_COOK);
1229 out_flush(); /* needed to disable mouse on some systems */
1230
1231# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001232 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233# endif
1234
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001235# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 sigcont_received = FALSE;
1237# endif
1238 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001239# if defined(_REENTRANT) && defined(SIGCONT)
1240 /*
1241 * Wait for the SIGCONT signal to be handled. It generally happens
1242 * immediately, but somehow not all the time. Do not call pause()
1243 * because there would be race condition which would hang Vim if
1244 * signal happened in between the test of sigcont_received and the
1245 * call to pause(). If signal is not yet received, call sleep(0)
1246 * to just yield CPU. Signal should then be received. If somehow
1247 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1248 * further if signal is not received after 1+2+3+4 ms (not expected
1249 * to happen).
1250 */
1251 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001252 long wait_time;
1253 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001254 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001255 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257# endif
1258
1259# ifdef FEAT_TITLE
1260 /*
1261 * Set oldtitle to NULL, so the current title is obtained again.
1262 */
1263 vim_free(oldtitle);
1264 oldtitle = NULL;
1265# endif
1266 settmode(TMODE_RAW);
1267 need_check_timestamps = TRUE;
1268 did_check_timestamps = FALSE;
1269#else
1270 suspend_shell();
1271#endif
1272}
1273
1274 void
1275mch_init()
1276{
1277 Columns = 80;
1278 Rows = 24;
1279
1280 out_flush();
1281 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001282
Bram Moolenaar56718732006-03-15 22:53:57 +00001283#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001284 mac_conv_init();
1285#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001286#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1287 win_clip_init();
1288#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289}
1290
1291 static void
1292set_signals()
1293{
1294#if defined(SIGWINCH)
1295 /*
1296 * WINDOW CHANGE signal is handled with sig_winch().
1297 */
1298 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1299#endif
1300
1301 /*
1302 * We want the STOP signal to work, to make mch_suspend() work.
1303 * For "rvim" the STOP signal is ignored.
1304 */
1305#ifdef SIGTSTP
1306 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1307#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001308#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309 signal(SIGCONT, sigcont_handler);
1310#endif
1311
1312 /*
1313 * We want to ignore breaking of PIPEs.
1314 */
1315#ifdef SIGPIPE
1316 signal(SIGPIPE, SIG_IGN);
1317#endif
1318
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001320 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321#endif
1322
1323 /*
1324 * Ignore alarm signals (Perl's alarm() generates it).
1325 */
1326#ifdef SIGALRM
1327 signal(SIGALRM, SIG_IGN);
1328#endif
1329
1330 /*
1331 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1332 * work will be lost.
1333 */
1334#ifdef SIGPWR
1335 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1336#endif
1337
1338 /*
1339 * Arrange for other signals to gracefully shutdown Vim.
1340 */
1341 catch_signals(deathtrap, SIG_ERR);
1342
1343#if defined(FEAT_GUI) && defined(SIGHUP)
1344 /*
1345 * When the GUI is running, ignore the hangup signal.
1346 */
1347 if (gui.in_use)
1348 signal(SIGHUP, SIG_IGN);
1349#endif
1350}
1351
Bram Moolenaardf177f62005-02-22 08:39:57 +00001352#if defined(SIGINT) || defined(PROTO)
1353/*
1354 * Catch CTRL-C (only works while in Cooked mode).
1355 */
1356 static void
1357catch_int_signal()
1358{
1359 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1360}
1361#endif
1362
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363 void
1364reset_signals()
1365{
1366 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001367#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 /* SIGCONT isn't in the list, because its default action is ignore */
1369 signal(SIGCONT, SIG_DFL);
1370#endif
1371}
1372
1373 static void
1374catch_signals(func_deadly, func_other)
1375 RETSIGTYPE (*func_deadly)();
1376 RETSIGTYPE (*func_other)();
1377{
1378 int i;
1379
1380 for (i = 0; signal_info[i].sig != -1; i++)
1381 if (signal_info[i].deadly)
1382 {
1383#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1384 struct sigaction sa;
1385
1386 /* Setup to use the alternate stack for the signal function. */
1387 sa.sa_handler = func_deadly;
1388 sigemptyset(&sa.sa_mask);
1389# if defined(__linux__) && defined(_REENTRANT)
1390 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1391 * thread handling in combination with using the alternate stack:
1392 * pthread library functions try to use the stack pointer to
1393 * identify the current thread, causing a SEGV signal, which
1394 * recursively calls deathtrap() and hangs. */
1395 sa.sa_flags = 0;
1396# else
1397 sa.sa_flags = SA_ONSTACK;
1398# endif
1399 sigaction(signal_info[i].sig, &sa, NULL);
1400#else
1401# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1402 struct sigvec sv;
1403
1404 /* Setup to use the alternate stack for the signal function. */
1405 sv.sv_handler = func_deadly;
1406 sv.sv_mask = 0;
1407 sv.sv_flags = SV_ONSTACK;
1408 sigvec(signal_info[i].sig, &sv, NULL);
1409# else
1410 signal(signal_info[i].sig, func_deadly);
1411# endif
1412#endif
1413 }
1414 else if (func_other != SIG_ERR)
1415 signal(signal_info[i].sig, func_other);
1416}
1417
1418/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001419 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001420 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1421 * return TRUE
1422 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1423 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001424 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001425 * Returns TRUE when Vim should exit.
1426 */
1427 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001428vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001429 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001430{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001431 static int got_signal = 0;
1432 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001433
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001434 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001435 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001436 case SIGNAL_BLOCK: blocked = TRUE;
1437 break;
1438
1439 case SIGNAL_UNBLOCK: blocked = FALSE;
1440 if (got_signal != 0)
1441 {
1442 kill(getpid(), got_signal);
1443 got_signal = 0;
1444 }
1445 break;
1446
1447 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001448 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001449 got_signal = sig;
1450#ifdef SIGPWR
1451 if (sig != SIGPWR)
1452#endif
1453 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001454 break;
1455 }
1456 return FALSE;
1457}
1458
1459/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 * Check_win checks whether we have an interactive stdout.
1461 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 int
1463mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001464 int argc UNUSED;
1465 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466{
1467#ifdef OS2
1468 /*
1469 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1470 * name, mostly it's just "vim" and found in the path, which is unusable.
1471 */
1472 if (mch_isFullName(argv[0]))
1473 exe_name = vim_strsave((char_u *)argv[0]);
1474#endif
1475 if (isatty(1))
1476 return OK;
1477 return FAIL;
1478}
1479
1480/*
1481 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1482 */
1483 int
1484mch_input_isatty()
1485{
1486 if (isatty(read_cmd_fd))
1487 return TRUE;
1488 return FALSE;
1489}
1490
1491#ifdef FEAT_X11
1492
1493# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1494 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1495
1496static void xopen_message __ARGS((struct timeval *tvp));
1497
1498/*
1499 * Give a message about the elapsed time for opening the X window.
1500 */
1501 static void
1502xopen_message(tvp)
1503 struct timeval *tvp; /* must contain start time */
1504{
1505 struct timeval end_tv;
1506
1507 /* Compute elapsed time. */
1508 gettimeofday(&end_tv, NULL);
1509 smsg((char_u *)_("Opening the X display took %ld msec"),
1510 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001511 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512}
1513# endif
1514#endif
1515
1516#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1517/*
1518 * A few functions shared by X11 title and clipboard code.
1519 */
1520static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1521static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1522static int x_connect_to_server __ARGS((void));
1523static int test_x11_window __ARGS((Display *dpy));
1524
1525static int got_x_error = FALSE;
1526
1527/*
1528 * X Error handler, otherwise X just exits! (very rude) -- webb
1529 */
1530 static int
1531x_error_handler(dpy, error_event)
1532 Display *dpy;
1533 XErrorEvent *error_event;
1534{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001535 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 STRCAT(IObuff, _("\nVim: Got X error\n"));
1537
1538 /* We cannot print a message and continue, because no X calls are allowed
1539 * here (causes my system to hang). Silently continuing might be an
1540 * alternative... */
1541 preserve_exit(); /* preserve files and exit */
1542
1543 return 0; /* NOTREACHED */
1544}
1545
1546/*
1547 * Another X Error handler, just used to check for errors.
1548 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 static int
1550x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001551 Display *dpy UNUSED;
1552 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553{
1554 got_x_error = TRUE;
1555 return 0;
1556}
1557
1558#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1559# if defined(HAVE_SETJMP_H)
1560/*
1561 * An X IO Error handler, used to catch error while opening the display.
1562 */
1563static int x_IOerror_check __ARGS((Display *dpy));
1564
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 static int
1566x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001567 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568{
1569 /* This function should not return, it causes exit(). Longjump instead. */
1570 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001571# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001572 return 0; /* avoid the compiler complains about missing return value */
1573# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574}
1575# endif
1576
1577/*
1578 * An X IO Error handler, used to catch terminal errors.
1579 */
1580static int x_IOerror_handler __ARGS((Display *dpy));
1581
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 static int
1583x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001584 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585{
1586 xterm_dpy = NULL;
1587 x11_window = 0;
1588 x11_display = NULL;
1589 xterm_Shell = (Widget)0;
1590
1591 /* This function should not return, it causes exit(). Longjump instead. */
1592 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001593# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001594 return 0; /* avoid the compiler complains about missing return value */
1595# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596}
1597#endif
1598
1599/*
1600 * Return TRUE when connection to the X server is desired.
1601 */
1602 static int
1603x_connect_to_server()
1604{
1605 regmatch_T regmatch;
1606
1607#if defined(FEAT_CLIENTSERVER)
1608 if (x_force_connect)
1609 return TRUE;
1610#endif
1611 if (x_no_connect)
1612 return FALSE;
1613
1614 /* Check for a match with "exclude:" from 'clipboard'. */
1615 if (clip_exclude_prog != NULL)
1616 {
1617 regmatch.rm_ic = FALSE; /* Don't ignore case */
1618 regmatch.regprog = clip_exclude_prog;
1619 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1620 return FALSE;
1621 }
1622 return TRUE;
1623}
1624
1625/*
1626 * Test if "dpy" and x11_window are valid by getting the window title.
1627 * I don't actually want it yet, so there may be a simpler call to use, but
1628 * this will cause the error handler x_error_check() to be called if anything
1629 * is wrong, such as the window pointer being invalid (as can happen when the
1630 * user changes his DISPLAY, but not his WINDOWID) -- webb
1631 */
1632 static int
1633test_x11_window(dpy)
1634 Display *dpy;
1635{
1636 int (*old_handler)();
1637 XTextProperty text_prop;
1638
1639 old_handler = XSetErrorHandler(x_error_check);
1640 got_x_error = FALSE;
1641 if (XGetWMName(dpy, x11_window, &text_prop))
1642 XFree((void *)text_prop.value);
1643 XSync(dpy, False);
1644 (void)XSetErrorHandler(old_handler);
1645
1646 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001647 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648
1649 return (got_x_error ? FAIL : OK);
1650}
1651#endif
1652
1653#ifdef FEAT_TITLE
1654
1655#ifdef FEAT_X11
1656
1657static int get_x11_thing __ARGS((int get_title, int test_only));
1658
1659/*
1660 * try to get x11 window and display
1661 *
1662 * return FAIL for failure, OK otherwise
1663 */
1664 static int
1665get_x11_windis()
1666{
1667 char *winid;
1668 static int result = -1;
1669#define XD_NONE 0 /* x11_display not set here */
1670#define XD_HERE 1 /* x11_display opened here */
1671#define XD_GUI 2 /* x11_display used from gui.dpy */
1672#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1673 static int x11_display_from = XD_NONE;
1674 static int did_set_error_handler = FALSE;
1675
1676 if (!did_set_error_handler)
1677 {
1678 /* X just exits if it finds an error otherwise! */
1679 (void)XSetErrorHandler(x_error_handler);
1680 did_set_error_handler = TRUE;
1681 }
1682
Bram Moolenaar9372a112005-12-06 19:59:18 +00001683#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 if (gui.in_use)
1685 {
1686 /*
1687 * If the X11 display was opened here before, for the window where Vim
1688 * was started, close that one now to avoid a memory leak.
1689 */
1690 if (x11_display_from == XD_HERE && x11_display != NULL)
1691 {
1692 XCloseDisplay(x11_display);
1693 x11_display_from = XD_NONE;
1694 }
1695 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1696 {
1697 x11_display_from = XD_GUI;
1698 return OK;
1699 }
1700 x11_display = NULL;
1701 return FAIL;
1702 }
1703 else if (x11_display_from == XD_GUI)
1704 {
1705 /* GUI must have stopped somehow, clear x11_display */
1706 x11_window = 0;
1707 x11_display = NULL;
1708 x11_display_from = XD_NONE;
1709 }
1710#endif
1711
1712 /* When started with the "-X" argument, don't try connecting. */
1713 if (!x_connect_to_server())
1714 return FAIL;
1715
1716 /*
1717 * If WINDOWID not set, should try another method to find out
1718 * what the current window number is. The only code I know for
1719 * this is very complicated.
1720 * We assume that zero is invalid for WINDOWID.
1721 */
1722 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1723 x11_window = (Window)atol(winid);
1724
1725#ifdef FEAT_XCLIPBOARD
1726 if (xterm_dpy != NULL && x11_window != 0)
1727 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001728 /* We may have checked it already, but Gnome terminal can move us to
1729 * another window, so we need to check every time. */
1730 if (x11_display_from != XD_XTERM)
1731 {
1732 /*
1733 * If the X11 display was opened here before, for the window where
1734 * Vim was started, close that one now to avoid a memory leak.
1735 */
1736 if (x11_display_from == XD_HERE && x11_display != NULL)
1737 XCloseDisplay(x11_display);
1738 x11_display = xterm_dpy;
1739 x11_display_from = XD_XTERM;
1740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 if (test_x11_window(x11_display) == FAIL)
1742 {
1743 /* probably bad $WINDOWID */
1744 x11_window = 0;
1745 x11_display = NULL;
1746 x11_display_from = XD_NONE;
1747 return FAIL;
1748 }
1749 return OK;
1750 }
1751#endif
1752
1753 if (x11_window == 0 || x11_display == NULL)
1754 result = -1;
1755
1756 if (result != -1) /* Have already been here and set this */
1757 return result; /* Don't do all these X calls again */
1758
1759 if (x11_window != 0 && x11_display == NULL)
1760 {
1761#ifdef SET_SIG_ALARM
1762 RETSIGTYPE (*sig_save)();
1763#endif
1764#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1765 struct timeval start_tv;
1766
1767 if (p_verbose > 0)
1768 gettimeofday(&start_tv, NULL);
1769#endif
1770
1771#ifdef SET_SIG_ALARM
1772 /*
1773 * Opening the Display may hang if the DISPLAY setting is wrong, or
1774 * the network connection is bad. Set an alarm timer to get out.
1775 */
1776 sig_alarm_called = FALSE;
1777 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1778 (RETSIGTYPE (*)())sig_alarm);
1779 alarm(2);
1780#endif
1781 x11_display = XOpenDisplay(NULL);
1782
1783#ifdef SET_SIG_ALARM
1784 alarm(0);
1785 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1786 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001787 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788#endif
1789 if (x11_display != NULL)
1790 {
1791# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1792 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001793 {
1794 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001796 verbose_leave();
1797 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798# endif
1799 if (test_x11_window(x11_display) == FAIL)
1800 {
1801 /* Maybe window id is bad */
1802 x11_window = 0;
1803 XCloseDisplay(x11_display);
1804 x11_display = NULL;
1805 }
1806 else
1807 x11_display_from = XD_HERE;
1808 }
1809 }
1810 if (x11_window == 0 || x11_display == NULL)
1811 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001812
1813# ifdef FEAT_EVAL
1814 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1815# endif
1816
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 return (result = OK);
1818}
1819
1820/*
1821 * Determine original x11 Window Title
1822 */
1823 static int
1824get_x11_title(test_only)
1825 int test_only;
1826{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001827 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828}
1829
1830/*
1831 * Determine original x11 Window icon
1832 */
1833 static int
1834get_x11_icon(test_only)
1835 int test_only;
1836{
1837 int retval = FALSE;
1838
1839 retval = get_x11_thing(FALSE, test_only);
1840
1841 /* could not get old icon, use terminal name */
1842 if (oldicon == NULL && !test_only)
1843 {
1844 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001845 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001847 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 }
1849
1850 return retval;
1851}
1852
1853 static int
1854get_x11_thing(get_title, test_only)
1855 int get_title; /* get title string */
1856 int test_only;
1857{
1858 XTextProperty text_prop;
1859 int retval = FALSE;
1860 Status status;
1861
1862 if (get_x11_windis() == OK)
1863 {
1864 /* Get window/icon name if any */
1865 if (get_title)
1866 status = XGetWMName(x11_display, x11_window, &text_prop);
1867 else
1868 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1869
1870 /*
1871 * If terminal is xterm, then x11_window may be a child window of the
1872 * outer xterm window that actually contains the window/icon name, so
1873 * keep traversing up the tree until a window with a title/icon is
1874 * found.
1875 */
1876 /* Previously this was only done for xterm and alikes. I don't see a
1877 * reason why it would fail for other terminal emulators.
1878 * if (term_is_xterm) */
1879 {
1880 Window root;
1881 Window parent;
1882 Window win = x11_window;
1883 Window *children;
1884 unsigned int num_children;
1885
1886 while (!status || text_prop.value == NULL)
1887 {
1888 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1889 &num_children))
1890 break;
1891 if (children)
1892 XFree((void *)children);
1893 if (parent == root || parent == 0)
1894 break;
1895
1896 win = parent;
1897 if (get_title)
1898 status = XGetWMName(x11_display, win, &text_prop);
1899 else
1900 status = XGetWMIconName(x11_display, win, &text_prop);
1901 }
1902 }
1903 if (status && text_prop.value != NULL)
1904 {
1905 retval = TRUE;
1906 if (!test_only)
1907 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001908#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1909 if (text_prop.encoding == XA_STRING
1910# ifdef FEAT_MBYTE
1911 && !has_mbyte
1912# endif
1913 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 {
1915#endif
1916 if (get_title)
1917 oldtitle = vim_strsave((char_u *)text_prop.value);
1918 else
1919 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001920#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 }
1922 else
1923 {
1924 char **cl;
1925 Status transform_status;
1926 int n = 0;
1927
1928 transform_status = XmbTextPropertyToTextList(x11_display,
1929 &text_prop,
1930 &cl, &n);
1931 if (transform_status >= Success && n > 0 && cl[0])
1932 {
1933 if (get_title)
1934 oldtitle = vim_strsave((char_u *) cl[0]);
1935 else
1936 oldicon = vim_strsave((char_u *) cl[0]);
1937 XFreeStringList(cl);
1938 }
1939 else
1940 {
1941 if (get_title)
1942 oldtitle = vim_strsave((char_u *)text_prop.value);
1943 else
1944 oldicon = vim_strsave((char_u *)text_prop.value);
1945 }
1946 }
1947#endif
1948 }
1949 XFree((void *)text_prop.value);
1950 }
1951 }
1952 return retval;
1953}
1954
1955/* Are Xutf8 functions available? Avoid error from old compilers. */
1956#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1957# if X_HAVE_UTF8_STRING
1958# define USE_UTF8_STRING
1959# endif
1960#endif
1961
1962/*
1963 * Set x11 Window Title
1964 *
1965 * get_x11_windis() must be called before this and have returned OK
1966 */
1967 static void
1968set_x11_title(title)
1969 char_u *title;
1970{
1971 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1972 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1973 * supported everywhere and STRING doesn't work for multi-byte titles.
1974 */
1975#ifdef USE_UTF8_STRING
1976 if (enc_utf8)
1977 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1978 NULL, NULL, 0, NULL, NULL, NULL);
1979 else
1980#endif
1981 {
1982#if XtSpecificationRelease >= 4
1983# ifdef FEAT_XFONTSET
1984 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1985 NULL, NULL, 0, NULL, NULL, NULL);
1986# else
1987 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001988 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989
1990 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001991 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 XSetWMProperties(x11_display, x11_window, &text_prop,
1993 NULL, NULL, 0, NULL, NULL, NULL);
1994# endif
1995#else
1996 XStoreName(x11_display, x11_window, (char *)title);
1997#endif
1998 }
1999 XFlush(x11_display);
2000}
2001
2002/*
2003 * Set x11 Window icon
2004 *
2005 * get_x11_windis() must be called before this and have returned OK
2006 */
2007 static void
2008set_x11_icon(icon)
2009 char_u *icon;
2010{
2011 /* See above for comments about using X*SetWMProperties(). */
2012#ifdef USE_UTF8_STRING
2013 if (enc_utf8)
2014 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2015 NULL, 0, NULL, NULL, NULL);
2016 else
2017#endif
2018 {
2019#if XtSpecificationRelease >= 4
2020# ifdef FEAT_XFONTSET
2021 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2022 NULL, 0, NULL, NULL, NULL);
2023# else
2024 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002025 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002027 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2029 NULL, 0, NULL, NULL, NULL);
2030# endif
2031#else
2032 XSetIconName(x11_display, x11_window, (char *)icon);
2033#endif
2034 }
2035 XFlush(x11_display);
2036}
2037
2038#else /* FEAT_X11 */
2039
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 static int
2041get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002042 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043{
2044 return FALSE;
2045}
2046
2047 static int
2048get_x11_icon(test_only)
2049 int test_only;
2050{
2051 if (!test_only)
2052 {
2053 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002054 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002056 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
2058 return FALSE;
2059}
2060
2061#endif /* FEAT_X11 */
2062
2063 int
2064mch_can_restore_title()
2065{
2066 return get_x11_title(TRUE);
2067}
2068
2069 int
2070mch_can_restore_icon()
2071{
2072 return get_x11_icon(TRUE);
2073}
2074
2075/*
2076 * Set the window title and icon.
2077 */
2078 void
2079mch_settitle(title, icon)
2080 char_u *title;
2081 char_u *icon;
2082{
2083 int type = 0;
2084 static int recursive = 0;
2085
2086 if (T_NAME == NULL) /* no terminal name (yet) */
2087 return;
2088 if (title == NULL && icon == NULL) /* nothing to do */
2089 return;
2090
2091 /* When one of the X11 functions causes a deadly signal, we get here again
2092 * recursively. Avoid hanging then (something is probably locked). */
2093 if (recursive)
2094 return;
2095 ++recursive;
2096
2097 /*
2098 * if the window ID and the display is known, we may use X11 calls
2099 */
2100#ifdef FEAT_X11
2101 if (get_x11_windis() == OK)
2102 type = 1;
2103#else
2104# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2105 if (gui.in_use)
2106 type = 1;
2107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108#endif
2109
2110 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002111 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 * than x11 calls, because the x11 calls don't always work
2113 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 if ((type || *T_TS != NUL) && title != NULL)
2115 {
2116 if (oldtitle == NULL
2117#ifdef FEAT_GUI
2118 && !gui.in_use
2119#endif
2120 ) /* first call but not in GUI, save title */
2121 (void)get_x11_title(FALSE);
2122
2123 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2124 term_settitle(title);
2125#ifdef FEAT_X11
2126 else
2127# ifdef FEAT_GUI_GTK
2128 if (!gui.in_use) /* don't do this if GTK+ is running */
2129# endif
2130 set_x11_title(title); /* x11 */
2131#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002132#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2134 else
2135 gui_mch_settitle(title, icon);
2136#endif
2137 did_set_title = TRUE;
2138 }
2139
2140 if ((type || *T_CIS != NUL) && icon != NULL)
2141 {
2142 if (oldicon == NULL
2143#ifdef FEAT_GUI
2144 && !gui.in_use
2145#endif
2146 ) /* first call, save icon */
2147 get_x11_icon(FALSE);
2148
2149 if (*T_CIS != NUL)
2150 {
2151 out_str(T_CIS); /* set icon start */
2152 out_str_nf(icon);
2153 out_str(T_CIE); /* set icon end */
2154 out_flush();
2155 }
2156#ifdef FEAT_X11
2157 else
2158# ifdef FEAT_GUI_GTK
2159 if (!gui.in_use) /* don't do this if GTK+ is running */
2160# endif
2161 set_x11_icon(icon); /* x11 */
2162#endif
2163 did_set_icon = TRUE;
2164 }
2165 --recursive;
2166}
2167
2168/*
2169 * Restore the window/icon title.
2170 * "which" is one of:
2171 * 1 only restore title
2172 * 2 only restore icon
2173 * 3 restore title and icon
2174 */
2175 void
2176mch_restore_title(which)
2177 int which;
2178{
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
2192vim_is_xterm(name)
2193 char_u *name;
2194{
2195 if (name == NULL)
2196 return FALSE;
2197 return (STRNICMP(name, "xterm", 5) == 0
2198 || STRNICMP(name, "nxterm", 6) == 0
2199 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002200 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 || STRNICMP(name, "rxvt", 4) == 0
2202 || STRCMP(name, "builtin_xterm") == 0);
2203}
2204
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002205#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2206/*
2207 * Return TRUE if "name" appears to be that of a terminal
2208 * known to support the xterm-style mouse protocol.
2209 * Relies on term_is_xterm having been set to its correct value.
2210 */
2211 int
2212use_xterm_like_mouse(name)
2213 char_u *name;
2214{
2215 return (name != NULL
2216 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2217}
2218#endif
2219
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2221/*
2222 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2223 * Return 1 for "xterm".
2224 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002225 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002226 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 */
2228 int
2229use_xterm_mouse()
2230{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002231 if (ttym_flags == TTYM_SGR)
2232 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002233 if (ttym_flags == TTYM_URXVT)
2234 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 if (ttym_flags == TTYM_XTERM2)
2236 return 2;
2237 if (ttym_flags == TTYM_XTERM)
2238 return 1;
2239 return 0;
2240}
2241#endif
2242
2243 int
2244vim_is_iris(name)
2245 char_u *name;
2246{
2247 if (name == NULL)
2248 return FALSE;
2249 return (STRNICMP(name, "iris-ansi", 9) == 0
2250 || STRCMP(name, "builtin_iris-ansi") == 0);
2251}
2252
2253 int
2254vim_is_vt300(name)
2255 char_u *name;
2256{
2257 if (name == NULL)
2258 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002259 /* catch VT100 - VT5xx */
2260 return ((STRNICMP(name, "vt", 2) == 0
2261 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 || STRCMP(name, "builtin_vt320") == 0);
2263}
2264
2265/*
2266 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2267 * This should include all windowed terminal emulators.
2268 */
2269 int
2270vim_is_fastterm(name)
2271 char_u *name;
2272{
2273 if (name == NULL)
2274 return FALSE;
2275 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2276 return TRUE;
2277 return ( STRNICMP(name, "hpterm", 6) == 0
2278 || STRNICMP(name, "sun-cmd", 7) == 0
2279 || STRNICMP(name, "screen", 6) == 0
2280 || STRNICMP(name, "dtterm", 6) == 0);
2281}
2282
2283/*
2284 * Insert user name in s[len].
2285 * Return OK if a name found.
2286 */
2287 int
2288mch_get_user_name(s, len)
2289 char_u *s;
2290 int len;
2291{
2292#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002293 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 return OK;
2295#else
2296 return mch_get_uname(getuid(), s, len);
2297#endif
2298}
2299
2300/*
2301 * Insert user name for "uid" in s[len].
2302 * Return OK if a name found.
2303 */
2304 int
2305mch_get_uname(uid, s, len)
2306 uid_t uid;
2307 char_u *s;
2308 int len;
2309{
2310#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2311 struct passwd *pw;
2312
2313 if ((pw = getpwuid(uid)) != NULL
2314 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2315 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002316 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 return OK;
2318 }
2319#endif
2320 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2321 return FAIL; /* a number is not a name */
2322}
2323
2324/*
2325 * Insert host name is s[len].
2326 */
2327
2328#ifdef HAVE_SYS_UTSNAME_H
2329 void
2330mch_get_host_name(s, len)
2331 char_u *s;
2332 int len;
2333{
2334 struct utsname vutsname;
2335
2336 if (uname(&vutsname) < 0)
2337 *s = NUL;
2338 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002339 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340}
2341#else /* HAVE_SYS_UTSNAME_H */
2342
2343# ifdef HAVE_SYS_SYSTEMINFO_H
2344# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2345# endif
2346
2347 void
2348mch_get_host_name(s, len)
2349 char_u *s;
2350 int len;
2351{
2352# ifdef VAXC
2353 vaxc$gethostname((char *)s, len);
2354# else
2355 gethostname((char *)s, len);
2356# endif
2357 s[len - 1] = NUL; /* make sure it's terminated */
2358}
2359#endif /* HAVE_SYS_UTSNAME_H */
2360
2361/*
2362 * return process ID
2363 */
2364 long
2365mch_get_pid()
2366{
2367 return (long)getpid();
2368}
2369
2370#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2371static char *strerror __ARGS((int));
2372
2373 static char *
2374strerror(err)
2375 int err;
2376{
2377 extern int sys_nerr;
2378 extern char *sys_errlist[];
2379 static char er[20];
2380
2381 if (err > 0 && err < sys_nerr)
2382 return (sys_errlist[err]);
2383 sprintf(er, "Error %d", err);
2384 return er;
2385}
2386#endif
2387
2388/*
2389 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2390 * Return OK for success, FAIL for failure.
2391 */
2392 int
2393mch_dirname(buf, len)
2394 char_u *buf;
2395 int len;
2396{
2397#if defined(USE_GETCWD)
2398 if (getcwd((char *)buf, len) == NULL)
2399 {
2400 STRCPY(buf, strerror(errno));
2401 return FAIL;
2402 }
2403 return OK;
2404#else
2405 return (getwd((char *)buf) != NULL ? OK : FAIL);
2406#endif
2407}
2408
2409#if defined(OS2) || defined(PROTO)
2410/*
2411 * Replace all slashes by backslashes.
2412 * When 'shellslash' set do it the other way around.
2413 */
2414 void
2415slash_adjust(p)
2416 char_u *p;
2417{
2418 while (*p)
2419 {
2420 if (*p == psepcN)
2421 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002422 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 }
2424}
2425#endif
2426
2427/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002428 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 *
2430 * return FAIL for failure, OK for success
2431 */
2432 int
2433mch_FullName(fname, buf, len, force)
2434 char_u *fname, *buf;
2435 int len;
2436 int force; /* also expand when already absolute path */
2437{
2438 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002439#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002441#endif
2442#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 int fd = -1;
2444 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002445#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446 char_u olddir[MAXPATHL];
2447 char_u *p;
2448 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002449#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002450 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2451 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002452#endif
2453
Bram Moolenaar38323e42007-03-06 19:22:53 +00002454#ifdef VMS
2455 fname = vms_fixfilename(fname);
2456#endif
2457
Bram Moolenaara2442432007-04-26 14:26:37 +00002458#ifdef __CYGWIN__
2459 /*
2460 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2461 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002462# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2463 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2464# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002465 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002466# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002467 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002468#endif
2469
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 /* expand it if forced or not an absolute path */
2471 if (force || !mch_isFullName(fname))
2472 {
2473 /*
2474 * If the file name has a path, change to that directory for a moment,
2475 * and then do the getwd() (and get back to where we were).
2476 * This will get the correct path name with "../" things.
2477 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002478#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 only_drive = 0;
2480 if (((p = vim_strrchr(fname, '/')) != NULL)
2481 || ((p = vim_strrchr(fname, '\\')) != NULL)
2482 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002483#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002487#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 /*
2489 * Use fchdir() if possible, it's said to be faster and more
2490 * reliable. But on SunOS 4 it might not work. Check this by
2491 * doing a fchdir() right now.
2492 */
2493 if (!dont_fchdir)
2494 {
2495 fd = open(".", O_RDONLY | O_EXTRA, 0);
2496 if (fd >= 0 && fchdir(fd) < 0)
2497 {
2498 close(fd);
2499 fd = -1;
2500 dont_fchdir = TRUE; /* don't try again */
2501 }
2502 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002503#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504
2505 /* Only change directory when we are sure we can return to where
2506 * we are now. After doing "su" chdir(".") might not work. */
2507 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002508#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 (mch_dirname(olddir, MAXPATHL) == FAIL
2512 || mch_chdir((char *)olddir) != 0))
2513 {
2514 p = NULL; /* can't get current dir: don't chdir */
2515 retval = FAIL;
2516 }
2517 else
2518 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002519#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 /*
2521 * compensate for case where ':' from "D:" was the only
2522 * path separator detected in the file name; the _next_
2523 * character has to be removed, and then restored later.
2524 */
2525 if (only_drive)
2526 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002527#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 /* The directory is copied into buf[], to be able to remove
2529 * the file name without changing it (could be a string in
2530 * read-only memory) */
2531 if (p - fname >= len)
2532 retval = FAIL;
2533 else
2534 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002535 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (mch_chdir((char *)buf))
2537 retval = FAIL;
2538 else
2539 fname = p + 1;
2540 *buf = NUL;
2541 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002542#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 if (only_drive)
2544 {
2545 p--;
2546 if (retval != FAIL)
2547 fname--;
2548 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002549#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 }
2551 }
2552 if (mch_dirname(buf, len) == FAIL)
2553 {
2554 retval = FAIL;
2555 *buf = NUL;
2556 }
2557 if (p != NULL)
2558 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002559#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 if (fd >= 0)
2561 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002562 if (p_verbose >= 5)
2563 {
2564 verbose_enter();
2565 MSG("fchdir() to previous dir");
2566 verbose_leave();
2567 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 l = fchdir(fd);
2569 close(fd);
2570 }
2571 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 l = mch_chdir((char *)olddir);
2574 if (l != 0)
2575 EMSG(_(e_prev_dir));
2576 }
2577
2578 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002579 if (l >= len - 1)
2580 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002581#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002582 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002584 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002585#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002587
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002589 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 return FAIL;
2591
2592 /* Do not append ".", "/dir/." is equal to "/dir". */
2593 if (STRCMP(fname, ".") != 0)
2594 STRCAT(buf, fname);
2595
2596 return OK;
2597}
2598
2599/*
2600 * Return TRUE if "fname" does not depend on the current directory.
2601 */
2602 int
2603mch_isFullName(fname)
2604 char_u *fname;
2605{
2606#ifdef __EMX__
2607 return _fnisabs(fname);
2608#else
2609# ifdef VMS
2610 return ( fname[0] == '/' || fname[0] == '.' ||
2611 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2612 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2613 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2614# else
2615 return (*fname == '/' || *fname == '~');
2616# endif
2617#endif
2618}
2619
Bram Moolenaar24552be2005-12-10 20:17:30 +00002620#if defined(USE_FNAME_CASE) || defined(PROTO)
2621/*
2622 * Set the case of the file name, if it already exists. This will cause the
2623 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002624 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002625 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002626 void
2627fname_case(name, len)
2628 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002629 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002630{
2631 struct stat st;
2632 char_u *slash, *tail;
2633 DIR *dirp;
2634 struct dirent *dp;
2635
2636 if (lstat((char *)name, &st) >= 0)
2637 {
2638 /* Open the directory where the file is located. */
2639 slash = vim_strrchr(name, '/');
2640 if (slash == NULL)
2641 {
2642 dirp = opendir(".");
2643 tail = name;
2644 }
2645 else
2646 {
2647 *slash = NUL;
2648 dirp = opendir((char *)name);
2649 *slash = '/';
2650 tail = slash + 1;
2651 }
2652
2653 if (dirp != NULL)
2654 {
2655 while ((dp = readdir(dirp)) != NULL)
2656 {
2657 /* Only accept names that differ in case and are the same byte
2658 * length. TODO: accept different length name. */
2659 if (STRICMP(tail, dp->d_name) == 0
2660 && STRLEN(tail) == STRLEN(dp->d_name))
2661 {
2662 char_u newname[MAXPATHL + 1];
2663 struct stat st2;
2664
2665 /* Verify the inode is equal. */
2666 vim_strncpy(newname, name, MAXPATHL);
2667 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2668 MAXPATHL - (tail - name));
2669 if (lstat((char *)newname, &st2) >= 0
2670 && st.st_ino == st2.st_ino
2671 && st.st_dev == st2.st_dev)
2672 {
2673 STRCPY(tail, dp->d_name);
2674 break;
2675 }
2676 }
2677 }
2678
2679 closedir(dirp);
2680 }
2681 }
2682}
2683#endif
2684
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685/*
2686 * Get file permissions for 'name'.
2687 * Returns -1 when it doesn't exist.
2688 */
2689 long
2690mch_getperm(name)
2691 char_u *name;
2692{
2693 struct stat statb;
2694
2695 /* Keep the #ifdef outside of stat(), it may be a macro. */
2696#ifdef VMS
2697 if (stat((char *)vms_fixfilename(name), &statb))
2698#else
2699 if (stat((char *)name, &statb))
2700#endif
2701 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002702#ifdef __INTERIX
2703 /* The top bit makes the value negative, which means the file doesn't
2704 * exist. Remove the bit, we don't use it. */
2705 return statb.st_mode & ~S_ADDACE;
2706#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002708#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709}
2710
2711/*
2712 * set file permission for 'name' to 'perm'
2713 *
2714 * return FAIL for failure, OK otherwise
2715 */
2716 int
2717mch_setperm(name, perm)
2718 char_u *name;
2719 long perm;
2720{
2721 return (chmod((char *)
2722#ifdef VMS
2723 vms_fixfilename(name),
2724#else
2725 name,
2726#endif
2727 (mode_t)perm) == 0 ? OK : FAIL);
2728}
2729
2730#if defined(HAVE_ACL) || defined(PROTO)
2731# ifdef HAVE_SYS_ACL_H
2732# include <sys/acl.h>
2733# endif
2734# ifdef HAVE_SYS_ACCESS_H
2735# include <sys/access.h>
2736# endif
2737
2738# ifdef HAVE_SOLARIS_ACL
2739typedef struct vim_acl_solaris_T {
2740 int acl_cnt;
2741 aclent_t *acl_entry;
2742} vim_acl_solaris_T;
2743# endif
2744
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002745#if defined(HAVE_SELINUX) || defined(PROTO)
2746/*
2747 * Copy security info from "from_file" to "to_file".
2748 */
2749 void
2750mch_copy_sec(from_file, to_file)
2751 char_u *from_file;
2752 char_u *to_file;
2753{
2754 if (from_file == NULL)
2755 return;
2756
2757 if (selinux_enabled == -1)
2758 selinux_enabled = is_selinux_enabled();
2759
2760 if (selinux_enabled > 0)
2761 {
2762 security_context_t from_context = NULL;
2763 security_context_t to_context = NULL;
2764
2765 if (getfilecon((char *)from_file, &from_context) < 0)
2766 {
2767 /* If the filesystem doesn't support extended attributes,
2768 the original had no special security context and the
2769 target cannot have one either. */
2770 if (errno == EOPNOTSUPP)
2771 return;
2772
2773 MSG_PUTS(_("\nCould not get security context for "));
2774 msg_outtrans(from_file);
2775 msg_putchar('\n');
2776 return;
2777 }
2778 if (getfilecon((char *)to_file, &to_context) < 0)
2779 {
2780 MSG_PUTS(_("\nCould not get security context for "));
2781 msg_outtrans(to_file);
2782 msg_putchar('\n');
2783 freecon (from_context);
2784 return ;
2785 }
2786 if (strcmp(from_context, to_context) != 0)
2787 {
2788 if (setfilecon((char *)to_file, from_context) < 0)
2789 {
2790 MSG_PUTS(_("\nCould not set security context for "));
2791 msg_outtrans(to_file);
2792 msg_putchar('\n');
2793 }
2794 }
2795 freecon(to_context);
2796 freecon(from_context);
2797 }
2798}
2799#endif /* HAVE_SELINUX */
2800
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801/*
2802 * Return a pointer to the ACL of file "fname" in allocated memory.
2803 * Return NULL if the ACL is not available for whatever reason.
2804 */
2805 vim_acl_T
2806mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002807 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808{
2809 vim_acl_T ret = NULL;
2810#ifdef HAVE_POSIX_ACL
2811 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2812#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002813#ifdef HAVE_SOLARIS_ZFS_ACL
2814 acl_t *aclent;
2815
2816 if (acl_get((char *)fname, 0, &aclent) < 0)
2817 return NULL;
2818 ret = (vim_acl_T)aclent;
2819#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820#ifdef HAVE_SOLARIS_ACL
2821 vim_acl_solaris_T *aclent;
2822
2823 aclent = malloc(sizeof(vim_acl_solaris_T));
2824 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2825 {
2826 free(aclent);
2827 return NULL;
2828 }
2829 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2830 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2831 {
2832 free(aclent->acl_entry);
2833 free(aclent);
2834 return NULL;
2835 }
2836 ret = (vim_acl_T)aclent;
2837#else
2838#if defined(HAVE_AIX_ACL)
2839 int aclsize;
2840 struct acl *aclent;
2841
2842 aclsize = sizeof(struct acl);
2843 aclent = malloc(aclsize);
2844 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2845 {
2846 if (errno == ENOSPC)
2847 {
2848 aclsize = aclent->acl_len;
2849 aclent = realloc(aclent, aclsize);
2850 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2851 {
2852 free(aclent);
2853 return NULL;
2854 }
2855 }
2856 else
2857 {
2858 free(aclent);
2859 return NULL;
2860 }
2861 }
2862 ret = (vim_acl_T)aclent;
2863#endif /* HAVE_AIX_ACL */
2864#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002865#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866#endif /* HAVE_POSIX_ACL */
2867 return ret;
2868}
2869
2870/*
2871 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2872 */
2873 void
2874mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002875 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 vim_acl_T aclent;
2877{
2878 if (aclent == NULL)
2879 return;
2880#ifdef HAVE_POSIX_ACL
2881 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2882#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002883#ifdef HAVE_SOLARIS_ZFS_ACL
2884 acl_set((char *)fname, (acl_t *)aclent);
2885#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886#ifdef HAVE_SOLARIS_ACL
2887 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2888 ((vim_acl_solaris_T *)aclent)->acl_entry);
2889#else
2890#ifdef HAVE_AIX_ACL
2891 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2892#endif /* HAVE_AIX_ACL */
2893#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002894#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895#endif /* HAVE_POSIX_ACL */
2896}
2897
2898 void
2899mch_free_acl(aclent)
2900 vim_acl_T aclent;
2901{
2902 if (aclent == NULL)
2903 return;
2904#ifdef HAVE_POSIX_ACL
2905 acl_free((acl_t)aclent);
2906#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002907#ifdef HAVE_SOLARIS_ZFS_ACL
2908 acl_free((acl_t *)aclent);
2909#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910#ifdef HAVE_SOLARIS_ACL
2911 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2912 free(aclent);
2913#else
2914#ifdef HAVE_AIX_ACL
2915 free(aclent);
2916#endif /* HAVE_AIX_ACL */
2917#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002918#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919#endif /* HAVE_POSIX_ACL */
2920}
2921#endif
2922
2923/*
2924 * Set hidden flag for "name".
2925 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 void
2927mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002928 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929{
2930 /* can't hide a file */
2931}
2932
2933/*
2934 * return TRUE if "name" is a directory
2935 * return FALSE if "name" is not a directory
2936 * return FALSE for error
2937 */
2938 int
2939mch_isdir(name)
2940 char_u *name;
2941{
2942 struct stat statb;
2943
2944 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2945 return FALSE;
2946 if (stat((char *)name, &statb))
2947 return FALSE;
2948#ifdef _POSIX_SOURCE
2949 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2950#else
2951 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2952#endif
2953}
2954
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955static int executable_file __ARGS((char_u *name));
2956
2957/*
2958 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2959 */
2960 static int
2961executable_file(name)
2962 char_u *name;
2963{
2964 struct stat st;
2965
2966 if (stat((char *)name, &st))
2967 return 0;
2968 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2969}
2970
2971/*
2972 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2973 * Return -1 if unknown.
2974 */
2975 int
2976mch_can_exe(name)
2977 char_u *name;
2978{
2979 char_u *buf;
2980 char_u *p, *e;
2981 int retval;
2982
2983 /* If it's an absolute or relative path don't need to use $PATH. */
2984 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2985 || (name[1] == '.' && name[2] == '/'))))
2986 return executable_file(name);
2987
2988 p = (char_u *)getenv("PATH");
2989 if (p == NULL || *p == NUL)
2990 return -1;
2991 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2992 if (buf == NULL)
2993 return -1;
2994
2995 /*
2996 * Walk through all entries in $PATH to check if "name" exists there and
2997 * is an executable file.
2998 */
2999 for (;;)
3000 {
3001 e = (char_u *)strchr((char *)p, ':');
3002 if (e == NULL)
3003 e = p + STRLEN(p);
3004 if (e - p <= 1) /* empty entry means current dir */
3005 STRCPY(buf, "./");
3006 else
3007 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003008 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 add_pathsep(buf);
3010 }
3011 STRCAT(buf, name);
3012 retval = executable_file(buf);
3013 if (retval == 1)
3014 break;
3015
3016 if (*e != ':')
3017 break;
3018 p = e + 1;
3019 }
3020
3021 vim_free(buf);
3022 return retval;
3023}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003024
3025/*
3026 * Check what "name" is:
3027 * NODE_NORMAL: file or directory (or doesn't exist)
3028 * NODE_WRITABLE: writable device, socket, fifo, etc.
3029 * NODE_OTHER: non-writable things
3030 */
3031 int
3032mch_nodetype(name)
3033 char_u *name;
3034{
3035 struct stat st;
3036
3037 if (stat((char *)name, &st))
3038 return NODE_NORMAL;
3039 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3040 return NODE_NORMAL;
3041#ifndef OS2
3042 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3043 return NODE_OTHER;
3044#endif
3045 /* Everything else is writable? */
3046 return NODE_WRITABLE;
3047}
3048
3049 void
3050mch_early_init()
3051{
3052#ifdef HAVE_CHECK_STACK_GROWTH
3053 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 check_stack_growth((char *)&i);
3056
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003057# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 get_stack_limit();
3059# endif
3060
3061#endif
3062
3063 /*
3064 * Setup an alternative stack for signals. Helps to catch signals when
3065 * running out of stack space.
3066 * Use of sigaltstack() is preferred, it's more portable.
3067 * Ignore any errors.
3068 */
3069#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003070 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 init_signal_stack();
3072#endif
3073}
3074
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003075#if defined(EXITFREE) || defined(PROTO)
3076 void
3077mch_free_mem()
3078{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003079# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3080 if (clip_star.owned)
3081 clip_lose_selection(&clip_star);
3082 if (clip_plus.owned)
3083 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003084# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003085# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003086 if (xterm_Shell != (Widget)0)
3087 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003088# ifndef LESSTIF_VERSION
3089 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003090 if (xterm_dpy != NULL)
3091 XtCloseDisplay(xterm_dpy);
3092 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003093 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003094 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003095# ifdef FEAT_X11
3096 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3097# endif
3098 }
3099# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003100# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003101# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003102 if (x11_display != NULL
3103# ifdef FEAT_XCLIPBOARD
3104 && x11_display != xterm_dpy
3105# endif
3106 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003107 XCloseDisplay(x11_display);
3108# endif
3109# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3110 vim_free(signal_stack);
3111 signal_stack = NULL;
3112# endif
3113# ifdef FEAT_TITLE
3114 vim_free(oldtitle);
3115 vim_free(oldicon);
3116# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003117}
3118#endif
3119
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120static void exit_scroll __ARGS((void));
3121
3122/*
3123 * Output a newline when exiting.
3124 * Make sure the newline goes to the same stream as the text.
3125 */
3126 static void
3127exit_scroll()
3128{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003129 if (silent_mode)
3130 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 if (newline_on_exit || msg_didout)
3132 {
3133 if (msg_use_printf())
3134 {
3135 if (info_message)
3136 mch_msg("\n");
3137 else
3138 mch_errmsg("\r\n");
3139 }
3140 else
3141 out_char('\n');
3142 }
3143 else
3144 {
3145 restore_cterm_colors(); /* get original colors back */
3146 msg_clr_eos_force(); /* clear the rest of the display */
3147 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3148 }
3149}
3150
3151 void
3152mch_exit(r)
3153 int r;
3154{
3155 exiting = TRUE;
3156
3157#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3158 x11_export_final_selection();
3159#endif
3160
3161#ifdef FEAT_GUI
3162 if (!gui.in_use)
3163#endif
3164 {
3165 settmode(TMODE_COOK);
3166#ifdef FEAT_TITLE
3167 mch_restore_title(3); /* restore xterm title and icon name */
3168#endif
3169 /*
3170 * When t_ti is not empty but it doesn't cause swapping terminal
3171 * pages, need to output a newline when msg_didout is set. But when
3172 * t_ti does swap pages it should not go to the shell page. Do this
3173 * before stoptermcap().
3174 */
3175 if (swapping_screen() && !newline_on_exit)
3176 exit_scroll();
3177
3178 /* Stop termcap: May need to check for T_CRV response, which
3179 * requires RAW mode. */
3180 stoptermcap();
3181
3182 /*
3183 * A newline is only required after a message in the alternate screen.
3184 * This is set to TRUE by wait_return().
3185 */
3186 if (!swapping_screen() || newline_on_exit)
3187 exit_scroll();
3188
3189 /* Cursor may have been switched off without calling starttermcap()
3190 * when doing "vim -u vimrc" and vimrc contains ":q". */
3191 if (full_screen)
3192 cursor_on();
3193 }
3194 out_flush();
3195 ml_close_all(TRUE); /* remove all memfiles */
3196 may_core_dump();
3197#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 gui_exit(r);
3200#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003201
Bram Moolenaar56718732006-03-15 22:53:57 +00003202#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003203 mac_conv_cleanup();
3204#endif
3205
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206#ifdef __QNX__
3207 /* A core dump won't be created if the signal handler
3208 * doesn't return, so we can't call exit() */
3209 if (deadly_signal != 0)
3210 return;
3211#endif
3212
Bram Moolenaar009b2592004-10-24 19:18:58 +00003213#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003214 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003215#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003216
3217#ifdef EXITFREE
3218 free_all_mem();
3219#endif
3220
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 exit(r);
3222}
3223
3224 static void
3225may_core_dump()
3226{
3227 if (deadly_signal != 0)
3228 {
3229 signal(deadly_signal, SIG_DFL);
3230 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3231 }
3232}
3233
3234#ifndef VMS
3235
3236 void
3237mch_settmode(tmode)
3238 int tmode;
3239{
3240 static int first = TRUE;
3241
3242 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3243#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3244 /*
3245 * for "new" tty systems
3246 */
3247# ifdef HAVE_TERMIOS_H
3248 static struct termios told;
3249 struct termios tnew;
3250# else
3251 static struct termio told;
3252 struct termio tnew;
3253# endif
3254
3255 if (first)
3256 {
3257 first = FALSE;
3258# if defined(HAVE_TERMIOS_H)
3259 tcgetattr(read_cmd_fd, &told);
3260# else
3261 ioctl(read_cmd_fd, TCGETA, &told);
3262# endif
3263 }
3264
3265 tnew = told;
3266 if (tmode == TMODE_RAW)
3267 {
3268 /*
3269 * ~ICRNL enables typing ^V^M
3270 */
3271 tnew.c_iflag &= ~ICRNL;
3272 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3273# if defined(IEXTEN) && !defined(__MINT__)
3274 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3275 /* but it breaks function keys on MINT */
3276# endif
3277 );
3278# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3279 tnew.c_oflag &= ~ONLCR;
3280# endif
3281 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3282 tnew.c_cc[VTIME] = 0; /* don't wait */
3283 }
3284 else if (tmode == TMODE_SLEEP)
3285 tnew.c_lflag &= ~(ECHO);
3286
3287# if defined(HAVE_TERMIOS_H)
3288 {
3289 int n = 10;
3290
3291 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3292 * few times. */
3293 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3294 && errno == EINTR && n > 0)
3295 --n;
3296 }
3297# else
3298 ioctl(read_cmd_fd, TCSETA, &tnew);
3299# endif
3300
3301#else
3302
3303 /*
3304 * for "old" tty systems
3305 */
3306# ifndef TIOCSETN
3307# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3308# endif
3309 static struct sgttyb ttybold;
3310 struct sgttyb ttybnew;
3311
3312 if (first)
3313 {
3314 first = FALSE;
3315 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3316 }
3317
3318 ttybnew = ttybold;
3319 if (tmode == TMODE_RAW)
3320 {
3321 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3322 ttybnew.sg_flags |= RAW;
3323 }
3324 else if (tmode == TMODE_SLEEP)
3325 ttybnew.sg_flags &= ~(ECHO);
3326 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3327#endif
3328 curr_tmode = tmode;
3329}
3330
3331/*
3332 * Try to get the code for "t_kb" from the stty setting
3333 *
3334 * Even if termcap claims a backspace key, the user's setting *should*
3335 * prevail. stty knows more about reality than termcap does, and if
3336 * somebody's usual erase key is DEL (which, for most BSD users, it will
3337 * be), they're going to get really annoyed if their erase key starts
3338 * doing forward deletes for no reason. (Eric Fischer)
3339 */
3340 void
3341get_stty()
3342{
3343 char_u buf[2];
3344 char_u *p;
3345
3346 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3347#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3348 /* for "new" tty systems */
3349# ifdef HAVE_TERMIOS_H
3350 struct termios keys;
3351# else
3352 struct termio keys;
3353# endif
3354
3355# if defined(HAVE_TERMIOS_H)
3356 if (tcgetattr(read_cmd_fd, &keys) != -1)
3357# else
3358 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3359# endif
3360 {
3361 buf[0] = keys.c_cc[VERASE];
3362 intr_char = keys.c_cc[VINTR];
3363#else
3364 /* for "old" tty systems */
3365 struct sgttyb keys;
3366
3367 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3368 {
3369 buf[0] = keys.sg_erase;
3370 intr_char = keys.sg_kill;
3371#endif
3372 buf[1] = NUL;
3373 add_termcode((char_u *)"kb", buf, FALSE);
3374
3375 /*
3376 * If <BS> and <DEL> are now the same, redefine <DEL>.
3377 */
3378 p = find_termcode((char_u *)"kD");
3379 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3380 do_fixdel(NULL);
3381 }
3382#if 0
3383 } /* to keep cindent happy */
3384#endif
3385}
3386
3387#endif /* VMS */
3388
3389#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3390/*
3391 * Set mouse clicks on or off.
3392 */
3393 void
3394mch_setmouse(on)
3395 int on;
3396{
3397 static int ison = FALSE;
3398 int xterm_mouse_vers;
3399
3400 if (on == ison) /* return quickly if nothing to do */
3401 return;
3402
3403 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003404
3405# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003406 if (ttym_flags == TTYM_URXVT)
3407 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003408 out_str_nf((char_u *)
3409 (on
3410 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3411 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3412 ison = on;
3413 }
3414# endif
3415
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003416# ifdef FEAT_MOUSE_SGR
3417 if (ttym_flags == TTYM_SGR)
3418 {
3419 out_str_nf((char_u *)
3420 (on
3421 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3422 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3423 ison = on;
3424 }
3425# endif
3426
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 if (xterm_mouse_vers > 0)
3428 {
3429 if (on) /* enable mouse events, use mouse tracking if available */
3430 out_str_nf((char_u *)
3431 (xterm_mouse_vers > 1
3432 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3433 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3434 else /* disable mouse events, could probably always send the same */
3435 out_str_nf((char_u *)
3436 (xterm_mouse_vers > 1
3437 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3438 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3439 ison = on;
3440 }
3441
3442# ifdef FEAT_MOUSE_DEC
3443 else if (ttym_flags == TTYM_DEC)
3444 {
3445 if (on) /* enable mouse events */
3446 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3447 else /* disable mouse events */
3448 out_str_nf((char_u *)"\033['z");
3449 ison = on;
3450 }
3451# endif
3452
3453# ifdef FEAT_MOUSE_GPM
3454 else
3455 {
3456 if (on)
3457 {
3458 if (gpm_open())
3459 ison = TRUE;
3460 }
3461 else
3462 {
3463 gpm_close();
3464 ison = FALSE;
3465 }
3466 }
3467# endif
3468
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003469# ifdef FEAT_SYSMOUSE
3470 else
3471 {
3472 if (on)
3473 {
3474 if (sysmouse_open() == OK)
3475 ison = TRUE;
3476 }
3477 else
3478 {
3479 sysmouse_close();
3480 ison = FALSE;
3481 }
3482 }
3483# endif
3484
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485# ifdef FEAT_MOUSE_JSB
3486 else
3487 {
3488 if (on)
3489 {
3490 /* D - Enable Mouse up/down messages
3491 * L - Enable Left Button Reporting
3492 * M - Enable Middle Button Reporting
3493 * R - Enable Right Button Reporting
3494 * K - Enable SHIFT and CTRL key Reporting
3495 * + - Enable Advanced messaging of mouse moves and up/down messages
3496 * Q - Quiet No Ack
3497 * # - Numeric value of mouse pointer required
3498 * 0 = Multiview 2000 cursor, used as standard
3499 * 1 = Windows Arrow
3500 * 2 = Windows I Beam
3501 * 3 = Windows Hour Glass
3502 * 4 = Windows Cross Hair
3503 * 5 = Windows UP Arrow
3504 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003505# ifdef JSBTERM_MOUSE_NONADVANCED
3506 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3508 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003509# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3511 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003512# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 ison = TRUE;
3514 }
3515 else
3516 {
3517 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3518 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3519 ison = FALSE;
3520 }
3521 }
3522# endif
3523# ifdef FEAT_MOUSE_PTERM
3524 else
3525 {
3526 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3527 if (on)
3528 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3529 else
3530 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3531 ison = on;
3532 }
3533# endif
3534}
3535
3536/*
3537 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3538 */
3539 void
3540check_mouse_termcode()
3541{
3542# ifdef FEAT_MOUSE_XTERM
3543 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003544# ifdef FEAT_MOUSE_URXVT
3545 && use_xterm_mouse() != 3
3546# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547# ifdef FEAT_GUI
3548 && !gui.in_use
3549# endif
3550 )
3551 {
3552 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003553 ? IF_EB("\233M", CSI_STR "M")
3554 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 if (*p_mouse != NUL)
3556 {
3557 /* force mouse off and maybe on to send possibly new mouse
3558 * activation sequence to the xterm, with(out) drag tracing. */
3559 mch_setmouse(FALSE);
3560 setmouse();
3561 }
3562 }
3563 else
3564 del_mouse_termcode(KS_MOUSE);
3565# endif
3566
3567# ifdef FEAT_MOUSE_GPM
3568 if (!use_xterm_mouse()
3569# ifdef FEAT_GUI
3570 && !gui.in_use
3571# endif
3572 )
3573 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3574# endif
3575
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003576# ifdef FEAT_SYSMOUSE
3577 if (!use_xterm_mouse()
3578# ifdef FEAT_GUI
3579 && !gui.in_use
3580# endif
3581 )
3582 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3583# endif
3584
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585# ifdef FEAT_MOUSE_JSB
3586 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3587 if (!use_xterm_mouse()
3588# ifdef FEAT_GUI
3589 && !gui.in_use
3590# endif
3591 )
3592 set_mouse_termcode(KS_JSBTERM_MOUSE,
3593 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3594 else
3595 del_mouse_termcode(KS_JSBTERM_MOUSE);
3596# endif
3597
3598# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003599 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600 * define it in the GUI or when using an xterm. */
3601 if (!use_xterm_mouse()
3602# ifdef FEAT_GUI
3603 && !gui.in_use
3604# endif
3605 )
3606 set_mouse_termcode(KS_NETTERM_MOUSE,
3607 (char_u *)IF_EB("\033}", ESC_STR "}"));
3608 else
3609 del_mouse_termcode(KS_NETTERM_MOUSE);
3610# endif
3611
3612# ifdef FEAT_MOUSE_DEC
3613 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3614 if (!use_xterm_mouse()
3615# ifdef FEAT_GUI
3616 && !gui.in_use
3617# endif
3618 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003619 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3620 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 else
3622 del_mouse_termcode(KS_DEC_MOUSE);
3623# endif
3624# ifdef FEAT_MOUSE_PTERM
3625 /* same as the dec mouse */
3626 if (!use_xterm_mouse()
3627# ifdef FEAT_GUI
3628 && !gui.in_use
3629# endif
3630 )
3631 set_mouse_termcode(KS_PTERM_MOUSE,
3632 (char_u *) IF_EB("\033[", ESC_STR "["));
3633 else
3634 del_mouse_termcode(KS_PTERM_MOUSE);
3635# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003636# ifdef FEAT_MOUSE_URXVT
3637 /* same as the dec mouse */
3638 if (use_xterm_mouse() == 3
3639# ifdef FEAT_GUI
3640 && !gui.in_use
3641# endif
3642 )
3643 {
3644 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3645 ? IF_EB("\233", CSI_STR)
3646 : IF_EB("\033[", ESC_STR "[")));
3647
3648 if (*p_mouse != NUL)
3649 {
3650 mch_setmouse(FALSE);
3651 setmouse();
3652 }
3653 }
3654 else
3655 del_mouse_termcode(KS_URXVT_MOUSE);
3656# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003657# ifdef FEAT_MOUSE_SGR
3658 /* same as the dec mouse */
3659 if (use_xterm_mouse() == 4
3660# ifdef FEAT_GUI
3661 && !gui.in_use
3662# endif
3663 )
3664 {
3665 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3666 ? IF_EB("\233<", CSI_STR "<")
3667 : IF_EB("\033[<", ESC_STR "[<")));
3668
3669 if (*p_mouse != NUL)
3670 {
3671 mch_setmouse(FALSE);
3672 setmouse();
3673 }
3674 }
3675 else
3676 del_mouse_termcode(KS_SGR_MOUSE);
3677# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678}
3679#endif
3680
3681/*
3682 * set screen mode, always fails.
3683 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 int
3685mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003686 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687{
3688 EMSG(_(e_screenmode));
3689 return FAIL;
3690}
3691
3692#ifndef VMS
3693
3694/*
3695 * Try to get the current window size:
3696 * 1. with an ioctl(), most accurate method
3697 * 2. from the environment variables LINES and COLUMNS
3698 * 3. from the termcap
3699 * 4. keep using the old values
3700 * Return OK when size could be determined, FAIL otherwise.
3701 */
3702 int
3703mch_get_shellsize()
3704{
3705 long rows = 0;
3706 long columns = 0;
3707 char_u *p;
3708
3709 /*
3710 * For OS/2 use _scrsize().
3711 */
3712# ifdef __EMX__
3713 {
3714 int s[2];
3715
3716 _scrsize(s);
3717 columns = s[0];
3718 rows = s[1];
3719 }
3720# endif
3721
3722 /*
3723 * 1. try using an ioctl. It is the most accurate method.
3724 *
3725 * Try using TIOCGWINSZ first, some systems that have it also define
3726 * TIOCGSIZE but don't have a struct ttysize.
3727 */
3728# ifdef TIOCGWINSZ
3729 {
3730 struct winsize ws;
3731 int fd = 1;
3732
3733 /* When stdout is not a tty, use stdin for the ioctl(). */
3734 if (!isatty(fd) && isatty(read_cmd_fd))
3735 fd = read_cmd_fd;
3736 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3737 {
3738 columns = ws.ws_col;
3739 rows = ws.ws_row;
3740 }
3741 }
3742# else /* TIOCGWINSZ */
3743# ifdef TIOCGSIZE
3744 {
3745 struct ttysize ts;
3746 int fd = 1;
3747
3748 /* When stdout is not a tty, use stdin for the ioctl(). */
3749 if (!isatty(fd) && isatty(read_cmd_fd))
3750 fd = read_cmd_fd;
3751 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3752 {
3753 columns = ts.ts_cols;
3754 rows = ts.ts_lines;
3755 }
3756 }
3757# endif /* TIOCGSIZE */
3758# endif /* TIOCGWINSZ */
3759
3760 /*
3761 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003762 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3763 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003765 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 {
3767 if ((p = (char_u *)getenv("LINES")))
3768 rows = atoi((char *)p);
3769 if ((p = (char_u *)getenv("COLUMNS")))
3770 columns = atoi((char *)p);
3771 }
3772
3773#ifdef HAVE_TGETENT
3774 /*
3775 * 3. try reading "co" and "li" entries from termcap
3776 */
3777 if (columns == 0 || rows == 0)
3778 getlinecol(&columns, &rows);
3779#endif
3780
3781 /*
3782 * 4. If everything fails, use the old values
3783 */
3784 if (columns <= 0 || rows <= 0)
3785 return FAIL;
3786
3787 Rows = rows;
3788 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003789 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 return OK;
3791}
3792
3793/*
3794 * Try to set the window size to Rows and Columns.
3795 */
3796 void
3797mch_set_shellsize()
3798{
3799 if (*T_CWS)
3800 {
3801 /*
3802 * NOTE: if you get an error here that term_set_winsize() is
3803 * undefined, check the output of configure. It could probably not
3804 * find a ncurses, termcap or termlib library.
3805 */
3806 term_set_winsize((int)Rows, (int)Columns);
3807 out_flush();
3808 screen_start(); /* don't know where cursor is now */
3809 }
3810}
3811
3812#endif /* VMS */
3813
3814/*
3815 * Rows and/or Columns has changed.
3816 */
3817 void
3818mch_new_shellsize()
3819{
3820 /* Nothing to do. */
3821}
3822
Bram Moolenaar205b8862011-09-07 15:04:31 +02003823/*
3824 * Wait for process "child" to end.
3825 * Return "child" if it exited properly, <= 0 on error.
3826 */
3827 static pid_t
3828wait4pid(child, status)
3829 pid_t child;
3830 waitstatus *status;
3831{
3832 pid_t wait_pid = 0;
3833
3834 while (wait_pid != child)
3835 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003836 /* When compiled with Python threads are probably used, in which case
3837 * wait() sometimes hangs for no obvious reason. Use waitpid()
3838 * instead and loop (like the GUI). Also needed for other interfaces,
3839 * they might call system(). */
3840# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003841 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003842# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003843 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003844# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003845 if (wait_pid == 0)
3846 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003847 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003848 mch_delay(10L, TRUE);
3849 continue;
3850 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003851 if (wait_pid <= 0
3852# ifdef ECHILD
3853 && errno == ECHILD
3854# endif
3855 )
3856 break;
3857 }
3858 return wait_pid;
3859}
3860
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 int
3862mch_call_shell(cmd, options)
3863 char_u *cmd;
3864 int options; /* SHELL_*, see vim.h */
3865{
3866#ifdef VMS
3867 char *ifn = NULL;
3868 char *ofn = NULL;
3869#endif
3870 int tmode = cur_tmode;
3871#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3872 int x;
3873# ifndef __EMX__
3874 char_u *newcmd; /* only needed for unix */
3875# else
3876 /*
3877 * Set the preferred shell in the EMXSHELL environment variable (but
3878 * only if it is different from what is already in the environment).
3879 * Emx then takes care of whether to use "/c" or "-c" in an
3880 * intelligent way. Simply pass the whole thing to emx's system() call.
3881 * Emx also starts an interactive shell if system() is passed an empty
3882 * string.
3883 */
3884 char_u *p, *old;
3885
3886 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3887 {
3888 /* should check HAVE_SETENV, but I know we don't have it. */
3889 p = alloc(10 + strlen(p_sh));
3890 if (p)
3891 {
3892 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3893 putenv((char *)p); /* don't free the pointer! */
3894 }
3895 }
3896# endif
3897
3898 out_flush();
3899
3900 if (options & SHELL_COOKED)
3901 settmode(TMODE_COOK); /* set to normal mode */
3902
Bram Moolenaar62b42182010-09-21 22:09:37 +02003903# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003904 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02003905 loose_clipboard();
3906# endif
3907
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908# ifdef __EMX__
3909 if (cmd == NULL)
3910 x = system(""); /* this starts an interactive shell in emx */
3911 else
3912 x = system((char *)cmd);
3913 /* system() returns -1 when error occurs in starting shell */
3914 if (x == -1 && !emsg_silent)
3915 {
3916 MSG_PUTS(_("\nCannot execute shell "));
3917 msg_outtrans(p_sh);
3918 msg_putchar('\n');
3919 }
3920# else /* not __EMX__ */
3921 if (cmd == NULL)
3922 x = system((char *)p_sh);
3923 else
3924 {
3925# ifdef VMS
3926 if (ofn = strchr((char *)cmd, '>'))
3927 *ofn++ = '\0';
3928 if (ifn = strchr((char *)cmd, '<'))
3929 {
3930 char *p;
3931
3932 *ifn++ = '\0';
3933 p = strchr(ifn,' '); /* chop off any trailing spaces */
3934 if (p)
3935 *p = '\0';
3936 }
3937 if (ofn)
3938 x = vms_sys((char *)cmd, ofn, ifn);
3939 else
3940 x = system((char *)cmd);
3941# else
3942 newcmd = lalloc(STRLEN(p_sh)
3943 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3944 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3945 if (newcmd == NULL)
3946 x = 0;
3947 else
3948 {
3949 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3950 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3951 (char *)p_shcf,
3952 (char *)cmd);
3953 x = system((char *)newcmd);
3954 vim_free(newcmd);
3955 }
3956# endif
3957 }
3958# ifdef VMS
3959 x = vms_sys_status(x);
3960# endif
3961 if (emsg_silent)
3962 ;
3963 else if (x == 127)
3964 MSG_PUTS(_("\nCannot execute shell sh\n"));
3965# endif /* __EMX__ */
3966 else if (x && !(options & SHELL_SILENT))
3967 {
3968 MSG_PUTS(_("\nshell returned "));
3969 msg_outnum((long)x);
3970 msg_putchar('\n');
3971 }
3972
3973 if (tmode == TMODE_RAW)
3974 settmode(TMODE_RAW); /* set to raw mode */
3975# ifdef FEAT_TITLE
3976 resettitle();
3977# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003978# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3979 restore_clipboard();
3980# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981 return x;
3982
3983#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3984
Bram Moolenaardf177f62005-02-22 08:39:57 +00003985# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3986 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987
3988 char_u *newcmd = NULL;
3989 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003990 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991 pid_t wait_pid = 0;
3992# ifdef HAVE_UNION_WAIT
3993 union wait status;
3994# else
3995 int status = -1;
3996# endif
3997 int retval = -1;
3998 char **argv = NULL;
3999 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004000 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 int i;
4002 char_u *p;
4003 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004005# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 int pty_slave_fd = -1;
4007 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004008# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004009 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 int fd_fromshell[2];
4011 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004012# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004014# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 static char envbuf_Rows[20];
4016 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004018 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019
Bram Moolenaar62b42182010-09-21 22:09:37 +02004020 newcmd = vim_strsave(p_sh);
4021 if (newcmd == NULL) /* out of memory */
4022 goto error;
4023
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024 out_flush();
4025 if (options & SHELL_COOKED)
4026 settmode(TMODE_COOK); /* set to normal mode */
4027
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004028 /*
4029 * Do this loop twice:
4030 * 1: find number of arguments
4031 * 2: separate them and build argv[]
4032 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033 for (i = 0; i < 2; ++i)
4034 {
4035 p = newcmd;
4036 inquote = FALSE;
4037 argc = 0;
4038 for (;;)
4039 {
4040 if (i == 1)
4041 argv[argc] = (char *)p;
4042 ++argc;
4043 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4044 {
4045 if (*p == '"')
4046 inquote = !inquote;
4047 ++p;
4048 }
4049 if (*p == NUL)
4050 break;
4051 if (i == 1)
4052 *p++ = NUL;
4053 p = skipwhite(p);
4054 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004055 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004056 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004057 /*
4058 * Account for possible multiple args in p_shcf.
4059 */
4060 p = p_shcf;
4061 for (;;)
4062 {
4063 p = skiptowhite(p);
4064 if (*p == NUL)
4065 break;
4066 ++argc;
4067 p = skipwhite(p);
4068 }
4069
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4071 if (argv == NULL) /* out of memory */
4072 goto error;
4073 }
4074 }
4075 if (cmd != NULL)
4076 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004077 char_u *s;
4078
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 if (extra_shell_arg != NULL)
4080 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004081
4082 /* Break 'shellcmdflag' into white separated parts. This doesn't
4083 * handle quoted strings, they are very unlikely to appear. */
4084 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4085 if (p_shcf_copy == NULL) /* out of memory */
4086 goto error;
4087 s = p_shcf_copy;
4088 p = p_shcf;
4089 while (*p != NUL)
4090 {
4091 argv[argc++] = (char *)s;
4092 while (*p && *p != ' ' && *p != TAB)
4093 *s++ = *p++;
4094 *s++ = NUL;
4095 p = skipwhite(p);
4096 }
4097
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098 argv[argc++] = (char *)cmd;
4099 }
4100 argv[argc] = NULL;
4101
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004103 * For the GUI, when writing the output into the buffer and when reading
4104 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4105 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004107 if ((options & (SHELL_READ|SHELL_WRITE))
4108# ifdef FEAT_GUI
4109 || (gui.in_use && show_shell_mess)
4110# endif
4111 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004113# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 /*
4115 * Try to open a master pty.
4116 * If this works, open the slave pty.
4117 * If the slave can't be opened, close the master pty.
4118 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004119 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 {
4121 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004122 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004124 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4125 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4126 * adding O_NOCTTY always works when defined. */
4127#ifdef O_NOCTTY
4128 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4129#else
4130 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4131#endif
4132 if (pty_slave_fd < 0)
4133 {
4134 close(pty_master_fd);
4135 pty_master_fd = -1;
4136 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 }
4138 }
4139 /*
4140 * If not opening a pty or it didn't work, try using pipes.
4141 */
4142 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004143# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 {
4145 pipe_error = (pipe(fd_toshell) < 0);
4146 if (!pipe_error) /* pipe create OK */
4147 {
4148 pipe_error = (pipe(fd_fromshell) < 0);
4149 if (pipe_error) /* pipe create failed */
4150 {
4151 close(fd_toshell[0]);
4152 close(fd_toshell[1]);
4153 }
4154 }
4155 if (pipe_error)
4156 {
4157 MSG_PUTS(_("\nCannot create pipes\n"));
4158 out_flush();
4159 }
4160 }
4161 }
4162
4163 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 {
4165# ifdef __BEOS__
4166 beos_cleanup_read_thread();
4167# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004168
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4170 {
4171 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004172 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004174 || (gui.in_use && show_shell_mess)
4175# endif
4176 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004178# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 if (pty_master_fd >= 0) /* close the pseudo tty */
4180 {
4181 close(pty_master_fd);
4182 close(pty_slave_fd);
4183 }
4184 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004185# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 {
4187 close(fd_toshell[0]);
4188 close(fd_toshell[1]);
4189 close(fd_fromshell[0]);
4190 close(fd_fromshell[1]);
4191 }
4192 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 }
4194 else if (pid == 0) /* child */
4195 {
4196 reset_signals(); /* handle signals normally */
4197
4198 if (!show_shell_mess || (options & SHELL_EXPAND))
4199 {
4200 int fd;
4201
4202 /*
4203 * Don't want to show any message from the shell. Can't just
4204 * close stdout and stderr though, because some systems will
4205 * break if you try to write to them after that, so we must
4206 * use dup() to replace them with something else -- webb
4207 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4208 * waiting for input.
4209 */
4210 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4211 fclose(stdin);
4212 fclose(stdout);
4213 fclose(stderr);
4214
4215 /*
4216 * If any of these open()'s and dup()'s fail, we just continue
4217 * anyway. It's not fatal, and on most systems it will make
4218 * no difference at all. On a few it will cause the execvp()
4219 * to exit with a non-zero status even when the completion
4220 * could be done, which is nothing too serious. If the open()
4221 * or dup() failed we'd just do the same thing ourselves
4222 * anyway -- webb
4223 */
4224 if (fd >= 0)
4225 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004226 ignored = dup(fd); /* To replace stdin (fd 0) */
4227 ignored = dup(fd); /* To replace stdout (fd 1) */
4228 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229
4230 /* Don't need this now that we've duplicated it */
4231 close(fd);
4232 }
4233 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004234 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004236 || gui.in_use
4237# endif
4238 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 {
4240
Bram Moolenaardf177f62005-02-22 08:39:57 +00004241# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004242 /* Create our own process group, so that the child and all its
4243 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004244 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004245 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004246 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004247 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004248# if defined(SIGHUP)
4249 /* When doing "!xterm&" and 'shell' is bash: the shell
4250 * will exit and send SIGHUP to all processes in its
4251 * group, killing the just started process. Ignore SIGHUP
4252 * to avoid that. (suggested by Simon Schubert)
4253 */
4254 signal(SIGHUP, SIG_IGN);
4255# endif
4256 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004257# endif
4258# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004259 if (pty_slave_fd >= 0)
4260 {
4261 /* push stream discipline modules */
4262 if (options & SHELL_COOKED)
4263 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004265 /* Try to become controlling tty (probably doesn't work,
4266 * unless run by root) */
4267 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004269 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004270# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004272# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 setenv("TERM", "dumb", 1);
4274 sprintf((char *)envbuf, "%ld", Rows);
4275 setenv("ROWS", (char *)envbuf, 1);
4276 sprintf((char *)envbuf, "%ld", Rows);
4277 setenv("LINES", (char *)envbuf, 1);
4278 sprintf((char *)envbuf, "%ld", Columns);
4279 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004280# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 /*
4282 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004283 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 */
4285 putenv("TERM=dumb");
4286 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4287 putenv(envbuf_Rows);
4288 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4289 putenv(envbuf_Rows);
4290 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4291 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004292# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293
Bram Moolenaara5792f52005-11-23 21:25:05 +00004294 /*
4295 * stderr is only redirected when using the GUI, so that a
4296 * program like gpg can still access the terminal to get a
4297 * passphrase using stderr.
4298 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004299# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 if (pty_master_fd >= 0)
4301 {
4302 close(pty_master_fd); /* close master side of pty */
4303
4304 /* set up stdin/stdout/stderr for the child */
4305 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004306 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004308 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004309 if (gui.in_use)
4310 {
4311 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004312 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004313 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314
4315 close(pty_slave_fd); /* has been dupped, close it now */
4316 }
4317 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004318# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 {
4320 /* set up stdin for the child */
4321 close(fd_toshell[1]);
4322 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004323 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 close(fd_toshell[0]);
4325
4326 /* set up stdout for the child */
4327 close(fd_fromshell[0]);
4328 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004329 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004330 close(fd_fromshell[1]);
4331
Bram Moolenaara5792f52005-11-23 21:25:05 +00004332# ifdef FEAT_GUI
4333 if (gui.in_use)
4334 {
4335 /* set up stderr for the child */
4336 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004337 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004338 }
4339# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 }
4341 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004342
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 /*
4344 * There is no type cast for the argv, because the type may be
4345 * different on different machines. This may cause a warning
4346 * message with strict compilers, don't worry about it.
4347 * Call _exit() instead of exit() to avoid closing the connection
4348 * to the X server (esp. with GTK, which uses atexit()).
4349 */
4350 execvp(argv[0], argv);
4351 _exit(EXEC_FAILED); /* exec failed, return failure code */
4352 }
4353 else /* parent */
4354 {
4355 /*
4356 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004357 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 */
4359 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004360 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361
4362 /*
4363 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004364 * This is also used to pipe stdin/stdout to/from the external
4365 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004367 if ((options & (SHELL_READ|SHELL_WRITE))
4368# ifdef FEAT_GUI
4369 || (gui.in_use && show_shell_mess)
4370# endif
4371 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004373# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004375# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004377# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4379 int ta_len = 0; /* valid bytes in ta_buf[] */
4380 int len;
4381 int p_more_save;
4382 int old_State;
4383 int c;
4384 int toshell_fd;
4385 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004386 garray_T ga;
4387 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004388# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4389 struct timeval start_tv;
4390# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391
Bram Moolenaardf177f62005-02-22 08:39:57 +00004392# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 if (pty_master_fd >= 0)
4394 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395 fromshell_fd = pty_master_fd;
4396 toshell_fd = dup(pty_master_fd);
4397 }
4398 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004399# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 {
4401 close(fd_toshell[0]);
4402 close(fd_fromshell[1]);
4403 toshell_fd = fd_toshell[1];
4404 fromshell_fd = fd_fromshell[0];
4405 }
4406
4407 /*
4408 * Write to the child if there are typed characters.
4409 * Read from the child if there are characters available.
4410 * Repeat the reading a few times if more characters are
4411 * available. Need to check for typed keys now and then, but
4412 * not too often (delays when no chars are available).
4413 * This loop is quit if no characters can be read from the pty
4414 * (WaitForChar detected special condition), or there are no
4415 * characters available and the child has exited.
4416 * Only check if the child has exited when there is no more
4417 * output. The child may exit before all the output has
4418 * been printed.
4419 *
4420 * Currently this busy loops!
4421 * This can probably dead-lock when the write blocks!
4422 */
4423 p_more_save = p_more;
4424 p_more = FALSE;
4425 old_State = State;
4426 State = EXTERNCMD; /* don't redraw at window resize */
4427
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004428 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004429 {
4430 /* Fork a process that will write the lines to the
4431 * external program. */
4432 if ((wpid = fork()) == -1)
4433 {
4434 MSG_PUTS(_("\nCannot fork\n"));
4435 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004436 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004437 {
4438 linenr_T lnum = curbuf->b_op_start.lnum;
4439 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004440 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004441 size_t l;
4442
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004443 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004444 for (;;)
4445 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004446 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004447 if (l == 0)
4448 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004449 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004450 /* NL -> NUL translation */
4451 len = write(toshell_fd, "", (size_t)1);
4452 else
4453 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004454 char_u *s = vim_strchr(lp + written, NL);
4455
Bram Moolenaar89d40322006-08-29 15:30:07 +00004456 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004457 s == NULL ? l
4458 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004459 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004460 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004461 {
4462 /* Finished a line, add a NL, unless this line
4463 * should not have one. */
4464 if (lnum != curbuf->b_op_end.lnum
4465 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004466 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004467 && (lnum !=
4468 curbuf->b_ml.ml_line_count
4469 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004470 ignored = write(toshell_fd, "\n",
4471 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004472 ++lnum;
4473 if (lnum > curbuf->b_op_end.lnum)
4474 {
4475 /* finished all the lines, close pipe */
4476 close(toshell_fd);
4477 toshell_fd = -1;
4478 break;
4479 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004480 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004481 written = 0;
4482 }
4483 else if (len > 0)
4484 written += len;
4485 }
4486 _exit(0);
4487 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004488 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004489 {
4490 close(toshell_fd);
4491 toshell_fd = -1;
4492 }
4493 }
4494
4495 if (options & SHELL_READ)
4496 ga_init2(&ga, 1, BUFLEN);
4497
4498 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004499# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4500 gettimeofday(&start_tv, NULL);
4501# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 for (;;)
4503 {
4504 /*
4505 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004506 * if there are any.
4507 * Don't do this if we are expanding wild cards (would eat
4508 * typeahead).
4509 * Don't do this when filtering and terminal is in cooked
4510 * mode, the shell command will handle the I/O. Avoids
4511 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004512 * Don't get characters when the child has already
4513 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004514 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004515 * while (noread_cnt > 4), avoids that ":r !ls" eats
4516 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 */
4518 len = 0;
4519 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004520 && ((options &
4521 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4522 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004523# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004524 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004525# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004526 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004527 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004528 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004530 if (ta_len == 0)
4531 {
4532 /* Get extra characters when we don't have any.
4533 * Reset the counter and timer. */
4534 noread_cnt = 0;
4535# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4536 gettimeofday(&start_tv, NULL);
4537# endif
4538 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4539 }
4540 if (ta_len > 0 || len > 0)
4541 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 /*
4543 * For pipes:
4544 * Check for CTRL-C: send interrupt signal to child.
4545 * Check for CTRL-D: EOF, close pipe to child.
4546 */
4547 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4548 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004549# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 /*
4551 * Send SIGINT to the child's group or all
4552 * processes in our group.
4553 */
4554 if (ta_buf[ta_len] == Ctrl_C
4555 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004556 {
4557# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004559# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004562 if (wpid > 0)
4563 kill(wpid, SIGINT);
4564 }
4565# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 if (pty_master_fd < 0 && toshell_fd >= 0
4567 && ta_buf[ta_len] == Ctrl_D)
4568 {
4569 close(toshell_fd);
4570 toshell_fd = -1;
4571 }
4572 }
4573
4574 /* replace K_BS by <BS> and K_DEL by <DEL> */
4575 for (i = ta_len; i < ta_len + len; ++i)
4576 {
4577 if (ta_buf[i] == CSI && len - i > 2)
4578 {
4579 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4580 if (c == K_DEL || c == K_KDEL || c == K_BS)
4581 {
4582 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4583 (size_t)(len - i - 2));
4584 if (c == K_DEL || c == K_KDEL)
4585 ta_buf[i] = DEL;
4586 else
4587 ta_buf[i] = Ctrl_H;
4588 len -= 2;
4589 }
4590 }
4591 else if (ta_buf[i] == '\r')
4592 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004593# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004595 i += (*mb_ptr2len_len)(ta_buf + i,
4596 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004597# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 }
4599
4600 /*
4601 * For pipes: echo the typed characters.
4602 * For a pty this does not seem to work.
4603 */
4604 if (pty_master_fd < 0)
4605 {
4606 for (i = ta_len; i < ta_len + len; ++i)
4607 {
4608 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4609 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004610# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 else if (has_mbyte)
4612 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004613 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614
4615 msg_outtrans_len(ta_buf + i, l);
4616 i += l - 1;
4617 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004618# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 else
4620 msg_outtrans_len(ta_buf + i, 1);
4621 }
4622 windgoto(msg_row, msg_col);
4623 out_flush();
4624 }
4625
4626 ta_len += len;
4627
4628 /*
4629 * Write the characters to the child, unless EOF has
4630 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004631 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004632 * When writing buffer lines, drop the typed
4633 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004635 if (options & SHELL_WRITE)
4636 ta_len = 0;
4637 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 {
4639 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4640 if (len > 0)
4641 {
4642 ta_len -= len;
4643 mch_memmove(ta_buf, ta_buf + len, ta_len);
4644 }
4645 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004646 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647 }
4648
Bram Moolenaardf177f62005-02-22 08:39:57 +00004649 if (got_int)
4650 {
4651 /* CTRL-C sends a signal to the child, we ignore it
4652 * ourselves */
4653# ifdef HAVE_SETSID
4654 kill(-pid, SIGINT);
4655# else
4656 kill(0, SIGINT);
4657# endif
4658 if (wpid > 0)
4659 kill(wpid, SIGINT);
4660 got_int = FALSE;
4661 }
4662
Bram Moolenaar071d4272004-06-13 20:20:40 +00004663 /*
4664 * Check if the child has any characters to be printed.
4665 * Read them and write them to our window. Repeat this as
4666 * long as there is something to do, avoid the 10ms wait
4667 * for mch_inchar(), or sending typeahead characters to
4668 * the external process.
4669 * TODO: This should handle escape sequences, compatible
4670 * to some terminal (vt52?).
4671 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004672 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4674 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004675 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004676# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004678# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004680# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 );
4682 if (len <= 0) /* end of file or error */
4683 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004684
4685 noread_cnt = 0;
4686 if (options & SHELL_READ)
4687 {
4688 /* Do NUL -> NL translation, append NL separated
4689 * lines to the current buffer. */
4690 for (i = 0; i < len; ++i)
4691 {
4692 if (buffer[i] == NL)
4693 append_ga_line(&ga);
4694 else if (buffer[i] == NUL)
4695 ga_append(&ga, NL);
4696 else
4697 ga_append(&ga, buffer[i]);
4698 }
4699 }
4700# ifdef FEAT_MBYTE
4701 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 {
4703 int l;
4704
Bram Moolenaardf177f62005-02-22 08:39:57 +00004705 len += buffer_off;
4706 buffer[len] = NUL;
4707
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708 /* Check if the last character in buffer[] is
4709 * incomplete, keep these bytes for the next
4710 * round. */
4711 for (p = buffer; p < buffer + len; p += l)
4712 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004713 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714 if (l == 0)
4715 l = 1; /* NUL byte? */
4716 else if (MB_BYTE2LEN(*p) != l)
4717 break;
4718 }
4719 if (p == buffer) /* no complete character */
4720 {
4721 /* avoid getting stuck at an illegal byte */
4722 if (len >= 12)
4723 ++p;
4724 else
4725 {
4726 buffer_off = len;
4727 continue;
4728 }
4729 }
4730 c = *p;
4731 *p = NUL;
4732 msg_puts(buffer);
4733 if (p < buffer + len)
4734 {
4735 *p = c;
4736 buffer_off = (buffer + len) - p;
4737 mch_memmove(buffer, p, buffer_off);
4738 continue;
4739 }
4740 buffer_off = 0;
4741 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004742# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 {
4745 buffer[len] = NUL;
4746 msg_puts(buffer);
4747 }
4748
4749 windgoto(msg_row, msg_col);
4750 cursor_on();
4751 out_flush();
4752 if (got_int)
4753 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004754
4755# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4756 {
4757 struct timeval now_tv;
4758 long msec;
4759
4760 /* Avoid that we keep looping here without
4761 * checking for a CTRL-C for a long time. Don't
4762 * break out too often to avoid losing typeahead. */
4763 gettimeofday(&now_tv, NULL);
4764 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4765 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4766 if (msec > 2000)
4767 {
4768 noread_cnt = 5;
4769 break;
4770 }
4771 }
4772# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 }
4774
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004775 /* If we already detected the child has finished break the
4776 * loop now. */
4777 if (wait_pid == pid)
4778 break;
4779
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780 /*
4781 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004782 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004784# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004785 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004786# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004788# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004789 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4790 || (wait_pid == pid && WIFEXITED(status)))
4791 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004792 /* Don't break the loop yet, try reading more
4793 * characters from "fromshell_fd" first. When using
4794 * pipes there might still be something to read and
4795 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004798 else
4799 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004800
Bram Moolenaar95a51352013-03-21 22:53:50 +01004801# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004802 /* Handle any X events, e.g. serving the clipboard. */
4803 clip_update();
4804# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 }
4806finished:
4807 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004808 if (options & SHELL_READ)
4809 {
4810 if (ga.ga_len > 0)
4811 {
4812 append_ga_line(&ga);
4813 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004814 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004815 }
4816 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004817 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004818 ga_clear(&ga);
4819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 /*
4822 * Give all typeahead that wasn't used back to ui_inchar().
4823 */
4824 if (ta_len)
4825 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 State = old_State;
4827 if (toshell_fd >= 0)
4828 close(toshell_fd);
4829 close(fromshell_fd);
4830 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004831# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004832 else
4833 {
4834 /*
4835 * Similar to the loop above, but only handle X events, no
4836 * I/O.
4837 */
4838 for (;;)
4839 {
4840 if (got_int)
4841 {
4842 /* CTRL-C sends a signal to the child, we ignore it
4843 * ourselves */
4844# ifdef HAVE_SETSID
4845 kill(-pid, SIGINT);
4846# else
4847 kill(0, SIGINT);
4848# endif
4849 got_int = FALSE;
4850 }
4851# ifdef __NeXT__
4852 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4853# else
4854 wait_pid = waitpid(pid, &status, WNOHANG);
4855# endif
4856 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4857 || (wait_pid == pid && WIFEXITED(status)))
4858 {
4859 wait_pid = pid;
4860 break;
4861 }
4862
4863 /* Handle any X events, e.g. serving the clipboard. */
4864 clip_update();
4865
4866 mch_delay(10L, TRUE);
4867 }
4868 }
4869# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870
4871 /*
4872 * Wait until our child has exited.
4873 * Ignore wait() returning pids of other children and returning
4874 * because of some signal like SIGWINCH.
4875 * Don't wait if wait_pid was already set above, indicating the
4876 * child already exited.
4877 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004878 if (wait_pid != pid)
4879 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880
Bram Moolenaar624891f2010-10-13 16:22:09 +02004881# ifdef FEAT_GUI
4882 /* Close slave side of pty. Only do this after the child has
4883 * exited, otherwise the child may hang when it tries to write on
4884 * the pty. */
4885 if (pty_master_fd >= 0)
4886 close(pty_slave_fd);
4887# endif
4888
Bram Moolenaardf177f62005-02-22 08:39:57 +00004889 /* Make sure the child that writes to the external program is
4890 * dead. */
4891 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004892 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004893 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004894 wait4pid(wpid, NULL);
4895 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004896
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 /*
4898 * Set to raw mode right now, otherwise a CTRL-C after
4899 * catch_signals() will kill Vim.
4900 */
4901 if (tmode == TMODE_RAW)
4902 settmode(TMODE_RAW);
4903 did_settmode = TRUE;
4904 set_signals();
4905
4906 if (WIFEXITED(status))
4907 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004908 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01004910 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 {
4912 if (retval == EXEC_FAILED)
4913 {
4914 MSG_PUTS(_("\nCannot execute shell "));
4915 msg_outtrans(p_sh);
4916 msg_putchar('\n');
4917 }
4918 else if (!(options & SHELL_SILENT))
4919 {
4920 MSG_PUTS(_("\nshell returned "));
4921 msg_outnum((long)retval);
4922 msg_putchar('\n');
4923 }
4924 }
4925 }
4926 else
4927 MSG_PUTS(_("\nCommand terminated\n"));
4928 }
4929 }
4930 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004931 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932
4933error:
4934 if (!did_settmode)
4935 if (tmode == TMODE_RAW)
4936 settmode(TMODE_RAW); /* set to raw mode */
4937# ifdef FEAT_TITLE
4938 resettitle();
4939# endif
4940 vim_free(newcmd);
4941
4942 return retval;
4943
4944#endif /* USE_SYSTEM */
4945}
4946
4947/*
4948 * Check for CTRL-C typed by reading all available characters.
4949 * In cooked mode we should get SIGINT, no need to check.
4950 */
4951 void
4952mch_breakcheck()
4953{
4954 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4955 fill_input_buf(FALSE);
4956}
4957
4958/*
4959 * Wait "msec" msec until a character is available from the keyboard or from
4960 * inbuf[]. msec == -1 will block forever.
4961 * When a GUI is being used, this will never get called -- webb
4962 */
4963 static int
4964WaitForChar(msec)
4965 long msec;
4966{
4967#ifdef FEAT_MOUSE_GPM
4968 int gpm_process_wanted;
4969#endif
4970#ifdef FEAT_XCLIPBOARD
4971 int rest;
4972#endif
4973 int avail;
4974
4975 if (input_available()) /* something in inbuf[] */
4976 return 1;
4977
4978#if defined(FEAT_MOUSE_DEC)
4979 /* May need to query the mouse position. */
4980 if (WantQueryMouse)
4981 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004982 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4984 }
4985#endif
4986
4987 /*
4988 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4989 * events. This is a bit complicated, because they might both be defined.
4990 */
4991#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4992# ifdef FEAT_XCLIPBOARD
4993 rest = 0;
4994 if (do_xterm_trace())
4995 rest = msec;
4996# endif
4997 do
4998 {
4999# ifdef FEAT_XCLIPBOARD
5000 if (rest != 0)
5001 {
5002 msec = XT_TRACE_DELAY;
5003 if (rest >= 0 && rest < XT_TRACE_DELAY)
5004 msec = rest;
5005 if (rest >= 0)
5006 rest -= msec;
5007 }
5008# endif
5009# ifdef FEAT_MOUSE_GPM
5010 gpm_process_wanted = 0;
5011 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5012# else
5013 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5014# endif
5015 if (!avail)
5016 {
5017 if (input_available())
5018 return 1;
5019# ifdef FEAT_XCLIPBOARD
5020 if (rest == 0 || !do_xterm_trace())
5021# endif
5022 break;
5023 }
5024 }
5025 while (FALSE
5026# ifdef FEAT_MOUSE_GPM
5027 || (gpm_process_wanted && mch_gpm_process() == 0)
5028# endif
5029# ifdef FEAT_XCLIPBOARD
5030 || (!avail && rest != 0)
5031# endif
5032 );
5033
5034#else
5035 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5036#endif
5037 return avail;
5038}
5039
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005040#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041/*
5042 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005043 * "msec" == 0 will check for characters once.
5044 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 * When a GUI is being used, this will not be used for input -- webb
5046 * Returns also, when a request from Sniff is waiting -- toni.
5047 * Or when a Linux GPM mouse event is waiting.
5048 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049#if defined(__BEOS__)
5050 int
5051#else
5052 static int
5053#endif
5054RealWaitForChar(fd, msec, check_for_gpm)
5055 int fd;
5056 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005057 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058{
5059 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005060#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005061 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005062#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005063#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005064 static int busy = FALSE;
5065
5066 /* May retry getting characters after an event was handled. */
5067# define MAY_LOOP
5068
5069# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5070 /* Remember at what time we started, so that we know how much longer we
5071 * should wait after being interrupted. */
5072# define USE_START_TV
5073 struct timeval start_tv;
5074
5075 if (msec > 0 && (
5076# ifdef FEAT_XCLIPBOARD
5077 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005078# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005079 ||
5080# endif
5081# endif
5082# ifdef USE_XSMP
5083 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005084# ifdef FEAT_MZSCHEME
5085 ||
5086# endif
5087# endif
5088# ifdef FEAT_MZSCHEME
5089 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090# endif
5091 ))
5092 gettimeofday(&start_tv, NULL);
5093# endif
5094
5095 /* Handle being called recursively. This may happen for the session
5096 * manager stuff, it may save the file, which does a breakcheck. */
5097 if (busy)
5098 return 0;
5099#endif
5100
5101#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005102 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103#endif
5104 {
5105#ifdef MAY_LOOP
5106 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005107# ifdef FEAT_MZSCHEME
5108 int mzquantum_used = FALSE;
5109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005110#endif
5111#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005112 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113 int nfd;
5114# ifdef FEAT_XCLIPBOARD
5115 int xterm_idx = -1;
5116# endif
5117# ifdef FEAT_MOUSE_GPM
5118 int gpm_idx = -1;
5119# endif
5120# ifdef USE_XSMP
5121 int xsmp_idx = -1;
5122# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005123# ifdef FEAT_NETBEANS_INTG
5124 int nb_idx = -1;
5125# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005126 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005128# ifdef FEAT_MZSCHEME
5129 mzvim_check_threads();
5130 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5131 {
5132 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5133 mzquantum_used = TRUE;
5134 }
5135# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136 fds[0].fd = fd;
5137 fds[0].events = POLLIN;
5138 nfd = 1;
5139
5140# ifdef FEAT_SNIFF
5141# define SNIFF_IDX 1
5142 if (want_sniff_request)
5143 {
5144 fds[SNIFF_IDX].fd = fd_from_sniff;
5145 fds[SNIFF_IDX].events = POLLIN;
5146 nfd++;
5147 }
5148# endif
5149# ifdef FEAT_XCLIPBOARD
5150 if (xterm_Shell != (Widget)0)
5151 {
5152 xterm_idx = nfd;
5153 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5154 fds[nfd].events = POLLIN;
5155 nfd++;
5156 }
5157# endif
5158# ifdef FEAT_MOUSE_GPM
5159 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5160 {
5161 gpm_idx = nfd;
5162 fds[nfd].fd = gpm_fd;
5163 fds[nfd].events = POLLIN;
5164 nfd++;
5165 }
5166# endif
5167# ifdef USE_XSMP
5168 if (xsmp_icefd != -1)
5169 {
5170 xsmp_idx = nfd;
5171 fds[nfd].fd = xsmp_icefd;
5172 fds[nfd].events = POLLIN;
5173 nfd++;
5174 }
5175# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005176#ifdef FEAT_NETBEANS_INTG
5177 if (nb_fd != -1)
5178 {
5179 nb_idx = nfd;
5180 fds[nfd].fd = nb_fd;
5181 fds[nfd].events = POLLIN;
5182 nfd++;
5183 }
5184#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005186 ret = poll(fds, nfd, towait);
5187# ifdef FEAT_MZSCHEME
5188 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005189 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005190 finished = FALSE;
5191# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192
5193# ifdef FEAT_SNIFF
5194 if (ret < 0)
5195 sniff_disconnect(1);
5196 else if (want_sniff_request)
5197 {
5198 if (fds[SNIFF_IDX].revents & POLLHUP)
5199 sniff_disconnect(1);
5200 if (fds[SNIFF_IDX].revents & POLLIN)
5201 sniff_request_waiting = 1;
5202 }
5203# endif
5204# ifdef FEAT_XCLIPBOARD
5205 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5206 {
5207 xterm_update(); /* Maybe we should hand out clipboard */
5208 if (--ret == 0 && !input_available())
5209 /* Try again */
5210 finished = FALSE;
5211 }
5212# endif
5213# ifdef FEAT_MOUSE_GPM
5214 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5215 {
5216 *check_for_gpm = 1;
5217 }
5218# endif
5219# ifdef USE_XSMP
5220 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5221 {
5222 if (fds[xsmp_idx].revents & POLLIN)
5223 {
5224 busy = TRUE;
5225 xsmp_handle_requests();
5226 busy = FALSE;
5227 }
5228 else if (fds[xsmp_idx].revents & POLLHUP)
5229 {
5230 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005231 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005232 xsmp_close();
5233 }
5234 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005235 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236 }
5237# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005238#ifdef FEAT_NETBEANS_INTG
5239 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5240 {
5241 netbeans_read();
5242 --ret;
5243 }
5244#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245
5246
5247#else /* HAVE_SELECT */
5248
5249 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005250 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251 fd_set rfds, efds;
5252 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005253 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005255# ifdef FEAT_MZSCHEME
5256 mzvim_check_threads();
5257 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5258 {
5259 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5260 mzquantum_used = TRUE;
5261 }
5262# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263# ifdef __EMX__
5264 /* don't check for incoming chars if not in raw mode, because select()
5265 * always returns TRUE then (in some version of emx.dll) */
5266 if (curr_tmode != TMODE_RAW)
5267 return 0;
5268# endif
5269
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005270 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005272 tv.tv_sec = towait / 1000;
5273 tv.tv_usec = (towait % 1000) * (1000000/1000);
5274 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005275 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005276 else
5277 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278
5279 /*
5280 * Select on ready for reading and exceptional condition (end of file).
5281 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005282select_eintr:
5283 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284 FD_ZERO(&efds);
5285 FD_SET(fd, &rfds);
5286# if !defined(__QNX__) && !defined(__CYGWIN32__)
5287 /* For QNX select() always returns 1 if this is set. Why? */
5288 FD_SET(fd, &efds);
5289# endif
5290 maxfd = fd;
5291
5292# ifdef FEAT_SNIFF
5293 if (want_sniff_request)
5294 {
5295 FD_SET(fd_from_sniff, &rfds);
5296 FD_SET(fd_from_sniff, &efds);
5297 if (maxfd < fd_from_sniff)
5298 maxfd = fd_from_sniff;
5299 }
5300# endif
5301# ifdef FEAT_XCLIPBOARD
5302 if (xterm_Shell != (Widget)0)
5303 {
5304 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5305 if (maxfd < ConnectionNumber(xterm_dpy))
5306 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005307
5308 /* An event may have already been read but not handled. In
5309 * particulary, XFlush may cause this. */
5310 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311 }
5312# endif
5313# ifdef FEAT_MOUSE_GPM
5314 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5315 {
5316 FD_SET(gpm_fd, &rfds);
5317 FD_SET(gpm_fd, &efds);
5318 if (maxfd < gpm_fd)
5319 maxfd = gpm_fd;
5320 }
5321# endif
5322# ifdef USE_XSMP
5323 if (xsmp_icefd != -1)
5324 {
5325 FD_SET(xsmp_icefd, &rfds);
5326 FD_SET(xsmp_icefd, &efds);
5327 if (maxfd < xsmp_icefd)
5328 maxfd = xsmp_icefd;
5329 }
5330# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005331# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005332 if (nb_fd != -1)
5333 {
5334 FD_SET(nb_fd, &rfds);
5335 if (maxfd < nb_fd)
5336 maxfd = nb_fd;
5337 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005338# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005340 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005341# ifdef EINTR
5342 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005343 {
5344 /* Check whether window has been resized, EINTR may be caused by
5345 * SIGWINCH. */
5346 if (do_resize)
5347 handle_resize();
5348
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005349 /* Interrupted by a signal, need to try again. We ignore msec
5350 * here, because we do want to check even after a timeout if
5351 * characters are available. Needed for reading output of an
5352 * external command after the process has finished. */
5353 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005354 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005355# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005356# ifdef __TANDEM
5357 if (ret == -1 && errno == ENOTSUP)
5358 {
5359 FD_ZERO(&rfds);
5360 FD_ZERO(&efds);
5361 ret = 0;
5362 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005363# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005364# ifdef FEAT_MZSCHEME
5365 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005366 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005367 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368# endif
5369
5370# ifdef FEAT_SNIFF
5371 if (ret < 0 )
5372 sniff_disconnect(1);
5373 else if (ret > 0 && want_sniff_request)
5374 {
5375 if (FD_ISSET(fd_from_sniff, &efds))
5376 sniff_disconnect(1);
5377 if (FD_ISSET(fd_from_sniff, &rfds))
5378 sniff_request_waiting = 1;
5379 }
5380# endif
5381# ifdef FEAT_XCLIPBOARD
5382 if (ret > 0 && xterm_Shell != (Widget)0
5383 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5384 {
5385 xterm_update(); /* Maybe we should hand out clipboard */
5386 /* continue looping when we only got the X event and the input
5387 * buffer is empty */
5388 if (--ret == 0 && !input_available())
5389 {
5390 /* Try again */
5391 finished = FALSE;
5392 }
5393 }
5394# endif
5395# ifdef FEAT_MOUSE_GPM
5396 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5397 {
5398 if (FD_ISSET(gpm_fd, &efds))
5399 gpm_close();
5400 else if (FD_ISSET(gpm_fd, &rfds))
5401 *check_for_gpm = 1;
5402 }
5403# endif
5404# ifdef USE_XSMP
5405 if (ret > 0 && xsmp_icefd != -1)
5406 {
5407 if (FD_ISSET(xsmp_icefd, &efds))
5408 {
5409 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005410 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 xsmp_close();
5412 if (--ret == 0)
5413 finished = FALSE; /* keep going if event was only one */
5414 }
5415 else if (FD_ISSET(xsmp_icefd, &rfds))
5416 {
5417 busy = TRUE;
5418 xsmp_handle_requests();
5419 busy = FALSE;
5420 if (--ret == 0)
5421 finished = FALSE; /* keep going if event was only one */
5422 }
5423 }
5424# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005425#ifdef FEAT_NETBEANS_INTG
5426 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5427 {
5428 netbeans_read();
5429 --ret;
5430 }
5431#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432
5433#endif /* HAVE_SELECT */
5434
5435#ifdef MAY_LOOP
5436 if (finished || msec == 0)
5437 break;
5438
5439 /* We're going to loop around again, find out for how long */
5440 if (msec > 0)
5441 {
5442# ifdef USE_START_TV
5443 struct timeval mtv;
5444
5445 /* Compute remaining wait time. */
5446 gettimeofday(&mtv, NULL);
5447 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5448 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5449# else
5450 /* Guess we got interrupted halfway. */
5451 msec = msec / 2;
5452# endif
5453 if (msec <= 0)
5454 break; /* waited long enough */
5455 }
5456#endif
5457 }
5458
5459 return (ret > 0);
5460}
5461
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005464 * Expand a path into all matching files and/or directories. Handles "*",
5465 * "?", "[a-z]", "**", etc.
5466 * "path" has backslashes before chars that are not to be expanded.
5467 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 */
5469 int
5470mch_expandpath(gap, path, flags)
5471 garray_T *gap;
5472 char_u *path;
5473 int flags; /* EW_* flags */
5474{
Bram Moolenaar02743632005-07-25 20:42:36 +00005475 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476}
5477#endif
5478
5479/*
5480 * mch_expand_wildcards() - this code does wild-card pattern matching using
5481 * the shell
5482 *
5483 * return OK for success, FAIL for error (you may lose some memory) and put
5484 * an error message in *file.
5485 *
5486 * num_pat is number of input patterns
5487 * pat is array of pointers to input patterns
5488 * num_file is pointer to number of matched file names
5489 * file is pointer to array of pointers to matched file names
5490 */
5491
5492#ifndef SEEK_SET
5493# define SEEK_SET 0
5494#endif
5495#ifndef SEEK_END
5496# define SEEK_END 2
5497#endif
5498
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005499#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005500
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501 int
5502mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5503 int num_pat;
5504 char_u **pat;
5505 int *num_file;
5506 char_u ***file;
5507 int flags; /* EW_* flags */
5508{
5509 int i;
5510 size_t len;
5511 char_u *p;
5512 int dir;
5513#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005514 /*
5515 * This is the OS/2 implementation.
5516 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517# define EXPL_ALLOC_INC 16
5518 char_u **expl_files;
5519 size_t files_alloced, files_free;
5520 char_u *buf;
5521 int has_wildcard;
5522
5523 *num_file = 0; /* default: no files found */
5524 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5525 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5526 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5527 if (*file == NULL)
5528 return FAIL;
5529
5530 for (; num_pat > 0; num_pat--, pat++)
5531 {
5532 expl_files = NULL;
5533 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5534 /* expand environment var or home dir */
5535 buf = expand_env_save(*pat);
5536 else
5537 buf = vim_strsave(*pat);
5538 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005539 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 if (has_wildcard) /* yes, so expand them */
5541 expl_files = (char_u **)_fnexplode(buf);
5542
5543 /*
5544 * return value of buf if no wildcards left,
5545 * OR if no match AND EW_NOTFOUND is set.
5546 */
5547 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5548 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5549 { /* simply save the current contents of *buf */
5550 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5551 if (expl_files != NULL)
5552 {
5553 expl_files[0] = vim_strsave(buf);
5554 expl_files[1] = NULL;
5555 }
5556 }
5557 vim_free(buf);
5558
5559 /*
5560 * Count number of names resulting from expansion,
5561 * At the same time add a backslash to the end of names that happen to
5562 * be directories, and replace slashes with backslashes.
5563 */
5564 if (expl_files)
5565 {
5566 for (i = 0; (p = expl_files[i]) != NULL; i++)
5567 {
5568 dir = mch_isdir(p);
5569 /* If we don't want dirs and this is one, skip it */
5570 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5571 continue;
5572
Bram Moolenaara2031822006-03-07 22:29:51 +00005573 /* Skip files that are not executable if we check for that. */
5574 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5575 continue;
5576
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 if (--files_free == 0)
5578 {
5579 /* need more room in table of pointers */
5580 files_alloced += EXPL_ALLOC_INC;
5581 *file = (char_u **)vim_realloc(*file,
5582 sizeof(char_u **) * files_alloced);
5583 if (*file == NULL)
5584 {
5585 EMSG(_(e_outofmem));
5586 *num_file = 0;
5587 return FAIL;
5588 }
5589 files_free = EXPL_ALLOC_INC;
5590 }
5591 slash_adjust(p);
5592 if (dir)
5593 {
5594 /* For a directory we add a '/', unless it's already
5595 * there. */
5596 len = STRLEN(p);
5597 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5598 {
5599 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005600 if (!after_pathsep((*file)[*num_file],
5601 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 {
5603 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005604 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 }
5606 }
5607 }
5608 else
5609 {
5610 (*file)[*num_file] = vim_strsave(p);
5611 }
5612
5613 /*
5614 * Error message already given by either alloc or vim_strsave.
5615 * Should return FAIL, but returning OK works also.
5616 */
5617 if ((*file)[*num_file] == NULL)
5618 break;
5619 (*num_file)++;
5620 }
5621 _fnexplodefree((char **)expl_files);
5622 }
5623 }
5624 return OK;
5625
5626#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005627 /*
5628 * This is the non-OS/2 implementation (really Unix).
5629 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630 int j;
5631 char_u *tempname;
5632 char_u *command;
5633 FILE *fd;
5634 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005635#define STYLE_ECHO 0 /* use "echo", the default */
5636#define STYLE_GLOB 1 /* use "glob", for csh */
5637#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5638#define STYLE_PRINT 3 /* use "print -N", for zsh */
5639#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5640 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 int shell_style = STYLE_ECHO;
5642 int check_spaces;
5643 static int did_find_nul = FALSE;
5644 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005645 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005646 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647
5648 *num_file = 0; /* default: no files found */
5649 *file = NULL;
5650
5651 /*
5652 * If there are no wildcards, just copy the names to allocated memory.
5653 * Saves a lot of time, because we don't have to start a new shell.
5654 */
5655 if (!have_wildcard(num_pat, pat))
5656 return save_patterns(num_pat, pat, num_file, file);
5657
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005658# ifdef HAVE_SANDBOX
5659 /* Don't allow any shell command in the sandbox. */
5660 if (sandbox != 0 && check_secure())
5661 return FAIL;
5662# endif
5663
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 /*
5665 * Don't allow the use of backticks in secure and restricted mode.
5666 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005667 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 for (i = 0; i < num_pat; ++i)
5669 if (vim_strchr(pat[i], '`') != NULL
5670 && (check_restricted() || check_secure()))
5671 return FAIL;
5672
5673 /*
5674 * get a name for the temp file
5675 */
5676 if ((tempname = vim_tempname('o')) == NULL)
5677 {
5678 EMSG(_(e_notmp));
5679 return FAIL;
5680 }
5681
5682 /*
5683 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005684 * file.
5685 * STYLE_BT: NL separated
5686 * If expanding `cmd` execute it directly.
5687 * STYLE_GLOB: NUL separated
5688 * If we use *csh, "glob" will work better than "echo".
5689 * STYLE_PRINT: NL or NUL separated
5690 * If we use *zsh, "print -N" will work better than "glob".
5691 * STYLE_VIMGLOB: NL separated
5692 * If we use *sh*, we define "vimglob()".
5693 * STYLE_ECHO: space separated.
5694 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 */
5696 if (num_pat == 1 && *pat[0] == '`'
5697 && (len = STRLEN(pat[0])) > 2
5698 && *(pat[0] + len - 1) == '`')
5699 shell_style = STYLE_BT;
5700 else if ((len = STRLEN(p_sh)) >= 3)
5701 {
5702 if (STRCMP(p_sh + len - 3, "csh") == 0)
5703 shell_style = STYLE_GLOB;
5704 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5705 shell_style = STYLE_PRINT;
5706 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005707 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5708 "sh") != NULL)
5709 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710
Bram Moolenaarc7247912008-01-13 12:54:11 +00005711 /* Compute the length of the command. We need 2 extra bytes: for the
5712 * optional '&' and for the NUL.
5713 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005715 if (shell_style == STYLE_VIMGLOB)
5716 len += STRLEN(sh_vimglob_func);
5717
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005718 for (i = 0; i < num_pat; ++i)
5719 {
5720 /* Count the length of the patterns in the same way as they are put in
5721 * "command" below. */
5722#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005724#else
5725 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005726 for (j = 0; pat[i][j] != NUL; ++j)
5727 {
5728 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5729 ++len; /* may add a backslash */
5730 ++len;
5731 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005732#endif
5733 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 command = alloc(len);
5735 if (command == NULL)
5736 {
5737 /* out of memory */
5738 vim_free(tempname);
5739 return FAIL;
5740 }
5741
5742 /*
5743 * Build the shell command:
5744 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5745 * recognizes this).
5746 * - Add the shell command to print the expanded names.
5747 * - Add the temp file name.
5748 * - Add the file name patterns.
5749 */
5750 if (shell_style == STYLE_BT)
5751 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005752 /* change `command; command& ` to (command; command ) */
5753 STRCPY(command, "(");
5754 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005756 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757 while (p > command && vim_iswhite(*p))
5758 --p;
5759 if (*p == '&') /* remove trailing '&' */
5760 {
5761 ampersent = TRUE;
5762 *p = ' ';
5763 }
5764 STRCAT(command, ">");
5765 }
5766 else
5767 {
5768 if (flags & EW_NOTFOUND)
5769 STRCPY(command, "set nonomatch; ");
5770 else
5771 STRCPY(command, "unset nonomatch; ");
5772 if (shell_style == STYLE_GLOB)
5773 STRCAT(command, "glob >");
5774 else if (shell_style == STYLE_PRINT)
5775 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005776 else if (shell_style == STYLE_VIMGLOB)
5777 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778 else
5779 STRCAT(command, "echo >");
5780 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005781
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005783
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 if (shell_style != STYLE_BT)
5785 for (i = 0; i < num_pat; ++i)
5786 {
5787 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005788 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005789 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790#ifdef USE_SYSTEM
5791 STRCAT(command, " \"");
5792 STRCAT(command, pat[i]);
5793 STRCAT(command, "\"");
5794#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005795 int intick = FALSE;
5796
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 p = command + STRLEN(command);
5798 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005799 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005800 {
5801 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005802 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005803 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5804 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005805 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005806 * backslash inside backticks, before a special character
5807 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005808 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005809 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5810 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005811 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005812 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005813 }
5814 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005815 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005816 /* Put a backslash before a special character, but not
5817 * when inside ``. */
5818 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005819
5820 /* Copy one character. */
5821 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005822 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 *p = NUL;
5824#endif
5825 }
5826 if (flags & EW_SILENT)
5827 show_shell_mess = FALSE;
5828 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005829 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005830
5831 /*
5832 * Using zsh -G: If a pattern has no matches, it is just deleted from
5833 * the argument list, otherwise zsh gives an error message and doesn't
5834 * expand any other pattern.
5835 */
5836 if (shell_style == STYLE_PRINT)
5837 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5838
5839 /*
5840 * If we use -f then shell variables set in .cshrc won't get expanded.
5841 * vi can do it, so we will too, but it is only necessary if there is a "$"
5842 * in one of the patterns, otherwise we can still use the fast option.
5843 */
5844 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5845 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5846
5847 /*
5848 * execute the shell command
5849 */
5850 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5851
5852 /* When running in the background, give it some time to create the temp
5853 * file, but don't wait for it to finish. */
5854 if (ampersent)
5855 mch_delay(10L, TRUE);
5856
5857 extra_shell_arg = NULL; /* cleanup */
5858 show_shell_mess = TRUE;
5859 vim_free(command);
5860
Bram Moolenaarc7247912008-01-13 12:54:11 +00005861 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 {
5863 mch_remove(tempname);
5864 vim_free(tempname);
5865 /*
5866 * With interactive completion, the error message is not printed.
5867 * However with USE_SYSTEM, I don't know how to turn off error messages
5868 * from the shell, so screen may still get messed up -- webb.
5869 */
5870#ifndef USE_SYSTEM
5871 if (!(flags & EW_SILENT))
5872#endif
5873 {
5874 redraw_later_clear(); /* probably messed up screen */
5875 msg_putchar('\n'); /* clear bottom line quickly */
5876 cmdline_row = Rows - 1; /* continue on last line */
5877#ifdef USE_SYSTEM
5878 if (!(flags & EW_SILENT))
5879#endif
5880 {
5881 MSG(_(e_wildexpand));
5882 msg_start(); /* don't overwrite this message */
5883 }
5884 }
5885 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5886 * EW_NOTFOUND is given */
5887 if (shell_style == STYLE_BT)
5888 return FAIL;
5889 goto notfound;
5890 }
5891
5892 /*
5893 * read the names from the file into memory
5894 */
5895 fd = fopen((char *)tempname, READBIN);
5896 if (fd == NULL)
5897 {
5898 /* Something went wrong, perhaps a file name with a special char. */
5899 if (!(flags & EW_SILENT))
5900 {
5901 MSG(_(e_wildexpand));
5902 msg_start(); /* don't overwrite this message */
5903 }
5904 vim_free(tempname);
5905 goto notfound;
5906 }
5907 fseek(fd, 0L, SEEK_END);
5908 len = ftell(fd); /* get size of temp file */
5909 fseek(fd, 0L, SEEK_SET);
5910 buffer = alloc(len + 1);
5911 if (buffer == NULL)
5912 {
5913 /* out of memory */
5914 mch_remove(tempname);
5915 vim_free(tempname);
5916 fclose(fd);
5917 return FAIL;
5918 }
5919 i = fread((char *)buffer, 1, len, fd);
5920 fclose(fd);
5921 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005922 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923 {
5924 /* unexpected read error */
5925 EMSG2(_(e_notread), tempname);
5926 vim_free(tempname);
5927 vim_free(buffer);
5928 return FAIL;
5929 }
5930 vim_free(tempname);
5931
Bram Moolenaarc7247912008-01-13 12:54:11 +00005932# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5934 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02005935 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5937 *p++ = buffer[i];
5938 len = p - buffer;
5939# endif
5940
5941
5942 /* file names are separated with Space */
5943 if (shell_style == STYLE_ECHO)
5944 {
5945 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5946 p = buffer;
5947 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5948 {
5949 while (*p != ' ' && *p != '\n')
5950 ++p;
5951 p = skipwhite(p); /* skip to next entry */
5952 }
5953 }
5954 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005955 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 {
5957 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5958 p = buffer;
5959 for (i = 0; *p != NUL; ++i) /* count number of entries */
5960 {
5961 while (*p != '\n' && *p != NUL)
5962 ++p;
5963 if (*p != NUL)
5964 ++p;
5965 p = skipwhite(p); /* skip leading white space */
5966 }
5967 }
5968 /* file names are separated with NUL */
5969 else
5970 {
5971 /*
5972 * Some versions of zsh use spaces instead of NULs to separate
5973 * results. Only do this when there is no NUL before the end of the
5974 * buffer, otherwise we would never be able to use file names with
5975 * embedded spaces when zsh does use NULs.
5976 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5977 * don't check for spaces again.
5978 */
5979 check_spaces = FALSE;
5980 if (shell_style == STYLE_PRINT && !did_find_nul)
5981 {
5982 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005983 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01005984 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985 did_find_nul = TRUE;
5986 else
5987 check_spaces = TRUE;
5988 }
5989
5990 /*
5991 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5992 * already is one, for STYLE_GLOB it needs to be added.
5993 */
5994 if (len && buffer[len - 1] == NUL)
5995 --len;
5996 else
5997 buffer[len] = NUL;
5998 i = 0;
5999 for (p = buffer; p < buffer + len; ++p)
6000 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6001 {
6002 ++i;
6003 *p = NUL;
6004 }
6005 if (len)
6006 ++i; /* count last entry */
6007 }
6008 if (i == 0)
6009 {
6010 /*
6011 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6012 * /bin/sh will happily expand it to nothing rather than returning an
6013 * error; and hey, it's good to check anyway -- webb.
6014 */
6015 vim_free(buffer);
6016 goto notfound;
6017 }
6018 *num_file = i;
6019 *file = (char_u **)alloc(sizeof(char_u *) * i);
6020 if (*file == NULL)
6021 {
6022 /* out of memory */
6023 vim_free(buffer);
6024 return FAIL;
6025 }
6026
6027 /*
6028 * Isolate the individual file names.
6029 */
6030 p = buffer;
6031 for (i = 0; i < *num_file; ++i)
6032 {
6033 (*file)[i] = p;
6034 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006035 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6036 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006038 while (!(shell_style == STYLE_ECHO && *p == ' ')
6039 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 ++p;
6041 if (p == buffer + len) /* last entry */
6042 *p = NUL;
6043 else
6044 {
6045 *p++ = NUL;
6046 p = skipwhite(p); /* skip to next entry */
6047 }
6048 }
6049 else /* NUL separates */
6050 {
6051 while (*p && p < buffer + len) /* skip entry */
6052 ++p;
6053 ++p; /* skip NUL */
6054 }
6055 }
6056
6057 /*
6058 * Move the file names to allocated memory.
6059 */
6060 for (j = 0, i = 0; i < *num_file; ++i)
6061 {
6062 /* Require the files to exist. Helps when using /bin/sh */
6063 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6064 continue;
6065
6066 /* check if this entry should be included */
6067 dir = (mch_isdir((*file)[i]));
6068 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6069 continue;
6070
Bram Moolenaara2031822006-03-07 22:29:51 +00006071 /* Skip files that are not executable if we check for that. */
6072 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
6073 continue;
6074
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6076 if (p)
6077 {
6078 STRCPY(p, (*file)[i]);
6079 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006080 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 (*file)[j++] = p;
6082 }
6083 }
6084 vim_free(buffer);
6085 *num_file = j;
6086
6087 if (*num_file == 0) /* rejected all entries */
6088 {
6089 vim_free(*file);
6090 *file = NULL;
6091 goto notfound;
6092 }
6093
6094 return OK;
6095
6096notfound:
6097 if (flags & EW_NOTFOUND)
6098 return save_patterns(num_pat, pat, num_file, file);
6099 return FAIL;
6100
6101#endif /* __EMX__ */
6102}
6103
6104#endif /* VMS */
6105
6106#ifndef __EMX__
6107 static int
6108save_patterns(num_pat, pat, num_file, file)
6109 int num_pat;
6110 char_u **pat;
6111 int *num_file;
6112 char_u ***file;
6113{
6114 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006115 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116
6117 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6118 if (*file == NULL)
6119 return FAIL;
6120 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006121 {
6122 s = vim_strsave(pat[i]);
6123 if (s != NULL)
6124 /* Be compatible with expand_filename(): halve the number of
6125 * backslashes. */
6126 backslash_halve(s);
6127 (*file)[i] = s;
6128 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 *num_file = num_pat;
6130 return OK;
6131}
6132#endif
6133
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134/*
6135 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6136 * expand.
6137 */
6138 int
6139mch_has_exp_wildcard(p)
6140 char_u *p;
6141{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006142 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 {
6144#ifndef OS2
6145 if (*p == '\\' && p[1] != NUL)
6146 ++p;
6147 else
6148#endif
6149 if (vim_strchr((char_u *)
6150#ifdef VMS
6151 "*?%"
6152#else
6153# ifdef OS2
6154 "*?"
6155# else
6156 "*?[{'"
6157# endif
6158#endif
6159 , *p) != NULL)
6160 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 }
6162 return FALSE;
6163}
6164
6165/*
6166 * Return TRUE if the string "p" contains a wildcard.
6167 * Don't recognize '~' at the end as a wildcard.
6168 */
6169 int
6170mch_has_wildcard(p)
6171 char_u *p;
6172{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006173 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 {
6175#ifndef OS2
6176 if (*p == '\\' && p[1] != NUL)
6177 ++p;
6178 else
6179#endif
6180 if (vim_strchr((char_u *)
6181#ifdef VMS
6182 "*?%$"
6183#else
6184# ifdef OS2
6185# ifdef VIM_BACKTICK
6186 "*?$`"
6187# else
6188 "*?$"
6189# endif
6190# else
6191 "*?[{`'$"
6192# endif
6193#endif
6194 , *p) != NULL
6195 || (*p == '~' && p[1] != NUL))
6196 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 }
6198 return FALSE;
6199}
6200
6201#ifndef __EMX__
6202 static int
6203have_wildcard(num, file)
6204 int num;
6205 char_u **file;
6206{
6207 int i;
6208
6209 for (i = 0; i < num; i++)
6210 if (mch_has_wildcard(file[i]))
6211 return 1;
6212 return 0;
6213}
6214
6215 static int
6216have_dollars(num, file)
6217 int num;
6218 char_u **file;
6219{
6220 int i;
6221
6222 for (i = 0; i < num; i++)
6223 if (vim_strchr(file[i], '$') != NULL)
6224 return TRUE;
6225 return FALSE;
6226}
6227#endif /* ifndef __EMX__ */
6228
6229#ifndef HAVE_RENAME
6230/*
6231 * Scaled-down version of rename(), which is missing in Xenix.
6232 * This version can only move regular files and will fail if the
6233 * destination exists.
6234 */
6235 int
6236mch_rename(src, dest)
6237 const char *src, *dest;
6238{
6239 struct stat st;
6240
6241 if (stat(dest, &st) >= 0) /* fail if destination exists */
6242 return -1;
6243 if (link(src, dest) != 0) /* link file to new name */
6244 return -1;
6245 if (mch_remove(src) == 0) /* delete link to old name */
6246 return 0;
6247 return -1;
6248}
6249#endif /* !HAVE_RENAME */
6250
6251#ifdef FEAT_MOUSE_GPM
6252/*
6253 * Initializes connection with gpm (if it isn't already opened)
6254 * Return 1 if succeeded (or connection already opened), 0 if failed
6255 */
6256 static int
6257gpm_open()
6258{
6259 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6260
6261 if (!gpm_flag)
6262 {
6263 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6264 gpm_connect.defaultMask = ~GPM_HARD;
6265 /* Default handling for mouse move*/
6266 gpm_connect.minMod = 0; /* Handle any modifier keys */
6267 gpm_connect.maxMod = 0xffff;
6268 if (Gpm_Open(&gpm_connect, 0) > 0)
6269 {
6270 /* gpm library tries to handling TSTP causes
6271 * problems. Anyways, we close connection to Gpm whenever
6272 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006273 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006275# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006277# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 return 1; /* succeed */
6279 }
6280 if (gpm_fd == -2)
6281 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6282 return 0;
6283 }
6284 return 1; /* already open */
6285}
6286
6287/*
6288 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 */
6290 static void
6291gpm_close()
6292{
6293 if (gpm_flag && gpm_fd >= 0) /* if Open */
6294 Gpm_Close();
6295}
6296
6297/* Reads gpm event and adds special keys to input buf. Returns length of
6298 * generated key sequence.
6299 * This function is made after gui_send_mouse_event
6300 */
6301 static int
6302mch_gpm_process()
6303{
6304 int button;
6305 static Gpm_Event gpm_event;
6306 char_u string[6];
6307 int_u vim_modifiers;
6308 int row,col;
6309 unsigned char buttons_mask;
6310 unsigned char gpm_modifiers;
6311 static unsigned char old_buttons = 0;
6312
6313 Gpm_GetEvent(&gpm_event);
6314
6315#ifdef FEAT_GUI
6316 /* Don't put events in the input queue now. */
6317 if (hold_gui_events)
6318 return 0;
6319#endif
6320
6321 row = gpm_event.y - 1;
6322 col = gpm_event.x - 1;
6323
6324 string[0] = ESC; /* Our termcode */
6325 string[1] = 'M';
6326 string[2] = 'G';
6327 switch (GPM_BARE_EVENTS(gpm_event.type))
6328 {
6329 case GPM_DRAG:
6330 string[3] = MOUSE_DRAG;
6331 break;
6332 case GPM_DOWN:
6333 buttons_mask = gpm_event.buttons & ~old_buttons;
6334 old_buttons = gpm_event.buttons;
6335 switch (buttons_mask)
6336 {
6337 case GPM_B_LEFT:
6338 button = MOUSE_LEFT;
6339 break;
6340 case GPM_B_MIDDLE:
6341 button = MOUSE_MIDDLE;
6342 break;
6343 case GPM_B_RIGHT:
6344 button = MOUSE_RIGHT;
6345 break;
6346 default:
6347 return 0;
6348 /*Don't know what to do. Can more than one button be
6349 * reported in one event? */
6350 }
6351 string[3] = (char_u)(button | 0x20);
6352 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6353 break;
6354 case GPM_UP:
6355 string[3] = MOUSE_RELEASE;
6356 old_buttons &= ~gpm_event.buttons;
6357 break;
6358 default:
6359 return 0;
6360 }
6361 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6362 gpm_modifiers = gpm_event.modifiers;
6363 vim_modifiers = 0x0;
6364 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6365 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6366 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6367 */
6368 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6369 vim_modifiers |= MOUSE_SHIFT;
6370
6371 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6372 vim_modifiers |= MOUSE_CTRL;
6373 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6374 vim_modifiers |= MOUSE_ALT;
6375 string[3] |= vim_modifiers;
6376 string[4] = (char_u)(col + ' ' + 1);
6377 string[5] = (char_u)(row + ' ' + 1);
6378 add_to_input_buf(string, 6);
6379 return 6;
6380}
6381#endif /* FEAT_MOUSE_GPM */
6382
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006383#ifdef FEAT_SYSMOUSE
6384/*
6385 * Initialize connection with sysmouse.
6386 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6387 * output, any sysmouse output than will be processed via sig_sysmouse().
6388 * Return OK if succeeded, FAIL if failed.
6389 */
6390 static int
6391sysmouse_open()
6392{
6393 struct mouse_info mouse;
6394
6395 mouse.operation = MOUSE_MODE;
6396 mouse.u.mode.mode = 0;
6397 mouse.u.mode.signal = SIGUSR2;
6398 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6399 {
6400 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6401 mouse.operation = MOUSE_SHOW;
6402 ioctl(1, CONS_MOUSECTL, &mouse);
6403 return OK;
6404 }
6405 return FAIL;
6406}
6407
6408/*
6409 * Stop processing SIGUSR2 signals, and also make sure that
6410 * virtual console do not send us any sysmouse related signal.
6411 */
6412 static void
6413sysmouse_close()
6414{
6415 struct mouse_info mouse;
6416
6417 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6418 mouse.operation = MOUSE_MODE;
6419 mouse.u.mode.mode = 0;
6420 mouse.u.mode.signal = 0;
6421 ioctl(1, CONS_MOUSECTL, &mouse);
6422}
6423
6424/*
6425 * Gets info from sysmouse and adds special keys to input buf.
6426 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006427 static RETSIGTYPE
6428sig_sysmouse SIGDEFARG(sigarg)
6429{
6430 struct mouse_info mouse;
6431 struct video_info video;
6432 char_u string[6];
6433 int row, col;
6434 int button;
6435 int buttons;
6436 static int oldbuttons = 0;
6437
6438#ifdef FEAT_GUI
6439 /* Don't put events in the input queue now. */
6440 if (hold_gui_events)
6441 return;
6442#endif
6443
6444 mouse.operation = MOUSE_GETINFO;
6445 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6446 && ioctl(1, FBIO_MODEINFO, &video) != -1
6447 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6448 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6449 {
6450 row = mouse.u.data.y / video.vi_cheight;
6451 col = mouse.u.data.x / video.vi_cwidth;
6452 buttons = mouse.u.data.buttons;
6453 string[0] = ESC; /* Our termcode */
6454 string[1] = 'M';
6455 string[2] = 'S';
6456 if (oldbuttons == buttons && buttons != 0)
6457 {
6458 button = MOUSE_DRAG;
6459 }
6460 else
6461 {
6462 switch (buttons)
6463 {
6464 case 0:
6465 button = MOUSE_RELEASE;
6466 break;
6467 case 1:
6468 button = MOUSE_LEFT;
6469 break;
6470 case 2:
6471 button = MOUSE_MIDDLE;
6472 break;
6473 case 4:
6474 button = MOUSE_RIGHT;
6475 break;
6476 default:
6477 return;
6478 }
6479 oldbuttons = buttons;
6480 }
6481 string[3] = (char_u)(button);
6482 string[4] = (char_u)(col + ' ' + 1);
6483 string[5] = (char_u)(row + ' ' + 1);
6484 add_to_input_buf(string, 6);
6485 }
6486 return;
6487}
6488#endif /* FEAT_SYSMOUSE */
6489
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490#if defined(FEAT_LIBCALL) || defined(PROTO)
6491typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6492typedef char_u * (*INTPROCSTR)__ARGS((int));
6493typedef int (*STRPROCINT)__ARGS((char_u *));
6494typedef int (*INTPROCINT)__ARGS((int));
6495
6496/*
6497 * Call a DLL routine which takes either a string or int param
6498 * and returns an allocated string.
6499 */
6500 int
6501mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6502 char_u *libname;
6503 char_u *funcname;
6504 char_u *argstring; /* NULL when using a argint */
6505 int argint;
6506 char_u **string_result;/* NULL when using number_result */
6507 int *number_result;
6508{
6509# if defined(USE_DLOPEN)
6510 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006511 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512# else
6513 shl_t hinstLib;
6514# endif
6515 STRPROCSTR ProcAdd;
6516 INTPROCSTR ProcAddI;
6517 char_u *retval_str = NULL;
6518 int retval_int = 0;
6519 int success = FALSE;
6520
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006521 /*
6522 * Get a handle to the DLL module.
6523 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006525 /* First clear any error, it's not cleared by the dlopen() call. */
6526 (void)dlerror();
6527
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 hinstLib = dlopen((char *)libname, RTLD_LAZY
6529# ifdef RTLD_LOCAL
6530 | RTLD_LOCAL
6531# endif
6532 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006533 if (hinstLib == NULL)
6534 {
6535 /* "dlerr" must be used before dlclose() */
6536 dlerr = (char *)dlerror();
6537 if (dlerr != NULL)
6538 EMSG2(_("dlerror = \"%s\""), dlerr);
6539 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540# else
6541 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6542# endif
6543
6544 /* If the handle is valid, try to get the function address. */
6545 if (hinstLib != NULL)
6546 {
6547# ifdef HAVE_SETJMP_H
6548 /*
6549 * Catch a crash when calling the library function. For example when
6550 * using a number where a string pointer is expected.
6551 */
6552 mch_startjmp();
6553 if (SETJMP(lc_jump_env) != 0)
6554 {
6555 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006556# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006557 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 mch_didjmp();
6560 }
6561 else
6562# endif
6563 {
6564 retval_str = NULL;
6565 retval_int = 0;
6566
6567 if (argstring != NULL)
6568 {
6569# if defined(USE_DLOPEN)
6570 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006571 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572# else
6573 if (shl_findsym(&hinstLib, (const char *)funcname,
6574 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6575 ProcAdd = NULL;
6576# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006577 if ((success = (ProcAdd != NULL
6578# if defined(USE_DLOPEN)
6579 && dlerr == NULL
6580# endif
6581 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 {
6583 if (string_result == NULL)
6584 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6585 else
6586 retval_str = (ProcAdd)(argstring);
6587 }
6588 }
6589 else
6590 {
6591# if defined(USE_DLOPEN)
6592 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006593 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594# else
6595 if (shl_findsym(&hinstLib, (const char *)funcname,
6596 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6597 ProcAddI = NULL;
6598# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006599 if ((success = (ProcAddI != NULL
6600# if defined(USE_DLOPEN)
6601 && dlerr == NULL
6602# endif
6603 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 {
6605 if (string_result == NULL)
6606 retval_int = ((INTPROCINT)ProcAddI)(argint);
6607 else
6608 retval_str = (ProcAddI)(argint);
6609 }
6610 }
6611
6612 /* Save the string before we free the library. */
6613 /* Assume that a "1" or "-1" result is an illegal pointer. */
6614 if (string_result == NULL)
6615 *number_result = retval_int;
6616 else if (retval_str != NULL
6617 && retval_str != (char_u *)1
6618 && retval_str != (char_u *)-1)
6619 *string_result = vim_strsave(retval_str);
6620 }
6621
6622# ifdef HAVE_SETJMP_H
6623 mch_endjmp();
6624# ifdef SIGHASARG
6625 if (lc_signal != 0)
6626 {
6627 int i;
6628
6629 /* try to find the name of this signal */
6630 for (i = 0; signal_info[i].sig != -1; i++)
6631 if (lc_signal == signal_info[i].sig)
6632 break;
6633 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6634 }
6635# endif
6636# endif
6637
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006639 /* "dlerr" must be used before dlclose() */
6640 if (dlerr != NULL)
6641 EMSG2(_("dlerror = \"%s\""), dlerr);
6642
6643 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 (void)dlclose(hinstLib);
6645# else
6646 (void)shl_unload(hinstLib);
6647# endif
6648 }
6649
6650 if (!success)
6651 {
6652 EMSG2(_(e_libcall), funcname);
6653 return FAIL;
6654 }
6655
6656 return OK;
6657}
6658#endif
6659
6660#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6661static int xterm_trace = -1; /* default: disabled */
6662static int xterm_button;
6663
6664/*
6665 * Setup a dummy window for X selections in a terminal.
6666 */
6667 void
6668setup_term_clip()
6669{
6670 int z = 0;
6671 char *strp = "";
6672 Widget AppShell;
6673
6674 if (!x_connect_to_server())
6675 return;
6676
6677 open_app_context();
6678 if (app_context != NULL && xterm_Shell == (Widget)0)
6679 {
6680 int (*oldhandler)();
6681#if defined(HAVE_SETJMP_H)
6682 int (*oldIOhandler)();
6683#endif
6684# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6685 struct timeval start_tv;
6686
6687 if (p_verbose > 0)
6688 gettimeofday(&start_tv, NULL);
6689# endif
6690
6691 /* Ignore X errors while opening the display */
6692 oldhandler = XSetErrorHandler(x_error_check);
6693
6694#if defined(HAVE_SETJMP_H)
6695 /* Ignore X IO errors while opening the display */
6696 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6697 mch_startjmp();
6698 if (SETJMP(lc_jump_env) != 0)
6699 {
6700 mch_didjmp();
6701 xterm_dpy = NULL;
6702 }
6703 else
6704#endif
6705 {
6706 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6707 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6708#if defined(HAVE_SETJMP_H)
6709 mch_endjmp();
6710#endif
6711 }
6712
6713#if defined(HAVE_SETJMP_H)
6714 /* Now handle X IO errors normally. */
6715 (void)XSetIOErrorHandler(oldIOhandler);
6716#endif
6717 /* Now handle X errors normally. */
6718 (void)XSetErrorHandler(oldhandler);
6719
6720 if (xterm_dpy == NULL)
6721 {
6722 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006723 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724 return;
6725 }
6726
6727 /* Catch terminating error of the X server connection. */
6728 (void)XSetIOErrorHandler(x_IOerror_handler);
6729
6730# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6731 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006732 {
6733 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006735 verbose_leave();
6736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006737# endif
6738
6739 /* Create a Shell to make converters work. */
6740 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6741 applicationShellWidgetClass, xterm_dpy,
6742 NULL);
6743 if (AppShell == (Widget)0)
6744 return;
6745 xterm_Shell = XtVaCreatePopupShell("VIM",
6746 topLevelShellWidgetClass, AppShell,
6747 XtNmappedWhenManaged, 0,
6748 XtNwidth, 1,
6749 XtNheight, 1,
6750 NULL);
6751 if (xterm_Shell == (Widget)0)
6752 return;
6753
6754 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006755 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 if (x11_display == NULL)
6757 x11_display = xterm_dpy;
6758
6759 XtRealizeWidget(xterm_Shell);
6760 XSync(xterm_dpy, False);
6761 xterm_update();
6762 }
6763 if (xterm_Shell != (Widget)0)
6764 {
6765 clip_init(TRUE);
6766 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6767 x11_window = (Window)atol(strp);
6768 /* Check if $WINDOWID is valid. */
6769 if (test_x11_window(xterm_dpy) == FAIL)
6770 x11_window = 0;
6771 if (x11_window != 0)
6772 xterm_trace = 0;
6773 }
6774}
6775
6776 void
6777start_xterm_trace(button)
6778 int button;
6779{
6780 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6781 return;
6782 xterm_trace = 1;
6783 xterm_button = button;
6784 do_xterm_trace();
6785}
6786
6787
6788 void
6789stop_xterm_trace()
6790{
6791 if (xterm_trace < 0)
6792 return;
6793 xterm_trace = 0;
6794}
6795
6796/*
6797 * Query the xterm pointer and generate mouse termcodes if necessary
6798 * return TRUE if dragging is active, else FALSE
6799 */
6800 static int
6801do_xterm_trace()
6802{
6803 Window root, child;
6804 int root_x, root_y;
6805 int win_x, win_y;
6806 int row, col;
6807 int_u mask_return;
6808 char_u buf[50];
6809 char_u *strp;
6810 long got_hints;
6811 static char_u *mouse_code;
6812 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6813 static int prev_row = 0, prev_col = 0;
6814 static XSizeHints xterm_hints;
6815
6816 if (xterm_trace <= 0)
6817 return FALSE;
6818
6819 if (xterm_trace == 1)
6820 {
6821 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006822 * have changed recently. */
6823 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6824 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825 || xterm_hints.width_inc <= 1
6826 || xterm_hints.height_inc <= 1)
6827 {
6828 xterm_trace = -1; /* Not enough data -- disable tracing */
6829 return FALSE;
6830 }
6831
6832 /* Rely on the same mouse code for the duration of this */
6833 mouse_code = find_termcode(mouse_name);
6834 prev_row = mouse_row;
6835 prev_row = mouse_col;
6836 xterm_trace = 2;
6837
6838 /* Find the offset of the chars, there might be a scrollbar on the
6839 * left of the window and/or a menu on the top (eterm etc.) */
6840 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6841 &win_x, &win_y, &mask_return);
6842 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6843 - (xterm_hints.height_inc / 2);
6844 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6845 xterm_hints.y = 2;
6846 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6847 - (xterm_hints.width_inc / 2);
6848 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6849 xterm_hints.x = 2;
6850 return TRUE;
6851 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006852 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 {
6854 xterm_trace = 0;
6855 return FALSE;
6856 }
6857
6858 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6859 &win_x, &win_y, &mask_return);
6860
6861 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6862 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6863 if (row == prev_row && col == prev_col)
6864 return TRUE;
6865
6866 STRCPY(buf, mouse_code);
6867 strp = buf + STRLEN(buf);
6868 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6869 *strp++ = (char_u)(col + ' ' + 1);
6870 *strp++ = (char_u)(row + ' ' + 1);
6871 *strp = 0;
6872 add_to_input_buf(buf, STRLEN(buf));
6873
6874 prev_row = row;
6875 prev_col = col;
6876 return TRUE;
6877}
6878
6879# if defined(FEAT_GUI) || defined(PROTO)
6880/*
6881 * Destroy the display, window and app_context. Required for GTK.
6882 */
6883 void
6884clear_xterm_clip()
6885{
6886 if (xterm_Shell != (Widget)0)
6887 {
6888 XtDestroyWidget(xterm_Shell);
6889 xterm_Shell = (Widget)0;
6890 }
6891 if (xterm_dpy != NULL)
6892 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006893# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 /* Lesstif and Solaris crash here, lose some memory */
6895 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006896# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 if (x11_display == xterm_dpy)
6898 x11_display = NULL;
6899 xterm_dpy = NULL;
6900 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006901# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 if (app_context != (XtAppContext)NULL)
6903 {
6904 /* Lesstif and Solaris crash here, lose some memory */
6905 XtDestroyApplicationContext(app_context);
6906 app_context = (XtAppContext)NULL;
6907 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006908# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909}
6910# endif
6911
6912/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01006913 * Catch up with GUI or X events.
6914 */
6915 static void
6916clip_update()
6917{
6918# ifdef FEAT_GUI
6919 if (gui.in_use)
6920 gui_mch_update();
6921 else
6922# endif
6923 if (xterm_Shell != (Widget)0)
6924 xterm_update();
6925}
6926
6927/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 * Catch up with any queued X events. This may put keyboard input into the
6929 * input buffer, call resize call-backs, trigger timers etc. If there is
6930 * nothing in the X event queue (& no timers pending), then we return
6931 * immediately.
6932 */
6933 static void
6934xterm_update()
6935{
6936 XEvent event;
6937
6938 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6939 {
6940 XtAppNextEvent(app_context, &event);
6941#ifdef FEAT_CLIENTSERVER
6942 {
6943 XPropertyEvent *e = (XPropertyEvent *)&event;
6944
6945 if (e->type == PropertyNotify && e->window == commWindow
6946 && e->atom == commProperty && e->state == PropertyNewValue)
6947 serverEventProc(xterm_dpy, &event);
6948 }
6949#endif
6950 XtDispatchEvent(&event);
6951 }
6952}
6953
6954 int
6955clip_xterm_own_selection(cbd)
6956 VimClipboard *cbd;
6957{
6958 if (xterm_Shell != (Widget)0)
6959 return clip_x11_own_selection(xterm_Shell, cbd);
6960 return FAIL;
6961}
6962
6963 void
6964clip_xterm_lose_selection(cbd)
6965 VimClipboard *cbd;
6966{
6967 if (xterm_Shell != (Widget)0)
6968 clip_x11_lose_selection(xterm_Shell, cbd);
6969}
6970
6971 void
6972clip_xterm_request_selection(cbd)
6973 VimClipboard *cbd;
6974{
6975 if (xterm_Shell != (Widget)0)
6976 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6977}
6978
6979 void
6980clip_xterm_set_selection(cbd)
6981 VimClipboard *cbd;
6982{
6983 clip_x11_set_selection(cbd);
6984}
6985#endif
6986
6987
6988#if defined(USE_XSMP) || defined(PROTO)
6989/*
6990 * Code for X Session Management Protocol.
6991 */
6992static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6993static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6994static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6995static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6996static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6997
6998
6999# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7000static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7001
7002/*
7003 * This is our chance to ask the user if they want to save,
7004 * or abort the logout
7005 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 static void
7007xsmp_handle_interaction(smc_conn, client_data)
7008 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007009 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010{
7011 cmdmod_T save_cmdmod;
7012 int cancel_shutdown = False;
7013
7014 save_cmdmod = cmdmod;
7015 cmdmod.confirm = TRUE;
7016 if (check_changed_any(FALSE))
7017 /* Mustn't logout */
7018 cancel_shutdown = True;
7019 cmdmod = save_cmdmod;
7020 setcursor(); /* position cursor */
7021 out_flush();
7022
7023 /* Done interaction */
7024 SmcInteractDone(smc_conn, cancel_shutdown);
7025
7026 /* Finish off
7027 * Only end save-yourself here if we're not cancelling shutdown;
7028 * we'll get a cancelled callback later in which we'll end it.
7029 * Hopefully get around glitchy SMs (like GNOME-1)
7030 */
7031 if (!cancel_shutdown)
7032 {
7033 xsmp.save_yourself = False;
7034 SmcSaveYourselfDone(smc_conn, True);
7035 }
7036}
7037# endif
7038
7039/*
7040 * Callback that starts save-yourself.
7041 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042 static void
7043xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7044 shutdown, interact_style, fast)
7045 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007046 SmPointer client_data UNUSED;
7047 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007049 int interact_style UNUSED;
7050 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051{
7052 /* Handle already being in saveyourself */
7053 if (xsmp.save_yourself)
7054 SmcSaveYourselfDone(smc_conn, True);
7055 xsmp.save_yourself = True;
7056 xsmp.shutdown = shutdown;
7057
7058 /* First up, preserve all files */
7059 out_flush();
7060 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7061
7062 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007063 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064
7065# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7066 /* Now see if we can ask about unsaved files */
7067 if (shutdown && !fast && gui.in_use)
7068 /* Need to interact with user, but need SM's permission */
7069 SmcInteractRequest(smc_conn, SmDialogError,
7070 xsmp_handle_interaction, client_data);
7071 else
7072# endif
7073 {
7074 /* Can stop the cycle here */
7075 SmcSaveYourselfDone(smc_conn, True);
7076 xsmp.save_yourself = False;
7077 }
7078}
7079
7080
7081/*
7082 * Callback to warn us of imminent death.
7083 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 static void
7085xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007086 SmcConn smc_conn UNUSED;
7087 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088{
7089 xsmp_close();
7090
7091 /* quit quickly leaving swapfiles for modified buffers behind */
7092 getout_preserve_modified(0);
7093}
7094
7095
7096/*
7097 * Callback to tell us that save-yourself has completed.
7098 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 static void
7100xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007101 SmcConn smc_conn UNUSED;
7102 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103{
7104 xsmp.save_yourself = False;
7105}
7106
7107
7108/*
7109 * Callback to tell us that an instigated shutdown was cancelled
7110 * (maybe even by us)
7111 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 static void
7113xsmp_shutdown_cancelled(smc_conn, client_data)
7114 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007115 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116{
7117 if (xsmp.save_yourself)
7118 SmcSaveYourselfDone(smc_conn, True);
7119 xsmp.save_yourself = False;
7120 xsmp.shutdown = False;
7121}
7122
7123
7124/*
7125 * Callback to tell us that a new ICE connection has been established.
7126 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127 static void
7128xsmp_ice_connection(iceConn, clientData, opening, watchData)
7129 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007130 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007132 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133{
7134 /* Intercept creation of ICE connection fd */
7135 if (opening)
7136 {
7137 xsmp_icefd = IceConnectionNumber(iceConn);
7138 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7139 }
7140}
7141
7142
7143/* Handle any ICE processing that's required; return FAIL if SM lost */
7144 int
7145xsmp_handle_requests()
7146{
7147 Bool rep;
7148
7149 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7150 == IceProcessMessagesIOError)
7151 {
7152 /* Lost ICE */
7153 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007154 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007155 xsmp_close();
7156 return FAIL;
7157 }
7158 else
7159 return OK;
7160}
7161
7162static int dummy;
7163
7164/* Set up X Session Management Protocol */
7165 void
7166xsmp_init(void)
7167{
7168 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 SmcCallbacks smcallbacks;
7170#if 0
7171 SmPropValue smname;
7172 SmProp smnameprop;
7173 SmProp *smprops[1];
7174#endif
7175
7176 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007177 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178
7179 xsmp.save_yourself = xsmp.shutdown = False;
7180
7181 /* Set up SM callbacks - must have all, even if they're not used */
7182 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7183 smcallbacks.save_yourself.client_data = NULL;
7184 smcallbacks.die.callback = xsmp_die;
7185 smcallbacks.die.client_data = NULL;
7186 smcallbacks.save_complete.callback = xsmp_save_complete;
7187 smcallbacks.save_complete.client_data = NULL;
7188 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7189 smcallbacks.shutdown_cancelled.client_data = NULL;
7190
7191 /* Set up a watch on ICE connection creations. The "dummy" argument is
7192 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7193 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7194 {
7195 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007196 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 return;
7198 }
7199
7200 /* Create an SM connection */
7201 xsmp.smcconn = SmcOpenConnection(
7202 NULL,
7203 NULL,
7204 SmProtoMajor,
7205 SmProtoMinor,
7206 SmcSaveYourselfProcMask | SmcDieProcMask
7207 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7208 &smcallbacks,
7209 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007210 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 sizeof(errorstring),
7212 errorstring);
7213 if (xsmp.smcconn == NULL)
7214 {
7215 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007216
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007218 {
7219 vim_snprintf(errorreport, sizeof(errorreport),
7220 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7221 verb_msg((char_u *)errorreport);
7222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 return;
7224 }
7225 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7226
7227#if 0
7228 /* ID ourselves */
7229 smname.value = "vim";
7230 smname.length = 3;
7231 smnameprop.name = "SmProgram";
7232 smnameprop.type = "SmARRAY8";
7233 smnameprop.num_vals = 1;
7234 smnameprop.vals = &smname;
7235
7236 smprops[0] = &smnameprop;
7237 SmcSetProperties(xsmp.smcconn, 1, smprops);
7238#endif
7239}
7240
7241
7242/* Shut down XSMP comms. */
7243 void
7244xsmp_close()
7245{
7246 if (xsmp_icefd != -1)
7247 {
7248 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007249 if (xsmp.clientid != NULL)
7250 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007251 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 xsmp_icefd = -1;
7253 }
7254}
7255#endif /* USE_XSMP */
7256
7257
7258#ifdef EBCDIC
7259/* Translate character to its CTRL- value */
7260char CtrlTable[] =
7261{
7262/* 00 - 5E */
7263 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7264 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7266 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7267 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7268 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7269/* ^ */ 0x1E,
7270/* - */ 0x1F,
7271/* 61 - 6C */
7272 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7273/* _ */ 0x1F,
7274/* 6E - 80 */
7275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7276/* a */ 0x01,
7277/* b */ 0x02,
7278/* c */ 0x03,
7279/* d */ 0x37,
7280/* e */ 0x2D,
7281/* f */ 0x2E,
7282/* g */ 0x2F,
7283/* h */ 0x16,
7284/* i */ 0x05,
7285/* 8A - 90 */
7286 0, 0, 0, 0, 0, 0, 0,
7287/* j */ 0x15,
7288/* k */ 0x0B,
7289/* l */ 0x0C,
7290/* m */ 0x0D,
7291/* n */ 0x0E,
7292/* o */ 0x0F,
7293/* p */ 0x10,
7294/* q */ 0x11,
7295/* r */ 0x12,
7296/* 9A - A1 */
7297 0, 0, 0, 0, 0, 0, 0, 0,
7298/* s */ 0x13,
7299/* t */ 0x3C,
7300/* u */ 0x3D,
7301/* v */ 0x32,
7302/* w */ 0x26,
7303/* x */ 0x18,
7304/* y */ 0x19,
7305/* z */ 0x3F,
7306/* AA - AC */
7307 0, 0, 0,
7308/* [ */ 0x27,
7309/* AE - BC */
7310 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7311/* ] */ 0x1D,
7312/* BE - C0 */ 0, 0, 0,
7313/* A */ 0x01,
7314/* B */ 0x02,
7315/* C */ 0x03,
7316/* D */ 0x37,
7317/* E */ 0x2D,
7318/* F */ 0x2E,
7319/* G */ 0x2F,
7320/* H */ 0x16,
7321/* I */ 0x05,
7322/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7323/* J */ 0x15,
7324/* K */ 0x0B,
7325/* L */ 0x0C,
7326/* M */ 0x0D,
7327/* N */ 0x0E,
7328/* O */ 0x0F,
7329/* P */ 0x10,
7330/* Q */ 0x11,
7331/* R */ 0x12,
7332/* DA - DF */ 0, 0, 0, 0, 0, 0,
7333/* \ */ 0x1C,
7334/* E1 */ 0,
7335/* S */ 0x13,
7336/* T */ 0x3C,
7337/* U */ 0x3D,
7338/* V */ 0x32,
7339/* W */ 0x26,
7340/* X */ 0x18,
7341/* Y */ 0x19,
7342/* Z */ 0x3F,
7343/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7344 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7345};
7346
7347char MetaCharTable[]=
7348{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7349 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7350 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7351 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7352 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7353};
7354
7355
7356/* TODO: Use characters NOT numbers!!! */
7357char CtrlCharTable[]=
7358{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7359 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7360 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7361 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7362 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7363};
7364
7365
7366#endif