blob: 5eb0936c88e544d8b78894a99bf76c9b4618f390 [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));
171#if defined(__BEOS__)
172int 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 Moolenaar48bae372010-07-29 23:12:15 +0200438#ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200440 * We want to be interrupted by the winch signal
441 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200443 if (WaitForChar(-1L) == 0)
444 {
445 if (do_resize) /* interrupted by SIGWINCH signal */
446 handle_resize();
447 return 0;
448 }
Bram Moolenaar48bae372010-07-29 23:12:15 +0200449#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450
451 /* If input was put directly in typeahead buffer bail out here. */
452 if (typebuf_changed(tb_change_cnt))
453 return 0;
454
455 /*
456 * For some terminals we only get one character at a time.
457 * We want the get all available characters, so we could keep on
458 * trying until none is available
459 * For some other terminals this is quite slow, that's why we don't do
460 * it.
461 */
462 len = read_from_input_buf(buf, (long)maxlen);
463 if (len > 0)
464 {
465#ifdef OS2
466 int i;
467
468 for (i = 0; i < len; i++)
469 if (buf[i] == 0)
470 buf[i] = K_NUL;
471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472 return len;
473 }
474 }
475}
476
477 static void
478handle_resize()
479{
480 do_resize = FALSE;
481 shell_resized();
482}
483
484/*
485 * return non-zero if a character is available
486 */
487 int
488mch_char_avail()
489{
490 return WaitForChar(0L);
491}
492
493#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
494# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000495# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496# endif
497# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
498# include <sys/sysctl.h>
499# endif
500# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
501# include <sys/sysinfo.h>
502# endif
503
504/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000505 * Return total amount of memory available in Kbyte.
506 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 long_u
509mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000510 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511{
512# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000513 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514# else
515 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000516 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517
518# ifdef HAVE_SYSCTL
519 int mib[2], physmem;
520 size_t len;
521
522 /* BSD way of getting the amount of RAM available. */
523 mib[0] = CTL_HW;
524 mib[1] = HW_USERMEM;
525 len = sizeof(physmem);
526 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
527 mem = (long_u)physmem;
528# endif
529
530# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
531 if (mem == 0)
532 {
533 struct sysinfo sinfo;
534
535 /* Linux way of getting amount of RAM available */
536 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000537 {
538# ifdef HAVE_SYSINFO_MEM_UNIT
539 /* avoid overflow as much as possible */
540 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
541 {
542 sinfo.mem_unit = sinfo.mem_unit >> 1;
543 --shiftright;
544 }
545 mem = sinfo.totalram * sinfo.mem_unit;
546# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000548# endif
549 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550 }
551# endif
552
553# ifdef HAVE_SYSCONF
554 if (mem == 0)
555 {
556 long pagesize, pagecount;
557
558 /* Solaris way of getting amount of RAM available */
559 pagesize = sysconf(_SC_PAGESIZE);
560 pagecount = sysconf(_SC_PHYS_PAGES);
561 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000562 {
563 /* avoid overflow as much as possible */
564 while (shiftright > 0 && (pagesize & 1) == 0)
565 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000566 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000567 --shiftright;
568 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571 }
572# endif
573
574 /* Return the minimum of the physical memory and the user limit, because
575 * using more than the user limit may cause Vim to be terminated. */
576# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
577 {
578 struct rlimit rlp;
579
580 if (getrlimit(RLIMIT_DATA, &rlp) == 0
581 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
582# ifdef RLIM_INFINITY
583 && rlp.rlim_cur != RLIM_INFINITY
584# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000585 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000587 {
588 mem = (long_u)rlp.rlim_cur;
589 shiftright = 10;
590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591 }
592# endif
593
594 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000595 return mem >> shiftright;
596 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597# endif
598}
599#endif
600
601 void
602mch_delay(msec, ignoreinput)
603 long msec;
604 int ignoreinput;
605{
606 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000607#ifdef FEAT_MZSCHEME
608 long total = msec; /* remember original value */
609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610
611 if (ignoreinput)
612 {
613 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000614 * here. But we don't want QUIT to kill us (CTRL-\ used in a
615 * shell may produce SIGQUIT). */
616 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617 old_tmode = curr_tmode;
618 if (curr_tmode == TMODE_RAW)
619 settmode(TMODE_SLEEP);
620
621 /*
622 * Everybody sleeps in a different way...
623 * Prefer nanosleep(), some versions of usleep() can only sleep up to
624 * one second.
625 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000626#ifdef FEAT_MZSCHEME
627 do
628 {
629 /* if total is large enough, wait by portions in p_mzq */
630 if (total > p_mzq)
631 msec = p_mzq;
632 else
633 msec = total;
634 total -= msec;
635#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636#ifdef HAVE_NANOSLEEP
637 {
638 struct timespec ts;
639
640 ts.tv_sec = msec / 1000;
641 ts.tv_nsec = (msec % 1000) * 1000000;
642 (void)nanosleep(&ts, NULL);
643 }
644#else
645# ifdef HAVE_USLEEP
646 while (msec >= 1000)
647 {
648 usleep((unsigned int)(999 * 1000));
649 msec -= 999;
650 }
651 usleep((unsigned int)(msec * 1000));
652# else
653# ifndef HAVE_SELECT
654 poll(NULL, 0, (int)msec);
655# else
656# ifdef __EMX__
657 _sleep2(msec);
658# else
659 {
660 struct timeval tv;
661
662 tv.tv_sec = msec / 1000;
663 tv.tv_usec = (msec % 1000) * 1000;
664 /*
665 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
666 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
667 */
668 select(0, NULL, NULL, NULL, &tv);
669 }
670# endif /* __EMX__ */
671# endif /* HAVE_SELECT */
672# endif /* HAVE_NANOSLEEP */
673#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000674#ifdef FEAT_MZSCHEME
675 }
676 while (total > 0);
677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678
679 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000680 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681 }
682 else
683 WaitForChar(msec);
684}
685
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000686#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
688# define HAVE_CHECK_STACK_GROWTH
689/*
690 * Support for checking for an almost-out-of-stack-space situation.
691 */
692
693/*
694 * Return a pointer to an item on the stack. Used to find out if the stack
695 * grows up or down.
696 */
697static void check_stack_growth __ARGS((char *p));
698static int stack_grows_downwards;
699
700/*
701 * Find out if the stack grows upwards or downwards.
702 * "p" points to a variable on the stack of the caller.
703 */
704 static void
705check_stack_growth(p)
706 char *p;
707{
708 int i;
709
710 stack_grows_downwards = (p > (char *)&i);
711}
712#endif
713
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000714#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715static char *stack_limit = NULL;
716
717#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
718# include <pthread.h>
719# include <pthread_np.h>
720#endif
721
722/*
723 * Find out until how var the stack can grow without getting into trouble.
724 * Called when starting up and when switching to the signal stack in
725 * deathtrap().
726 */
727 static void
728get_stack_limit()
729{
730 struct rlimit rlp;
731 int i;
732 long lim;
733
734 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
735 * limit doesn't fit in a long (rlim_cur might be "long long"). */
736 if (getrlimit(RLIMIT_STACK, &rlp) == 0
737 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
738# ifdef RLIM_INFINITY
739 && rlp.rlim_cur != RLIM_INFINITY
740# endif
741 )
742 {
743 lim = (long)rlp.rlim_cur;
744#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
745 {
746 pthread_attr_t attr;
747 size_t size;
748
749 /* On FreeBSD the initial thread always has a fixed stack size, no
750 * matter what the limits are set to. Normally it's 1 Mbyte. */
751 pthread_attr_init(&attr);
752 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
753 {
754 pthread_attr_getstacksize(&attr, &size);
755 if (lim > (long)size)
756 lim = (long)size;
757 }
758 pthread_attr_destroy(&attr);
759 }
760#endif
761 if (stack_grows_downwards)
762 {
763 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
764 if (stack_limit >= (char *)&i)
765 /* overflow, set to 1/16 of current stack position */
766 stack_limit = (char *)((long)&i / 16L);
767 }
768 else
769 {
770 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
771 if (stack_limit <= (char *)&i)
772 stack_limit = NULL; /* overflow */
773 }
774 }
775}
776
777/*
778 * Return FAIL when running out of stack space.
779 * "p" must point to any variable local to the caller that's on the stack.
780 */
781 int
782mch_stackcheck(p)
783 char *p;
784{
785 if (stack_limit != NULL)
786 {
787 if (stack_grows_downwards)
788 {
789 if (p < stack_limit)
790 return FAIL;
791 }
792 else if (p > stack_limit)
793 return FAIL;
794 }
795 return OK;
796}
797#endif
798
799#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
800/*
801 * Support for using the signal stack.
802 * This helps when we run out of stack space, which causes a SIGSEGV. The
803 * signal handler then must run on another stack, since the normal stack is
804 * completely full.
805 */
806
Bram Moolenaar39766a72013-11-03 00:41:00 +0100807#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100808# include <AvailabilityMacros.h>
809#endif
810
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811#ifndef SIGSTKSZ
812# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
813#endif
814
815# ifdef HAVE_SIGALTSTACK
816static stack_t sigstk; /* for sigaltstack() */
817# else
818static struct sigstack sigstk; /* for sigstack() */
819# endif
820
821static void init_signal_stack __ARGS((void));
822static char *signal_stack;
823
824 static void
825init_signal_stack()
826{
827 if (signal_stack != NULL)
828 {
829# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000830# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
831 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
833 * "struct sigaltstack" needs to be declared. */
834 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
835# endif
836
837# ifdef HAVE_SS_BASE
838 sigstk.ss_base = signal_stack;
839# else
840 sigstk.ss_sp = signal_stack;
841# endif
842 sigstk.ss_size = SIGSTKSZ;
843 sigstk.ss_flags = 0;
844 (void)sigaltstack(&sigstk, NULL);
845# else
846 sigstk.ss_sp = signal_stack;
847 if (stack_grows_downwards)
848 sigstk.ss_sp += SIGSTKSZ - 1;
849 sigstk.ss_onstack = 0;
850 (void)sigstack(&sigstk, NULL);
851# endif
852 }
853}
854#endif
855
856/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000857 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858 * will barf when the second argument to signal() is ``wrong''.
859 * Let me try it with a few tricky defines from my own osdef.h (jw).
860 */
861#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 static RETSIGTYPE
863sig_winch SIGDEFARG(sigarg)
864{
865 /* this is not required on all systems, but it doesn't hurt anybody */
866 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
867 do_resize = TRUE;
868 SIGRETURN;
869}
870#endif
871
872#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 static RETSIGTYPE
874catch_sigint SIGDEFARG(sigarg)
875{
876 /* this is not required on all systems, but it doesn't hurt anybody */
877 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
878 got_int = TRUE;
879 SIGRETURN;
880}
881#endif
882
883#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884 static RETSIGTYPE
885catch_sigpwr SIGDEFARG(sigarg)
886{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000887 /* this is not required on all systems, but it doesn't hurt anybody */
888 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 /*
890 * I'm not sure we get the SIGPWR signal when the system is really going
891 * down or when the batteries are almost empty. Just preserve the swap
892 * files and don't exit, that can't do any harm.
893 */
894 ml_sync_all(FALSE, FALSE);
895 SIGRETURN;
896}
897#endif
898
899#ifdef SET_SIG_ALARM
900/*
901 * signal function for alarm().
902 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 static RETSIGTYPE
904sig_alarm SIGDEFARG(sigarg)
905{
906 /* doesn't do anything, just to break a system call */
907 sig_alarm_called = TRUE;
908 SIGRETURN;
909}
910#endif
911
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000912#if (defined(HAVE_SETJMP_H) \
913 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
914 || defined(FEAT_LIBCALL))) \
915 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916/*
917 * A simplistic version of setjmp() that only allows one level of using.
918 * Don't call twice before calling mch_endjmp()!.
919 * Usage:
920 * mch_startjmp();
921 * if (SETJMP(lc_jump_env) != 0)
922 * {
923 * mch_didjmp();
924 * EMSG("crash!");
925 * }
926 * else
927 * {
928 * do_the_work;
929 * mch_endjmp();
930 * }
931 * Note: Can't move SETJMP() here, because a function calling setjmp() must
932 * not return before the saved environment is used.
933 * Returns OK for normal return, FAIL when the protected code caused a
934 * problem and LONGJMP() was used.
935 */
936 void
937mch_startjmp()
938{
939#ifdef SIGHASARG
940 lc_signal = 0;
941#endif
942 lc_active = TRUE;
943}
944
945 void
946mch_endjmp()
947{
948 lc_active = FALSE;
949}
950
951 void
952mch_didjmp()
953{
954# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
955 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
956 * otherwise catching the signal only works once. */
957 init_signal_stack();
958# endif
959}
960#endif
961
962/*
963 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200964 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200966 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
967 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 */
969 static RETSIGTYPE
970deathtrap SIGDEFARG(sigarg)
971{
972 static int entered = 0; /* count the number of times we got here.
973 Note: when memory has been corrupted
974 this may get an arbitrary value! */
975#ifdef SIGHASARG
976 int i;
977#endif
978
979#if defined(HAVE_SETJMP_H)
980 /*
981 * Catch a crash in protected code.
982 * Restores the environment saved in lc_jump_env, which looks like
983 * SETJMP() returns 1.
984 */
985 if (lc_active)
986 {
987# if defined(SIGHASARG)
988 lc_signal = sigarg;
989# endif
990 lc_active = FALSE; /* don't jump again */
991 LONGJMP(lc_jump_env, 1);
992 /* NOTREACHED */
993 }
994#endif
995
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000996#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000997# ifdef SIGQUIT
998 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
999 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1000 * pressing CTRL-\, but we don't want Vim to exit then. */
1001 if (in_mch_delay && sigarg == SIGQUIT)
1002 SIGRETURN;
1003# endif
1004
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001005 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1006 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1007 * free(). Calling free() again may then cause a crash. */
1008 if (entered == 0
1009 && (0
1010# ifdef SIGHUP
1011 || sigarg == SIGHUP
1012# endif
1013# ifdef SIGQUIT
1014 || sigarg == SIGQUIT
1015# endif
1016# ifdef SIGTERM
1017 || sigarg == SIGTERM
1018# endif
1019# ifdef SIGPWR
1020 || sigarg == SIGPWR
1021# endif
1022# ifdef SIGUSR1
1023 || sigarg == SIGUSR1
1024# endif
1025# ifdef SIGUSR2
1026 || sigarg == SIGUSR2
1027# endif
1028 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001029 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001030 SIGRETURN;
1031#endif
1032
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 /* Remember how often we have been called. */
1034 ++entered;
1035
1036#ifdef FEAT_EVAL
1037 /* Set the v:dying variable. */
1038 set_vim_var_nr(VV_DYING, (long)entered);
1039#endif
1040
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001041#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 /* Since we are now using the signal stack, need to reset the stack
1043 * limit. Otherwise using a regexp will fail. */
1044 get_stack_limit();
1045#endif
1046
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001047#if 0
1048 /* This is for opening gdb the moment Vim crashes.
1049 * You need to manually adjust the file name and Vim executable name.
1050 * Suggested by SungHyun Nam. */
1051 {
1052# define VI_GDB_FILE "/tmp/vimgdb"
1053# define VIM_NAME "/usr/bin/vim"
1054 FILE *fp = fopen(VI_GDB_FILE, "w");
1055 if (fp)
1056 {
1057 fprintf(fp,
1058 "file %s\n"
1059 "attach %d\n"
1060 "set height 1000\n"
1061 "bt full\n"
1062 , VIM_NAME, getpid());
1063 fclose(fp);
1064 system("xterm -e gdb -x "VI_GDB_FILE);
1065 unlink(VI_GDB_FILE);
1066 }
1067 }
1068#endif
1069
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070#ifdef SIGHASARG
1071 /* try to find the name of this signal */
1072 for (i = 0; signal_info[i].sig != -1; i++)
1073 if (sigarg == signal_info[i].sig)
1074 break;
1075 deadly_signal = sigarg;
1076#endif
1077
1078 full_screen = FALSE; /* don't write message to the GUI, it might be
1079 * part of the problem... */
1080 /*
1081 * If something goes wrong after entering here, we may get here again.
1082 * When this happens, give a message and try to exit nicely (resetting the
1083 * terminal mode, etc.)
1084 * When this happens twice, just exit, don't even try to give a message,
1085 * stack may be corrupt or something weird.
1086 * When this still happens again (or memory was corrupted in such a way
1087 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1088 */
1089 if (entered >= 3)
1090 {
1091 reset_signals(); /* don't catch any signals anymore */
1092 may_core_dump();
1093 if (entered >= 4)
1094 _exit(8);
1095 exit(7);
1096 }
1097 if (entered == 2)
1098 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001099 /* No translation, it may call malloc(). */
1100 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 out_flush();
1102 getout(1);
1103 }
1104
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001105 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001107 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108 signal_info[i].name);
1109#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001110 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001112
1113 /* Preserve files and exit. This sets the really_exiting flag to prevent
1114 * calling free(). */
1115 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116
Bram Moolenaar009b2592004-10-24 19:18:58 +00001117#ifdef NBDEBUG
1118 reset_signals();
1119 may_core_dump();
1120 abort();
1121#endif
1122
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123 SIGRETURN;
1124}
1125
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001126#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127/*
1128 * On Solaris with multi-threading, suspending might not work immediately.
1129 * Catch the SIGCONT signal, which will be used as an indication whether the
1130 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001131 *
1132 * On Linux, signal is not always handled immediately either.
1133 * See https://bugs.launchpad.net/bugs/291373
1134 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001135 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001137static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1139
1140/*
1141 * signal handler for SIGCONT
1142 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 static RETSIGTYPE
1144sigcont_handler SIGDEFARG(sigarg)
1145{
1146 sigcont_received = TRUE;
1147 SIGRETURN;
1148}
1149#endif
1150
Bram Moolenaar62b42182010-09-21 22:09:37 +02001151# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1152static void loose_clipboard __ARGS((void));
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001153# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001154static void save_clipboard __ARGS((void));
1155static void restore_clipboard __ARGS((void));
1156
1157static void *clip_star_save = NULL;
1158static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001159# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001160
1161/*
1162 * Called when Vim is going to sleep or execute a shell command.
1163 * We can't respond to requests for the X selections. Lose them, otherwise
1164 * other applications will hang. But first copy the text to cut buffer 0.
1165 */
1166 static void
1167loose_clipboard()
1168{
1169 if (clip_star.owned || clip_plus.owned)
1170 {
1171 x11_export_final_selection();
1172 if (clip_star.owned)
1173 clip_lose_selection(&clip_star);
1174 if (clip_plus.owned)
1175 clip_lose_selection(&clip_plus);
1176 if (x11_display != NULL)
1177 XFlush(x11_display);
1178 }
1179}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001180
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001181# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001182/*
1183 * Save clipboard text to restore later.
1184 */
1185 static void
1186save_clipboard()
1187{
1188 if (clip_star.owned)
1189 clip_star_save = get_register('*', TRUE);
1190 if (clip_plus.owned)
1191 clip_plus_save = get_register('+', TRUE);
1192}
1193
1194/*
1195 * Restore clipboard text if no one own the X selection.
1196 */
1197 static void
1198restore_clipboard()
1199{
1200 if (clip_star_save != NULL)
1201 {
1202 if (!clip_gen_owner_exists(&clip_star))
1203 put_register('*', clip_star_save);
1204 else
1205 free_register(clip_star_save);
1206 clip_star_save = NULL;
1207 }
1208 if (clip_plus_save != NULL)
1209 {
1210 if (!clip_gen_owner_exists(&clip_plus))
1211 put_register('+', clip_plus_save);
1212 else
1213 free_register(clip_plus_save);
1214 clip_plus_save = NULL;
1215 }
1216}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001217# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001218#endif
1219
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220/*
1221 * If the machine has job control, use it to suspend the program,
1222 * otherwise fake it by starting a new shell.
1223 */
1224 void
1225mch_suspend()
1226{
1227 /* BeOS does have SIGTSTP, but it doesn't work. */
1228#if defined(SIGTSTP) && !defined(__BEOS__)
1229 out_flush(); /* needed to make cursor visible on some systems */
1230 settmode(TMODE_COOK);
1231 out_flush(); /* needed to disable mouse on some systems */
1232
1233# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001234 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235# endif
1236
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001237# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 sigcont_received = FALSE;
1239# endif
1240 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001241# if defined(_REENTRANT) && defined(SIGCONT)
1242 /*
1243 * Wait for the SIGCONT signal to be handled. It generally happens
1244 * immediately, but somehow not all the time. Do not call pause()
1245 * because there would be race condition which would hang Vim if
1246 * signal happened in between the test of sigcont_received and the
1247 * call to pause(). If signal is not yet received, call sleep(0)
1248 * to just yield CPU. Signal should then be received. If somehow
1249 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1250 * further if signal is not received after 1+2+3+4 ms (not expected
1251 * to happen).
1252 */
1253 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001254 long wait_time;
1255 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001256 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001257 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001258 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259# endif
1260
1261# ifdef FEAT_TITLE
1262 /*
1263 * Set oldtitle to NULL, so the current title is obtained again.
1264 */
1265 vim_free(oldtitle);
1266 oldtitle = NULL;
1267# endif
1268 settmode(TMODE_RAW);
1269 need_check_timestamps = TRUE;
1270 did_check_timestamps = FALSE;
1271#else
1272 suspend_shell();
1273#endif
1274}
1275
1276 void
1277mch_init()
1278{
1279 Columns = 80;
1280 Rows = 24;
1281
1282 out_flush();
1283 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001284
Bram Moolenaar56718732006-03-15 22:53:57 +00001285#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001286 mac_conv_init();
1287#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001288#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1289 win_clip_init();
1290#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291}
1292
1293 static void
1294set_signals()
1295{
1296#if defined(SIGWINCH)
1297 /*
1298 * WINDOW CHANGE signal is handled with sig_winch().
1299 */
1300 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1301#endif
1302
1303 /*
1304 * We want the STOP signal to work, to make mch_suspend() work.
1305 * For "rvim" the STOP signal is ignored.
1306 */
1307#ifdef SIGTSTP
1308 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1309#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001310#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 signal(SIGCONT, sigcont_handler);
1312#endif
1313
1314 /*
1315 * We want to ignore breaking of PIPEs.
1316 */
1317#ifdef SIGPIPE
1318 signal(SIGPIPE, SIG_IGN);
1319#endif
1320
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001322 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323#endif
1324
1325 /*
1326 * Ignore alarm signals (Perl's alarm() generates it).
1327 */
1328#ifdef SIGALRM
1329 signal(SIGALRM, SIG_IGN);
1330#endif
1331
1332 /*
1333 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1334 * work will be lost.
1335 */
1336#ifdef SIGPWR
1337 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1338#endif
1339
1340 /*
1341 * Arrange for other signals to gracefully shutdown Vim.
1342 */
1343 catch_signals(deathtrap, SIG_ERR);
1344
1345#if defined(FEAT_GUI) && defined(SIGHUP)
1346 /*
1347 * When the GUI is running, ignore the hangup signal.
1348 */
1349 if (gui.in_use)
1350 signal(SIGHUP, SIG_IGN);
1351#endif
1352}
1353
Bram Moolenaardf177f62005-02-22 08:39:57 +00001354#if defined(SIGINT) || defined(PROTO)
1355/*
1356 * Catch CTRL-C (only works while in Cooked mode).
1357 */
1358 static void
1359catch_int_signal()
1360{
1361 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1362}
1363#endif
1364
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365 void
1366reset_signals()
1367{
1368 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001369#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 /* SIGCONT isn't in the list, because its default action is ignore */
1371 signal(SIGCONT, SIG_DFL);
1372#endif
1373}
1374
1375 static void
1376catch_signals(func_deadly, func_other)
1377 RETSIGTYPE (*func_deadly)();
1378 RETSIGTYPE (*func_other)();
1379{
1380 int i;
1381
1382 for (i = 0; signal_info[i].sig != -1; i++)
1383 if (signal_info[i].deadly)
1384 {
1385#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1386 struct sigaction sa;
1387
1388 /* Setup to use the alternate stack for the signal function. */
1389 sa.sa_handler = func_deadly;
1390 sigemptyset(&sa.sa_mask);
1391# if defined(__linux__) && defined(_REENTRANT)
1392 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1393 * thread handling in combination with using the alternate stack:
1394 * pthread library functions try to use the stack pointer to
1395 * identify the current thread, causing a SEGV signal, which
1396 * recursively calls deathtrap() and hangs. */
1397 sa.sa_flags = 0;
1398# else
1399 sa.sa_flags = SA_ONSTACK;
1400# endif
1401 sigaction(signal_info[i].sig, &sa, NULL);
1402#else
1403# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1404 struct sigvec sv;
1405
1406 /* Setup to use the alternate stack for the signal function. */
1407 sv.sv_handler = func_deadly;
1408 sv.sv_mask = 0;
1409 sv.sv_flags = SV_ONSTACK;
1410 sigvec(signal_info[i].sig, &sv, NULL);
1411# else
1412 signal(signal_info[i].sig, func_deadly);
1413# endif
1414#endif
1415 }
1416 else if (func_other != SIG_ERR)
1417 signal(signal_info[i].sig, func_other);
1418}
1419
1420/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001421 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001422 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1423 * return TRUE
1424 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1425 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001426 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001427 * Returns TRUE when Vim should exit.
1428 */
1429 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001430vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001431 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001432{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001433 static int got_signal = 0;
1434 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001435
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001436 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001437 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001438 case SIGNAL_BLOCK: blocked = TRUE;
1439 break;
1440
1441 case SIGNAL_UNBLOCK: blocked = FALSE;
1442 if (got_signal != 0)
1443 {
1444 kill(getpid(), got_signal);
1445 got_signal = 0;
1446 }
1447 break;
1448
1449 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001450 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001451 got_signal = sig;
1452#ifdef SIGPWR
1453 if (sig != SIGPWR)
1454#endif
1455 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001456 break;
1457 }
1458 return FALSE;
1459}
1460
1461/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 * Check_win checks whether we have an interactive stdout.
1463 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464 int
1465mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001466 int argc UNUSED;
1467 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468{
1469#ifdef OS2
1470 /*
1471 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1472 * name, mostly it's just "vim" and found in the path, which is unusable.
1473 */
1474 if (mch_isFullName(argv[0]))
1475 exe_name = vim_strsave((char_u *)argv[0]);
1476#endif
1477 if (isatty(1))
1478 return OK;
1479 return FAIL;
1480}
1481
1482/*
1483 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1484 */
1485 int
1486mch_input_isatty()
1487{
1488 if (isatty(read_cmd_fd))
1489 return TRUE;
1490 return FALSE;
1491}
1492
1493#ifdef FEAT_X11
1494
1495# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1496 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1497
1498static void xopen_message __ARGS((struct timeval *tvp));
1499
1500/*
1501 * Give a message about the elapsed time for opening the X window.
1502 */
1503 static void
1504xopen_message(tvp)
1505 struct timeval *tvp; /* must contain start time */
1506{
1507 struct timeval end_tv;
1508
1509 /* Compute elapsed time. */
1510 gettimeofday(&end_tv, NULL);
1511 smsg((char_u *)_("Opening the X display took %ld msec"),
1512 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001513 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514}
1515# endif
1516#endif
1517
1518#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1519/*
1520 * A few functions shared by X11 title and clipboard code.
1521 */
1522static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1523static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1524static int x_connect_to_server __ARGS((void));
1525static int test_x11_window __ARGS((Display *dpy));
1526
1527static int got_x_error = FALSE;
1528
1529/*
1530 * X Error handler, otherwise X just exits! (very rude) -- webb
1531 */
1532 static int
1533x_error_handler(dpy, error_event)
1534 Display *dpy;
1535 XErrorEvent *error_event;
1536{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001537 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 STRCAT(IObuff, _("\nVim: Got X error\n"));
1539
1540 /* We cannot print a message and continue, because no X calls are allowed
1541 * here (causes my system to hang). Silently continuing might be an
1542 * alternative... */
1543 preserve_exit(); /* preserve files and exit */
1544
1545 return 0; /* NOTREACHED */
1546}
1547
1548/*
1549 * Another X Error handler, just used to check for errors.
1550 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 static int
1552x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001553 Display *dpy UNUSED;
1554 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555{
1556 got_x_error = TRUE;
1557 return 0;
1558}
1559
1560#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1561# if defined(HAVE_SETJMP_H)
1562/*
1563 * An X IO Error handler, used to catch error while opening the display.
1564 */
1565static int x_IOerror_check __ARGS((Display *dpy));
1566
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 static int
1568x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001569 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570{
1571 /* This function should not return, it causes exit(). Longjump instead. */
1572 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001573# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001574 return 0; /* avoid the compiler complains about missing return value */
1575# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576}
1577# endif
1578
1579/*
1580 * An X IO Error handler, used to catch terminal errors.
1581 */
1582static int x_IOerror_handler __ARGS((Display *dpy));
1583
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 static int
1585x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001586 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587{
1588 xterm_dpy = NULL;
1589 x11_window = 0;
1590 x11_display = NULL;
1591 xterm_Shell = (Widget)0;
1592
1593 /* This function should not return, it causes exit(). Longjump instead. */
1594 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001595# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001596 return 0; /* avoid the compiler complains about missing return value */
1597# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598}
1599#endif
1600
1601/*
1602 * Return TRUE when connection to the X server is desired.
1603 */
1604 static int
1605x_connect_to_server()
1606{
1607 regmatch_T regmatch;
1608
1609#if defined(FEAT_CLIENTSERVER)
1610 if (x_force_connect)
1611 return TRUE;
1612#endif
1613 if (x_no_connect)
1614 return FALSE;
1615
1616 /* Check for a match with "exclude:" from 'clipboard'. */
1617 if (clip_exclude_prog != NULL)
1618 {
1619 regmatch.rm_ic = FALSE; /* Don't ignore case */
1620 regmatch.regprog = clip_exclude_prog;
1621 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1622 return FALSE;
1623 }
1624 return TRUE;
1625}
1626
1627/*
1628 * Test if "dpy" and x11_window are valid by getting the window title.
1629 * I don't actually want it yet, so there may be a simpler call to use, but
1630 * this will cause the error handler x_error_check() to be called if anything
1631 * is wrong, such as the window pointer being invalid (as can happen when the
1632 * user changes his DISPLAY, but not his WINDOWID) -- webb
1633 */
1634 static int
1635test_x11_window(dpy)
1636 Display *dpy;
1637{
1638 int (*old_handler)();
1639 XTextProperty text_prop;
1640
1641 old_handler = XSetErrorHandler(x_error_check);
1642 got_x_error = FALSE;
1643 if (XGetWMName(dpy, x11_window, &text_prop))
1644 XFree((void *)text_prop.value);
1645 XSync(dpy, False);
1646 (void)XSetErrorHandler(old_handler);
1647
1648 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001649 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651 return (got_x_error ? FAIL : OK);
1652}
1653#endif
1654
1655#ifdef FEAT_TITLE
1656
1657#ifdef FEAT_X11
1658
1659static int get_x11_thing __ARGS((int get_title, int test_only));
1660
1661/*
1662 * try to get x11 window and display
1663 *
1664 * return FAIL for failure, OK otherwise
1665 */
1666 static int
1667get_x11_windis()
1668{
1669 char *winid;
1670 static int result = -1;
1671#define XD_NONE 0 /* x11_display not set here */
1672#define XD_HERE 1 /* x11_display opened here */
1673#define XD_GUI 2 /* x11_display used from gui.dpy */
1674#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1675 static int x11_display_from = XD_NONE;
1676 static int did_set_error_handler = FALSE;
1677
1678 if (!did_set_error_handler)
1679 {
1680 /* X just exits if it finds an error otherwise! */
1681 (void)XSetErrorHandler(x_error_handler);
1682 did_set_error_handler = TRUE;
1683 }
1684
Bram Moolenaar9372a112005-12-06 19:59:18 +00001685#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 if (gui.in_use)
1687 {
1688 /*
1689 * If the X11 display was opened here before, for the window where Vim
1690 * was started, close that one now to avoid a memory leak.
1691 */
1692 if (x11_display_from == XD_HERE && x11_display != NULL)
1693 {
1694 XCloseDisplay(x11_display);
1695 x11_display_from = XD_NONE;
1696 }
1697 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1698 {
1699 x11_display_from = XD_GUI;
1700 return OK;
1701 }
1702 x11_display = NULL;
1703 return FAIL;
1704 }
1705 else if (x11_display_from == XD_GUI)
1706 {
1707 /* GUI must have stopped somehow, clear x11_display */
1708 x11_window = 0;
1709 x11_display = NULL;
1710 x11_display_from = XD_NONE;
1711 }
1712#endif
1713
1714 /* When started with the "-X" argument, don't try connecting. */
1715 if (!x_connect_to_server())
1716 return FAIL;
1717
1718 /*
1719 * If WINDOWID not set, should try another method to find out
1720 * what the current window number is. The only code I know for
1721 * this is very complicated.
1722 * We assume that zero is invalid for WINDOWID.
1723 */
1724 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1725 x11_window = (Window)atol(winid);
1726
1727#ifdef FEAT_XCLIPBOARD
1728 if (xterm_dpy != NULL && x11_window != 0)
1729 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001730 /* We may have checked it already, but Gnome terminal can move us to
1731 * another window, so we need to check every time. */
1732 if (x11_display_from != XD_XTERM)
1733 {
1734 /*
1735 * If the X11 display was opened here before, for the window where
1736 * Vim was started, close that one now to avoid a memory leak.
1737 */
1738 if (x11_display_from == XD_HERE && x11_display != NULL)
1739 XCloseDisplay(x11_display);
1740 x11_display = xterm_dpy;
1741 x11_display_from = XD_XTERM;
1742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 if (test_x11_window(x11_display) == FAIL)
1744 {
1745 /* probably bad $WINDOWID */
1746 x11_window = 0;
1747 x11_display = NULL;
1748 x11_display_from = XD_NONE;
1749 return FAIL;
1750 }
1751 return OK;
1752 }
1753#endif
1754
1755 if (x11_window == 0 || x11_display == NULL)
1756 result = -1;
1757
1758 if (result != -1) /* Have already been here and set this */
1759 return result; /* Don't do all these X calls again */
1760
1761 if (x11_window != 0 && x11_display == NULL)
1762 {
1763#ifdef SET_SIG_ALARM
1764 RETSIGTYPE (*sig_save)();
1765#endif
1766#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1767 struct timeval start_tv;
1768
1769 if (p_verbose > 0)
1770 gettimeofday(&start_tv, NULL);
1771#endif
1772
1773#ifdef SET_SIG_ALARM
1774 /*
1775 * Opening the Display may hang if the DISPLAY setting is wrong, or
1776 * the network connection is bad. Set an alarm timer to get out.
1777 */
1778 sig_alarm_called = FALSE;
1779 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1780 (RETSIGTYPE (*)())sig_alarm);
1781 alarm(2);
1782#endif
1783 x11_display = XOpenDisplay(NULL);
1784
1785#ifdef SET_SIG_ALARM
1786 alarm(0);
1787 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1788 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001789 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790#endif
1791 if (x11_display != NULL)
1792 {
1793# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1794 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001795 {
1796 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001798 verbose_leave();
1799 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800# endif
1801 if (test_x11_window(x11_display) == FAIL)
1802 {
1803 /* Maybe window id is bad */
1804 x11_window = 0;
1805 XCloseDisplay(x11_display);
1806 x11_display = NULL;
1807 }
1808 else
1809 x11_display_from = XD_HERE;
1810 }
1811 }
1812 if (x11_window == 0 || x11_display == NULL)
1813 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001814
1815# ifdef FEAT_EVAL
1816 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1817# endif
1818
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 return (result = OK);
1820}
1821
1822/*
1823 * Determine original x11 Window Title
1824 */
1825 static int
1826get_x11_title(test_only)
1827 int test_only;
1828{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001829 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830}
1831
1832/*
1833 * Determine original x11 Window icon
1834 */
1835 static int
1836get_x11_icon(test_only)
1837 int test_only;
1838{
1839 int retval = FALSE;
1840
1841 retval = get_x11_thing(FALSE, test_only);
1842
1843 /* could not get old icon, use terminal name */
1844 if (oldicon == NULL && !test_only)
1845 {
1846 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001847 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001849 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 }
1851
1852 return retval;
1853}
1854
1855 static int
1856get_x11_thing(get_title, test_only)
1857 int get_title; /* get title string */
1858 int test_only;
1859{
1860 XTextProperty text_prop;
1861 int retval = FALSE;
1862 Status status;
1863
1864 if (get_x11_windis() == OK)
1865 {
1866 /* Get window/icon name if any */
1867 if (get_title)
1868 status = XGetWMName(x11_display, x11_window, &text_prop);
1869 else
1870 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1871
1872 /*
1873 * If terminal is xterm, then x11_window may be a child window of the
1874 * outer xterm window that actually contains the window/icon name, so
1875 * keep traversing up the tree until a window with a title/icon is
1876 * found.
1877 */
1878 /* Previously this was only done for xterm and alikes. I don't see a
1879 * reason why it would fail for other terminal emulators.
1880 * if (term_is_xterm) */
1881 {
1882 Window root;
1883 Window parent;
1884 Window win = x11_window;
1885 Window *children;
1886 unsigned int num_children;
1887
1888 while (!status || text_prop.value == NULL)
1889 {
1890 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1891 &num_children))
1892 break;
1893 if (children)
1894 XFree((void *)children);
1895 if (parent == root || parent == 0)
1896 break;
1897
1898 win = parent;
1899 if (get_title)
1900 status = XGetWMName(x11_display, win, &text_prop);
1901 else
1902 status = XGetWMIconName(x11_display, win, &text_prop);
1903 }
1904 }
1905 if (status && text_prop.value != NULL)
1906 {
1907 retval = TRUE;
1908 if (!test_only)
1909 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001910#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1911 if (text_prop.encoding == XA_STRING
1912# ifdef FEAT_MBYTE
1913 && !has_mbyte
1914# endif
1915 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917#endif
1918 if (get_title)
1919 oldtitle = vim_strsave((char_u *)text_prop.value);
1920 else
1921 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001922#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
1924 else
1925 {
1926 char **cl;
1927 Status transform_status;
1928 int n = 0;
1929
1930 transform_status = XmbTextPropertyToTextList(x11_display,
1931 &text_prop,
1932 &cl, &n);
1933 if (transform_status >= Success && n > 0 && cl[0])
1934 {
1935 if (get_title)
1936 oldtitle = vim_strsave((char_u *) cl[0]);
1937 else
1938 oldicon = vim_strsave((char_u *) cl[0]);
1939 XFreeStringList(cl);
1940 }
1941 else
1942 {
1943 if (get_title)
1944 oldtitle = vim_strsave((char_u *)text_prop.value);
1945 else
1946 oldicon = vim_strsave((char_u *)text_prop.value);
1947 }
1948 }
1949#endif
1950 }
1951 XFree((void *)text_prop.value);
1952 }
1953 }
1954 return retval;
1955}
1956
1957/* Are Xutf8 functions available? Avoid error from old compilers. */
1958#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1959# if X_HAVE_UTF8_STRING
1960# define USE_UTF8_STRING
1961# endif
1962#endif
1963
1964/*
1965 * Set x11 Window Title
1966 *
1967 * get_x11_windis() must be called before this and have returned OK
1968 */
1969 static void
1970set_x11_title(title)
1971 char_u *title;
1972{
1973 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1974 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1975 * supported everywhere and STRING doesn't work for multi-byte titles.
1976 */
1977#ifdef USE_UTF8_STRING
1978 if (enc_utf8)
1979 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1980 NULL, NULL, 0, NULL, NULL, NULL);
1981 else
1982#endif
1983 {
1984#if XtSpecificationRelease >= 4
1985# ifdef FEAT_XFONTSET
1986 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1987 NULL, NULL, 0, NULL, NULL, NULL);
1988# else
1989 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001990 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991
1992 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001993 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 XSetWMProperties(x11_display, x11_window, &text_prop,
1995 NULL, NULL, 0, NULL, NULL, NULL);
1996# endif
1997#else
1998 XStoreName(x11_display, x11_window, (char *)title);
1999#endif
2000 }
2001 XFlush(x11_display);
2002}
2003
2004/*
2005 * Set x11 Window icon
2006 *
2007 * get_x11_windis() must be called before this and have returned OK
2008 */
2009 static void
2010set_x11_icon(icon)
2011 char_u *icon;
2012{
2013 /* See above for comments about using X*SetWMProperties(). */
2014#ifdef USE_UTF8_STRING
2015 if (enc_utf8)
2016 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2017 NULL, 0, NULL, NULL, NULL);
2018 else
2019#endif
2020 {
2021#if XtSpecificationRelease >= 4
2022# ifdef FEAT_XFONTSET
2023 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2024 NULL, 0, NULL, NULL, NULL);
2025# else
2026 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002027 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002029 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2031 NULL, 0, NULL, NULL, NULL);
2032# endif
2033#else
2034 XSetIconName(x11_display, x11_window, (char *)icon);
2035#endif
2036 }
2037 XFlush(x11_display);
2038}
2039
2040#else /* FEAT_X11 */
2041
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 static int
2043get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002044 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045{
2046 return FALSE;
2047}
2048
2049 static int
2050get_x11_icon(test_only)
2051 int test_only;
2052{
2053 if (!test_only)
2054 {
2055 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002056 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002058 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 }
2060 return FALSE;
2061}
2062
2063#endif /* FEAT_X11 */
2064
2065 int
2066mch_can_restore_title()
2067{
2068 return get_x11_title(TRUE);
2069}
2070
2071 int
2072mch_can_restore_icon()
2073{
2074 return get_x11_icon(TRUE);
2075}
2076
2077/*
2078 * Set the window title and icon.
2079 */
2080 void
2081mch_settitle(title, icon)
2082 char_u *title;
2083 char_u *icon;
2084{
2085 int type = 0;
2086 static int recursive = 0;
2087
2088 if (T_NAME == NULL) /* no terminal name (yet) */
2089 return;
2090 if (title == NULL && icon == NULL) /* nothing to do */
2091 return;
2092
2093 /* When one of the X11 functions causes a deadly signal, we get here again
2094 * recursively. Avoid hanging then (something is probably locked). */
2095 if (recursive)
2096 return;
2097 ++recursive;
2098
2099 /*
2100 * if the window ID and the display is known, we may use X11 calls
2101 */
2102#ifdef FEAT_X11
2103 if (get_x11_windis() == OK)
2104 type = 1;
2105#else
2106# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2107 if (gui.in_use)
2108 type = 1;
2109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110#endif
2111
2112 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002113 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 * than x11 calls, because the x11 calls don't always work
2115 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 if ((type || *T_TS != NUL) && title != NULL)
2117 {
2118 if (oldtitle == NULL
2119#ifdef FEAT_GUI
2120 && !gui.in_use
2121#endif
2122 ) /* first call but not in GUI, save title */
2123 (void)get_x11_title(FALSE);
2124
2125 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2126 term_settitle(title);
2127#ifdef FEAT_X11
2128 else
2129# ifdef FEAT_GUI_GTK
2130 if (!gui.in_use) /* don't do this if GTK+ is running */
2131# endif
2132 set_x11_title(title); /* x11 */
2133#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002134#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2136 else
2137 gui_mch_settitle(title, icon);
2138#endif
2139 did_set_title = TRUE;
2140 }
2141
2142 if ((type || *T_CIS != NUL) && icon != NULL)
2143 {
2144 if (oldicon == NULL
2145#ifdef FEAT_GUI
2146 && !gui.in_use
2147#endif
2148 ) /* first call, save icon */
2149 get_x11_icon(FALSE);
2150
2151 if (*T_CIS != NUL)
2152 {
2153 out_str(T_CIS); /* set icon start */
2154 out_str_nf(icon);
2155 out_str(T_CIE); /* set icon end */
2156 out_flush();
2157 }
2158#ifdef FEAT_X11
2159 else
2160# ifdef FEAT_GUI_GTK
2161 if (!gui.in_use) /* don't do this if GTK+ is running */
2162# endif
2163 set_x11_icon(icon); /* x11 */
2164#endif
2165 did_set_icon = TRUE;
2166 }
2167 --recursive;
2168}
2169
2170/*
2171 * Restore the window/icon title.
2172 * "which" is one of:
2173 * 1 only restore title
2174 * 2 only restore icon
2175 * 3 restore title and icon
2176 */
2177 void
2178mch_restore_title(which)
2179 int which;
2180{
2181 /* only restore the title or icon when it has been set */
2182 mch_settitle(((which & 1) && did_set_title) ?
2183 (oldtitle ? oldtitle : p_titleold) : NULL,
2184 ((which & 2) && did_set_icon) ? oldicon : NULL);
2185}
2186
2187#endif /* FEAT_TITLE */
2188
2189/*
2190 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002191 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 */
2193 int
2194vim_is_xterm(name)
2195 char_u *name;
2196{
2197 if (name == NULL)
2198 return FALSE;
2199 return (STRNICMP(name, "xterm", 5) == 0
2200 || STRNICMP(name, "nxterm", 6) == 0
2201 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002202 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203 || STRNICMP(name, "rxvt", 4) == 0
2204 || STRCMP(name, "builtin_xterm") == 0);
2205}
2206
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002207#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2208/*
2209 * Return TRUE if "name" appears to be that of a terminal
2210 * known to support the xterm-style mouse protocol.
2211 * Relies on term_is_xterm having been set to its correct value.
2212 */
2213 int
2214use_xterm_like_mouse(name)
2215 char_u *name;
2216{
2217 return (name != NULL
2218 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2219}
2220#endif
2221
Bram Moolenaar071d4272004-06-13 20:20:40 +00002222#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2223/*
2224 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2225 * Return 1 for "xterm".
2226 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002227 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002228 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 */
2230 int
2231use_xterm_mouse()
2232{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002233 if (ttym_flags == TTYM_SGR)
2234 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002235 if (ttym_flags == TTYM_URXVT)
2236 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 if (ttym_flags == TTYM_XTERM2)
2238 return 2;
2239 if (ttym_flags == TTYM_XTERM)
2240 return 1;
2241 return 0;
2242}
2243#endif
2244
2245 int
2246vim_is_iris(name)
2247 char_u *name;
2248{
2249 if (name == NULL)
2250 return FALSE;
2251 return (STRNICMP(name, "iris-ansi", 9) == 0
2252 || STRCMP(name, "builtin_iris-ansi") == 0);
2253}
2254
2255 int
2256vim_is_vt300(name)
2257 char_u *name;
2258{
2259 if (name == NULL)
2260 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002261 /* catch VT100 - VT5xx */
2262 return ((STRNICMP(name, "vt", 2) == 0
2263 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 || STRCMP(name, "builtin_vt320") == 0);
2265}
2266
2267/*
2268 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2269 * This should include all windowed terminal emulators.
2270 */
2271 int
2272vim_is_fastterm(name)
2273 char_u *name;
2274{
2275 if (name == NULL)
2276 return FALSE;
2277 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2278 return TRUE;
2279 return ( STRNICMP(name, "hpterm", 6) == 0
2280 || STRNICMP(name, "sun-cmd", 7) == 0
2281 || STRNICMP(name, "screen", 6) == 0
2282 || STRNICMP(name, "dtterm", 6) == 0);
2283}
2284
2285/*
2286 * Insert user name in s[len].
2287 * Return OK if a name found.
2288 */
2289 int
2290mch_get_user_name(s, len)
2291 char_u *s;
2292 int len;
2293{
2294#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002295 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 return OK;
2297#else
2298 return mch_get_uname(getuid(), s, len);
2299#endif
2300}
2301
2302/*
2303 * Insert user name for "uid" in s[len].
2304 * Return OK if a name found.
2305 */
2306 int
2307mch_get_uname(uid, s, len)
2308 uid_t uid;
2309 char_u *s;
2310 int len;
2311{
2312#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2313 struct passwd *pw;
2314
2315 if ((pw = getpwuid(uid)) != NULL
2316 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2317 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002318 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 return OK;
2320 }
2321#endif
2322 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2323 return FAIL; /* a number is not a name */
2324}
2325
2326/*
2327 * Insert host name is s[len].
2328 */
2329
2330#ifdef HAVE_SYS_UTSNAME_H
2331 void
2332mch_get_host_name(s, len)
2333 char_u *s;
2334 int len;
2335{
2336 struct utsname vutsname;
2337
2338 if (uname(&vutsname) < 0)
2339 *s = NUL;
2340 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002341 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342}
2343#else /* HAVE_SYS_UTSNAME_H */
2344
2345# ifdef HAVE_SYS_SYSTEMINFO_H
2346# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2347# endif
2348
2349 void
2350mch_get_host_name(s, len)
2351 char_u *s;
2352 int len;
2353{
2354# ifdef VAXC
2355 vaxc$gethostname((char *)s, len);
2356# else
2357 gethostname((char *)s, len);
2358# endif
2359 s[len - 1] = NUL; /* make sure it's terminated */
2360}
2361#endif /* HAVE_SYS_UTSNAME_H */
2362
2363/*
2364 * return process ID
2365 */
2366 long
2367mch_get_pid()
2368{
2369 return (long)getpid();
2370}
2371
2372#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2373static char *strerror __ARGS((int));
2374
2375 static char *
2376strerror(err)
2377 int err;
2378{
2379 extern int sys_nerr;
2380 extern char *sys_errlist[];
2381 static char er[20];
2382
2383 if (err > 0 && err < sys_nerr)
2384 return (sys_errlist[err]);
2385 sprintf(er, "Error %d", err);
2386 return er;
2387}
2388#endif
2389
2390/*
2391 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2392 * Return OK for success, FAIL for failure.
2393 */
2394 int
2395mch_dirname(buf, len)
2396 char_u *buf;
2397 int len;
2398{
2399#if defined(USE_GETCWD)
2400 if (getcwd((char *)buf, len) == NULL)
2401 {
2402 STRCPY(buf, strerror(errno));
2403 return FAIL;
2404 }
2405 return OK;
2406#else
2407 return (getwd((char *)buf) != NULL ? OK : FAIL);
2408#endif
2409}
2410
2411#if defined(OS2) || defined(PROTO)
2412/*
2413 * Replace all slashes by backslashes.
2414 * When 'shellslash' set do it the other way around.
2415 */
2416 void
2417slash_adjust(p)
2418 char_u *p;
2419{
2420 while (*p)
2421 {
2422 if (*p == psepcN)
2423 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002424 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 }
2426}
2427#endif
2428
2429/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002430 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 *
2432 * return FAIL for failure, OK for success
2433 */
2434 int
2435mch_FullName(fname, buf, len, force)
2436 char_u *fname, *buf;
2437 int len;
2438 int force; /* also expand when already absolute path */
2439{
2440 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002441#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002443#endif
2444#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 int fd = -1;
2446 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002447#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 char_u olddir[MAXPATHL];
2449 char_u *p;
2450 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002451#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002452 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2453 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002454#endif
2455
Bram Moolenaar38323e42007-03-06 19:22:53 +00002456#ifdef VMS
2457 fname = vms_fixfilename(fname);
2458#endif
2459
Bram Moolenaara2442432007-04-26 14:26:37 +00002460#ifdef __CYGWIN__
2461 /*
2462 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2463 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002464# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2465 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2466# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002467 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002468# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002469 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002470#endif
2471
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 /* expand it if forced or not an absolute path */
2473 if (force || !mch_isFullName(fname))
2474 {
2475 /*
2476 * If the file name has a path, change to that directory for a moment,
2477 * and then do the getwd() (and get back to where we were).
2478 * This will get the correct path name with "../" things.
2479 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002480#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 only_drive = 0;
2482 if (((p = vim_strrchr(fname, '/')) != NULL)
2483 || ((p = vim_strrchr(fname, '\\')) != NULL)
2484 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002485#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002489#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 /*
2491 * Use fchdir() if possible, it's said to be faster and more
2492 * reliable. But on SunOS 4 it might not work. Check this by
2493 * doing a fchdir() right now.
2494 */
2495 if (!dont_fchdir)
2496 {
2497 fd = open(".", O_RDONLY | O_EXTRA, 0);
2498 if (fd >= 0 && fchdir(fd) < 0)
2499 {
2500 close(fd);
2501 fd = -1;
2502 dont_fchdir = TRUE; /* don't try again */
2503 }
2504 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506
2507 /* Only change directory when we are sure we can return to where
2508 * we are now. After doing "su" chdir(".") might not work. */
2509 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002510#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002512#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 (mch_dirname(olddir, MAXPATHL) == FAIL
2514 || mch_chdir((char *)olddir) != 0))
2515 {
2516 p = NULL; /* can't get current dir: don't chdir */
2517 retval = FAIL;
2518 }
2519 else
2520 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002521#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 /*
2523 * compensate for case where ':' from "D:" was the only
2524 * path separator detected in the file name; the _next_
2525 * character has to be removed, and then restored later.
2526 */
2527 if (only_drive)
2528 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 /* The directory is copied into buf[], to be able to remove
2531 * the file name without changing it (could be a string in
2532 * read-only memory) */
2533 if (p - fname >= len)
2534 retval = FAIL;
2535 else
2536 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002537 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 if (mch_chdir((char *)buf))
2539 retval = FAIL;
2540 else
2541 fname = p + 1;
2542 *buf = NUL;
2543 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002544#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 if (only_drive)
2546 {
2547 p--;
2548 if (retval != FAIL)
2549 fname--;
2550 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002551#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 }
2553 }
2554 if (mch_dirname(buf, len) == FAIL)
2555 {
2556 retval = FAIL;
2557 *buf = NUL;
2558 }
2559 if (p != NULL)
2560 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002561#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 if (fd >= 0)
2563 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002564 if (p_verbose >= 5)
2565 {
2566 verbose_enter();
2567 MSG("fchdir() to previous dir");
2568 verbose_leave();
2569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570 l = fchdir(fd);
2571 close(fd);
2572 }
2573 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002574#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 l = mch_chdir((char *)olddir);
2576 if (l != 0)
2577 EMSG(_(e_prev_dir));
2578 }
2579
2580 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002581 if (l >= len - 1)
2582 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002583#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002584 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002586 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002587#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002589
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002591 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 return FAIL;
2593
2594 /* Do not append ".", "/dir/." is equal to "/dir". */
2595 if (STRCMP(fname, ".") != 0)
2596 STRCAT(buf, fname);
2597
2598 return OK;
2599}
2600
2601/*
2602 * Return TRUE if "fname" does not depend on the current directory.
2603 */
2604 int
2605mch_isFullName(fname)
2606 char_u *fname;
2607{
2608#ifdef __EMX__
2609 return _fnisabs(fname);
2610#else
2611# ifdef VMS
2612 return ( fname[0] == '/' || fname[0] == '.' ||
2613 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2614 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2615 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2616# else
2617 return (*fname == '/' || *fname == '~');
2618# endif
2619#endif
2620}
2621
Bram Moolenaar24552be2005-12-10 20:17:30 +00002622#if defined(USE_FNAME_CASE) || defined(PROTO)
2623/*
2624 * Set the case of the file name, if it already exists. This will cause the
2625 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002626 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002627 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002628 void
2629fname_case(name, len)
2630 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002631 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002632{
2633 struct stat st;
2634 char_u *slash, *tail;
2635 DIR *dirp;
2636 struct dirent *dp;
2637
2638 if (lstat((char *)name, &st) >= 0)
2639 {
2640 /* Open the directory where the file is located. */
2641 slash = vim_strrchr(name, '/');
2642 if (slash == NULL)
2643 {
2644 dirp = opendir(".");
2645 tail = name;
2646 }
2647 else
2648 {
2649 *slash = NUL;
2650 dirp = opendir((char *)name);
2651 *slash = '/';
2652 tail = slash + 1;
2653 }
2654
2655 if (dirp != NULL)
2656 {
2657 while ((dp = readdir(dirp)) != NULL)
2658 {
2659 /* Only accept names that differ in case and are the same byte
2660 * length. TODO: accept different length name. */
2661 if (STRICMP(tail, dp->d_name) == 0
2662 && STRLEN(tail) == STRLEN(dp->d_name))
2663 {
2664 char_u newname[MAXPATHL + 1];
2665 struct stat st2;
2666
2667 /* Verify the inode is equal. */
2668 vim_strncpy(newname, name, MAXPATHL);
2669 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2670 MAXPATHL - (tail - name));
2671 if (lstat((char *)newname, &st2) >= 0
2672 && st.st_ino == st2.st_ino
2673 && st.st_dev == st2.st_dev)
2674 {
2675 STRCPY(tail, dp->d_name);
2676 break;
2677 }
2678 }
2679 }
2680
2681 closedir(dirp);
2682 }
2683 }
2684}
2685#endif
2686
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687/*
2688 * Get file permissions for 'name'.
2689 * Returns -1 when it doesn't exist.
2690 */
2691 long
2692mch_getperm(name)
2693 char_u *name;
2694{
2695 struct stat statb;
2696
2697 /* Keep the #ifdef outside of stat(), it may be a macro. */
2698#ifdef VMS
2699 if (stat((char *)vms_fixfilename(name), &statb))
2700#else
2701 if (stat((char *)name, &statb))
2702#endif
2703 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002704#ifdef __INTERIX
2705 /* The top bit makes the value negative, which means the file doesn't
2706 * exist. Remove the bit, we don't use it. */
2707 return statb.st_mode & ~S_ADDACE;
2708#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002710#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711}
2712
2713/*
2714 * set file permission for 'name' to 'perm'
2715 *
2716 * return FAIL for failure, OK otherwise
2717 */
2718 int
2719mch_setperm(name, perm)
2720 char_u *name;
2721 long perm;
2722{
2723 return (chmod((char *)
2724#ifdef VMS
2725 vms_fixfilename(name),
2726#else
2727 name,
2728#endif
2729 (mode_t)perm) == 0 ? OK : FAIL);
2730}
2731
2732#if defined(HAVE_ACL) || defined(PROTO)
2733# ifdef HAVE_SYS_ACL_H
2734# include <sys/acl.h>
2735# endif
2736# ifdef HAVE_SYS_ACCESS_H
2737# include <sys/access.h>
2738# endif
2739
2740# ifdef HAVE_SOLARIS_ACL
2741typedef struct vim_acl_solaris_T {
2742 int acl_cnt;
2743 aclent_t *acl_entry;
2744} vim_acl_solaris_T;
2745# endif
2746
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002747#if defined(HAVE_SELINUX) || defined(PROTO)
2748/*
2749 * Copy security info from "from_file" to "to_file".
2750 */
2751 void
2752mch_copy_sec(from_file, to_file)
2753 char_u *from_file;
2754 char_u *to_file;
2755{
2756 if (from_file == NULL)
2757 return;
2758
2759 if (selinux_enabled == -1)
2760 selinux_enabled = is_selinux_enabled();
2761
2762 if (selinux_enabled > 0)
2763 {
2764 security_context_t from_context = NULL;
2765 security_context_t to_context = NULL;
2766
2767 if (getfilecon((char *)from_file, &from_context) < 0)
2768 {
2769 /* If the filesystem doesn't support extended attributes,
2770 the original had no special security context and the
2771 target cannot have one either. */
2772 if (errno == EOPNOTSUPP)
2773 return;
2774
2775 MSG_PUTS(_("\nCould not get security context for "));
2776 msg_outtrans(from_file);
2777 msg_putchar('\n');
2778 return;
2779 }
2780 if (getfilecon((char *)to_file, &to_context) < 0)
2781 {
2782 MSG_PUTS(_("\nCould not get security context for "));
2783 msg_outtrans(to_file);
2784 msg_putchar('\n');
2785 freecon (from_context);
2786 return ;
2787 }
2788 if (strcmp(from_context, to_context) != 0)
2789 {
2790 if (setfilecon((char *)to_file, from_context) < 0)
2791 {
2792 MSG_PUTS(_("\nCould not set security context for "));
2793 msg_outtrans(to_file);
2794 msg_putchar('\n');
2795 }
2796 }
2797 freecon(to_context);
2798 freecon(from_context);
2799 }
2800}
2801#endif /* HAVE_SELINUX */
2802
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803/*
2804 * Return a pointer to the ACL of file "fname" in allocated memory.
2805 * Return NULL if the ACL is not available for whatever reason.
2806 */
2807 vim_acl_T
2808mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002809 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810{
2811 vim_acl_T ret = NULL;
2812#ifdef HAVE_POSIX_ACL
2813 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2814#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002815#ifdef HAVE_SOLARIS_ZFS_ACL
2816 acl_t *aclent;
2817
2818 if (acl_get((char *)fname, 0, &aclent) < 0)
2819 return NULL;
2820 ret = (vim_acl_T)aclent;
2821#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822#ifdef HAVE_SOLARIS_ACL
2823 vim_acl_solaris_T *aclent;
2824
2825 aclent = malloc(sizeof(vim_acl_solaris_T));
2826 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2827 {
2828 free(aclent);
2829 return NULL;
2830 }
2831 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2832 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2833 {
2834 free(aclent->acl_entry);
2835 free(aclent);
2836 return NULL;
2837 }
2838 ret = (vim_acl_T)aclent;
2839#else
2840#if defined(HAVE_AIX_ACL)
2841 int aclsize;
2842 struct acl *aclent;
2843
2844 aclsize = sizeof(struct acl);
2845 aclent = malloc(aclsize);
2846 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2847 {
2848 if (errno == ENOSPC)
2849 {
2850 aclsize = aclent->acl_len;
2851 aclent = realloc(aclent, aclsize);
2852 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2853 {
2854 free(aclent);
2855 return NULL;
2856 }
2857 }
2858 else
2859 {
2860 free(aclent);
2861 return NULL;
2862 }
2863 }
2864 ret = (vim_acl_T)aclent;
2865#endif /* HAVE_AIX_ACL */
2866#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002867#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868#endif /* HAVE_POSIX_ACL */
2869 return ret;
2870}
2871
2872/*
2873 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2874 */
2875 void
2876mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002877 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 vim_acl_T aclent;
2879{
2880 if (aclent == NULL)
2881 return;
2882#ifdef HAVE_POSIX_ACL
2883 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2884#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002885#ifdef HAVE_SOLARIS_ZFS_ACL
2886 acl_set((char *)fname, (acl_t *)aclent);
2887#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888#ifdef HAVE_SOLARIS_ACL
2889 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2890 ((vim_acl_solaris_T *)aclent)->acl_entry);
2891#else
2892#ifdef HAVE_AIX_ACL
2893 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2894#endif /* HAVE_AIX_ACL */
2895#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002896#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897#endif /* HAVE_POSIX_ACL */
2898}
2899
2900 void
2901mch_free_acl(aclent)
2902 vim_acl_T aclent;
2903{
2904 if (aclent == NULL)
2905 return;
2906#ifdef HAVE_POSIX_ACL
2907 acl_free((acl_t)aclent);
2908#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002909#ifdef HAVE_SOLARIS_ZFS_ACL
2910 acl_free((acl_t *)aclent);
2911#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912#ifdef HAVE_SOLARIS_ACL
2913 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2914 free(aclent);
2915#else
2916#ifdef HAVE_AIX_ACL
2917 free(aclent);
2918#endif /* HAVE_AIX_ACL */
2919#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002920#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921#endif /* HAVE_POSIX_ACL */
2922}
2923#endif
2924
2925/*
2926 * Set hidden flag for "name".
2927 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 void
2929mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002930 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931{
2932 /* can't hide a file */
2933}
2934
2935/*
2936 * return TRUE if "name" is a directory
2937 * return FALSE if "name" is not a directory
2938 * return FALSE for error
2939 */
2940 int
2941mch_isdir(name)
2942 char_u *name;
2943{
2944 struct stat statb;
2945
2946 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2947 return FALSE;
2948 if (stat((char *)name, &statb))
2949 return FALSE;
2950#ifdef _POSIX_SOURCE
2951 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2952#else
2953 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2954#endif
2955}
2956
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957static int executable_file __ARGS((char_u *name));
2958
2959/*
2960 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2961 */
2962 static int
2963executable_file(name)
2964 char_u *name;
2965{
2966 struct stat st;
2967
2968 if (stat((char *)name, &st))
2969 return 0;
2970 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2971}
2972
2973/*
2974 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2975 * Return -1 if unknown.
2976 */
2977 int
2978mch_can_exe(name)
2979 char_u *name;
2980{
2981 char_u *buf;
2982 char_u *p, *e;
2983 int retval;
2984
2985 /* If it's an absolute or relative path don't need to use $PATH. */
2986 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2987 || (name[1] == '.' && name[2] == '/'))))
2988 return executable_file(name);
2989
2990 p = (char_u *)getenv("PATH");
2991 if (p == NULL || *p == NUL)
2992 return -1;
2993 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2994 if (buf == NULL)
2995 return -1;
2996
2997 /*
2998 * Walk through all entries in $PATH to check if "name" exists there and
2999 * is an executable file.
3000 */
3001 for (;;)
3002 {
3003 e = (char_u *)strchr((char *)p, ':');
3004 if (e == NULL)
3005 e = p + STRLEN(p);
3006 if (e - p <= 1) /* empty entry means current dir */
3007 STRCPY(buf, "./");
3008 else
3009 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003010 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 add_pathsep(buf);
3012 }
3013 STRCAT(buf, name);
3014 retval = executable_file(buf);
3015 if (retval == 1)
3016 break;
3017
3018 if (*e != ':')
3019 break;
3020 p = e + 1;
3021 }
3022
3023 vim_free(buf);
3024 return retval;
3025}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
3027/*
3028 * Check what "name" is:
3029 * NODE_NORMAL: file or directory (or doesn't exist)
3030 * NODE_WRITABLE: writable device, socket, fifo, etc.
3031 * NODE_OTHER: non-writable things
3032 */
3033 int
3034mch_nodetype(name)
3035 char_u *name;
3036{
3037 struct stat st;
3038
3039 if (stat((char *)name, &st))
3040 return NODE_NORMAL;
3041 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3042 return NODE_NORMAL;
3043#ifndef OS2
3044 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3045 return NODE_OTHER;
3046#endif
3047 /* Everything else is writable? */
3048 return NODE_WRITABLE;
3049}
3050
3051 void
3052mch_early_init()
3053{
3054#ifdef HAVE_CHECK_STACK_GROWTH
3055 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 check_stack_growth((char *)&i);
3058
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003059# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060 get_stack_limit();
3061# endif
3062
3063#endif
3064
3065 /*
3066 * Setup an alternative stack for signals. Helps to catch signals when
3067 * running out of stack space.
3068 * Use of sigaltstack() is preferred, it's more portable.
3069 * Ignore any errors.
3070 */
3071#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003072 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073 init_signal_stack();
3074#endif
3075}
3076
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003077#if defined(EXITFREE) || defined(PROTO)
3078 void
3079mch_free_mem()
3080{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003081# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3082 if (clip_star.owned)
3083 clip_lose_selection(&clip_star);
3084 if (clip_plus.owned)
3085 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003086# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003087# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003088 if (xterm_Shell != (Widget)0)
3089 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003090# ifndef LESSTIF_VERSION
3091 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003092 if (xterm_dpy != NULL)
3093 XtCloseDisplay(xterm_dpy);
3094 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003095 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003096 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003097# ifdef FEAT_X11
3098 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3099# endif
3100 }
3101# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003102# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003103# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003104 if (x11_display != NULL
3105# ifdef FEAT_XCLIPBOARD
3106 && x11_display != xterm_dpy
3107# endif
3108 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003109 XCloseDisplay(x11_display);
3110# endif
3111# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3112 vim_free(signal_stack);
3113 signal_stack = NULL;
3114# endif
3115# ifdef FEAT_TITLE
3116 vim_free(oldtitle);
3117 vim_free(oldicon);
3118# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003119}
3120#endif
3121
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122static void exit_scroll __ARGS((void));
3123
3124/*
3125 * Output a newline when exiting.
3126 * Make sure the newline goes to the same stream as the text.
3127 */
3128 static void
3129exit_scroll()
3130{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003131 if (silent_mode)
3132 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 if (newline_on_exit || msg_didout)
3134 {
3135 if (msg_use_printf())
3136 {
3137 if (info_message)
3138 mch_msg("\n");
3139 else
3140 mch_errmsg("\r\n");
3141 }
3142 else
3143 out_char('\n');
3144 }
3145 else
3146 {
3147 restore_cterm_colors(); /* get original colors back */
3148 msg_clr_eos_force(); /* clear the rest of the display */
3149 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3150 }
3151}
3152
3153 void
3154mch_exit(r)
3155 int r;
3156{
3157 exiting = TRUE;
3158
3159#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3160 x11_export_final_selection();
3161#endif
3162
3163#ifdef FEAT_GUI
3164 if (!gui.in_use)
3165#endif
3166 {
3167 settmode(TMODE_COOK);
3168#ifdef FEAT_TITLE
3169 mch_restore_title(3); /* restore xterm title and icon name */
3170#endif
3171 /*
3172 * When t_ti is not empty but it doesn't cause swapping terminal
3173 * pages, need to output a newline when msg_didout is set. But when
3174 * t_ti does swap pages it should not go to the shell page. Do this
3175 * before stoptermcap().
3176 */
3177 if (swapping_screen() && !newline_on_exit)
3178 exit_scroll();
3179
3180 /* Stop termcap: May need to check for T_CRV response, which
3181 * requires RAW mode. */
3182 stoptermcap();
3183
3184 /*
3185 * A newline is only required after a message in the alternate screen.
3186 * This is set to TRUE by wait_return().
3187 */
3188 if (!swapping_screen() || newline_on_exit)
3189 exit_scroll();
3190
3191 /* Cursor may have been switched off without calling starttermcap()
3192 * when doing "vim -u vimrc" and vimrc contains ":q". */
3193 if (full_screen)
3194 cursor_on();
3195 }
3196 out_flush();
3197 ml_close_all(TRUE); /* remove all memfiles */
3198 may_core_dump();
3199#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 gui_exit(r);
3202#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003203
Bram Moolenaar56718732006-03-15 22:53:57 +00003204#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003205 mac_conv_cleanup();
3206#endif
3207
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208#ifdef __QNX__
3209 /* A core dump won't be created if the signal handler
3210 * doesn't return, so we can't call exit() */
3211 if (deadly_signal != 0)
3212 return;
3213#endif
3214
Bram Moolenaar009b2592004-10-24 19:18:58 +00003215#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003216 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003217#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003218
3219#ifdef EXITFREE
3220 free_all_mem();
3221#endif
3222
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 exit(r);
3224}
3225
3226 static void
3227may_core_dump()
3228{
3229 if (deadly_signal != 0)
3230 {
3231 signal(deadly_signal, SIG_DFL);
3232 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3233 }
3234}
3235
3236#ifndef VMS
3237
3238 void
3239mch_settmode(tmode)
3240 int tmode;
3241{
3242 static int first = TRUE;
3243
3244 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3245#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3246 /*
3247 * for "new" tty systems
3248 */
3249# ifdef HAVE_TERMIOS_H
3250 static struct termios told;
3251 struct termios tnew;
3252# else
3253 static struct termio told;
3254 struct termio tnew;
3255# endif
3256
3257 if (first)
3258 {
3259 first = FALSE;
3260# if defined(HAVE_TERMIOS_H)
3261 tcgetattr(read_cmd_fd, &told);
3262# else
3263 ioctl(read_cmd_fd, TCGETA, &told);
3264# endif
3265 }
3266
3267 tnew = told;
3268 if (tmode == TMODE_RAW)
3269 {
3270 /*
3271 * ~ICRNL enables typing ^V^M
3272 */
3273 tnew.c_iflag &= ~ICRNL;
3274 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3275# if defined(IEXTEN) && !defined(__MINT__)
3276 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3277 /* but it breaks function keys on MINT */
3278# endif
3279 );
3280# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3281 tnew.c_oflag &= ~ONLCR;
3282# endif
3283 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3284 tnew.c_cc[VTIME] = 0; /* don't wait */
3285 }
3286 else if (tmode == TMODE_SLEEP)
3287 tnew.c_lflag &= ~(ECHO);
3288
3289# if defined(HAVE_TERMIOS_H)
3290 {
3291 int n = 10;
3292
3293 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3294 * few times. */
3295 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3296 && errno == EINTR && n > 0)
3297 --n;
3298 }
3299# else
3300 ioctl(read_cmd_fd, TCSETA, &tnew);
3301# endif
3302
3303#else
3304
3305 /*
3306 * for "old" tty systems
3307 */
3308# ifndef TIOCSETN
3309# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3310# endif
3311 static struct sgttyb ttybold;
3312 struct sgttyb ttybnew;
3313
3314 if (first)
3315 {
3316 first = FALSE;
3317 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3318 }
3319
3320 ttybnew = ttybold;
3321 if (tmode == TMODE_RAW)
3322 {
3323 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3324 ttybnew.sg_flags |= RAW;
3325 }
3326 else if (tmode == TMODE_SLEEP)
3327 ttybnew.sg_flags &= ~(ECHO);
3328 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3329#endif
3330 curr_tmode = tmode;
3331}
3332
3333/*
3334 * Try to get the code for "t_kb" from the stty setting
3335 *
3336 * Even if termcap claims a backspace key, the user's setting *should*
3337 * prevail. stty knows more about reality than termcap does, and if
3338 * somebody's usual erase key is DEL (which, for most BSD users, it will
3339 * be), they're going to get really annoyed if their erase key starts
3340 * doing forward deletes for no reason. (Eric Fischer)
3341 */
3342 void
3343get_stty()
3344{
3345 char_u buf[2];
3346 char_u *p;
3347
3348 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3349#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3350 /* for "new" tty systems */
3351# ifdef HAVE_TERMIOS_H
3352 struct termios keys;
3353# else
3354 struct termio keys;
3355# endif
3356
3357# if defined(HAVE_TERMIOS_H)
3358 if (tcgetattr(read_cmd_fd, &keys) != -1)
3359# else
3360 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3361# endif
3362 {
3363 buf[0] = keys.c_cc[VERASE];
3364 intr_char = keys.c_cc[VINTR];
3365#else
3366 /* for "old" tty systems */
3367 struct sgttyb keys;
3368
3369 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3370 {
3371 buf[0] = keys.sg_erase;
3372 intr_char = keys.sg_kill;
3373#endif
3374 buf[1] = NUL;
3375 add_termcode((char_u *)"kb", buf, FALSE);
3376
3377 /*
3378 * If <BS> and <DEL> are now the same, redefine <DEL>.
3379 */
3380 p = find_termcode((char_u *)"kD");
3381 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3382 do_fixdel(NULL);
3383 }
3384#if 0
3385 } /* to keep cindent happy */
3386#endif
3387}
3388
3389#endif /* VMS */
3390
3391#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3392/*
3393 * Set mouse clicks on or off.
3394 */
3395 void
3396mch_setmouse(on)
3397 int on;
3398{
3399 static int ison = FALSE;
3400 int xterm_mouse_vers;
3401
3402 if (on == ison) /* return quickly if nothing to do */
3403 return;
3404
3405 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003406
3407# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003408 if (ttym_flags == TTYM_URXVT)
3409 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003410 out_str_nf((char_u *)
3411 (on
3412 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3413 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3414 ison = on;
3415 }
3416# endif
3417
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003418# ifdef FEAT_MOUSE_SGR
3419 if (ttym_flags == TTYM_SGR)
3420 {
3421 out_str_nf((char_u *)
3422 (on
3423 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3424 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3425 ison = on;
3426 }
3427# endif
3428
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 if (xterm_mouse_vers > 0)
3430 {
3431 if (on) /* enable mouse events, use mouse tracking if available */
3432 out_str_nf((char_u *)
3433 (xterm_mouse_vers > 1
3434 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3435 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3436 else /* disable mouse events, could probably always send the same */
3437 out_str_nf((char_u *)
3438 (xterm_mouse_vers > 1
3439 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3440 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3441 ison = on;
3442 }
3443
3444# ifdef FEAT_MOUSE_DEC
3445 else if (ttym_flags == TTYM_DEC)
3446 {
3447 if (on) /* enable mouse events */
3448 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3449 else /* disable mouse events */
3450 out_str_nf((char_u *)"\033['z");
3451 ison = on;
3452 }
3453# endif
3454
3455# ifdef FEAT_MOUSE_GPM
3456 else
3457 {
3458 if (on)
3459 {
3460 if (gpm_open())
3461 ison = TRUE;
3462 }
3463 else
3464 {
3465 gpm_close();
3466 ison = FALSE;
3467 }
3468 }
3469# endif
3470
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003471# ifdef FEAT_SYSMOUSE
3472 else
3473 {
3474 if (on)
3475 {
3476 if (sysmouse_open() == OK)
3477 ison = TRUE;
3478 }
3479 else
3480 {
3481 sysmouse_close();
3482 ison = FALSE;
3483 }
3484 }
3485# endif
3486
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487# ifdef FEAT_MOUSE_JSB
3488 else
3489 {
3490 if (on)
3491 {
3492 /* D - Enable Mouse up/down messages
3493 * L - Enable Left Button Reporting
3494 * M - Enable Middle Button Reporting
3495 * R - Enable Right Button Reporting
3496 * K - Enable SHIFT and CTRL key Reporting
3497 * + - Enable Advanced messaging of mouse moves and up/down messages
3498 * Q - Quiet No Ack
3499 * # - Numeric value of mouse pointer required
3500 * 0 = Multiview 2000 cursor, used as standard
3501 * 1 = Windows Arrow
3502 * 2 = Windows I Beam
3503 * 3 = Windows Hour Glass
3504 * 4 = Windows Cross Hair
3505 * 5 = Windows UP Arrow
3506 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003507# ifdef JSBTERM_MOUSE_NONADVANCED
3508 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3510 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003511# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3513 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515 ison = TRUE;
3516 }
3517 else
3518 {
3519 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3520 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3521 ison = FALSE;
3522 }
3523 }
3524# endif
3525# ifdef FEAT_MOUSE_PTERM
3526 else
3527 {
3528 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3529 if (on)
3530 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3531 else
3532 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3533 ison = on;
3534 }
3535# endif
3536}
3537
3538/*
3539 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3540 */
3541 void
3542check_mouse_termcode()
3543{
3544# ifdef FEAT_MOUSE_XTERM
3545 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003546# ifdef FEAT_MOUSE_URXVT
3547 && use_xterm_mouse() != 3
3548# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549# ifdef FEAT_GUI
3550 && !gui.in_use
3551# endif
3552 )
3553 {
3554 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003555 ? IF_EB("\233M", CSI_STR "M")
3556 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 if (*p_mouse != NUL)
3558 {
3559 /* force mouse off and maybe on to send possibly new mouse
3560 * activation sequence to the xterm, with(out) drag tracing. */
3561 mch_setmouse(FALSE);
3562 setmouse();
3563 }
3564 }
3565 else
3566 del_mouse_termcode(KS_MOUSE);
3567# endif
3568
3569# ifdef FEAT_MOUSE_GPM
3570 if (!use_xterm_mouse()
3571# ifdef FEAT_GUI
3572 && !gui.in_use
3573# endif
3574 )
3575 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3576# endif
3577
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003578# ifdef FEAT_SYSMOUSE
3579 if (!use_xterm_mouse()
3580# ifdef FEAT_GUI
3581 && !gui.in_use
3582# endif
3583 )
3584 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3585# endif
3586
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587# ifdef FEAT_MOUSE_JSB
3588 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3589 if (!use_xterm_mouse()
3590# ifdef FEAT_GUI
3591 && !gui.in_use
3592# endif
3593 )
3594 set_mouse_termcode(KS_JSBTERM_MOUSE,
3595 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3596 else
3597 del_mouse_termcode(KS_JSBTERM_MOUSE);
3598# endif
3599
3600# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003601 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 * define it in the GUI or when using an xterm. */
3603 if (!use_xterm_mouse()
3604# ifdef FEAT_GUI
3605 && !gui.in_use
3606# endif
3607 )
3608 set_mouse_termcode(KS_NETTERM_MOUSE,
3609 (char_u *)IF_EB("\033}", ESC_STR "}"));
3610 else
3611 del_mouse_termcode(KS_NETTERM_MOUSE);
3612# endif
3613
3614# ifdef FEAT_MOUSE_DEC
3615 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3616 if (!use_xterm_mouse()
3617# ifdef FEAT_GUI
3618 && !gui.in_use
3619# endif
3620 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003621 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3622 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 else
3624 del_mouse_termcode(KS_DEC_MOUSE);
3625# endif
3626# ifdef FEAT_MOUSE_PTERM
3627 /* same as the dec mouse */
3628 if (!use_xterm_mouse()
3629# ifdef FEAT_GUI
3630 && !gui.in_use
3631# endif
3632 )
3633 set_mouse_termcode(KS_PTERM_MOUSE,
3634 (char_u *) IF_EB("\033[", ESC_STR "["));
3635 else
3636 del_mouse_termcode(KS_PTERM_MOUSE);
3637# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003638# ifdef FEAT_MOUSE_URXVT
3639 /* same as the dec mouse */
3640 if (use_xterm_mouse() == 3
3641# ifdef FEAT_GUI
3642 && !gui.in_use
3643# endif
3644 )
3645 {
3646 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3647 ? IF_EB("\233", CSI_STR)
3648 : IF_EB("\033[", ESC_STR "[")));
3649
3650 if (*p_mouse != NUL)
3651 {
3652 mch_setmouse(FALSE);
3653 setmouse();
3654 }
3655 }
3656 else
3657 del_mouse_termcode(KS_URXVT_MOUSE);
3658# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003659# ifdef FEAT_MOUSE_SGR
3660 /* same as the dec mouse */
3661 if (use_xterm_mouse() == 4
3662# ifdef FEAT_GUI
3663 && !gui.in_use
3664# endif
3665 )
3666 {
3667 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3668 ? IF_EB("\233<", CSI_STR "<")
3669 : IF_EB("\033[<", ESC_STR "[<")));
3670
3671 if (*p_mouse != NUL)
3672 {
3673 mch_setmouse(FALSE);
3674 setmouse();
3675 }
3676 }
3677 else
3678 del_mouse_termcode(KS_SGR_MOUSE);
3679# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680}
3681#endif
3682
3683/*
3684 * set screen mode, always fails.
3685 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686 int
3687mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003688 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689{
3690 EMSG(_(e_screenmode));
3691 return FAIL;
3692}
3693
3694#ifndef VMS
3695
3696/*
3697 * Try to get the current window size:
3698 * 1. with an ioctl(), most accurate method
3699 * 2. from the environment variables LINES and COLUMNS
3700 * 3. from the termcap
3701 * 4. keep using the old values
3702 * Return OK when size could be determined, FAIL otherwise.
3703 */
3704 int
3705mch_get_shellsize()
3706{
3707 long rows = 0;
3708 long columns = 0;
3709 char_u *p;
3710
3711 /*
3712 * For OS/2 use _scrsize().
3713 */
3714# ifdef __EMX__
3715 {
3716 int s[2];
3717
3718 _scrsize(s);
3719 columns = s[0];
3720 rows = s[1];
3721 }
3722# endif
3723
3724 /*
3725 * 1. try using an ioctl. It is the most accurate method.
3726 *
3727 * Try using TIOCGWINSZ first, some systems that have it also define
3728 * TIOCGSIZE but don't have a struct ttysize.
3729 */
3730# ifdef TIOCGWINSZ
3731 {
3732 struct winsize ws;
3733 int fd = 1;
3734
3735 /* When stdout is not a tty, use stdin for the ioctl(). */
3736 if (!isatty(fd) && isatty(read_cmd_fd))
3737 fd = read_cmd_fd;
3738 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3739 {
3740 columns = ws.ws_col;
3741 rows = ws.ws_row;
3742 }
3743 }
3744# else /* TIOCGWINSZ */
3745# ifdef TIOCGSIZE
3746 {
3747 struct ttysize ts;
3748 int fd = 1;
3749
3750 /* When stdout is not a tty, use stdin for the ioctl(). */
3751 if (!isatty(fd) && isatty(read_cmd_fd))
3752 fd = read_cmd_fd;
3753 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3754 {
3755 columns = ts.ts_cols;
3756 rows = ts.ts_lines;
3757 }
3758 }
3759# endif /* TIOCGSIZE */
3760# endif /* TIOCGWINSZ */
3761
3762 /*
3763 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003764 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3765 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003767 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 {
3769 if ((p = (char_u *)getenv("LINES")))
3770 rows = atoi((char *)p);
3771 if ((p = (char_u *)getenv("COLUMNS")))
3772 columns = atoi((char *)p);
3773 }
3774
3775#ifdef HAVE_TGETENT
3776 /*
3777 * 3. try reading "co" and "li" entries from termcap
3778 */
3779 if (columns == 0 || rows == 0)
3780 getlinecol(&columns, &rows);
3781#endif
3782
3783 /*
3784 * 4. If everything fails, use the old values
3785 */
3786 if (columns <= 0 || rows <= 0)
3787 return FAIL;
3788
3789 Rows = rows;
3790 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003791 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 return OK;
3793}
3794
3795/*
3796 * Try to set the window size to Rows and Columns.
3797 */
3798 void
3799mch_set_shellsize()
3800{
3801 if (*T_CWS)
3802 {
3803 /*
3804 * NOTE: if you get an error here that term_set_winsize() is
3805 * undefined, check the output of configure. It could probably not
3806 * find a ncurses, termcap or termlib library.
3807 */
3808 term_set_winsize((int)Rows, (int)Columns);
3809 out_flush();
3810 screen_start(); /* don't know where cursor is now */
3811 }
3812}
3813
3814#endif /* VMS */
3815
3816/*
3817 * Rows and/or Columns has changed.
3818 */
3819 void
3820mch_new_shellsize()
3821{
3822 /* Nothing to do. */
3823}
3824
Bram Moolenaar205b8862011-09-07 15:04:31 +02003825/*
3826 * Wait for process "child" to end.
3827 * Return "child" if it exited properly, <= 0 on error.
3828 */
3829 static pid_t
3830wait4pid(child, status)
3831 pid_t child;
3832 waitstatus *status;
3833{
3834 pid_t wait_pid = 0;
3835
3836 while (wait_pid != child)
3837 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003838 /* When compiled with Python threads are probably used, in which case
3839 * wait() sometimes hangs for no obvious reason. Use waitpid()
3840 * instead and loop (like the GUI). Also needed for other interfaces,
3841 * they might call system(). */
3842# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003843 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003844# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003845 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003846# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003847 if (wait_pid == 0)
3848 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003849 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003850 mch_delay(10L, TRUE);
3851 continue;
3852 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003853 if (wait_pid <= 0
3854# ifdef ECHILD
3855 && errno == ECHILD
3856# endif
3857 )
3858 break;
3859 }
3860 return wait_pid;
3861}
3862
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 int
3864mch_call_shell(cmd, options)
3865 char_u *cmd;
3866 int options; /* SHELL_*, see vim.h */
3867{
3868#ifdef VMS
3869 char *ifn = NULL;
3870 char *ofn = NULL;
3871#endif
3872 int tmode = cur_tmode;
3873#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3874 int x;
3875# ifndef __EMX__
3876 char_u *newcmd; /* only needed for unix */
3877# else
3878 /*
3879 * Set the preferred shell in the EMXSHELL environment variable (but
3880 * only if it is different from what is already in the environment).
3881 * Emx then takes care of whether to use "/c" or "-c" in an
3882 * intelligent way. Simply pass the whole thing to emx's system() call.
3883 * Emx also starts an interactive shell if system() is passed an empty
3884 * string.
3885 */
3886 char_u *p, *old;
3887
3888 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3889 {
3890 /* should check HAVE_SETENV, but I know we don't have it. */
3891 p = alloc(10 + strlen(p_sh));
3892 if (p)
3893 {
3894 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3895 putenv((char *)p); /* don't free the pointer! */
3896 }
3897 }
3898# endif
3899
3900 out_flush();
3901
3902 if (options & SHELL_COOKED)
3903 settmode(TMODE_COOK); /* set to normal mode */
3904
Bram Moolenaar62b42182010-09-21 22:09:37 +02003905# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003906 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02003907 loose_clipboard();
3908# endif
3909
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910# ifdef __EMX__
3911 if (cmd == NULL)
3912 x = system(""); /* this starts an interactive shell in emx */
3913 else
3914 x = system((char *)cmd);
3915 /* system() returns -1 when error occurs in starting shell */
3916 if (x == -1 && !emsg_silent)
3917 {
3918 MSG_PUTS(_("\nCannot execute shell "));
3919 msg_outtrans(p_sh);
3920 msg_putchar('\n');
3921 }
3922# else /* not __EMX__ */
3923 if (cmd == NULL)
3924 x = system((char *)p_sh);
3925 else
3926 {
3927# ifdef VMS
3928 if (ofn = strchr((char *)cmd, '>'))
3929 *ofn++ = '\0';
3930 if (ifn = strchr((char *)cmd, '<'))
3931 {
3932 char *p;
3933
3934 *ifn++ = '\0';
3935 p = strchr(ifn,' '); /* chop off any trailing spaces */
3936 if (p)
3937 *p = '\0';
3938 }
3939 if (ofn)
3940 x = vms_sys((char *)cmd, ofn, ifn);
3941 else
3942 x = system((char *)cmd);
3943# else
3944 newcmd = lalloc(STRLEN(p_sh)
3945 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3946 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3947 if (newcmd == NULL)
3948 x = 0;
3949 else
3950 {
3951 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3952 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3953 (char *)p_shcf,
3954 (char *)cmd);
3955 x = system((char *)newcmd);
3956 vim_free(newcmd);
3957 }
3958# endif
3959 }
3960# ifdef VMS
3961 x = vms_sys_status(x);
3962# endif
3963 if (emsg_silent)
3964 ;
3965 else if (x == 127)
3966 MSG_PUTS(_("\nCannot execute shell sh\n"));
3967# endif /* __EMX__ */
3968 else if (x && !(options & SHELL_SILENT))
3969 {
3970 MSG_PUTS(_("\nshell returned "));
3971 msg_outnum((long)x);
3972 msg_putchar('\n');
3973 }
3974
3975 if (tmode == TMODE_RAW)
3976 settmode(TMODE_RAW); /* set to raw mode */
3977# ifdef FEAT_TITLE
3978 resettitle();
3979# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003980# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3981 restore_clipboard();
3982# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983 return x;
3984
3985#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3986
Bram Moolenaardf177f62005-02-22 08:39:57 +00003987# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3988 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003989
3990 char_u *newcmd = NULL;
3991 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003992 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 pid_t wait_pid = 0;
3994# ifdef HAVE_UNION_WAIT
3995 union wait status;
3996# else
3997 int status = -1;
3998# endif
3999 int retval = -1;
4000 char **argv = NULL;
4001 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004002 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003 int i;
4004 char_u *p;
4005 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004007# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008 int pty_slave_fd = -1;
4009 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004010# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004011 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 int fd_fromshell[2];
4013 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004014# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004016# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 static char envbuf_Rows[20];
4018 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004020 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021
Bram Moolenaar62b42182010-09-21 22:09:37 +02004022 newcmd = vim_strsave(p_sh);
4023 if (newcmd == NULL) /* out of memory */
4024 goto error;
4025
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026 out_flush();
4027 if (options & SHELL_COOKED)
4028 settmode(TMODE_COOK); /* set to normal mode */
4029
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004030 /*
4031 * Do this loop twice:
4032 * 1: find number of arguments
4033 * 2: separate them and build argv[]
4034 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 for (i = 0; i < 2; ++i)
4036 {
4037 p = newcmd;
4038 inquote = FALSE;
4039 argc = 0;
4040 for (;;)
4041 {
4042 if (i == 1)
4043 argv[argc] = (char *)p;
4044 ++argc;
4045 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4046 {
4047 if (*p == '"')
4048 inquote = !inquote;
4049 ++p;
4050 }
4051 if (*p == NUL)
4052 break;
4053 if (i == 1)
4054 *p++ = NUL;
4055 p = skipwhite(p);
4056 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004057 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004059 /*
4060 * Account for possible multiple args in p_shcf.
4061 */
4062 p = p_shcf;
4063 for (;;)
4064 {
4065 p = skiptowhite(p);
4066 if (*p == NUL)
4067 break;
4068 ++argc;
4069 p = skipwhite(p);
4070 }
4071
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4073 if (argv == NULL) /* out of memory */
4074 goto error;
4075 }
4076 }
4077 if (cmd != NULL)
4078 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004079 char_u *s;
4080
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 if (extra_shell_arg != NULL)
4082 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004083
4084 /* Break 'shellcmdflag' into white separated parts. This doesn't
4085 * handle quoted strings, they are very unlikely to appear. */
4086 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4087 if (p_shcf_copy == NULL) /* out of memory */
4088 goto error;
4089 s = p_shcf_copy;
4090 p = p_shcf;
4091 while (*p != NUL)
4092 {
4093 argv[argc++] = (char *)s;
4094 while (*p && *p != ' ' && *p != TAB)
4095 *s++ = *p++;
4096 *s++ = NUL;
4097 p = skipwhite(p);
4098 }
4099
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 argv[argc++] = (char *)cmd;
4101 }
4102 argv[argc] = NULL;
4103
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004105 * For the GUI, when writing the output into the buffer and when reading
4106 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4107 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004109 if ((options & (SHELL_READ|SHELL_WRITE))
4110# ifdef FEAT_GUI
4111 || (gui.in_use && show_shell_mess)
4112# endif
4113 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004115# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 /*
4117 * Try to open a master pty.
4118 * If this works, open the slave pty.
4119 * If the slave can't be opened, close the master pty.
4120 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004121 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 {
4123 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004124 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004126 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4127 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4128 * adding O_NOCTTY always works when defined. */
4129#ifdef O_NOCTTY
4130 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4131#else
4132 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4133#endif
4134 if (pty_slave_fd < 0)
4135 {
4136 close(pty_master_fd);
4137 pty_master_fd = -1;
4138 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 }
4140 }
4141 /*
4142 * If not opening a pty or it didn't work, try using pipes.
4143 */
4144 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004145# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 {
4147 pipe_error = (pipe(fd_toshell) < 0);
4148 if (!pipe_error) /* pipe create OK */
4149 {
4150 pipe_error = (pipe(fd_fromshell) < 0);
4151 if (pipe_error) /* pipe create failed */
4152 {
4153 close(fd_toshell[0]);
4154 close(fd_toshell[1]);
4155 }
4156 }
4157 if (pipe_error)
4158 {
4159 MSG_PUTS(_("\nCannot create pipes\n"));
4160 out_flush();
4161 }
4162 }
4163 }
4164
4165 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 {
4167# ifdef __BEOS__
4168 beos_cleanup_read_thread();
4169# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004170
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4172 {
4173 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004174 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004176 || (gui.in_use && show_shell_mess)
4177# endif
4178 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004180# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 if (pty_master_fd >= 0) /* close the pseudo tty */
4182 {
4183 close(pty_master_fd);
4184 close(pty_slave_fd);
4185 }
4186 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004187# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 {
4189 close(fd_toshell[0]);
4190 close(fd_toshell[1]);
4191 close(fd_fromshell[0]);
4192 close(fd_fromshell[1]);
4193 }
4194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 }
4196 else if (pid == 0) /* child */
4197 {
4198 reset_signals(); /* handle signals normally */
4199
4200 if (!show_shell_mess || (options & SHELL_EXPAND))
4201 {
4202 int fd;
4203
4204 /*
4205 * Don't want to show any message from the shell. Can't just
4206 * close stdout and stderr though, because some systems will
4207 * break if you try to write to them after that, so we must
4208 * use dup() to replace them with something else -- webb
4209 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4210 * waiting for input.
4211 */
4212 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4213 fclose(stdin);
4214 fclose(stdout);
4215 fclose(stderr);
4216
4217 /*
4218 * If any of these open()'s and dup()'s fail, we just continue
4219 * anyway. It's not fatal, and on most systems it will make
4220 * no difference at all. On a few it will cause the execvp()
4221 * to exit with a non-zero status even when the completion
4222 * could be done, which is nothing too serious. If the open()
4223 * or dup() failed we'd just do the same thing ourselves
4224 * anyway -- webb
4225 */
4226 if (fd >= 0)
4227 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004228 ignored = dup(fd); /* To replace stdin (fd 0) */
4229 ignored = dup(fd); /* To replace stdout (fd 1) */
4230 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231
4232 /* Don't need this now that we've duplicated it */
4233 close(fd);
4234 }
4235 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004236 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004238 || gui.in_use
4239# endif
4240 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 {
4242
Bram Moolenaardf177f62005-02-22 08:39:57 +00004243# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004244 /* Create our own process group, so that the child and all its
4245 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004246 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004247 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004248 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004249 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004250# if defined(SIGHUP)
4251 /* When doing "!xterm&" and 'shell' is bash: the shell
4252 * will exit and send SIGHUP to all processes in its
4253 * group, killing the just started process. Ignore SIGHUP
4254 * to avoid that. (suggested by Simon Schubert)
4255 */
4256 signal(SIGHUP, SIG_IGN);
4257# endif
4258 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004259# endif
4260# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004261 if (pty_slave_fd >= 0)
4262 {
4263 /* push stream discipline modules */
4264 if (options & SHELL_COOKED)
4265 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004267 /* Try to become controlling tty (probably doesn't work,
4268 * unless run by root) */
4269 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004271 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004272# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004274# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 setenv("TERM", "dumb", 1);
4276 sprintf((char *)envbuf, "%ld", Rows);
4277 setenv("ROWS", (char *)envbuf, 1);
4278 sprintf((char *)envbuf, "%ld", Rows);
4279 setenv("LINES", (char *)envbuf, 1);
4280 sprintf((char *)envbuf, "%ld", Columns);
4281 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004282# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 /*
4284 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004285 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 */
4287 putenv("TERM=dumb");
4288 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4289 putenv(envbuf_Rows);
4290 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4291 putenv(envbuf_Rows);
4292 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4293 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004294# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295
Bram Moolenaara5792f52005-11-23 21:25:05 +00004296 /*
4297 * stderr is only redirected when using the GUI, so that a
4298 * program like gpg can still access the terminal to get a
4299 * passphrase using stderr.
4300 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004301# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 if (pty_master_fd >= 0)
4303 {
4304 close(pty_master_fd); /* close master side of pty */
4305
4306 /* set up stdin/stdout/stderr for the child */
4307 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004308 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004310 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004311 if (gui.in_use)
4312 {
4313 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004314 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316
4317 close(pty_slave_fd); /* has been dupped, close it now */
4318 }
4319 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004320# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 {
4322 /* set up stdin for the child */
4323 close(fd_toshell[1]);
4324 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004325 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326 close(fd_toshell[0]);
4327
4328 /* set up stdout for the child */
4329 close(fd_fromshell[0]);
4330 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004331 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332 close(fd_fromshell[1]);
4333
Bram Moolenaara5792f52005-11-23 21:25:05 +00004334# ifdef FEAT_GUI
4335 if (gui.in_use)
4336 {
4337 /* set up stderr for the child */
4338 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004339 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004340 }
4341# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 }
4343 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004344
Bram Moolenaar071d4272004-06-13 20:20:40 +00004345 /*
4346 * There is no type cast for the argv, because the type may be
4347 * different on different machines. This may cause a warning
4348 * message with strict compilers, don't worry about it.
4349 * Call _exit() instead of exit() to avoid closing the connection
4350 * to the X server (esp. with GTK, which uses atexit()).
4351 */
4352 execvp(argv[0], argv);
4353 _exit(EXEC_FAILED); /* exec failed, return failure code */
4354 }
4355 else /* parent */
4356 {
4357 /*
4358 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004359 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 */
4361 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004362 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363
4364 /*
4365 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004366 * This is also used to pipe stdin/stdout to/from the external
4367 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004369 if ((options & (SHELL_READ|SHELL_WRITE))
4370# ifdef FEAT_GUI
4371 || (gui.in_use && show_shell_mess)
4372# endif
4373 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004375# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004377# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004379# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4381 int ta_len = 0; /* valid bytes in ta_buf[] */
4382 int len;
4383 int p_more_save;
4384 int old_State;
4385 int c;
4386 int toshell_fd;
4387 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004388 garray_T ga;
4389 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004390# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4391 struct timeval start_tv;
4392# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393
Bram Moolenaardf177f62005-02-22 08:39:57 +00004394# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395 if (pty_master_fd >= 0)
4396 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397 fromshell_fd = pty_master_fd;
4398 toshell_fd = dup(pty_master_fd);
4399 }
4400 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402 {
4403 close(fd_toshell[0]);
4404 close(fd_fromshell[1]);
4405 toshell_fd = fd_toshell[1];
4406 fromshell_fd = fd_fromshell[0];
4407 }
4408
4409 /*
4410 * Write to the child if there are typed characters.
4411 * Read from the child if there are characters available.
4412 * Repeat the reading a few times if more characters are
4413 * available. Need to check for typed keys now and then, but
4414 * not too often (delays when no chars are available).
4415 * This loop is quit if no characters can be read from the pty
4416 * (WaitForChar detected special condition), or there are no
4417 * characters available and the child has exited.
4418 * Only check if the child has exited when there is no more
4419 * output. The child may exit before all the output has
4420 * been printed.
4421 *
4422 * Currently this busy loops!
4423 * This can probably dead-lock when the write blocks!
4424 */
4425 p_more_save = p_more;
4426 p_more = FALSE;
4427 old_State = State;
4428 State = EXTERNCMD; /* don't redraw at window resize */
4429
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004430 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004431 {
4432 /* Fork a process that will write the lines to the
4433 * external program. */
4434 if ((wpid = fork()) == -1)
4435 {
4436 MSG_PUTS(_("\nCannot fork\n"));
4437 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004438 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004439 {
4440 linenr_T lnum = curbuf->b_op_start.lnum;
4441 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004442 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004443 size_t l;
4444
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004445 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004446 for (;;)
4447 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004448 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004449 if (l == 0)
4450 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004451 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004452 /* NL -> NUL translation */
4453 len = write(toshell_fd, "", (size_t)1);
4454 else
4455 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004456 char_u *s = vim_strchr(lp + written, NL);
4457
Bram Moolenaar89d40322006-08-29 15:30:07 +00004458 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004459 s == NULL ? l
4460 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004461 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004462 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004463 {
4464 /* Finished a line, add a NL, unless this line
4465 * should not have one. */
4466 if (lnum != curbuf->b_op_end.lnum
4467 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004468 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004469 && (lnum !=
4470 curbuf->b_ml.ml_line_count
4471 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004472 ignored = write(toshell_fd, "\n",
4473 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004474 ++lnum;
4475 if (lnum > curbuf->b_op_end.lnum)
4476 {
4477 /* finished all the lines, close pipe */
4478 close(toshell_fd);
4479 toshell_fd = -1;
4480 break;
4481 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004482 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004483 written = 0;
4484 }
4485 else if (len > 0)
4486 written += len;
4487 }
4488 _exit(0);
4489 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004490 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004491 {
4492 close(toshell_fd);
4493 toshell_fd = -1;
4494 }
4495 }
4496
4497 if (options & SHELL_READ)
4498 ga_init2(&ga, 1, BUFLEN);
4499
4500 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004501# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4502 gettimeofday(&start_tv, NULL);
4503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 for (;;)
4505 {
4506 /*
4507 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004508 * if there are any.
4509 * Don't do this if we are expanding wild cards (would eat
4510 * typeahead).
4511 * Don't do this when filtering and terminal is in cooked
4512 * mode, the shell command will handle the I/O. Avoids
4513 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004514 * Don't get characters when the child has already
4515 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004516 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004517 * while (noread_cnt > 4), avoids that ":r !ls" eats
4518 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 */
4520 len = 0;
4521 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004522 && ((options &
4523 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4524 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004525# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004526 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004527# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004528 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004529 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004530 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004532 if (ta_len == 0)
4533 {
4534 /* Get extra characters when we don't have any.
4535 * Reset the counter and timer. */
4536 noread_cnt = 0;
4537# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4538 gettimeofday(&start_tv, NULL);
4539# endif
4540 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4541 }
4542 if (ta_len > 0 || len > 0)
4543 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 /*
4545 * For pipes:
4546 * Check for CTRL-C: send interrupt signal to child.
4547 * Check for CTRL-D: EOF, close pipe to child.
4548 */
4549 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4550 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004551# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 /*
4553 * Send SIGINT to the child's group or all
4554 * processes in our group.
4555 */
4556 if (ta_buf[ta_len] == Ctrl_C
4557 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004558 {
4559# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004561# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004564 if (wpid > 0)
4565 kill(wpid, SIGINT);
4566 }
4567# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 if (pty_master_fd < 0 && toshell_fd >= 0
4569 && ta_buf[ta_len] == Ctrl_D)
4570 {
4571 close(toshell_fd);
4572 toshell_fd = -1;
4573 }
4574 }
4575
4576 /* replace K_BS by <BS> and K_DEL by <DEL> */
4577 for (i = ta_len; i < ta_len + len; ++i)
4578 {
4579 if (ta_buf[i] == CSI && len - i > 2)
4580 {
4581 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4582 if (c == K_DEL || c == K_KDEL || c == K_BS)
4583 {
4584 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4585 (size_t)(len - i - 2));
4586 if (c == K_DEL || c == K_KDEL)
4587 ta_buf[i] = DEL;
4588 else
4589 ta_buf[i] = Ctrl_H;
4590 len -= 2;
4591 }
4592 }
4593 else if (ta_buf[i] == '\r')
4594 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004595# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004597 i += (*mb_ptr2len_len)(ta_buf + i,
4598 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600 }
4601
4602 /*
4603 * For pipes: echo the typed characters.
4604 * For a pty this does not seem to work.
4605 */
4606 if (pty_master_fd < 0)
4607 {
4608 for (i = ta_len; i < ta_len + len; ++i)
4609 {
4610 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4611 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004612# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004613 else if (has_mbyte)
4614 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004615 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616
4617 msg_outtrans_len(ta_buf + i, l);
4618 i += l - 1;
4619 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 else
4622 msg_outtrans_len(ta_buf + i, 1);
4623 }
4624 windgoto(msg_row, msg_col);
4625 out_flush();
4626 }
4627
4628 ta_len += len;
4629
4630 /*
4631 * Write the characters to the child, unless EOF has
4632 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004633 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004634 * When writing buffer lines, drop the typed
4635 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004637 if (options & SHELL_WRITE)
4638 ta_len = 0;
4639 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640 {
4641 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4642 if (len > 0)
4643 {
4644 ta_len -= len;
4645 mch_memmove(ta_buf, ta_buf + len, ta_len);
4646 }
4647 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 }
4650
Bram Moolenaardf177f62005-02-22 08:39:57 +00004651 if (got_int)
4652 {
4653 /* CTRL-C sends a signal to the child, we ignore it
4654 * ourselves */
4655# ifdef HAVE_SETSID
4656 kill(-pid, SIGINT);
4657# else
4658 kill(0, SIGINT);
4659# endif
4660 if (wpid > 0)
4661 kill(wpid, SIGINT);
4662 got_int = FALSE;
4663 }
4664
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665 /*
4666 * Check if the child has any characters to be printed.
4667 * Read them and write them to our window. Repeat this as
4668 * long as there is something to do, avoid the 10ms wait
4669 * for mch_inchar(), or sending typeahead characters to
4670 * the external process.
4671 * TODO: This should handle escape sequences, compatible
4672 * to some terminal (vt52?).
4673 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004674 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4676 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004677 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004678# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004680# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 );
4684 if (len <= 0) /* end of file or error */
4685 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004686
4687 noread_cnt = 0;
4688 if (options & SHELL_READ)
4689 {
4690 /* Do NUL -> NL translation, append NL separated
4691 * lines to the current buffer. */
4692 for (i = 0; i < len; ++i)
4693 {
4694 if (buffer[i] == NL)
4695 append_ga_line(&ga);
4696 else if (buffer[i] == NUL)
4697 ga_append(&ga, NL);
4698 else
4699 ga_append(&ga, buffer[i]);
4700 }
4701 }
4702# ifdef FEAT_MBYTE
4703 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704 {
4705 int l;
4706
Bram Moolenaardf177f62005-02-22 08:39:57 +00004707 len += buffer_off;
4708 buffer[len] = NUL;
4709
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 /* Check if the last character in buffer[] is
4711 * incomplete, keep these bytes for the next
4712 * round. */
4713 for (p = buffer; p < buffer + len; p += l)
4714 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004715 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 if (l == 0)
4717 l = 1; /* NUL byte? */
4718 else if (MB_BYTE2LEN(*p) != l)
4719 break;
4720 }
4721 if (p == buffer) /* no complete character */
4722 {
4723 /* avoid getting stuck at an illegal byte */
4724 if (len >= 12)
4725 ++p;
4726 else
4727 {
4728 buffer_off = len;
4729 continue;
4730 }
4731 }
4732 c = *p;
4733 *p = NUL;
4734 msg_puts(buffer);
4735 if (p < buffer + len)
4736 {
4737 *p = c;
4738 buffer_off = (buffer + len) - p;
4739 mch_memmove(buffer, p, buffer_off);
4740 continue;
4741 }
4742 buffer_off = 0;
4743 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004744# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746 {
4747 buffer[len] = NUL;
4748 msg_puts(buffer);
4749 }
4750
4751 windgoto(msg_row, msg_col);
4752 cursor_on();
4753 out_flush();
4754 if (got_int)
4755 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004756
4757# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4758 {
4759 struct timeval now_tv;
4760 long msec;
4761
4762 /* Avoid that we keep looping here without
4763 * checking for a CTRL-C for a long time. Don't
4764 * break out too often to avoid losing typeahead. */
4765 gettimeofday(&now_tv, NULL);
4766 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4767 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4768 if (msec > 2000)
4769 {
4770 noread_cnt = 5;
4771 break;
4772 }
4773 }
4774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775 }
4776
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004777 /* If we already detected the child has finished break the
4778 * loop now. */
4779 if (wait_pid == pid)
4780 break;
4781
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 /*
4783 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004784 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004786# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004787 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004788# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004789 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004790# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4792 || (wait_pid == pid && WIFEXITED(status)))
4793 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004794 /* Don't break the loop yet, try reading more
4795 * characters from "fromshell_fd" first. When using
4796 * pipes there might still be something to read and
4797 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004800 else
4801 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004802
Bram Moolenaar95a51352013-03-21 22:53:50 +01004803# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004804 /* Handle any X events, e.g. serving the clipboard. */
4805 clip_update();
4806# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 }
4808finished:
4809 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004810 if (options & SHELL_READ)
4811 {
4812 if (ga.ga_len > 0)
4813 {
4814 append_ga_line(&ga);
4815 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004816 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004817 }
4818 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004819 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004820 ga_clear(&ga);
4821 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 /*
4824 * Give all typeahead that wasn't used back to ui_inchar().
4825 */
4826 if (ta_len)
4827 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 State = old_State;
4829 if (toshell_fd >= 0)
4830 close(toshell_fd);
4831 close(fromshell_fd);
4832 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004833# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004834 else
4835 {
4836 /*
4837 * Similar to the loop above, but only handle X events, no
4838 * I/O.
4839 */
4840 for (;;)
4841 {
4842 if (got_int)
4843 {
4844 /* CTRL-C sends a signal to the child, we ignore it
4845 * ourselves */
4846# ifdef HAVE_SETSID
4847 kill(-pid, SIGINT);
4848# else
4849 kill(0, SIGINT);
4850# endif
4851 got_int = FALSE;
4852 }
4853# ifdef __NeXT__
4854 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4855# else
4856 wait_pid = waitpid(pid, &status, WNOHANG);
4857# endif
4858 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4859 || (wait_pid == pid && WIFEXITED(status)))
4860 {
4861 wait_pid = pid;
4862 break;
4863 }
4864
4865 /* Handle any X events, e.g. serving the clipboard. */
4866 clip_update();
4867
4868 mch_delay(10L, TRUE);
4869 }
4870 }
4871# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872
4873 /*
4874 * Wait until our child has exited.
4875 * Ignore wait() returning pids of other children and returning
4876 * because of some signal like SIGWINCH.
4877 * Don't wait if wait_pid was already set above, indicating the
4878 * child already exited.
4879 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004880 if (wait_pid != pid)
4881 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882
Bram Moolenaar624891f2010-10-13 16:22:09 +02004883# ifdef FEAT_GUI
4884 /* Close slave side of pty. Only do this after the child has
4885 * exited, otherwise the child may hang when it tries to write on
4886 * the pty. */
4887 if (pty_master_fd >= 0)
4888 close(pty_slave_fd);
4889# endif
4890
Bram Moolenaardf177f62005-02-22 08:39:57 +00004891 /* Make sure the child that writes to the external program is
4892 * dead. */
4893 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004894 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004895 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004896 wait4pid(wpid, NULL);
4897 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004898
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 /*
4900 * Set to raw mode right now, otherwise a CTRL-C after
4901 * catch_signals() will kill Vim.
4902 */
4903 if (tmode == TMODE_RAW)
4904 settmode(TMODE_RAW);
4905 did_settmode = TRUE;
4906 set_signals();
4907
4908 if (WIFEXITED(status))
4909 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004910 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01004912 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 {
4914 if (retval == EXEC_FAILED)
4915 {
4916 MSG_PUTS(_("\nCannot execute shell "));
4917 msg_outtrans(p_sh);
4918 msg_putchar('\n');
4919 }
4920 else if (!(options & SHELL_SILENT))
4921 {
4922 MSG_PUTS(_("\nshell returned "));
4923 msg_outnum((long)retval);
4924 msg_putchar('\n');
4925 }
4926 }
4927 }
4928 else
4929 MSG_PUTS(_("\nCommand terminated\n"));
4930 }
4931 }
4932 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004933 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934
4935error:
4936 if (!did_settmode)
4937 if (tmode == TMODE_RAW)
4938 settmode(TMODE_RAW); /* set to raw mode */
4939# ifdef FEAT_TITLE
4940 resettitle();
4941# endif
4942 vim_free(newcmd);
4943
4944 return retval;
4945
4946#endif /* USE_SYSTEM */
4947}
4948
4949/*
4950 * Check for CTRL-C typed by reading all available characters.
4951 * In cooked mode we should get SIGINT, no need to check.
4952 */
4953 void
4954mch_breakcheck()
4955{
4956 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4957 fill_input_buf(FALSE);
4958}
4959
4960/*
4961 * Wait "msec" msec until a character is available from the keyboard or from
4962 * inbuf[]. msec == -1 will block forever.
4963 * When a GUI is being used, this will never get called -- webb
4964 */
4965 static int
4966WaitForChar(msec)
4967 long msec;
4968{
4969#ifdef FEAT_MOUSE_GPM
4970 int gpm_process_wanted;
4971#endif
4972#ifdef FEAT_XCLIPBOARD
4973 int rest;
4974#endif
4975 int avail;
4976
4977 if (input_available()) /* something in inbuf[] */
4978 return 1;
4979
4980#if defined(FEAT_MOUSE_DEC)
4981 /* May need to query the mouse position. */
4982 if (WantQueryMouse)
4983 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004984 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4986 }
4987#endif
4988
4989 /*
4990 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4991 * events. This is a bit complicated, because they might both be defined.
4992 */
4993#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4994# ifdef FEAT_XCLIPBOARD
4995 rest = 0;
4996 if (do_xterm_trace())
4997 rest = msec;
4998# endif
4999 do
5000 {
5001# ifdef FEAT_XCLIPBOARD
5002 if (rest != 0)
5003 {
5004 msec = XT_TRACE_DELAY;
5005 if (rest >= 0 && rest < XT_TRACE_DELAY)
5006 msec = rest;
5007 if (rest >= 0)
5008 rest -= msec;
5009 }
5010# endif
5011# ifdef FEAT_MOUSE_GPM
5012 gpm_process_wanted = 0;
5013 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5014# else
5015 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5016# endif
5017 if (!avail)
5018 {
5019 if (input_available())
5020 return 1;
5021# ifdef FEAT_XCLIPBOARD
5022 if (rest == 0 || !do_xterm_trace())
5023# endif
5024 break;
5025 }
5026 }
5027 while (FALSE
5028# ifdef FEAT_MOUSE_GPM
5029 || (gpm_process_wanted && mch_gpm_process() == 0)
5030# endif
5031# ifdef FEAT_XCLIPBOARD
5032 || (!avail && rest != 0)
5033# endif
5034 );
5035
5036#else
5037 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5038#endif
5039 return avail;
5040}
5041
5042/*
5043 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005044 * "msec" == 0 will check for characters once.
5045 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 * When a GUI is being used, this will not be used for input -- webb
5047 * Returns also, when a request from Sniff is waiting -- toni.
5048 * Or when a Linux GPM mouse event is waiting.
5049 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050#if defined(__BEOS__)
5051 int
5052#else
5053 static int
5054#endif
5055RealWaitForChar(fd, msec, check_for_gpm)
5056 int fd;
5057 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005058 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059{
5060 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005061#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005062 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005063#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005064#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065 static int busy = FALSE;
5066
5067 /* May retry getting characters after an event was handled. */
5068# define MAY_LOOP
5069
5070# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5071 /* Remember at what time we started, so that we know how much longer we
5072 * should wait after being interrupted. */
5073# define USE_START_TV
5074 struct timeval start_tv;
5075
5076 if (msec > 0 && (
5077# ifdef FEAT_XCLIPBOARD
5078 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005079# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080 ||
5081# endif
5082# endif
5083# ifdef USE_XSMP
5084 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005085# ifdef FEAT_MZSCHEME
5086 ||
5087# endif
5088# endif
5089# ifdef FEAT_MZSCHEME
5090 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091# endif
5092 ))
5093 gettimeofday(&start_tv, NULL);
5094# endif
5095
5096 /* Handle being called recursively. This may happen for the session
5097 * manager stuff, it may save the file, which does a breakcheck. */
5098 if (busy)
5099 return 0;
5100#endif
5101
5102#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005103 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005104#endif
5105 {
5106#ifdef MAY_LOOP
5107 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005108# ifdef FEAT_MZSCHEME
5109 int mzquantum_used = FALSE;
5110# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111#endif
5112#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005113 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005114 int nfd;
5115# ifdef FEAT_XCLIPBOARD
5116 int xterm_idx = -1;
5117# endif
5118# ifdef FEAT_MOUSE_GPM
5119 int gpm_idx = -1;
5120# endif
5121# ifdef USE_XSMP
5122 int xsmp_idx = -1;
5123# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005124# ifdef FEAT_NETBEANS_INTG
5125 int nb_idx = -1;
5126# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005127 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005129# ifdef FEAT_MZSCHEME
5130 mzvim_check_threads();
5131 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5132 {
5133 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5134 mzquantum_used = TRUE;
5135 }
5136# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137 fds[0].fd = fd;
5138 fds[0].events = POLLIN;
5139 nfd = 1;
5140
5141# ifdef FEAT_SNIFF
5142# define SNIFF_IDX 1
5143 if (want_sniff_request)
5144 {
5145 fds[SNIFF_IDX].fd = fd_from_sniff;
5146 fds[SNIFF_IDX].events = POLLIN;
5147 nfd++;
5148 }
5149# endif
5150# ifdef FEAT_XCLIPBOARD
5151 if (xterm_Shell != (Widget)0)
5152 {
5153 xterm_idx = nfd;
5154 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5155 fds[nfd].events = POLLIN;
5156 nfd++;
5157 }
5158# endif
5159# ifdef FEAT_MOUSE_GPM
5160 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5161 {
5162 gpm_idx = nfd;
5163 fds[nfd].fd = gpm_fd;
5164 fds[nfd].events = POLLIN;
5165 nfd++;
5166 }
5167# endif
5168# ifdef USE_XSMP
5169 if (xsmp_icefd != -1)
5170 {
5171 xsmp_idx = nfd;
5172 fds[nfd].fd = xsmp_icefd;
5173 fds[nfd].events = POLLIN;
5174 nfd++;
5175 }
5176# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005177#ifdef FEAT_NETBEANS_INTG
5178 if (nb_fd != -1)
5179 {
5180 nb_idx = nfd;
5181 fds[nfd].fd = nb_fd;
5182 fds[nfd].events = POLLIN;
5183 nfd++;
5184 }
5185#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005187 ret = poll(fds, nfd, towait);
5188# ifdef FEAT_MZSCHEME
5189 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005190 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005191 finished = FALSE;
5192# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193
5194# ifdef FEAT_SNIFF
5195 if (ret < 0)
5196 sniff_disconnect(1);
5197 else if (want_sniff_request)
5198 {
5199 if (fds[SNIFF_IDX].revents & POLLHUP)
5200 sniff_disconnect(1);
5201 if (fds[SNIFF_IDX].revents & POLLIN)
5202 sniff_request_waiting = 1;
5203 }
5204# endif
5205# ifdef FEAT_XCLIPBOARD
5206 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5207 {
5208 xterm_update(); /* Maybe we should hand out clipboard */
5209 if (--ret == 0 && !input_available())
5210 /* Try again */
5211 finished = FALSE;
5212 }
5213# endif
5214# ifdef FEAT_MOUSE_GPM
5215 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5216 {
5217 *check_for_gpm = 1;
5218 }
5219# endif
5220# ifdef USE_XSMP
5221 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5222 {
5223 if (fds[xsmp_idx].revents & POLLIN)
5224 {
5225 busy = TRUE;
5226 xsmp_handle_requests();
5227 busy = FALSE;
5228 }
5229 else if (fds[xsmp_idx].revents & POLLHUP)
5230 {
5231 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005232 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 xsmp_close();
5234 }
5235 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005236 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 }
5238# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005239#ifdef FEAT_NETBEANS_INTG
5240 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5241 {
5242 netbeans_read();
5243 --ret;
5244 }
5245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246
5247
5248#else /* HAVE_SELECT */
5249
5250 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005251 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252 fd_set rfds, efds;
5253 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005254 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005256# ifdef FEAT_MZSCHEME
5257 mzvim_check_threads();
5258 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5259 {
5260 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5261 mzquantum_used = TRUE;
5262 }
5263# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264# ifdef __EMX__
5265 /* don't check for incoming chars if not in raw mode, because select()
5266 * always returns TRUE then (in some version of emx.dll) */
5267 if (curr_tmode != TMODE_RAW)
5268 return 0;
5269# endif
5270
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005271 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005273 tv.tv_sec = towait / 1000;
5274 tv.tv_usec = (towait % 1000) * (1000000/1000);
5275 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005277 else
5278 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279
5280 /*
5281 * Select on ready for reading and exceptional condition (end of file).
5282 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005283select_eintr:
5284 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285 FD_ZERO(&efds);
5286 FD_SET(fd, &rfds);
5287# if !defined(__QNX__) && !defined(__CYGWIN32__)
5288 /* For QNX select() always returns 1 if this is set. Why? */
5289 FD_SET(fd, &efds);
5290# endif
5291 maxfd = fd;
5292
5293# ifdef FEAT_SNIFF
5294 if (want_sniff_request)
5295 {
5296 FD_SET(fd_from_sniff, &rfds);
5297 FD_SET(fd_from_sniff, &efds);
5298 if (maxfd < fd_from_sniff)
5299 maxfd = fd_from_sniff;
5300 }
5301# endif
5302# ifdef FEAT_XCLIPBOARD
5303 if (xterm_Shell != (Widget)0)
5304 {
5305 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5306 if (maxfd < ConnectionNumber(xterm_dpy))
5307 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005308
5309 /* An event may have already been read but not handled. In
5310 * particulary, XFlush may cause this. */
5311 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312 }
5313# endif
5314# ifdef FEAT_MOUSE_GPM
5315 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5316 {
5317 FD_SET(gpm_fd, &rfds);
5318 FD_SET(gpm_fd, &efds);
5319 if (maxfd < gpm_fd)
5320 maxfd = gpm_fd;
5321 }
5322# endif
5323# ifdef USE_XSMP
5324 if (xsmp_icefd != -1)
5325 {
5326 FD_SET(xsmp_icefd, &rfds);
5327 FD_SET(xsmp_icefd, &efds);
5328 if (maxfd < xsmp_icefd)
5329 maxfd = xsmp_icefd;
5330 }
5331# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005332# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005333 if (nb_fd != -1)
5334 {
5335 FD_SET(nb_fd, &rfds);
5336 if (maxfd < nb_fd)
5337 maxfd = nb_fd;
5338 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005339# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340
5341# ifdef OLD_VMS
5342 /* Old VMS as v6.2 and older have broken select(). It waits more than
5343 * required. Should not be used */
5344 ret = 0;
5345# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005346 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5347# endif
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005348# ifdef EINTR
5349 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005350 {
5351 /* Check whether window has been resized, EINTR may be caused by
5352 * SIGWINCH. */
5353 if (do_resize)
5354 handle_resize();
5355
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005356 /* Interrupted by a signal, need to try again. We ignore msec
5357 * here, because we do want to check even after a timeout if
5358 * characters are available. Needed for reading output of an
5359 * external command after the process has finished. */
5360 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005361 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005362# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005363# ifdef __TANDEM
5364 if (ret == -1 && errno == ENOTSUP)
5365 {
5366 FD_ZERO(&rfds);
5367 FD_ZERO(&efds);
5368 ret = 0;
5369 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005370# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005371# ifdef FEAT_MZSCHEME
5372 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005373 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005374 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375# endif
5376
5377# ifdef FEAT_SNIFF
5378 if (ret < 0 )
5379 sniff_disconnect(1);
5380 else if (ret > 0 && want_sniff_request)
5381 {
5382 if (FD_ISSET(fd_from_sniff, &efds))
5383 sniff_disconnect(1);
5384 if (FD_ISSET(fd_from_sniff, &rfds))
5385 sniff_request_waiting = 1;
5386 }
5387# endif
5388# ifdef FEAT_XCLIPBOARD
5389 if (ret > 0 && xterm_Shell != (Widget)0
5390 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5391 {
5392 xterm_update(); /* Maybe we should hand out clipboard */
5393 /* continue looping when we only got the X event and the input
5394 * buffer is empty */
5395 if (--ret == 0 && !input_available())
5396 {
5397 /* Try again */
5398 finished = FALSE;
5399 }
5400 }
5401# endif
5402# ifdef FEAT_MOUSE_GPM
5403 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5404 {
5405 if (FD_ISSET(gpm_fd, &efds))
5406 gpm_close();
5407 else if (FD_ISSET(gpm_fd, &rfds))
5408 *check_for_gpm = 1;
5409 }
5410# endif
5411# ifdef USE_XSMP
5412 if (ret > 0 && xsmp_icefd != -1)
5413 {
5414 if (FD_ISSET(xsmp_icefd, &efds))
5415 {
5416 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005417 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005418 xsmp_close();
5419 if (--ret == 0)
5420 finished = FALSE; /* keep going if event was only one */
5421 }
5422 else if (FD_ISSET(xsmp_icefd, &rfds))
5423 {
5424 busy = TRUE;
5425 xsmp_handle_requests();
5426 busy = FALSE;
5427 if (--ret == 0)
5428 finished = FALSE; /* keep going if event was only one */
5429 }
5430 }
5431# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005432#ifdef FEAT_NETBEANS_INTG
5433 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5434 {
5435 netbeans_read();
5436 --ret;
5437 }
5438#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439
5440#endif /* HAVE_SELECT */
5441
5442#ifdef MAY_LOOP
5443 if (finished || msec == 0)
5444 break;
5445
5446 /* We're going to loop around again, find out for how long */
5447 if (msec > 0)
5448 {
5449# ifdef USE_START_TV
5450 struct timeval mtv;
5451
5452 /* Compute remaining wait time. */
5453 gettimeofday(&mtv, NULL);
5454 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5455 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5456# else
5457 /* Guess we got interrupted halfway. */
5458 msec = msec / 2;
5459# endif
5460 if (msec <= 0)
5461 break; /* waited long enough */
5462 }
5463#endif
5464 }
5465
5466 return (ret > 0);
5467}
5468
5469#ifndef VMS
5470
5471#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005473 * Expand a path into all matching files and/or directories. Handles "*",
5474 * "?", "[a-z]", "**", etc.
5475 * "path" has backslashes before chars that are not to be expanded.
5476 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477 */
5478 int
5479mch_expandpath(gap, path, flags)
5480 garray_T *gap;
5481 char_u *path;
5482 int flags; /* EW_* flags */
5483{
Bram Moolenaar02743632005-07-25 20:42:36 +00005484 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485}
5486#endif
5487
5488/*
5489 * mch_expand_wildcards() - this code does wild-card pattern matching using
5490 * the shell
5491 *
5492 * return OK for success, FAIL for error (you may lose some memory) and put
5493 * an error message in *file.
5494 *
5495 * num_pat is number of input patterns
5496 * pat is array of pointers to input patterns
5497 * num_file is pointer to number of matched file names
5498 * file is pointer to array of pointers to matched file names
5499 */
5500
5501#ifndef SEEK_SET
5502# define SEEK_SET 0
5503#endif
5504#ifndef SEEK_END
5505# define SEEK_END 2
5506#endif
5507
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005508#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005509
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 int
5511mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5512 int num_pat;
5513 char_u **pat;
5514 int *num_file;
5515 char_u ***file;
5516 int flags; /* EW_* flags */
5517{
5518 int i;
5519 size_t len;
5520 char_u *p;
5521 int dir;
5522#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005523 /*
5524 * This is the OS/2 implementation.
5525 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526# define EXPL_ALLOC_INC 16
5527 char_u **expl_files;
5528 size_t files_alloced, files_free;
5529 char_u *buf;
5530 int has_wildcard;
5531
5532 *num_file = 0; /* default: no files found */
5533 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5534 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5535 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5536 if (*file == NULL)
5537 return FAIL;
5538
5539 for (; num_pat > 0; num_pat--, pat++)
5540 {
5541 expl_files = NULL;
5542 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5543 /* expand environment var or home dir */
5544 buf = expand_env_save(*pat);
5545 else
5546 buf = vim_strsave(*pat);
5547 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005548 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 if (has_wildcard) /* yes, so expand them */
5550 expl_files = (char_u **)_fnexplode(buf);
5551
5552 /*
5553 * return value of buf if no wildcards left,
5554 * OR if no match AND EW_NOTFOUND is set.
5555 */
5556 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5557 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5558 { /* simply save the current contents of *buf */
5559 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5560 if (expl_files != NULL)
5561 {
5562 expl_files[0] = vim_strsave(buf);
5563 expl_files[1] = NULL;
5564 }
5565 }
5566 vim_free(buf);
5567
5568 /*
5569 * Count number of names resulting from expansion,
5570 * At the same time add a backslash to the end of names that happen to
5571 * be directories, and replace slashes with backslashes.
5572 */
5573 if (expl_files)
5574 {
5575 for (i = 0; (p = expl_files[i]) != NULL; i++)
5576 {
5577 dir = mch_isdir(p);
5578 /* If we don't want dirs and this is one, skip it */
5579 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5580 continue;
5581
Bram Moolenaara2031822006-03-07 22:29:51 +00005582 /* Skip files that are not executable if we check for that. */
5583 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5584 continue;
5585
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 if (--files_free == 0)
5587 {
5588 /* need more room in table of pointers */
5589 files_alloced += EXPL_ALLOC_INC;
5590 *file = (char_u **)vim_realloc(*file,
5591 sizeof(char_u **) * files_alloced);
5592 if (*file == NULL)
5593 {
5594 EMSG(_(e_outofmem));
5595 *num_file = 0;
5596 return FAIL;
5597 }
5598 files_free = EXPL_ALLOC_INC;
5599 }
5600 slash_adjust(p);
5601 if (dir)
5602 {
5603 /* For a directory we add a '/', unless it's already
5604 * there. */
5605 len = STRLEN(p);
5606 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5607 {
5608 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005609 if (!after_pathsep((*file)[*num_file],
5610 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611 {
5612 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005613 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 }
5615 }
5616 }
5617 else
5618 {
5619 (*file)[*num_file] = vim_strsave(p);
5620 }
5621
5622 /*
5623 * Error message already given by either alloc or vim_strsave.
5624 * Should return FAIL, but returning OK works also.
5625 */
5626 if ((*file)[*num_file] == NULL)
5627 break;
5628 (*num_file)++;
5629 }
5630 _fnexplodefree((char **)expl_files);
5631 }
5632 }
5633 return OK;
5634
5635#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005636 /*
5637 * This is the non-OS/2 implementation (really Unix).
5638 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 int j;
5640 char_u *tempname;
5641 char_u *command;
5642 FILE *fd;
5643 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005644#define STYLE_ECHO 0 /* use "echo", the default */
5645#define STYLE_GLOB 1 /* use "glob", for csh */
5646#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5647#define STYLE_PRINT 3 /* use "print -N", for zsh */
5648#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5649 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 int shell_style = STYLE_ECHO;
5651 int check_spaces;
5652 static int did_find_nul = FALSE;
5653 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005654 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005655 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656
5657 *num_file = 0; /* default: no files found */
5658 *file = NULL;
5659
5660 /*
5661 * If there are no wildcards, just copy the names to allocated memory.
5662 * Saves a lot of time, because we don't have to start a new shell.
5663 */
5664 if (!have_wildcard(num_pat, pat))
5665 return save_patterns(num_pat, pat, num_file, file);
5666
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005667# ifdef HAVE_SANDBOX
5668 /* Don't allow any shell command in the sandbox. */
5669 if (sandbox != 0 && check_secure())
5670 return FAIL;
5671# endif
5672
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 /*
5674 * Don't allow the use of backticks in secure and restricted mode.
5675 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005676 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677 for (i = 0; i < num_pat; ++i)
5678 if (vim_strchr(pat[i], '`') != NULL
5679 && (check_restricted() || check_secure()))
5680 return FAIL;
5681
5682 /*
5683 * get a name for the temp file
5684 */
5685 if ((tempname = vim_tempname('o')) == NULL)
5686 {
5687 EMSG(_(e_notmp));
5688 return FAIL;
5689 }
5690
5691 /*
5692 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005693 * file.
5694 * STYLE_BT: NL separated
5695 * If expanding `cmd` execute it directly.
5696 * STYLE_GLOB: NUL separated
5697 * If we use *csh, "glob" will work better than "echo".
5698 * STYLE_PRINT: NL or NUL separated
5699 * If we use *zsh, "print -N" will work better than "glob".
5700 * STYLE_VIMGLOB: NL separated
5701 * If we use *sh*, we define "vimglob()".
5702 * STYLE_ECHO: space separated.
5703 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 */
5705 if (num_pat == 1 && *pat[0] == '`'
5706 && (len = STRLEN(pat[0])) > 2
5707 && *(pat[0] + len - 1) == '`')
5708 shell_style = STYLE_BT;
5709 else if ((len = STRLEN(p_sh)) >= 3)
5710 {
5711 if (STRCMP(p_sh + len - 3, "csh") == 0)
5712 shell_style = STYLE_GLOB;
5713 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5714 shell_style = STYLE_PRINT;
5715 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005716 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5717 "sh") != NULL)
5718 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719
Bram Moolenaarc7247912008-01-13 12:54:11 +00005720 /* Compute the length of the command. We need 2 extra bytes: for the
5721 * optional '&' and for the NUL.
5722 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005724 if (shell_style == STYLE_VIMGLOB)
5725 len += STRLEN(sh_vimglob_func);
5726
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005727 for (i = 0; i < num_pat; ++i)
5728 {
5729 /* Count the length of the patterns in the same way as they are put in
5730 * "command" below. */
5731#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005733#else
5734 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005735 for (j = 0; pat[i][j] != NUL; ++j)
5736 {
5737 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5738 ++len; /* may add a backslash */
5739 ++len;
5740 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005741#endif
5742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743 command = alloc(len);
5744 if (command == NULL)
5745 {
5746 /* out of memory */
5747 vim_free(tempname);
5748 return FAIL;
5749 }
5750
5751 /*
5752 * Build the shell command:
5753 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5754 * recognizes this).
5755 * - Add the shell command to print the expanded names.
5756 * - Add the temp file name.
5757 * - Add the file name patterns.
5758 */
5759 if (shell_style == STYLE_BT)
5760 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005761 /* change `command; command& ` to (command; command ) */
5762 STRCPY(command, "(");
5763 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005765 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 while (p > command && vim_iswhite(*p))
5767 --p;
5768 if (*p == '&') /* remove trailing '&' */
5769 {
5770 ampersent = TRUE;
5771 *p = ' ';
5772 }
5773 STRCAT(command, ">");
5774 }
5775 else
5776 {
5777 if (flags & EW_NOTFOUND)
5778 STRCPY(command, "set nonomatch; ");
5779 else
5780 STRCPY(command, "unset nonomatch; ");
5781 if (shell_style == STYLE_GLOB)
5782 STRCAT(command, "glob >");
5783 else if (shell_style == STYLE_PRINT)
5784 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005785 else if (shell_style == STYLE_VIMGLOB)
5786 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 else
5788 STRCAT(command, "echo >");
5789 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005790
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005792
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 if (shell_style != STYLE_BT)
5794 for (i = 0; i < num_pat; ++i)
5795 {
5796 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005797 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005798 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799#ifdef USE_SYSTEM
5800 STRCAT(command, " \"");
5801 STRCAT(command, pat[i]);
5802 STRCAT(command, "\"");
5803#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005804 int intick = FALSE;
5805
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 p = command + STRLEN(command);
5807 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005808 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005809 {
5810 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005811 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005812 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5813 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005814 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005815 * backslash inside backticks, before a special character
5816 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005817 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005818 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5819 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005820 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005821 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005822 }
5823 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005824 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005825 /* Put a backslash before a special character, but not
5826 * when inside ``. */
5827 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005828
5829 /* Copy one character. */
5830 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 *p = NUL;
5833#endif
5834 }
5835 if (flags & EW_SILENT)
5836 show_shell_mess = FALSE;
5837 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005838 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839
5840 /*
5841 * Using zsh -G: If a pattern has no matches, it is just deleted from
5842 * the argument list, otherwise zsh gives an error message and doesn't
5843 * expand any other pattern.
5844 */
5845 if (shell_style == STYLE_PRINT)
5846 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5847
5848 /*
5849 * If we use -f then shell variables set in .cshrc won't get expanded.
5850 * vi can do it, so we will too, but it is only necessary if there is a "$"
5851 * in one of the patterns, otherwise we can still use the fast option.
5852 */
5853 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5854 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5855
5856 /*
5857 * execute the shell command
5858 */
5859 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5860
5861 /* When running in the background, give it some time to create the temp
5862 * file, but don't wait for it to finish. */
5863 if (ampersent)
5864 mch_delay(10L, TRUE);
5865
5866 extra_shell_arg = NULL; /* cleanup */
5867 show_shell_mess = TRUE;
5868 vim_free(command);
5869
Bram Moolenaarc7247912008-01-13 12:54:11 +00005870 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871 {
5872 mch_remove(tempname);
5873 vim_free(tempname);
5874 /*
5875 * With interactive completion, the error message is not printed.
5876 * However with USE_SYSTEM, I don't know how to turn off error messages
5877 * from the shell, so screen may still get messed up -- webb.
5878 */
5879#ifndef USE_SYSTEM
5880 if (!(flags & EW_SILENT))
5881#endif
5882 {
5883 redraw_later_clear(); /* probably messed up screen */
5884 msg_putchar('\n'); /* clear bottom line quickly */
5885 cmdline_row = Rows - 1; /* continue on last line */
5886#ifdef USE_SYSTEM
5887 if (!(flags & EW_SILENT))
5888#endif
5889 {
5890 MSG(_(e_wildexpand));
5891 msg_start(); /* don't overwrite this message */
5892 }
5893 }
5894 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5895 * EW_NOTFOUND is given */
5896 if (shell_style == STYLE_BT)
5897 return FAIL;
5898 goto notfound;
5899 }
5900
5901 /*
5902 * read the names from the file into memory
5903 */
5904 fd = fopen((char *)tempname, READBIN);
5905 if (fd == NULL)
5906 {
5907 /* Something went wrong, perhaps a file name with a special char. */
5908 if (!(flags & EW_SILENT))
5909 {
5910 MSG(_(e_wildexpand));
5911 msg_start(); /* don't overwrite this message */
5912 }
5913 vim_free(tempname);
5914 goto notfound;
5915 }
5916 fseek(fd, 0L, SEEK_END);
5917 len = ftell(fd); /* get size of temp file */
5918 fseek(fd, 0L, SEEK_SET);
5919 buffer = alloc(len + 1);
5920 if (buffer == NULL)
5921 {
5922 /* out of memory */
5923 mch_remove(tempname);
5924 vim_free(tempname);
5925 fclose(fd);
5926 return FAIL;
5927 }
5928 i = fread((char *)buffer, 1, len, fd);
5929 fclose(fd);
5930 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005931 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 {
5933 /* unexpected read error */
5934 EMSG2(_(e_notread), tempname);
5935 vim_free(tempname);
5936 vim_free(buffer);
5937 return FAIL;
5938 }
5939 vim_free(tempname);
5940
Bram Moolenaarc7247912008-01-13 12:54:11 +00005941# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5943 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02005944 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5946 *p++ = buffer[i];
5947 len = p - buffer;
5948# endif
5949
5950
5951 /* file names are separated with Space */
5952 if (shell_style == STYLE_ECHO)
5953 {
5954 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5955 p = buffer;
5956 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5957 {
5958 while (*p != ' ' && *p != '\n')
5959 ++p;
5960 p = skipwhite(p); /* skip to next entry */
5961 }
5962 }
5963 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005964 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965 {
5966 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5967 p = buffer;
5968 for (i = 0; *p != NUL; ++i) /* count number of entries */
5969 {
5970 while (*p != '\n' && *p != NUL)
5971 ++p;
5972 if (*p != NUL)
5973 ++p;
5974 p = skipwhite(p); /* skip leading white space */
5975 }
5976 }
5977 /* file names are separated with NUL */
5978 else
5979 {
5980 /*
5981 * Some versions of zsh use spaces instead of NULs to separate
5982 * results. Only do this when there is no NUL before the end of the
5983 * buffer, otherwise we would never be able to use file names with
5984 * embedded spaces when zsh does use NULs.
5985 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5986 * don't check for spaces again.
5987 */
5988 check_spaces = FALSE;
5989 if (shell_style == STYLE_PRINT && !did_find_nul)
5990 {
5991 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005992 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005993 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005994 did_find_nul = TRUE;
5995 else
5996 check_spaces = TRUE;
5997 }
5998
5999 /*
6000 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6001 * already is one, for STYLE_GLOB it needs to be added.
6002 */
6003 if (len && buffer[len - 1] == NUL)
6004 --len;
6005 else
6006 buffer[len] = NUL;
6007 i = 0;
6008 for (p = buffer; p < buffer + len; ++p)
6009 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6010 {
6011 ++i;
6012 *p = NUL;
6013 }
6014 if (len)
6015 ++i; /* count last entry */
6016 }
6017 if (i == 0)
6018 {
6019 /*
6020 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6021 * /bin/sh will happily expand it to nothing rather than returning an
6022 * error; and hey, it's good to check anyway -- webb.
6023 */
6024 vim_free(buffer);
6025 goto notfound;
6026 }
6027 *num_file = i;
6028 *file = (char_u **)alloc(sizeof(char_u *) * i);
6029 if (*file == NULL)
6030 {
6031 /* out of memory */
6032 vim_free(buffer);
6033 return FAIL;
6034 }
6035
6036 /*
6037 * Isolate the individual file names.
6038 */
6039 p = buffer;
6040 for (i = 0; i < *num_file; ++i)
6041 {
6042 (*file)[i] = p;
6043 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006044 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6045 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006047 while (!(shell_style == STYLE_ECHO && *p == ' ')
6048 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 ++p;
6050 if (p == buffer + len) /* last entry */
6051 *p = NUL;
6052 else
6053 {
6054 *p++ = NUL;
6055 p = skipwhite(p); /* skip to next entry */
6056 }
6057 }
6058 else /* NUL separates */
6059 {
6060 while (*p && p < buffer + len) /* skip entry */
6061 ++p;
6062 ++p; /* skip NUL */
6063 }
6064 }
6065
6066 /*
6067 * Move the file names to allocated memory.
6068 */
6069 for (j = 0, i = 0; i < *num_file; ++i)
6070 {
6071 /* Require the files to exist. Helps when using /bin/sh */
6072 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6073 continue;
6074
6075 /* check if this entry should be included */
6076 dir = (mch_isdir((*file)[i]));
6077 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6078 continue;
6079
Bram Moolenaara2031822006-03-07 22:29:51 +00006080 /* Skip files that are not executable if we check for that. */
6081 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
6082 continue;
6083
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6085 if (p)
6086 {
6087 STRCPY(p, (*file)[i]);
6088 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006089 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090 (*file)[j++] = p;
6091 }
6092 }
6093 vim_free(buffer);
6094 *num_file = j;
6095
6096 if (*num_file == 0) /* rejected all entries */
6097 {
6098 vim_free(*file);
6099 *file = NULL;
6100 goto notfound;
6101 }
6102
6103 return OK;
6104
6105notfound:
6106 if (flags & EW_NOTFOUND)
6107 return save_patterns(num_pat, pat, num_file, file);
6108 return FAIL;
6109
6110#endif /* __EMX__ */
6111}
6112
6113#endif /* VMS */
6114
6115#ifndef __EMX__
6116 static int
6117save_patterns(num_pat, pat, num_file, file)
6118 int num_pat;
6119 char_u **pat;
6120 int *num_file;
6121 char_u ***file;
6122{
6123 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006124 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125
6126 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6127 if (*file == NULL)
6128 return FAIL;
6129 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006130 {
6131 s = vim_strsave(pat[i]);
6132 if (s != NULL)
6133 /* Be compatible with expand_filename(): halve the number of
6134 * backslashes. */
6135 backslash_halve(s);
6136 (*file)[i] = s;
6137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 *num_file = num_pat;
6139 return OK;
6140}
6141#endif
6142
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143/*
6144 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6145 * expand.
6146 */
6147 int
6148mch_has_exp_wildcard(p)
6149 char_u *p;
6150{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006151 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 {
6153#ifndef OS2
6154 if (*p == '\\' && p[1] != NUL)
6155 ++p;
6156 else
6157#endif
6158 if (vim_strchr((char_u *)
6159#ifdef VMS
6160 "*?%"
6161#else
6162# ifdef OS2
6163 "*?"
6164# else
6165 "*?[{'"
6166# endif
6167#endif
6168 , *p) != NULL)
6169 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 }
6171 return FALSE;
6172}
6173
6174/*
6175 * Return TRUE if the string "p" contains a wildcard.
6176 * Don't recognize '~' at the end as a wildcard.
6177 */
6178 int
6179mch_has_wildcard(p)
6180 char_u *p;
6181{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006182 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 {
6184#ifndef OS2
6185 if (*p == '\\' && p[1] != NUL)
6186 ++p;
6187 else
6188#endif
6189 if (vim_strchr((char_u *)
6190#ifdef VMS
6191 "*?%$"
6192#else
6193# ifdef OS2
6194# ifdef VIM_BACKTICK
6195 "*?$`"
6196# else
6197 "*?$"
6198# endif
6199# else
6200 "*?[{`'$"
6201# endif
6202#endif
6203 , *p) != NULL
6204 || (*p == '~' && p[1] != NUL))
6205 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 }
6207 return FALSE;
6208}
6209
6210#ifndef __EMX__
6211 static int
6212have_wildcard(num, file)
6213 int num;
6214 char_u **file;
6215{
6216 int i;
6217
6218 for (i = 0; i < num; i++)
6219 if (mch_has_wildcard(file[i]))
6220 return 1;
6221 return 0;
6222}
6223
6224 static int
6225have_dollars(num, file)
6226 int num;
6227 char_u **file;
6228{
6229 int i;
6230
6231 for (i = 0; i < num; i++)
6232 if (vim_strchr(file[i], '$') != NULL)
6233 return TRUE;
6234 return FALSE;
6235}
6236#endif /* ifndef __EMX__ */
6237
6238#ifndef HAVE_RENAME
6239/*
6240 * Scaled-down version of rename(), which is missing in Xenix.
6241 * This version can only move regular files and will fail if the
6242 * destination exists.
6243 */
6244 int
6245mch_rename(src, dest)
6246 const char *src, *dest;
6247{
6248 struct stat st;
6249
6250 if (stat(dest, &st) >= 0) /* fail if destination exists */
6251 return -1;
6252 if (link(src, dest) != 0) /* link file to new name */
6253 return -1;
6254 if (mch_remove(src) == 0) /* delete link to old name */
6255 return 0;
6256 return -1;
6257}
6258#endif /* !HAVE_RENAME */
6259
6260#ifdef FEAT_MOUSE_GPM
6261/*
6262 * Initializes connection with gpm (if it isn't already opened)
6263 * Return 1 if succeeded (or connection already opened), 0 if failed
6264 */
6265 static int
6266gpm_open()
6267{
6268 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6269
6270 if (!gpm_flag)
6271 {
6272 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6273 gpm_connect.defaultMask = ~GPM_HARD;
6274 /* Default handling for mouse move*/
6275 gpm_connect.minMod = 0; /* Handle any modifier keys */
6276 gpm_connect.maxMod = 0xffff;
6277 if (Gpm_Open(&gpm_connect, 0) > 0)
6278 {
6279 /* gpm library tries to handling TSTP causes
6280 * problems. Anyways, we close connection to Gpm whenever
6281 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006282 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006284# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006286# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 return 1; /* succeed */
6288 }
6289 if (gpm_fd == -2)
6290 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6291 return 0;
6292 }
6293 return 1; /* already open */
6294}
6295
6296/*
6297 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 */
6299 static void
6300gpm_close()
6301{
6302 if (gpm_flag && gpm_fd >= 0) /* if Open */
6303 Gpm_Close();
6304}
6305
6306/* Reads gpm event and adds special keys to input buf. Returns length of
6307 * generated key sequence.
6308 * This function is made after gui_send_mouse_event
6309 */
6310 static int
6311mch_gpm_process()
6312{
6313 int button;
6314 static Gpm_Event gpm_event;
6315 char_u string[6];
6316 int_u vim_modifiers;
6317 int row,col;
6318 unsigned char buttons_mask;
6319 unsigned char gpm_modifiers;
6320 static unsigned char old_buttons = 0;
6321
6322 Gpm_GetEvent(&gpm_event);
6323
6324#ifdef FEAT_GUI
6325 /* Don't put events in the input queue now. */
6326 if (hold_gui_events)
6327 return 0;
6328#endif
6329
6330 row = gpm_event.y - 1;
6331 col = gpm_event.x - 1;
6332
6333 string[0] = ESC; /* Our termcode */
6334 string[1] = 'M';
6335 string[2] = 'G';
6336 switch (GPM_BARE_EVENTS(gpm_event.type))
6337 {
6338 case GPM_DRAG:
6339 string[3] = MOUSE_DRAG;
6340 break;
6341 case GPM_DOWN:
6342 buttons_mask = gpm_event.buttons & ~old_buttons;
6343 old_buttons = gpm_event.buttons;
6344 switch (buttons_mask)
6345 {
6346 case GPM_B_LEFT:
6347 button = MOUSE_LEFT;
6348 break;
6349 case GPM_B_MIDDLE:
6350 button = MOUSE_MIDDLE;
6351 break;
6352 case GPM_B_RIGHT:
6353 button = MOUSE_RIGHT;
6354 break;
6355 default:
6356 return 0;
6357 /*Don't know what to do. Can more than one button be
6358 * reported in one event? */
6359 }
6360 string[3] = (char_u)(button | 0x20);
6361 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6362 break;
6363 case GPM_UP:
6364 string[3] = MOUSE_RELEASE;
6365 old_buttons &= ~gpm_event.buttons;
6366 break;
6367 default:
6368 return 0;
6369 }
6370 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6371 gpm_modifiers = gpm_event.modifiers;
6372 vim_modifiers = 0x0;
6373 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6374 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6375 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6376 */
6377 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6378 vim_modifiers |= MOUSE_SHIFT;
6379
6380 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6381 vim_modifiers |= MOUSE_CTRL;
6382 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6383 vim_modifiers |= MOUSE_ALT;
6384 string[3] |= vim_modifiers;
6385 string[4] = (char_u)(col + ' ' + 1);
6386 string[5] = (char_u)(row + ' ' + 1);
6387 add_to_input_buf(string, 6);
6388 return 6;
6389}
6390#endif /* FEAT_MOUSE_GPM */
6391
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006392#ifdef FEAT_SYSMOUSE
6393/*
6394 * Initialize connection with sysmouse.
6395 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6396 * output, any sysmouse output than will be processed via sig_sysmouse().
6397 * Return OK if succeeded, FAIL if failed.
6398 */
6399 static int
6400sysmouse_open()
6401{
6402 struct mouse_info mouse;
6403
6404 mouse.operation = MOUSE_MODE;
6405 mouse.u.mode.mode = 0;
6406 mouse.u.mode.signal = SIGUSR2;
6407 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6408 {
6409 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6410 mouse.operation = MOUSE_SHOW;
6411 ioctl(1, CONS_MOUSECTL, &mouse);
6412 return OK;
6413 }
6414 return FAIL;
6415}
6416
6417/*
6418 * Stop processing SIGUSR2 signals, and also make sure that
6419 * virtual console do not send us any sysmouse related signal.
6420 */
6421 static void
6422sysmouse_close()
6423{
6424 struct mouse_info mouse;
6425
6426 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6427 mouse.operation = MOUSE_MODE;
6428 mouse.u.mode.mode = 0;
6429 mouse.u.mode.signal = 0;
6430 ioctl(1, CONS_MOUSECTL, &mouse);
6431}
6432
6433/*
6434 * Gets info from sysmouse and adds special keys to input buf.
6435 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006436 static RETSIGTYPE
6437sig_sysmouse SIGDEFARG(sigarg)
6438{
6439 struct mouse_info mouse;
6440 struct video_info video;
6441 char_u string[6];
6442 int row, col;
6443 int button;
6444 int buttons;
6445 static int oldbuttons = 0;
6446
6447#ifdef FEAT_GUI
6448 /* Don't put events in the input queue now. */
6449 if (hold_gui_events)
6450 return;
6451#endif
6452
6453 mouse.operation = MOUSE_GETINFO;
6454 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6455 && ioctl(1, FBIO_MODEINFO, &video) != -1
6456 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6457 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6458 {
6459 row = mouse.u.data.y / video.vi_cheight;
6460 col = mouse.u.data.x / video.vi_cwidth;
6461 buttons = mouse.u.data.buttons;
6462 string[0] = ESC; /* Our termcode */
6463 string[1] = 'M';
6464 string[2] = 'S';
6465 if (oldbuttons == buttons && buttons != 0)
6466 {
6467 button = MOUSE_DRAG;
6468 }
6469 else
6470 {
6471 switch (buttons)
6472 {
6473 case 0:
6474 button = MOUSE_RELEASE;
6475 break;
6476 case 1:
6477 button = MOUSE_LEFT;
6478 break;
6479 case 2:
6480 button = MOUSE_MIDDLE;
6481 break;
6482 case 4:
6483 button = MOUSE_RIGHT;
6484 break;
6485 default:
6486 return;
6487 }
6488 oldbuttons = buttons;
6489 }
6490 string[3] = (char_u)(button);
6491 string[4] = (char_u)(col + ' ' + 1);
6492 string[5] = (char_u)(row + ' ' + 1);
6493 add_to_input_buf(string, 6);
6494 }
6495 return;
6496}
6497#endif /* FEAT_SYSMOUSE */
6498
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499#if defined(FEAT_LIBCALL) || defined(PROTO)
6500typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6501typedef char_u * (*INTPROCSTR)__ARGS((int));
6502typedef int (*STRPROCINT)__ARGS((char_u *));
6503typedef int (*INTPROCINT)__ARGS((int));
6504
6505/*
6506 * Call a DLL routine which takes either a string or int param
6507 * and returns an allocated string.
6508 */
6509 int
6510mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6511 char_u *libname;
6512 char_u *funcname;
6513 char_u *argstring; /* NULL when using a argint */
6514 int argint;
6515 char_u **string_result;/* NULL when using number_result */
6516 int *number_result;
6517{
6518# if defined(USE_DLOPEN)
6519 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006520 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521# else
6522 shl_t hinstLib;
6523# endif
6524 STRPROCSTR ProcAdd;
6525 INTPROCSTR ProcAddI;
6526 char_u *retval_str = NULL;
6527 int retval_int = 0;
6528 int success = FALSE;
6529
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006530 /*
6531 * Get a handle to the DLL module.
6532 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006534 /* First clear any error, it's not cleared by the dlopen() call. */
6535 (void)dlerror();
6536
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 hinstLib = dlopen((char *)libname, RTLD_LAZY
6538# ifdef RTLD_LOCAL
6539 | RTLD_LOCAL
6540# endif
6541 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006542 if (hinstLib == NULL)
6543 {
6544 /* "dlerr" must be used before dlclose() */
6545 dlerr = (char *)dlerror();
6546 if (dlerr != NULL)
6547 EMSG2(_("dlerror = \"%s\""), dlerr);
6548 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549# else
6550 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6551# endif
6552
6553 /* If the handle is valid, try to get the function address. */
6554 if (hinstLib != NULL)
6555 {
6556# ifdef HAVE_SETJMP_H
6557 /*
6558 * Catch a crash when calling the library function. For example when
6559 * using a number where a string pointer is expected.
6560 */
6561 mch_startjmp();
6562 if (SETJMP(lc_jump_env) != 0)
6563 {
6564 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006565# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006566 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006567# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 mch_didjmp();
6569 }
6570 else
6571# endif
6572 {
6573 retval_str = NULL;
6574 retval_int = 0;
6575
6576 if (argstring != NULL)
6577 {
6578# if defined(USE_DLOPEN)
6579 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006580 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581# else
6582 if (shl_findsym(&hinstLib, (const char *)funcname,
6583 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6584 ProcAdd = NULL;
6585# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006586 if ((success = (ProcAdd != NULL
6587# if defined(USE_DLOPEN)
6588 && dlerr == NULL
6589# endif
6590 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 {
6592 if (string_result == NULL)
6593 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6594 else
6595 retval_str = (ProcAdd)(argstring);
6596 }
6597 }
6598 else
6599 {
6600# if defined(USE_DLOPEN)
6601 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006602 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603# else
6604 if (shl_findsym(&hinstLib, (const char *)funcname,
6605 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6606 ProcAddI = NULL;
6607# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006608 if ((success = (ProcAddI != NULL
6609# if defined(USE_DLOPEN)
6610 && dlerr == NULL
6611# endif
6612 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 {
6614 if (string_result == NULL)
6615 retval_int = ((INTPROCINT)ProcAddI)(argint);
6616 else
6617 retval_str = (ProcAddI)(argint);
6618 }
6619 }
6620
6621 /* Save the string before we free the library. */
6622 /* Assume that a "1" or "-1" result is an illegal pointer. */
6623 if (string_result == NULL)
6624 *number_result = retval_int;
6625 else if (retval_str != NULL
6626 && retval_str != (char_u *)1
6627 && retval_str != (char_u *)-1)
6628 *string_result = vim_strsave(retval_str);
6629 }
6630
6631# ifdef HAVE_SETJMP_H
6632 mch_endjmp();
6633# ifdef SIGHASARG
6634 if (lc_signal != 0)
6635 {
6636 int i;
6637
6638 /* try to find the name of this signal */
6639 for (i = 0; signal_info[i].sig != -1; i++)
6640 if (lc_signal == signal_info[i].sig)
6641 break;
6642 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6643 }
6644# endif
6645# endif
6646
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006648 /* "dlerr" must be used before dlclose() */
6649 if (dlerr != NULL)
6650 EMSG2(_("dlerror = \"%s\""), dlerr);
6651
6652 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 (void)dlclose(hinstLib);
6654# else
6655 (void)shl_unload(hinstLib);
6656# endif
6657 }
6658
6659 if (!success)
6660 {
6661 EMSG2(_(e_libcall), funcname);
6662 return FAIL;
6663 }
6664
6665 return OK;
6666}
6667#endif
6668
6669#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6670static int xterm_trace = -1; /* default: disabled */
6671static int xterm_button;
6672
6673/*
6674 * Setup a dummy window for X selections in a terminal.
6675 */
6676 void
6677setup_term_clip()
6678{
6679 int z = 0;
6680 char *strp = "";
6681 Widget AppShell;
6682
6683 if (!x_connect_to_server())
6684 return;
6685
6686 open_app_context();
6687 if (app_context != NULL && xterm_Shell == (Widget)0)
6688 {
6689 int (*oldhandler)();
6690#if defined(HAVE_SETJMP_H)
6691 int (*oldIOhandler)();
6692#endif
6693# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6694 struct timeval start_tv;
6695
6696 if (p_verbose > 0)
6697 gettimeofday(&start_tv, NULL);
6698# endif
6699
6700 /* Ignore X errors while opening the display */
6701 oldhandler = XSetErrorHandler(x_error_check);
6702
6703#if defined(HAVE_SETJMP_H)
6704 /* Ignore X IO errors while opening the display */
6705 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6706 mch_startjmp();
6707 if (SETJMP(lc_jump_env) != 0)
6708 {
6709 mch_didjmp();
6710 xterm_dpy = NULL;
6711 }
6712 else
6713#endif
6714 {
6715 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6716 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6717#if defined(HAVE_SETJMP_H)
6718 mch_endjmp();
6719#endif
6720 }
6721
6722#if defined(HAVE_SETJMP_H)
6723 /* Now handle X IO errors normally. */
6724 (void)XSetIOErrorHandler(oldIOhandler);
6725#endif
6726 /* Now handle X errors normally. */
6727 (void)XSetErrorHandler(oldhandler);
6728
6729 if (xterm_dpy == NULL)
6730 {
6731 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006732 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 return;
6734 }
6735
6736 /* Catch terminating error of the X server connection. */
6737 (void)XSetIOErrorHandler(x_IOerror_handler);
6738
6739# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6740 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006741 {
6742 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006744 verbose_leave();
6745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746# endif
6747
6748 /* Create a Shell to make converters work. */
6749 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6750 applicationShellWidgetClass, xterm_dpy,
6751 NULL);
6752 if (AppShell == (Widget)0)
6753 return;
6754 xterm_Shell = XtVaCreatePopupShell("VIM",
6755 topLevelShellWidgetClass, AppShell,
6756 XtNmappedWhenManaged, 0,
6757 XtNwidth, 1,
6758 XtNheight, 1,
6759 NULL);
6760 if (xterm_Shell == (Widget)0)
6761 return;
6762
6763 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006764 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 if (x11_display == NULL)
6766 x11_display = xterm_dpy;
6767
6768 XtRealizeWidget(xterm_Shell);
6769 XSync(xterm_dpy, False);
6770 xterm_update();
6771 }
6772 if (xterm_Shell != (Widget)0)
6773 {
6774 clip_init(TRUE);
6775 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6776 x11_window = (Window)atol(strp);
6777 /* Check if $WINDOWID is valid. */
6778 if (test_x11_window(xterm_dpy) == FAIL)
6779 x11_window = 0;
6780 if (x11_window != 0)
6781 xterm_trace = 0;
6782 }
6783}
6784
6785 void
6786start_xterm_trace(button)
6787 int button;
6788{
6789 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6790 return;
6791 xterm_trace = 1;
6792 xterm_button = button;
6793 do_xterm_trace();
6794}
6795
6796
6797 void
6798stop_xterm_trace()
6799{
6800 if (xterm_trace < 0)
6801 return;
6802 xterm_trace = 0;
6803}
6804
6805/*
6806 * Query the xterm pointer and generate mouse termcodes if necessary
6807 * return TRUE if dragging is active, else FALSE
6808 */
6809 static int
6810do_xterm_trace()
6811{
6812 Window root, child;
6813 int root_x, root_y;
6814 int win_x, win_y;
6815 int row, col;
6816 int_u mask_return;
6817 char_u buf[50];
6818 char_u *strp;
6819 long got_hints;
6820 static char_u *mouse_code;
6821 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6822 static int prev_row = 0, prev_col = 0;
6823 static XSizeHints xterm_hints;
6824
6825 if (xterm_trace <= 0)
6826 return FALSE;
6827
6828 if (xterm_trace == 1)
6829 {
6830 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006831 * have changed recently. */
6832 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6833 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 || xterm_hints.width_inc <= 1
6835 || xterm_hints.height_inc <= 1)
6836 {
6837 xterm_trace = -1; /* Not enough data -- disable tracing */
6838 return FALSE;
6839 }
6840
6841 /* Rely on the same mouse code for the duration of this */
6842 mouse_code = find_termcode(mouse_name);
6843 prev_row = mouse_row;
6844 prev_row = mouse_col;
6845 xterm_trace = 2;
6846
6847 /* Find the offset of the chars, there might be a scrollbar on the
6848 * left of the window and/or a menu on the top (eterm etc.) */
6849 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6850 &win_x, &win_y, &mask_return);
6851 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6852 - (xterm_hints.height_inc / 2);
6853 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6854 xterm_hints.y = 2;
6855 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6856 - (xterm_hints.width_inc / 2);
6857 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6858 xterm_hints.x = 2;
6859 return TRUE;
6860 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006861 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 {
6863 xterm_trace = 0;
6864 return FALSE;
6865 }
6866
6867 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6868 &win_x, &win_y, &mask_return);
6869
6870 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6871 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6872 if (row == prev_row && col == prev_col)
6873 return TRUE;
6874
6875 STRCPY(buf, mouse_code);
6876 strp = buf + STRLEN(buf);
6877 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6878 *strp++ = (char_u)(col + ' ' + 1);
6879 *strp++ = (char_u)(row + ' ' + 1);
6880 *strp = 0;
6881 add_to_input_buf(buf, STRLEN(buf));
6882
6883 prev_row = row;
6884 prev_col = col;
6885 return TRUE;
6886}
6887
6888# if defined(FEAT_GUI) || defined(PROTO)
6889/*
6890 * Destroy the display, window and app_context. Required for GTK.
6891 */
6892 void
6893clear_xterm_clip()
6894{
6895 if (xterm_Shell != (Widget)0)
6896 {
6897 XtDestroyWidget(xterm_Shell);
6898 xterm_Shell = (Widget)0;
6899 }
6900 if (xterm_dpy != NULL)
6901 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006902# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 /* Lesstif and Solaris crash here, lose some memory */
6904 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006905# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 if (x11_display == xterm_dpy)
6907 x11_display = NULL;
6908 xterm_dpy = NULL;
6909 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006910# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911 if (app_context != (XtAppContext)NULL)
6912 {
6913 /* Lesstif and Solaris crash here, lose some memory */
6914 XtDestroyApplicationContext(app_context);
6915 app_context = (XtAppContext)NULL;
6916 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006917# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918}
6919# endif
6920
6921/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01006922 * Catch up with GUI or X events.
6923 */
6924 static void
6925clip_update()
6926{
6927# ifdef FEAT_GUI
6928 if (gui.in_use)
6929 gui_mch_update();
6930 else
6931# endif
6932 if (xterm_Shell != (Widget)0)
6933 xterm_update();
6934}
6935
6936/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 * Catch up with any queued X events. This may put keyboard input into the
6938 * input buffer, call resize call-backs, trigger timers etc. If there is
6939 * nothing in the X event queue (& no timers pending), then we return
6940 * immediately.
6941 */
6942 static void
6943xterm_update()
6944{
6945 XEvent event;
6946
6947 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6948 {
6949 XtAppNextEvent(app_context, &event);
6950#ifdef FEAT_CLIENTSERVER
6951 {
6952 XPropertyEvent *e = (XPropertyEvent *)&event;
6953
6954 if (e->type == PropertyNotify && e->window == commWindow
6955 && e->atom == commProperty && e->state == PropertyNewValue)
6956 serverEventProc(xterm_dpy, &event);
6957 }
6958#endif
6959 XtDispatchEvent(&event);
6960 }
6961}
6962
6963 int
6964clip_xterm_own_selection(cbd)
6965 VimClipboard *cbd;
6966{
6967 if (xterm_Shell != (Widget)0)
6968 return clip_x11_own_selection(xterm_Shell, cbd);
6969 return FAIL;
6970}
6971
6972 void
6973clip_xterm_lose_selection(cbd)
6974 VimClipboard *cbd;
6975{
6976 if (xterm_Shell != (Widget)0)
6977 clip_x11_lose_selection(xterm_Shell, cbd);
6978}
6979
6980 void
6981clip_xterm_request_selection(cbd)
6982 VimClipboard *cbd;
6983{
6984 if (xterm_Shell != (Widget)0)
6985 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6986}
6987
6988 void
6989clip_xterm_set_selection(cbd)
6990 VimClipboard *cbd;
6991{
6992 clip_x11_set_selection(cbd);
6993}
6994#endif
6995
6996
6997#if defined(USE_XSMP) || defined(PROTO)
6998/*
6999 * Code for X Session Management Protocol.
7000 */
7001static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
7002static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
7003static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
7004static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
7005static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
7006
7007
7008# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7009static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7010
7011/*
7012 * This is our chance to ask the user if they want to save,
7013 * or abort the logout
7014 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 static void
7016xsmp_handle_interaction(smc_conn, client_data)
7017 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007018 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019{
7020 cmdmod_T save_cmdmod;
7021 int cancel_shutdown = False;
7022
7023 save_cmdmod = cmdmod;
7024 cmdmod.confirm = TRUE;
7025 if (check_changed_any(FALSE))
7026 /* Mustn't logout */
7027 cancel_shutdown = True;
7028 cmdmod = save_cmdmod;
7029 setcursor(); /* position cursor */
7030 out_flush();
7031
7032 /* Done interaction */
7033 SmcInteractDone(smc_conn, cancel_shutdown);
7034
7035 /* Finish off
7036 * Only end save-yourself here if we're not cancelling shutdown;
7037 * we'll get a cancelled callback later in which we'll end it.
7038 * Hopefully get around glitchy SMs (like GNOME-1)
7039 */
7040 if (!cancel_shutdown)
7041 {
7042 xsmp.save_yourself = False;
7043 SmcSaveYourselfDone(smc_conn, True);
7044 }
7045}
7046# endif
7047
7048/*
7049 * Callback that starts save-yourself.
7050 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 static void
7052xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7053 shutdown, interact_style, fast)
7054 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007055 SmPointer client_data UNUSED;
7056 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007058 int interact_style UNUSED;
7059 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060{
7061 /* Handle already being in saveyourself */
7062 if (xsmp.save_yourself)
7063 SmcSaveYourselfDone(smc_conn, True);
7064 xsmp.save_yourself = True;
7065 xsmp.shutdown = shutdown;
7066
7067 /* First up, preserve all files */
7068 out_flush();
7069 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7070
7071 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007072 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073
7074# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7075 /* Now see if we can ask about unsaved files */
7076 if (shutdown && !fast && gui.in_use)
7077 /* Need to interact with user, but need SM's permission */
7078 SmcInteractRequest(smc_conn, SmDialogError,
7079 xsmp_handle_interaction, client_data);
7080 else
7081# endif
7082 {
7083 /* Can stop the cycle here */
7084 SmcSaveYourselfDone(smc_conn, True);
7085 xsmp.save_yourself = False;
7086 }
7087}
7088
7089
7090/*
7091 * Callback to warn us of imminent death.
7092 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 static void
7094xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007095 SmcConn smc_conn UNUSED;
7096 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097{
7098 xsmp_close();
7099
7100 /* quit quickly leaving swapfiles for modified buffers behind */
7101 getout_preserve_modified(0);
7102}
7103
7104
7105/*
7106 * Callback to tell us that save-yourself has completed.
7107 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 static void
7109xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007110 SmcConn smc_conn UNUSED;
7111 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112{
7113 xsmp.save_yourself = False;
7114}
7115
7116
7117/*
7118 * Callback to tell us that an instigated shutdown was cancelled
7119 * (maybe even by us)
7120 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 static void
7122xsmp_shutdown_cancelled(smc_conn, client_data)
7123 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007124 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125{
7126 if (xsmp.save_yourself)
7127 SmcSaveYourselfDone(smc_conn, True);
7128 xsmp.save_yourself = False;
7129 xsmp.shutdown = False;
7130}
7131
7132
7133/*
7134 * Callback to tell us that a new ICE connection has been established.
7135 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 static void
7137xsmp_ice_connection(iceConn, clientData, opening, watchData)
7138 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007139 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007141 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142{
7143 /* Intercept creation of ICE connection fd */
7144 if (opening)
7145 {
7146 xsmp_icefd = IceConnectionNumber(iceConn);
7147 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7148 }
7149}
7150
7151
7152/* Handle any ICE processing that's required; return FAIL if SM lost */
7153 int
7154xsmp_handle_requests()
7155{
7156 Bool rep;
7157
7158 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7159 == IceProcessMessagesIOError)
7160 {
7161 /* Lost ICE */
7162 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007163 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164 xsmp_close();
7165 return FAIL;
7166 }
7167 else
7168 return OK;
7169}
7170
7171static int dummy;
7172
7173/* Set up X Session Management Protocol */
7174 void
7175xsmp_init(void)
7176{
7177 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 SmcCallbacks smcallbacks;
7179#if 0
7180 SmPropValue smname;
7181 SmProp smnameprop;
7182 SmProp *smprops[1];
7183#endif
7184
7185 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007186 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187
7188 xsmp.save_yourself = xsmp.shutdown = False;
7189
7190 /* Set up SM callbacks - must have all, even if they're not used */
7191 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7192 smcallbacks.save_yourself.client_data = NULL;
7193 smcallbacks.die.callback = xsmp_die;
7194 smcallbacks.die.client_data = NULL;
7195 smcallbacks.save_complete.callback = xsmp_save_complete;
7196 smcallbacks.save_complete.client_data = NULL;
7197 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7198 smcallbacks.shutdown_cancelled.client_data = NULL;
7199
7200 /* Set up a watch on ICE connection creations. The "dummy" argument is
7201 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7202 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7203 {
7204 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007205 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206 return;
7207 }
7208
7209 /* Create an SM connection */
7210 xsmp.smcconn = SmcOpenConnection(
7211 NULL,
7212 NULL,
7213 SmProtoMajor,
7214 SmProtoMinor,
7215 SmcSaveYourselfProcMask | SmcDieProcMask
7216 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7217 &smcallbacks,
7218 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007219 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220 sizeof(errorstring),
7221 errorstring);
7222 if (xsmp.smcconn == NULL)
7223 {
7224 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007225
Bram Moolenaar071d4272004-06-13 20:20:40 +00007226 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007227 {
7228 vim_snprintf(errorreport, sizeof(errorreport),
7229 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7230 verb_msg((char_u *)errorreport);
7231 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 return;
7233 }
7234 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7235
7236#if 0
7237 /* ID ourselves */
7238 smname.value = "vim";
7239 smname.length = 3;
7240 smnameprop.name = "SmProgram";
7241 smnameprop.type = "SmARRAY8";
7242 smnameprop.num_vals = 1;
7243 smnameprop.vals = &smname;
7244
7245 smprops[0] = &smnameprop;
7246 SmcSetProperties(xsmp.smcconn, 1, smprops);
7247#endif
7248}
7249
7250
7251/* Shut down XSMP comms. */
7252 void
7253xsmp_close()
7254{
7255 if (xsmp_icefd != -1)
7256 {
7257 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007258 if (xsmp.clientid != NULL)
7259 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007260 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 xsmp_icefd = -1;
7262 }
7263}
7264#endif /* USE_XSMP */
7265
7266
7267#ifdef EBCDIC
7268/* Translate character to its CTRL- value */
7269char CtrlTable[] =
7270{
7271/* 00 - 5E */
7272 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7273 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7276 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7277 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7278/* ^ */ 0x1E,
7279/* - */ 0x1F,
7280/* 61 - 6C */
7281 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7282/* _ */ 0x1F,
7283/* 6E - 80 */
7284 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7285/* a */ 0x01,
7286/* b */ 0x02,
7287/* c */ 0x03,
7288/* d */ 0x37,
7289/* e */ 0x2D,
7290/* f */ 0x2E,
7291/* g */ 0x2F,
7292/* h */ 0x16,
7293/* i */ 0x05,
7294/* 8A - 90 */
7295 0, 0, 0, 0, 0, 0, 0,
7296/* j */ 0x15,
7297/* k */ 0x0B,
7298/* l */ 0x0C,
7299/* m */ 0x0D,
7300/* n */ 0x0E,
7301/* o */ 0x0F,
7302/* p */ 0x10,
7303/* q */ 0x11,
7304/* r */ 0x12,
7305/* 9A - A1 */
7306 0, 0, 0, 0, 0, 0, 0, 0,
7307/* s */ 0x13,
7308/* t */ 0x3C,
7309/* u */ 0x3D,
7310/* v */ 0x32,
7311/* w */ 0x26,
7312/* x */ 0x18,
7313/* y */ 0x19,
7314/* z */ 0x3F,
7315/* AA - AC */
7316 0, 0, 0,
7317/* [ */ 0x27,
7318/* AE - BC */
7319 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7320/* ] */ 0x1D,
7321/* BE - C0 */ 0, 0, 0,
7322/* A */ 0x01,
7323/* B */ 0x02,
7324/* C */ 0x03,
7325/* D */ 0x37,
7326/* E */ 0x2D,
7327/* F */ 0x2E,
7328/* G */ 0x2F,
7329/* H */ 0x16,
7330/* I */ 0x05,
7331/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7332/* J */ 0x15,
7333/* K */ 0x0B,
7334/* L */ 0x0C,
7335/* M */ 0x0D,
7336/* N */ 0x0E,
7337/* O */ 0x0F,
7338/* P */ 0x10,
7339/* Q */ 0x11,
7340/* R */ 0x12,
7341/* DA - DF */ 0, 0, 0, 0, 0, 0,
7342/* \ */ 0x1C,
7343/* E1 */ 0,
7344/* S */ 0x13,
7345/* T */ 0x3C,
7346/* U */ 0x3D,
7347/* V */ 0x32,
7348/* W */ 0x26,
7349/* X */ 0x18,
7350/* Y */ 0x19,
7351/* Z */ 0x3F,
7352/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7353 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7354};
7355
7356char MetaCharTable[]=
7357{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7358 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7359 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7360 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7361 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7362};
7363
7364
7365/* TODO: Use characters NOT numbers!!! */
7366char CtrlCharTable[]=
7367{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7368 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7369 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7370 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7371 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7372};
7373
7374
7375#endif