blob: 80459c94eb6b0cc560665ced31f4a435df76a79b [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 Moolenaar4cc95d12013-11-02 21:49:32 +0100807#if defined(HAVE_AVAILABILITYMACROS_H) \
808 && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) \
809 && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1090)
810# include <AvailabilityMacros.h>
811#endif
812
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813#ifndef SIGSTKSZ
814# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
815#endif
816
817# ifdef HAVE_SIGALTSTACK
818static stack_t sigstk; /* for sigaltstack() */
819# else
820static struct sigstack sigstk; /* for sigstack() */
821# endif
822
823static void init_signal_stack __ARGS((void));
824static char *signal_stack;
825
826 static void
827init_signal_stack()
828{
829 if (signal_stack != NULL)
830 {
831# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000832# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
833 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
835 * "struct sigaltstack" needs to be declared. */
836 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
837# endif
838
839# ifdef HAVE_SS_BASE
840 sigstk.ss_base = signal_stack;
841# else
842 sigstk.ss_sp = signal_stack;
843# endif
844 sigstk.ss_size = SIGSTKSZ;
845 sigstk.ss_flags = 0;
846 (void)sigaltstack(&sigstk, NULL);
847# else
848 sigstk.ss_sp = signal_stack;
849 if (stack_grows_downwards)
850 sigstk.ss_sp += SIGSTKSZ - 1;
851 sigstk.ss_onstack = 0;
852 (void)sigstack(&sigstk, NULL);
853# endif
854 }
855}
856#endif
857
858/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000859 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 * will barf when the second argument to signal() is ``wrong''.
861 * Let me try it with a few tricky defines from my own osdef.h (jw).
862 */
863#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 static RETSIGTYPE
865sig_winch SIGDEFARG(sigarg)
866{
867 /* this is not required on all systems, but it doesn't hurt anybody */
868 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
869 do_resize = TRUE;
870 SIGRETURN;
871}
872#endif
873
874#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 static RETSIGTYPE
876catch_sigint SIGDEFARG(sigarg)
877{
878 /* this is not required on all systems, but it doesn't hurt anybody */
879 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
880 got_int = TRUE;
881 SIGRETURN;
882}
883#endif
884
885#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886 static RETSIGTYPE
887catch_sigpwr SIGDEFARG(sigarg)
888{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000889 /* this is not required on all systems, but it doesn't hurt anybody */
890 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000891 /*
892 * I'm not sure we get the SIGPWR signal when the system is really going
893 * down or when the batteries are almost empty. Just preserve the swap
894 * files and don't exit, that can't do any harm.
895 */
896 ml_sync_all(FALSE, FALSE);
897 SIGRETURN;
898}
899#endif
900
901#ifdef SET_SIG_ALARM
902/*
903 * signal function for alarm().
904 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 static RETSIGTYPE
906sig_alarm SIGDEFARG(sigarg)
907{
908 /* doesn't do anything, just to break a system call */
909 sig_alarm_called = TRUE;
910 SIGRETURN;
911}
912#endif
913
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000914#if (defined(HAVE_SETJMP_H) \
915 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
916 || defined(FEAT_LIBCALL))) \
917 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918/*
919 * A simplistic version of setjmp() that only allows one level of using.
920 * Don't call twice before calling mch_endjmp()!.
921 * Usage:
922 * mch_startjmp();
923 * if (SETJMP(lc_jump_env) != 0)
924 * {
925 * mch_didjmp();
926 * EMSG("crash!");
927 * }
928 * else
929 * {
930 * do_the_work;
931 * mch_endjmp();
932 * }
933 * Note: Can't move SETJMP() here, because a function calling setjmp() must
934 * not return before the saved environment is used.
935 * Returns OK for normal return, FAIL when the protected code caused a
936 * problem and LONGJMP() was used.
937 */
938 void
939mch_startjmp()
940{
941#ifdef SIGHASARG
942 lc_signal = 0;
943#endif
944 lc_active = TRUE;
945}
946
947 void
948mch_endjmp()
949{
950 lc_active = FALSE;
951}
952
953 void
954mch_didjmp()
955{
956# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
957 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
958 * otherwise catching the signal only works once. */
959 init_signal_stack();
960# endif
961}
962#endif
963
964/*
965 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200966 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200968 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
969 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970 */
971 static RETSIGTYPE
972deathtrap SIGDEFARG(sigarg)
973{
974 static int entered = 0; /* count the number of times we got here.
975 Note: when memory has been corrupted
976 this may get an arbitrary value! */
977#ifdef SIGHASARG
978 int i;
979#endif
980
981#if defined(HAVE_SETJMP_H)
982 /*
983 * Catch a crash in protected code.
984 * Restores the environment saved in lc_jump_env, which looks like
985 * SETJMP() returns 1.
986 */
987 if (lc_active)
988 {
989# if defined(SIGHASARG)
990 lc_signal = sigarg;
991# endif
992 lc_active = FALSE; /* don't jump again */
993 LONGJMP(lc_jump_env, 1);
994 /* NOTREACHED */
995 }
996#endif
997
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000998#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000999# ifdef SIGQUIT
1000 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1001 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1002 * pressing CTRL-\, but we don't want Vim to exit then. */
1003 if (in_mch_delay && sigarg == SIGQUIT)
1004 SIGRETURN;
1005# endif
1006
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001007 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1008 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1009 * free(). Calling free() again may then cause a crash. */
1010 if (entered == 0
1011 && (0
1012# ifdef SIGHUP
1013 || sigarg == SIGHUP
1014# endif
1015# ifdef SIGQUIT
1016 || sigarg == SIGQUIT
1017# endif
1018# ifdef SIGTERM
1019 || sigarg == SIGTERM
1020# endif
1021# ifdef SIGPWR
1022 || sigarg == SIGPWR
1023# endif
1024# ifdef SIGUSR1
1025 || sigarg == SIGUSR1
1026# endif
1027# ifdef SIGUSR2
1028 || sigarg == SIGUSR2
1029# endif
1030 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001031 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001032 SIGRETURN;
1033#endif
1034
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 /* Remember how often we have been called. */
1036 ++entered;
1037
1038#ifdef FEAT_EVAL
1039 /* Set the v:dying variable. */
1040 set_vim_var_nr(VV_DYING, (long)entered);
1041#endif
1042
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001043#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044 /* Since we are now using the signal stack, need to reset the stack
1045 * limit. Otherwise using a regexp will fail. */
1046 get_stack_limit();
1047#endif
1048
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001049#if 0
1050 /* This is for opening gdb the moment Vim crashes.
1051 * You need to manually adjust the file name and Vim executable name.
1052 * Suggested by SungHyun Nam. */
1053 {
1054# define VI_GDB_FILE "/tmp/vimgdb"
1055# define VIM_NAME "/usr/bin/vim"
1056 FILE *fp = fopen(VI_GDB_FILE, "w");
1057 if (fp)
1058 {
1059 fprintf(fp,
1060 "file %s\n"
1061 "attach %d\n"
1062 "set height 1000\n"
1063 "bt full\n"
1064 , VIM_NAME, getpid());
1065 fclose(fp);
1066 system("xterm -e gdb -x "VI_GDB_FILE);
1067 unlink(VI_GDB_FILE);
1068 }
1069 }
1070#endif
1071
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072#ifdef SIGHASARG
1073 /* try to find the name of this signal */
1074 for (i = 0; signal_info[i].sig != -1; i++)
1075 if (sigarg == signal_info[i].sig)
1076 break;
1077 deadly_signal = sigarg;
1078#endif
1079
1080 full_screen = FALSE; /* don't write message to the GUI, it might be
1081 * part of the problem... */
1082 /*
1083 * If something goes wrong after entering here, we may get here again.
1084 * When this happens, give a message and try to exit nicely (resetting the
1085 * terminal mode, etc.)
1086 * When this happens twice, just exit, don't even try to give a message,
1087 * stack may be corrupt or something weird.
1088 * When this still happens again (or memory was corrupted in such a way
1089 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1090 */
1091 if (entered >= 3)
1092 {
1093 reset_signals(); /* don't catch any signals anymore */
1094 may_core_dump();
1095 if (entered >= 4)
1096 _exit(8);
1097 exit(7);
1098 }
1099 if (entered == 2)
1100 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001101 /* No translation, it may call malloc(). */
1102 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 out_flush();
1104 getout(1);
1105 }
1106
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001107 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001109 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110 signal_info[i].name);
1111#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001112 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001114
1115 /* Preserve files and exit. This sets the really_exiting flag to prevent
1116 * calling free(). */
1117 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118
Bram Moolenaar009b2592004-10-24 19:18:58 +00001119#ifdef NBDEBUG
1120 reset_signals();
1121 may_core_dump();
1122 abort();
1123#endif
1124
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 SIGRETURN;
1126}
1127
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001128#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129/*
1130 * On Solaris with multi-threading, suspending might not work immediately.
1131 * Catch the SIGCONT signal, which will be used as an indication whether the
1132 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001133 *
1134 * On Linux, signal is not always handled immediately either.
1135 * See https://bugs.launchpad.net/bugs/291373
1136 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001137 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001139static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1141
1142/*
1143 * signal handler for SIGCONT
1144 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145 static RETSIGTYPE
1146sigcont_handler SIGDEFARG(sigarg)
1147{
1148 sigcont_received = TRUE;
1149 SIGRETURN;
1150}
1151#endif
1152
Bram Moolenaar62b42182010-09-21 22:09:37 +02001153# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1154static void loose_clipboard __ARGS((void));
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001155# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001156static void save_clipboard __ARGS((void));
1157static void restore_clipboard __ARGS((void));
1158
1159static void *clip_star_save = NULL;
1160static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001161# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001162
1163/*
1164 * Called when Vim is going to sleep or execute a shell command.
1165 * We can't respond to requests for the X selections. Lose them, otherwise
1166 * other applications will hang. But first copy the text to cut buffer 0.
1167 */
1168 static void
1169loose_clipboard()
1170{
1171 if (clip_star.owned || clip_plus.owned)
1172 {
1173 x11_export_final_selection();
1174 if (clip_star.owned)
1175 clip_lose_selection(&clip_star);
1176 if (clip_plus.owned)
1177 clip_lose_selection(&clip_plus);
1178 if (x11_display != NULL)
1179 XFlush(x11_display);
1180 }
1181}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001182
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001183# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001184/*
1185 * Save clipboard text to restore later.
1186 */
1187 static void
1188save_clipboard()
1189{
1190 if (clip_star.owned)
1191 clip_star_save = get_register('*', TRUE);
1192 if (clip_plus.owned)
1193 clip_plus_save = get_register('+', TRUE);
1194}
1195
1196/*
1197 * Restore clipboard text if no one own the X selection.
1198 */
1199 static void
1200restore_clipboard()
1201{
1202 if (clip_star_save != NULL)
1203 {
1204 if (!clip_gen_owner_exists(&clip_star))
1205 put_register('*', clip_star_save);
1206 else
1207 free_register(clip_star_save);
1208 clip_star_save = NULL;
1209 }
1210 if (clip_plus_save != NULL)
1211 {
1212 if (!clip_gen_owner_exists(&clip_plus))
1213 put_register('+', clip_plus_save);
1214 else
1215 free_register(clip_plus_save);
1216 clip_plus_save = NULL;
1217 }
1218}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001219# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001220#endif
1221
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222/*
1223 * If the machine has job control, use it to suspend the program,
1224 * otherwise fake it by starting a new shell.
1225 */
1226 void
1227mch_suspend()
1228{
1229 /* BeOS does have SIGTSTP, but it doesn't work. */
1230#if defined(SIGTSTP) && !defined(__BEOS__)
1231 out_flush(); /* needed to make cursor visible on some systems */
1232 settmode(TMODE_COOK);
1233 out_flush(); /* needed to disable mouse on some systems */
1234
1235# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001236 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237# endif
1238
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001239# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 sigcont_received = FALSE;
1241# endif
1242 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001243# if defined(_REENTRANT) && defined(SIGCONT)
1244 /*
1245 * Wait for the SIGCONT signal to be handled. It generally happens
1246 * immediately, but somehow not all the time. Do not call pause()
1247 * because there would be race condition which would hang Vim if
1248 * signal happened in between the test of sigcont_received and the
1249 * call to pause(). If signal is not yet received, call sleep(0)
1250 * to just yield CPU. Signal should then be received. If somehow
1251 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1252 * further if signal is not received after 1+2+3+4 ms (not expected
1253 * to happen).
1254 */
1255 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001256 long wait_time;
1257 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001258 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001259 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001260 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261# endif
1262
1263# ifdef FEAT_TITLE
1264 /*
1265 * Set oldtitle to NULL, so the current title is obtained again.
1266 */
1267 vim_free(oldtitle);
1268 oldtitle = NULL;
1269# endif
1270 settmode(TMODE_RAW);
1271 need_check_timestamps = TRUE;
1272 did_check_timestamps = FALSE;
1273#else
1274 suspend_shell();
1275#endif
1276}
1277
1278 void
1279mch_init()
1280{
1281 Columns = 80;
1282 Rows = 24;
1283
1284 out_flush();
1285 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001286
Bram Moolenaar56718732006-03-15 22:53:57 +00001287#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001288 mac_conv_init();
1289#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001290#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1291 win_clip_init();
1292#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293}
1294
1295 static void
1296set_signals()
1297{
1298#if defined(SIGWINCH)
1299 /*
1300 * WINDOW CHANGE signal is handled with sig_winch().
1301 */
1302 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1303#endif
1304
1305 /*
1306 * We want the STOP signal to work, to make mch_suspend() work.
1307 * For "rvim" the STOP signal is ignored.
1308 */
1309#ifdef SIGTSTP
1310 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1311#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001312#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 signal(SIGCONT, sigcont_handler);
1314#endif
1315
1316 /*
1317 * We want to ignore breaking of PIPEs.
1318 */
1319#ifdef SIGPIPE
1320 signal(SIGPIPE, SIG_IGN);
1321#endif
1322
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001324 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325#endif
1326
1327 /*
1328 * Ignore alarm signals (Perl's alarm() generates it).
1329 */
1330#ifdef SIGALRM
1331 signal(SIGALRM, SIG_IGN);
1332#endif
1333
1334 /*
1335 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1336 * work will be lost.
1337 */
1338#ifdef SIGPWR
1339 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1340#endif
1341
1342 /*
1343 * Arrange for other signals to gracefully shutdown Vim.
1344 */
1345 catch_signals(deathtrap, SIG_ERR);
1346
1347#if defined(FEAT_GUI) && defined(SIGHUP)
1348 /*
1349 * When the GUI is running, ignore the hangup signal.
1350 */
1351 if (gui.in_use)
1352 signal(SIGHUP, SIG_IGN);
1353#endif
1354}
1355
Bram Moolenaardf177f62005-02-22 08:39:57 +00001356#if defined(SIGINT) || defined(PROTO)
1357/*
1358 * Catch CTRL-C (only works while in Cooked mode).
1359 */
1360 static void
1361catch_int_signal()
1362{
1363 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1364}
1365#endif
1366
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 void
1368reset_signals()
1369{
1370 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001371#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 /* SIGCONT isn't in the list, because its default action is ignore */
1373 signal(SIGCONT, SIG_DFL);
1374#endif
1375}
1376
1377 static void
1378catch_signals(func_deadly, func_other)
1379 RETSIGTYPE (*func_deadly)();
1380 RETSIGTYPE (*func_other)();
1381{
1382 int i;
1383
1384 for (i = 0; signal_info[i].sig != -1; i++)
1385 if (signal_info[i].deadly)
1386 {
1387#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1388 struct sigaction sa;
1389
1390 /* Setup to use the alternate stack for the signal function. */
1391 sa.sa_handler = func_deadly;
1392 sigemptyset(&sa.sa_mask);
1393# if defined(__linux__) && defined(_REENTRANT)
1394 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1395 * thread handling in combination with using the alternate stack:
1396 * pthread library functions try to use the stack pointer to
1397 * identify the current thread, causing a SEGV signal, which
1398 * recursively calls deathtrap() and hangs. */
1399 sa.sa_flags = 0;
1400# else
1401 sa.sa_flags = SA_ONSTACK;
1402# endif
1403 sigaction(signal_info[i].sig, &sa, NULL);
1404#else
1405# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1406 struct sigvec sv;
1407
1408 /* Setup to use the alternate stack for the signal function. */
1409 sv.sv_handler = func_deadly;
1410 sv.sv_mask = 0;
1411 sv.sv_flags = SV_ONSTACK;
1412 sigvec(signal_info[i].sig, &sv, NULL);
1413# else
1414 signal(signal_info[i].sig, func_deadly);
1415# endif
1416#endif
1417 }
1418 else if (func_other != SIG_ERR)
1419 signal(signal_info[i].sig, func_other);
1420}
1421
1422/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001423 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001424 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1425 * return TRUE
1426 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1427 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001428 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001429 * Returns TRUE when Vim should exit.
1430 */
1431 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001432vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001433 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001434{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001435 static int got_signal = 0;
1436 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001437
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001438 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001439 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001440 case SIGNAL_BLOCK: blocked = TRUE;
1441 break;
1442
1443 case SIGNAL_UNBLOCK: blocked = FALSE;
1444 if (got_signal != 0)
1445 {
1446 kill(getpid(), got_signal);
1447 got_signal = 0;
1448 }
1449 break;
1450
1451 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001452 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001453 got_signal = sig;
1454#ifdef SIGPWR
1455 if (sig != SIGPWR)
1456#endif
1457 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001458 break;
1459 }
1460 return FALSE;
1461}
1462
1463/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464 * Check_win checks whether we have an interactive stdout.
1465 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 int
1467mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001468 int argc UNUSED;
1469 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470{
1471#ifdef OS2
1472 /*
1473 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1474 * name, mostly it's just "vim" and found in the path, which is unusable.
1475 */
1476 if (mch_isFullName(argv[0]))
1477 exe_name = vim_strsave((char_u *)argv[0]);
1478#endif
1479 if (isatty(1))
1480 return OK;
1481 return FAIL;
1482}
1483
1484/*
1485 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1486 */
1487 int
1488mch_input_isatty()
1489{
1490 if (isatty(read_cmd_fd))
1491 return TRUE;
1492 return FALSE;
1493}
1494
1495#ifdef FEAT_X11
1496
1497# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1498 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1499
1500static void xopen_message __ARGS((struct timeval *tvp));
1501
1502/*
1503 * Give a message about the elapsed time for opening the X window.
1504 */
1505 static void
1506xopen_message(tvp)
1507 struct timeval *tvp; /* must contain start time */
1508{
1509 struct timeval end_tv;
1510
1511 /* Compute elapsed time. */
1512 gettimeofday(&end_tv, NULL);
1513 smsg((char_u *)_("Opening the X display took %ld msec"),
1514 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001515 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516}
1517# endif
1518#endif
1519
1520#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1521/*
1522 * A few functions shared by X11 title and clipboard code.
1523 */
1524static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1525static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1526static int x_connect_to_server __ARGS((void));
1527static int test_x11_window __ARGS((Display *dpy));
1528
1529static int got_x_error = FALSE;
1530
1531/*
1532 * X Error handler, otherwise X just exits! (very rude) -- webb
1533 */
1534 static int
1535x_error_handler(dpy, error_event)
1536 Display *dpy;
1537 XErrorEvent *error_event;
1538{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001539 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 STRCAT(IObuff, _("\nVim: Got X error\n"));
1541
1542 /* We cannot print a message and continue, because no X calls are allowed
1543 * here (causes my system to hang). Silently continuing might be an
1544 * alternative... */
1545 preserve_exit(); /* preserve files and exit */
1546
1547 return 0; /* NOTREACHED */
1548}
1549
1550/*
1551 * Another X Error handler, just used to check for errors.
1552 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 static int
1554x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001555 Display *dpy UNUSED;
1556 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557{
1558 got_x_error = TRUE;
1559 return 0;
1560}
1561
1562#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1563# if defined(HAVE_SETJMP_H)
1564/*
1565 * An X IO Error handler, used to catch error while opening the display.
1566 */
1567static int x_IOerror_check __ARGS((Display *dpy));
1568
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569 static int
1570x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001571 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572{
1573 /* This function should not return, it causes exit(). Longjump instead. */
1574 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001575# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001576 return 0; /* avoid the compiler complains about missing return value */
1577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578}
1579# endif
1580
1581/*
1582 * An X IO Error handler, used to catch terminal errors.
1583 */
1584static int x_IOerror_handler __ARGS((Display *dpy));
1585
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 static int
1587x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001588 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589{
1590 xterm_dpy = NULL;
1591 x11_window = 0;
1592 x11_display = NULL;
1593 xterm_Shell = (Widget)0;
1594
1595 /* This function should not return, it causes exit(). Longjump instead. */
1596 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001597# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001598 return 0; /* avoid the compiler complains about missing return value */
1599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600}
1601#endif
1602
1603/*
1604 * Return TRUE when connection to the X server is desired.
1605 */
1606 static int
1607x_connect_to_server()
1608{
1609 regmatch_T regmatch;
1610
1611#if defined(FEAT_CLIENTSERVER)
1612 if (x_force_connect)
1613 return TRUE;
1614#endif
1615 if (x_no_connect)
1616 return FALSE;
1617
1618 /* Check for a match with "exclude:" from 'clipboard'. */
1619 if (clip_exclude_prog != NULL)
1620 {
1621 regmatch.rm_ic = FALSE; /* Don't ignore case */
1622 regmatch.regprog = clip_exclude_prog;
1623 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1624 return FALSE;
1625 }
1626 return TRUE;
1627}
1628
1629/*
1630 * Test if "dpy" and x11_window are valid by getting the window title.
1631 * I don't actually want it yet, so there may be a simpler call to use, but
1632 * this will cause the error handler x_error_check() to be called if anything
1633 * is wrong, such as the window pointer being invalid (as can happen when the
1634 * user changes his DISPLAY, but not his WINDOWID) -- webb
1635 */
1636 static int
1637test_x11_window(dpy)
1638 Display *dpy;
1639{
1640 int (*old_handler)();
1641 XTextProperty text_prop;
1642
1643 old_handler = XSetErrorHandler(x_error_check);
1644 got_x_error = FALSE;
1645 if (XGetWMName(dpy, x11_window, &text_prop))
1646 XFree((void *)text_prop.value);
1647 XSync(dpy, False);
1648 (void)XSetErrorHandler(old_handler);
1649
1650 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001651 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 return (got_x_error ? FAIL : OK);
1654}
1655#endif
1656
1657#ifdef FEAT_TITLE
1658
1659#ifdef FEAT_X11
1660
1661static int get_x11_thing __ARGS((int get_title, int test_only));
1662
1663/*
1664 * try to get x11 window and display
1665 *
1666 * return FAIL for failure, OK otherwise
1667 */
1668 static int
1669get_x11_windis()
1670{
1671 char *winid;
1672 static int result = -1;
1673#define XD_NONE 0 /* x11_display not set here */
1674#define XD_HERE 1 /* x11_display opened here */
1675#define XD_GUI 2 /* x11_display used from gui.dpy */
1676#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1677 static int x11_display_from = XD_NONE;
1678 static int did_set_error_handler = FALSE;
1679
1680 if (!did_set_error_handler)
1681 {
1682 /* X just exits if it finds an error otherwise! */
1683 (void)XSetErrorHandler(x_error_handler);
1684 did_set_error_handler = TRUE;
1685 }
1686
Bram Moolenaar9372a112005-12-06 19:59:18 +00001687#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 if (gui.in_use)
1689 {
1690 /*
1691 * If the X11 display was opened here before, for the window where Vim
1692 * was started, close that one now to avoid a memory leak.
1693 */
1694 if (x11_display_from == XD_HERE && x11_display != NULL)
1695 {
1696 XCloseDisplay(x11_display);
1697 x11_display_from = XD_NONE;
1698 }
1699 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1700 {
1701 x11_display_from = XD_GUI;
1702 return OK;
1703 }
1704 x11_display = NULL;
1705 return FAIL;
1706 }
1707 else if (x11_display_from == XD_GUI)
1708 {
1709 /* GUI must have stopped somehow, clear x11_display */
1710 x11_window = 0;
1711 x11_display = NULL;
1712 x11_display_from = XD_NONE;
1713 }
1714#endif
1715
1716 /* When started with the "-X" argument, don't try connecting. */
1717 if (!x_connect_to_server())
1718 return FAIL;
1719
1720 /*
1721 * If WINDOWID not set, should try another method to find out
1722 * what the current window number is. The only code I know for
1723 * this is very complicated.
1724 * We assume that zero is invalid for WINDOWID.
1725 */
1726 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1727 x11_window = (Window)atol(winid);
1728
1729#ifdef FEAT_XCLIPBOARD
1730 if (xterm_dpy != NULL && x11_window != 0)
1731 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001732 /* We may have checked it already, but Gnome terminal can move us to
1733 * another window, so we need to check every time. */
1734 if (x11_display_from != XD_XTERM)
1735 {
1736 /*
1737 * If the X11 display was opened here before, for the window where
1738 * Vim was started, close that one now to avoid a memory leak.
1739 */
1740 if (x11_display_from == XD_HERE && x11_display != NULL)
1741 XCloseDisplay(x11_display);
1742 x11_display = xterm_dpy;
1743 x11_display_from = XD_XTERM;
1744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 if (test_x11_window(x11_display) == FAIL)
1746 {
1747 /* probably bad $WINDOWID */
1748 x11_window = 0;
1749 x11_display = NULL;
1750 x11_display_from = XD_NONE;
1751 return FAIL;
1752 }
1753 return OK;
1754 }
1755#endif
1756
1757 if (x11_window == 0 || x11_display == NULL)
1758 result = -1;
1759
1760 if (result != -1) /* Have already been here and set this */
1761 return result; /* Don't do all these X calls again */
1762
1763 if (x11_window != 0 && x11_display == NULL)
1764 {
1765#ifdef SET_SIG_ALARM
1766 RETSIGTYPE (*sig_save)();
1767#endif
1768#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1769 struct timeval start_tv;
1770
1771 if (p_verbose > 0)
1772 gettimeofday(&start_tv, NULL);
1773#endif
1774
1775#ifdef SET_SIG_ALARM
1776 /*
1777 * Opening the Display may hang if the DISPLAY setting is wrong, or
1778 * the network connection is bad. Set an alarm timer to get out.
1779 */
1780 sig_alarm_called = FALSE;
1781 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1782 (RETSIGTYPE (*)())sig_alarm);
1783 alarm(2);
1784#endif
1785 x11_display = XOpenDisplay(NULL);
1786
1787#ifdef SET_SIG_ALARM
1788 alarm(0);
1789 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1790 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001791 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792#endif
1793 if (x11_display != NULL)
1794 {
1795# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1796 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001797 {
1798 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001800 verbose_leave();
1801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802# endif
1803 if (test_x11_window(x11_display) == FAIL)
1804 {
1805 /* Maybe window id is bad */
1806 x11_window = 0;
1807 XCloseDisplay(x11_display);
1808 x11_display = NULL;
1809 }
1810 else
1811 x11_display_from = XD_HERE;
1812 }
1813 }
1814 if (x11_window == 0 || x11_display == NULL)
1815 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001816
1817# ifdef FEAT_EVAL
1818 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1819# endif
1820
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 return (result = OK);
1822}
1823
1824/*
1825 * Determine original x11 Window Title
1826 */
1827 static int
1828get_x11_title(test_only)
1829 int test_only;
1830{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001831 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832}
1833
1834/*
1835 * Determine original x11 Window icon
1836 */
1837 static int
1838get_x11_icon(test_only)
1839 int test_only;
1840{
1841 int retval = FALSE;
1842
1843 retval = get_x11_thing(FALSE, test_only);
1844
1845 /* could not get old icon, use terminal name */
1846 if (oldicon == NULL && !test_only)
1847 {
1848 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001849 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001851 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 }
1853
1854 return retval;
1855}
1856
1857 static int
1858get_x11_thing(get_title, test_only)
1859 int get_title; /* get title string */
1860 int test_only;
1861{
1862 XTextProperty text_prop;
1863 int retval = FALSE;
1864 Status status;
1865
1866 if (get_x11_windis() == OK)
1867 {
1868 /* Get window/icon name if any */
1869 if (get_title)
1870 status = XGetWMName(x11_display, x11_window, &text_prop);
1871 else
1872 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1873
1874 /*
1875 * If terminal is xterm, then x11_window may be a child window of the
1876 * outer xterm window that actually contains the window/icon name, so
1877 * keep traversing up the tree until a window with a title/icon is
1878 * found.
1879 */
1880 /* Previously this was only done for xterm and alikes. I don't see a
1881 * reason why it would fail for other terminal emulators.
1882 * if (term_is_xterm) */
1883 {
1884 Window root;
1885 Window parent;
1886 Window win = x11_window;
1887 Window *children;
1888 unsigned int num_children;
1889
1890 while (!status || text_prop.value == NULL)
1891 {
1892 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1893 &num_children))
1894 break;
1895 if (children)
1896 XFree((void *)children);
1897 if (parent == root || parent == 0)
1898 break;
1899
1900 win = parent;
1901 if (get_title)
1902 status = XGetWMName(x11_display, win, &text_prop);
1903 else
1904 status = XGetWMIconName(x11_display, win, &text_prop);
1905 }
1906 }
1907 if (status && text_prop.value != NULL)
1908 {
1909 retval = TRUE;
1910 if (!test_only)
1911 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001912#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1913 if (text_prop.encoding == XA_STRING
1914# ifdef FEAT_MBYTE
1915 && !has_mbyte
1916# endif
1917 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 {
1919#endif
1920 if (get_title)
1921 oldtitle = vim_strsave((char_u *)text_prop.value);
1922 else
1923 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001924#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 }
1926 else
1927 {
1928 char **cl;
1929 Status transform_status;
1930 int n = 0;
1931
1932 transform_status = XmbTextPropertyToTextList(x11_display,
1933 &text_prop,
1934 &cl, &n);
1935 if (transform_status >= Success && n > 0 && cl[0])
1936 {
1937 if (get_title)
1938 oldtitle = vim_strsave((char_u *) cl[0]);
1939 else
1940 oldicon = vim_strsave((char_u *) cl[0]);
1941 XFreeStringList(cl);
1942 }
1943 else
1944 {
1945 if (get_title)
1946 oldtitle = vim_strsave((char_u *)text_prop.value);
1947 else
1948 oldicon = vim_strsave((char_u *)text_prop.value);
1949 }
1950 }
1951#endif
1952 }
1953 XFree((void *)text_prop.value);
1954 }
1955 }
1956 return retval;
1957}
1958
1959/* Are Xutf8 functions available? Avoid error from old compilers. */
1960#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1961# if X_HAVE_UTF8_STRING
1962# define USE_UTF8_STRING
1963# endif
1964#endif
1965
1966/*
1967 * Set x11 Window Title
1968 *
1969 * get_x11_windis() must be called before this and have returned OK
1970 */
1971 static void
1972set_x11_title(title)
1973 char_u *title;
1974{
1975 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1976 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1977 * supported everywhere and STRING doesn't work for multi-byte titles.
1978 */
1979#ifdef USE_UTF8_STRING
1980 if (enc_utf8)
1981 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1982 NULL, NULL, 0, NULL, NULL, NULL);
1983 else
1984#endif
1985 {
1986#if XtSpecificationRelease >= 4
1987# ifdef FEAT_XFONTSET
1988 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1989 NULL, NULL, 0, NULL, NULL, NULL);
1990# else
1991 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001992 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993
1994 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001995 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 XSetWMProperties(x11_display, x11_window, &text_prop,
1997 NULL, NULL, 0, NULL, NULL, NULL);
1998# endif
1999#else
2000 XStoreName(x11_display, x11_window, (char *)title);
2001#endif
2002 }
2003 XFlush(x11_display);
2004}
2005
2006/*
2007 * Set x11 Window icon
2008 *
2009 * get_x11_windis() must be called before this and have returned OK
2010 */
2011 static void
2012set_x11_icon(icon)
2013 char_u *icon;
2014{
2015 /* See above for comments about using X*SetWMProperties(). */
2016#ifdef USE_UTF8_STRING
2017 if (enc_utf8)
2018 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2019 NULL, 0, NULL, NULL, NULL);
2020 else
2021#endif
2022 {
2023#if XtSpecificationRelease >= 4
2024# ifdef FEAT_XFONTSET
2025 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2026 NULL, 0, NULL, NULL, NULL);
2027# else
2028 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002029 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002031 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2033 NULL, 0, NULL, NULL, NULL);
2034# endif
2035#else
2036 XSetIconName(x11_display, x11_window, (char *)icon);
2037#endif
2038 }
2039 XFlush(x11_display);
2040}
2041
2042#else /* FEAT_X11 */
2043
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 static int
2045get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002046 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047{
2048 return FALSE;
2049}
2050
2051 static int
2052get_x11_icon(test_only)
2053 int test_only;
2054{
2055 if (!test_only)
2056 {
2057 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002058 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002060 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 }
2062 return FALSE;
2063}
2064
2065#endif /* FEAT_X11 */
2066
2067 int
2068mch_can_restore_title()
2069{
2070 return get_x11_title(TRUE);
2071}
2072
2073 int
2074mch_can_restore_icon()
2075{
2076 return get_x11_icon(TRUE);
2077}
2078
2079/*
2080 * Set the window title and icon.
2081 */
2082 void
2083mch_settitle(title, icon)
2084 char_u *title;
2085 char_u *icon;
2086{
2087 int type = 0;
2088 static int recursive = 0;
2089
2090 if (T_NAME == NULL) /* no terminal name (yet) */
2091 return;
2092 if (title == NULL && icon == NULL) /* nothing to do */
2093 return;
2094
2095 /* When one of the X11 functions causes a deadly signal, we get here again
2096 * recursively. Avoid hanging then (something is probably locked). */
2097 if (recursive)
2098 return;
2099 ++recursive;
2100
2101 /*
2102 * if the window ID and the display is known, we may use X11 calls
2103 */
2104#ifdef FEAT_X11
2105 if (get_x11_windis() == OK)
2106 type = 1;
2107#else
2108# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2109 if (gui.in_use)
2110 type = 1;
2111# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112#endif
2113
2114 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002115 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 * than x11 calls, because the x11 calls don't always work
2117 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118 if ((type || *T_TS != NUL) && title != NULL)
2119 {
2120 if (oldtitle == NULL
2121#ifdef FEAT_GUI
2122 && !gui.in_use
2123#endif
2124 ) /* first call but not in GUI, save title */
2125 (void)get_x11_title(FALSE);
2126
2127 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2128 term_settitle(title);
2129#ifdef FEAT_X11
2130 else
2131# ifdef FEAT_GUI_GTK
2132 if (!gui.in_use) /* don't do this if GTK+ is running */
2133# endif
2134 set_x11_title(title); /* x11 */
2135#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002136#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2138 else
2139 gui_mch_settitle(title, icon);
2140#endif
2141 did_set_title = TRUE;
2142 }
2143
2144 if ((type || *T_CIS != NUL) && icon != NULL)
2145 {
2146 if (oldicon == NULL
2147#ifdef FEAT_GUI
2148 && !gui.in_use
2149#endif
2150 ) /* first call, save icon */
2151 get_x11_icon(FALSE);
2152
2153 if (*T_CIS != NUL)
2154 {
2155 out_str(T_CIS); /* set icon start */
2156 out_str_nf(icon);
2157 out_str(T_CIE); /* set icon end */
2158 out_flush();
2159 }
2160#ifdef FEAT_X11
2161 else
2162# ifdef FEAT_GUI_GTK
2163 if (!gui.in_use) /* don't do this if GTK+ is running */
2164# endif
2165 set_x11_icon(icon); /* x11 */
2166#endif
2167 did_set_icon = TRUE;
2168 }
2169 --recursive;
2170}
2171
2172/*
2173 * Restore the window/icon title.
2174 * "which" is one of:
2175 * 1 only restore title
2176 * 2 only restore icon
2177 * 3 restore title and icon
2178 */
2179 void
2180mch_restore_title(which)
2181 int which;
2182{
2183 /* only restore the title or icon when it has been set */
2184 mch_settitle(((which & 1) && did_set_title) ?
2185 (oldtitle ? oldtitle : p_titleold) : NULL,
2186 ((which & 2) && did_set_icon) ? oldicon : NULL);
2187}
2188
2189#endif /* FEAT_TITLE */
2190
2191/*
2192 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002193 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 */
2195 int
2196vim_is_xterm(name)
2197 char_u *name;
2198{
2199 if (name == NULL)
2200 return FALSE;
2201 return (STRNICMP(name, "xterm", 5) == 0
2202 || STRNICMP(name, "nxterm", 6) == 0
2203 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002204 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 || STRNICMP(name, "rxvt", 4) == 0
2206 || STRCMP(name, "builtin_xterm") == 0);
2207}
2208
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002209#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2210/*
2211 * Return TRUE if "name" appears to be that of a terminal
2212 * known to support the xterm-style mouse protocol.
2213 * Relies on term_is_xterm having been set to its correct value.
2214 */
2215 int
2216use_xterm_like_mouse(name)
2217 char_u *name;
2218{
2219 return (name != NULL
2220 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2221}
2222#endif
2223
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2225/*
2226 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2227 * Return 1 for "xterm".
2228 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002229 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002230 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 */
2232 int
2233use_xterm_mouse()
2234{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002235 if (ttym_flags == TTYM_SGR)
2236 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002237 if (ttym_flags == TTYM_URXVT)
2238 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239 if (ttym_flags == TTYM_XTERM2)
2240 return 2;
2241 if (ttym_flags == TTYM_XTERM)
2242 return 1;
2243 return 0;
2244}
2245#endif
2246
2247 int
2248vim_is_iris(name)
2249 char_u *name;
2250{
2251 if (name == NULL)
2252 return FALSE;
2253 return (STRNICMP(name, "iris-ansi", 9) == 0
2254 || STRCMP(name, "builtin_iris-ansi") == 0);
2255}
2256
2257 int
2258vim_is_vt300(name)
2259 char_u *name;
2260{
2261 if (name == NULL)
2262 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002263 /* catch VT100 - VT5xx */
2264 return ((STRNICMP(name, "vt", 2) == 0
2265 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 || STRCMP(name, "builtin_vt320") == 0);
2267}
2268
2269/*
2270 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2271 * This should include all windowed terminal emulators.
2272 */
2273 int
2274vim_is_fastterm(name)
2275 char_u *name;
2276{
2277 if (name == NULL)
2278 return FALSE;
2279 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2280 return TRUE;
2281 return ( STRNICMP(name, "hpterm", 6) == 0
2282 || STRNICMP(name, "sun-cmd", 7) == 0
2283 || STRNICMP(name, "screen", 6) == 0
2284 || STRNICMP(name, "dtterm", 6) == 0);
2285}
2286
2287/*
2288 * Insert user name in s[len].
2289 * Return OK if a name found.
2290 */
2291 int
2292mch_get_user_name(s, len)
2293 char_u *s;
2294 int len;
2295{
2296#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002297 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 return OK;
2299#else
2300 return mch_get_uname(getuid(), s, len);
2301#endif
2302}
2303
2304/*
2305 * Insert user name for "uid" in s[len].
2306 * Return OK if a name found.
2307 */
2308 int
2309mch_get_uname(uid, s, len)
2310 uid_t uid;
2311 char_u *s;
2312 int len;
2313{
2314#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2315 struct passwd *pw;
2316
2317 if ((pw = getpwuid(uid)) != NULL
2318 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2319 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002320 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 return OK;
2322 }
2323#endif
2324 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2325 return FAIL; /* a number is not a name */
2326}
2327
2328/*
2329 * Insert host name is s[len].
2330 */
2331
2332#ifdef HAVE_SYS_UTSNAME_H
2333 void
2334mch_get_host_name(s, len)
2335 char_u *s;
2336 int len;
2337{
2338 struct utsname vutsname;
2339
2340 if (uname(&vutsname) < 0)
2341 *s = NUL;
2342 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002343 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344}
2345#else /* HAVE_SYS_UTSNAME_H */
2346
2347# ifdef HAVE_SYS_SYSTEMINFO_H
2348# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2349# endif
2350
2351 void
2352mch_get_host_name(s, len)
2353 char_u *s;
2354 int len;
2355{
2356# ifdef VAXC
2357 vaxc$gethostname((char *)s, len);
2358# else
2359 gethostname((char *)s, len);
2360# endif
2361 s[len - 1] = NUL; /* make sure it's terminated */
2362}
2363#endif /* HAVE_SYS_UTSNAME_H */
2364
2365/*
2366 * return process ID
2367 */
2368 long
2369mch_get_pid()
2370{
2371 return (long)getpid();
2372}
2373
2374#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2375static char *strerror __ARGS((int));
2376
2377 static char *
2378strerror(err)
2379 int err;
2380{
2381 extern int sys_nerr;
2382 extern char *sys_errlist[];
2383 static char er[20];
2384
2385 if (err > 0 && err < sys_nerr)
2386 return (sys_errlist[err]);
2387 sprintf(er, "Error %d", err);
2388 return er;
2389}
2390#endif
2391
2392/*
2393 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2394 * Return OK for success, FAIL for failure.
2395 */
2396 int
2397mch_dirname(buf, len)
2398 char_u *buf;
2399 int len;
2400{
2401#if defined(USE_GETCWD)
2402 if (getcwd((char *)buf, len) == NULL)
2403 {
2404 STRCPY(buf, strerror(errno));
2405 return FAIL;
2406 }
2407 return OK;
2408#else
2409 return (getwd((char *)buf) != NULL ? OK : FAIL);
2410#endif
2411}
2412
2413#if defined(OS2) || defined(PROTO)
2414/*
2415 * Replace all slashes by backslashes.
2416 * When 'shellslash' set do it the other way around.
2417 */
2418 void
2419slash_adjust(p)
2420 char_u *p;
2421{
2422 while (*p)
2423 {
2424 if (*p == psepcN)
2425 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002426 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 }
2428}
2429#endif
2430
2431/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002432 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 *
2434 * return FAIL for failure, OK for success
2435 */
2436 int
2437mch_FullName(fname, buf, len, force)
2438 char_u *fname, *buf;
2439 int len;
2440 int force; /* also expand when already absolute path */
2441{
2442 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002443#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002445#endif
2446#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 int fd = -1;
2448 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002449#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 char_u olddir[MAXPATHL];
2451 char_u *p;
2452 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002453#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002454 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2455 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002456#endif
2457
Bram Moolenaar38323e42007-03-06 19:22:53 +00002458#ifdef VMS
2459 fname = vms_fixfilename(fname);
2460#endif
2461
Bram Moolenaara2442432007-04-26 14:26:37 +00002462#ifdef __CYGWIN__
2463 /*
2464 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2465 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002466# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2467 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2468# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002469 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002470# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002471 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002472#endif
2473
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 /* expand it if forced or not an absolute path */
2475 if (force || !mch_isFullName(fname))
2476 {
2477 /*
2478 * If the file name has a path, change to that directory for a moment,
2479 * and then do the getwd() (and get back to where we were).
2480 * This will get the correct path name with "../" things.
2481 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002482#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 only_drive = 0;
2484 if (((p = vim_strrchr(fname, '/')) != NULL)
2485 || ((p = vim_strrchr(fname, '\\')) != NULL)
2486 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002487#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002489#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002491#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 /*
2493 * Use fchdir() if possible, it's said to be faster and more
2494 * reliable. But on SunOS 4 it might not work. Check this by
2495 * doing a fchdir() right now.
2496 */
2497 if (!dont_fchdir)
2498 {
2499 fd = open(".", O_RDONLY | O_EXTRA, 0);
2500 if (fd >= 0 && fchdir(fd) < 0)
2501 {
2502 close(fd);
2503 fd = -1;
2504 dont_fchdir = TRUE; /* don't try again */
2505 }
2506 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002507#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508
2509 /* Only change directory when we are sure we can return to where
2510 * we are now. After doing "su" chdir(".") might not work. */
2511 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002512#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 (mch_dirname(olddir, MAXPATHL) == FAIL
2516 || mch_chdir((char *)olddir) != 0))
2517 {
2518 p = NULL; /* can't get current dir: don't chdir */
2519 retval = FAIL;
2520 }
2521 else
2522 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002523#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 /*
2525 * compensate for case where ':' from "D:" was the only
2526 * path separator detected in the file name; the _next_
2527 * character has to be removed, and then restored later.
2528 */
2529 if (only_drive)
2530 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532 /* The directory is copied into buf[], to be able to remove
2533 * the file name without changing it (could be a string in
2534 * read-only memory) */
2535 if (p - fname >= len)
2536 retval = FAIL;
2537 else
2538 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002539 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (mch_chdir((char *)buf))
2541 retval = FAIL;
2542 else
2543 fname = p + 1;
2544 *buf = NUL;
2545 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002546#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (only_drive)
2548 {
2549 p--;
2550 if (retval != FAIL)
2551 fname--;
2552 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002553#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 }
2555 }
2556 if (mch_dirname(buf, len) == FAIL)
2557 {
2558 retval = FAIL;
2559 *buf = NUL;
2560 }
2561 if (p != NULL)
2562 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002563#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 if (fd >= 0)
2565 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002566 if (p_verbose >= 5)
2567 {
2568 verbose_enter();
2569 MSG("fchdir() to previous dir");
2570 verbose_leave();
2571 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 l = fchdir(fd);
2573 close(fd);
2574 }
2575 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002576#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 l = mch_chdir((char *)olddir);
2578 if (l != 0)
2579 EMSG(_(e_prev_dir));
2580 }
2581
2582 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002583 if (l >= len - 1)
2584 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002585#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002586 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002588 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002589#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002591
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002593 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 return FAIL;
2595
2596 /* Do not append ".", "/dir/." is equal to "/dir". */
2597 if (STRCMP(fname, ".") != 0)
2598 STRCAT(buf, fname);
2599
2600 return OK;
2601}
2602
2603/*
2604 * Return TRUE if "fname" does not depend on the current directory.
2605 */
2606 int
2607mch_isFullName(fname)
2608 char_u *fname;
2609{
2610#ifdef __EMX__
2611 return _fnisabs(fname);
2612#else
2613# ifdef VMS
2614 return ( fname[0] == '/' || fname[0] == '.' ||
2615 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2616 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2617 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2618# else
2619 return (*fname == '/' || *fname == '~');
2620# endif
2621#endif
2622}
2623
Bram Moolenaar24552be2005-12-10 20:17:30 +00002624#if defined(USE_FNAME_CASE) || defined(PROTO)
2625/*
2626 * Set the case of the file name, if it already exists. This will cause the
2627 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002628 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002629 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002630 void
2631fname_case(name, len)
2632 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002633 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002634{
2635 struct stat st;
2636 char_u *slash, *tail;
2637 DIR *dirp;
2638 struct dirent *dp;
2639
2640 if (lstat((char *)name, &st) >= 0)
2641 {
2642 /* Open the directory where the file is located. */
2643 slash = vim_strrchr(name, '/');
2644 if (slash == NULL)
2645 {
2646 dirp = opendir(".");
2647 tail = name;
2648 }
2649 else
2650 {
2651 *slash = NUL;
2652 dirp = opendir((char *)name);
2653 *slash = '/';
2654 tail = slash + 1;
2655 }
2656
2657 if (dirp != NULL)
2658 {
2659 while ((dp = readdir(dirp)) != NULL)
2660 {
2661 /* Only accept names that differ in case and are the same byte
2662 * length. TODO: accept different length name. */
2663 if (STRICMP(tail, dp->d_name) == 0
2664 && STRLEN(tail) == STRLEN(dp->d_name))
2665 {
2666 char_u newname[MAXPATHL + 1];
2667 struct stat st2;
2668
2669 /* Verify the inode is equal. */
2670 vim_strncpy(newname, name, MAXPATHL);
2671 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2672 MAXPATHL - (tail - name));
2673 if (lstat((char *)newname, &st2) >= 0
2674 && st.st_ino == st2.st_ino
2675 && st.st_dev == st2.st_dev)
2676 {
2677 STRCPY(tail, dp->d_name);
2678 break;
2679 }
2680 }
2681 }
2682
2683 closedir(dirp);
2684 }
2685 }
2686}
2687#endif
2688
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689/*
2690 * Get file permissions for 'name'.
2691 * Returns -1 when it doesn't exist.
2692 */
2693 long
2694mch_getperm(name)
2695 char_u *name;
2696{
2697 struct stat statb;
2698
2699 /* Keep the #ifdef outside of stat(), it may be a macro. */
2700#ifdef VMS
2701 if (stat((char *)vms_fixfilename(name), &statb))
2702#else
2703 if (stat((char *)name, &statb))
2704#endif
2705 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002706#ifdef __INTERIX
2707 /* The top bit makes the value negative, which means the file doesn't
2708 * exist. Remove the bit, we don't use it. */
2709 return statb.st_mode & ~S_ADDACE;
2710#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002712#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713}
2714
2715/*
2716 * set file permission for 'name' to 'perm'
2717 *
2718 * return FAIL for failure, OK otherwise
2719 */
2720 int
2721mch_setperm(name, perm)
2722 char_u *name;
2723 long perm;
2724{
2725 return (chmod((char *)
2726#ifdef VMS
2727 vms_fixfilename(name),
2728#else
2729 name,
2730#endif
2731 (mode_t)perm) == 0 ? OK : FAIL);
2732}
2733
2734#if defined(HAVE_ACL) || defined(PROTO)
2735# ifdef HAVE_SYS_ACL_H
2736# include <sys/acl.h>
2737# endif
2738# ifdef HAVE_SYS_ACCESS_H
2739# include <sys/access.h>
2740# endif
2741
2742# ifdef HAVE_SOLARIS_ACL
2743typedef struct vim_acl_solaris_T {
2744 int acl_cnt;
2745 aclent_t *acl_entry;
2746} vim_acl_solaris_T;
2747# endif
2748
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002749#if defined(HAVE_SELINUX) || defined(PROTO)
2750/*
2751 * Copy security info from "from_file" to "to_file".
2752 */
2753 void
2754mch_copy_sec(from_file, to_file)
2755 char_u *from_file;
2756 char_u *to_file;
2757{
2758 if (from_file == NULL)
2759 return;
2760
2761 if (selinux_enabled == -1)
2762 selinux_enabled = is_selinux_enabled();
2763
2764 if (selinux_enabled > 0)
2765 {
2766 security_context_t from_context = NULL;
2767 security_context_t to_context = NULL;
2768
2769 if (getfilecon((char *)from_file, &from_context) < 0)
2770 {
2771 /* If the filesystem doesn't support extended attributes,
2772 the original had no special security context and the
2773 target cannot have one either. */
2774 if (errno == EOPNOTSUPP)
2775 return;
2776
2777 MSG_PUTS(_("\nCould not get security context for "));
2778 msg_outtrans(from_file);
2779 msg_putchar('\n');
2780 return;
2781 }
2782 if (getfilecon((char *)to_file, &to_context) < 0)
2783 {
2784 MSG_PUTS(_("\nCould not get security context for "));
2785 msg_outtrans(to_file);
2786 msg_putchar('\n');
2787 freecon (from_context);
2788 return ;
2789 }
2790 if (strcmp(from_context, to_context) != 0)
2791 {
2792 if (setfilecon((char *)to_file, from_context) < 0)
2793 {
2794 MSG_PUTS(_("\nCould not set security context for "));
2795 msg_outtrans(to_file);
2796 msg_putchar('\n');
2797 }
2798 }
2799 freecon(to_context);
2800 freecon(from_context);
2801 }
2802}
2803#endif /* HAVE_SELINUX */
2804
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805/*
2806 * Return a pointer to the ACL of file "fname" in allocated memory.
2807 * Return NULL if the ACL is not available for whatever reason.
2808 */
2809 vim_acl_T
2810mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002811 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812{
2813 vim_acl_T ret = NULL;
2814#ifdef HAVE_POSIX_ACL
2815 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2816#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002817#ifdef HAVE_SOLARIS_ZFS_ACL
2818 acl_t *aclent;
2819
2820 if (acl_get((char *)fname, 0, &aclent) < 0)
2821 return NULL;
2822 ret = (vim_acl_T)aclent;
2823#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824#ifdef HAVE_SOLARIS_ACL
2825 vim_acl_solaris_T *aclent;
2826
2827 aclent = malloc(sizeof(vim_acl_solaris_T));
2828 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2829 {
2830 free(aclent);
2831 return NULL;
2832 }
2833 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2834 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2835 {
2836 free(aclent->acl_entry);
2837 free(aclent);
2838 return NULL;
2839 }
2840 ret = (vim_acl_T)aclent;
2841#else
2842#if defined(HAVE_AIX_ACL)
2843 int aclsize;
2844 struct acl *aclent;
2845
2846 aclsize = sizeof(struct acl);
2847 aclent = malloc(aclsize);
2848 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2849 {
2850 if (errno == ENOSPC)
2851 {
2852 aclsize = aclent->acl_len;
2853 aclent = realloc(aclent, aclsize);
2854 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2855 {
2856 free(aclent);
2857 return NULL;
2858 }
2859 }
2860 else
2861 {
2862 free(aclent);
2863 return NULL;
2864 }
2865 }
2866 ret = (vim_acl_T)aclent;
2867#endif /* HAVE_AIX_ACL */
2868#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002869#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870#endif /* HAVE_POSIX_ACL */
2871 return ret;
2872}
2873
2874/*
2875 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2876 */
2877 void
2878mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002879 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 vim_acl_T aclent;
2881{
2882 if (aclent == NULL)
2883 return;
2884#ifdef HAVE_POSIX_ACL
2885 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2886#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002887#ifdef HAVE_SOLARIS_ZFS_ACL
2888 acl_set((char *)fname, (acl_t *)aclent);
2889#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890#ifdef HAVE_SOLARIS_ACL
2891 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2892 ((vim_acl_solaris_T *)aclent)->acl_entry);
2893#else
2894#ifdef HAVE_AIX_ACL
2895 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2896#endif /* HAVE_AIX_ACL */
2897#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002898#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899#endif /* HAVE_POSIX_ACL */
2900}
2901
2902 void
2903mch_free_acl(aclent)
2904 vim_acl_T aclent;
2905{
2906 if (aclent == NULL)
2907 return;
2908#ifdef HAVE_POSIX_ACL
2909 acl_free((acl_t)aclent);
2910#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002911#ifdef HAVE_SOLARIS_ZFS_ACL
2912 acl_free((acl_t *)aclent);
2913#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914#ifdef HAVE_SOLARIS_ACL
2915 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2916 free(aclent);
2917#else
2918#ifdef HAVE_AIX_ACL
2919 free(aclent);
2920#endif /* HAVE_AIX_ACL */
2921#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002922#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923#endif /* HAVE_POSIX_ACL */
2924}
2925#endif
2926
2927/*
2928 * Set hidden flag for "name".
2929 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 void
2931mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002932 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933{
2934 /* can't hide a file */
2935}
2936
2937/*
2938 * return TRUE if "name" is a directory
2939 * return FALSE if "name" is not a directory
2940 * return FALSE for error
2941 */
2942 int
2943mch_isdir(name)
2944 char_u *name;
2945{
2946 struct stat statb;
2947
2948 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2949 return FALSE;
2950 if (stat((char *)name, &statb))
2951 return FALSE;
2952#ifdef _POSIX_SOURCE
2953 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2954#else
2955 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2956#endif
2957}
2958
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959static int executable_file __ARGS((char_u *name));
2960
2961/*
2962 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2963 */
2964 static int
2965executable_file(name)
2966 char_u *name;
2967{
2968 struct stat st;
2969
2970 if (stat((char *)name, &st))
2971 return 0;
2972 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2973}
2974
2975/*
2976 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2977 * Return -1 if unknown.
2978 */
2979 int
2980mch_can_exe(name)
2981 char_u *name;
2982{
2983 char_u *buf;
2984 char_u *p, *e;
2985 int retval;
2986
2987 /* If it's an absolute or relative path don't need to use $PATH. */
2988 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2989 || (name[1] == '.' && name[2] == '/'))))
2990 return executable_file(name);
2991
2992 p = (char_u *)getenv("PATH");
2993 if (p == NULL || *p == NUL)
2994 return -1;
2995 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2996 if (buf == NULL)
2997 return -1;
2998
2999 /*
3000 * Walk through all entries in $PATH to check if "name" exists there and
3001 * is an executable file.
3002 */
3003 for (;;)
3004 {
3005 e = (char_u *)strchr((char *)p, ':');
3006 if (e == NULL)
3007 e = p + STRLEN(p);
3008 if (e - p <= 1) /* empty entry means current dir */
3009 STRCPY(buf, "./");
3010 else
3011 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003012 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 add_pathsep(buf);
3014 }
3015 STRCAT(buf, name);
3016 retval = executable_file(buf);
3017 if (retval == 1)
3018 break;
3019
3020 if (*e != ':')
3021 break;
3022 p = e + 1;
3023 }
3024
3025 vim_free(buf);
3026 return retval;
3027}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
3029/*
3030 * Check what "name" is:
3031 * NODE_NORMAL: file or directory (or doesn't exist)
3032 * NODE_WRITABLE: writable device, socket, fifo, etc.
3033 * NODE_OTHER: non-writable things
3034 */
3035 int
3036mch_nodetype(name)
3037 char_u *name;
3038{
3039 struct stat st;
3040
3041 if (stat((char *)name, &st))
3042 return NODE_NORMAL;
3043 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3044 return NODE_NORMAL;
3045#ifndef OS2
3046 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3047 return NODE_OTHER;
3048#endif
3049 /* Everything else is writable? */
3050 return NODE_WRITABLE;
3051}
3052
3053 void
3054mch_early_init()
3055{
3056#ifdef HAVE_CHECK_STACK_GROWTH
3057 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 check_stack_growth((char *)&i);
3060
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003061# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 get_stack_limit();
3063# endif
3064
3065#endif
3066
3067 /*
3068 * Setup an alternative stack for signals. Helps to catch signals when
3069 * running out of stack space.
3070 * Use of sigaltstack() is preferred, it's more portable.
3071 * Ignore any errors.
3072 */
3073#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003074 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 init_signal_stack();
3076#endif
3077}
3078
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003079#if defined(EXITFREE) || defined(PROTO)
3080 void
3081mch_free_mem()
3082{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003083# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3084 if (clip_star.owned)
3085 clip_lose_selection(&clip_star);
3086 if (clip_plus.owned)
3087 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003088# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003089# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003090 if (xterm_Shell != (Widget)0)
3091 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003092# ifndef LESSTIF_VERSION
3093 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003094 if (xterm_dpy != NULL)
3095 XtCloseDisplay(xterm_dpy);
3096 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003097 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003098 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003099# ifdef FEAT_X11
3100 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3101# endif
3102 }
3103# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003104# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003105# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003106 if (x11_display != NULL
3107# ifdef FEAT_XCLIPBOARD
3108 && x11_display != xterm_dpy
3109# endif
3110 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003111 XCloseDisplay(x11_display);
3112# endif
3113# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3114 vim_free(signal_stack);
3115 signal_stack = NULL;
3116# endif
3117# ifdef FEAT_TITLE
3118 vim_free(oldtitle);
3119 vim_free(oldicon);
3120# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003121}
3122#endif
3123
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124static void exit_scroll __ARGS((void));
3125
3126/*
3127 * Output a newline when exiting.
3128 * Make sure the newline goes to the same stream as the text.
3129 */
3130 static void
3131exit_scroll()
3132{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003133 if (silent_mode)
3134 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 if (newline_on_exit || msg_didout)
3136 {
3137 if (msg_use_printf())
3138 {
3139 if (info_message)
3140 mch_msg("\n");
3141 else
3142 mch_errmsg("\r\n");
3143 }
3144 else
3145 out_char('\n');
3146 }
3147 else
3148 {
3149 restore_cterm_colors(); /* get original colors back */
3150 msg_clr_eos_force(); /* clear the rest of the display */
3151 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3152 }
3153}
3154
3155 void
3156mch_exit(r)
3157 int r;
3158{
3159 exiting = TRUE;
3160
3161#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3162 x11_export_final_selection();
3163#endif
3164
3165#ifdef FEAT_GUI
3166 if (!gui.in_use)
3167#endif
3168 {
3169 settmode(TMODE_COOK);
3170#ifdef FEAT_TITLE
3171 mch_restore_title(3); /* restore xterm title and icon name */
3172#endif
3173 /*
3174 * When t_ti is not empty but it doesn't cause swapping terminal
3175 * pages, need to output a newline when msg_didout is set. But when
3176 * t_ti does swap pages it should not go to the shell page. Do this
3177 * before stoptermcap().
3178 */
3179 if (swapping_screen() && !newline_on_exit)
3180 exit_scroll();
3181
3182 /* Stop termcap: May need to check for T_CRV response, which
3183 * requires RAW mode. */
3184 stoptermcap();
3185
3186 /*
3187 * A newline is only required after a message in the alternate screen.
3188 * This is set to TRUE by wait_return().
3189 */
3190 if (!swapping_screen() || newline_on_exit)
3191 exit_scroll();
3192
3193 /* Cursor may have been switched off without calling starttermcap()
3194 * when doing "vim -u vimrc" and vimrc contains ":q". */
3195 if (full_screen)
3196 cursor_on();
3197 }
3198 out_flush();
3199 ml_close_all(TRUE); /* remove all memfiles */
3200 may_core_dump();
3201#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203 gui_exit(r);
3204#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003205
Bram Moolenaar56718732006-03-15 22:53:57 +00003206#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003207 mac_conv_cleanup();
3208#endif
3209
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210#ifdef __QNX__
3211 /* A core dump won't be created if the signal handler
3212 * doesn't return, so we can't call exit() */
3213 if (deadly_signal != 0)
3214 return;
3215#endif
3216
Bram Moolenaar009b2592004-10-24 19:18:58 +00003217#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003218 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003219#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003220
3221#ifdef EXITFREE
3222 free_all_mem();
3223#endif
3224
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225 exit(r);
3226}
3227
3228 static void
3229may_core_dump()
3230{
3231 if (deadly_signal != 0)
3232 {
3233 signal(deadly_signal, SIG_DFL);
3234 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3235 }
3236}
3237
3238#ifndef VMS
3239
3240 void
3241mch_settmode(tmode)
3242 int tmode;
3243{
3244 static int first = TRUE;
3245
3246 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3247#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3248 /*
3249 * for "new" tty systems
3250 */
3251# ifdef HAVE_TERMIOS_H
3252 static struct termios told;
3253 struct termios tnew;
3254# else
3255 static struct termio told;
3256 struct termio tnew;
3257# endif
3258
3259 if (first)
3260 {
3261 first = FALSE;
3262# if defined(HAVE_TERMIOS_H)
3263 tcgetattr(read_cmd_fd, &told);
3264# else
3265 ioctl(read_cmd_fd, TCGETA, &told);
3266# endif
3267 }
3268
3269 tnew = told;
3270 if (tmode == TMODE_RAW)
3271 {
3272 /*
3273 * ~ICRNL enables typing ^V^M
3274 */
3275 tnew.c_iflag &= ~ICRNL;
3276 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3277# if defined(IEXTEN) && !defined(__MINT__)
3278 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3279 /* but it breaks function keys on MINT */
3280# endif
3281 );
3282# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3283 tnew.c_oflag &= ~ONLCR;
3284# endif
3285 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3286 tnew.c_cc[VTIME] = 0; /* don't wait */
3287 }
3288 else if (tmode == TMODE_SLEEP)
3289 tnew.c_lflag &= ~(ECHO);
3290
3291# if defined(HAVE_TERMIOS_H)
3292 {
3293 int n = 10;
3294
3295 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3296 * few times. */
3297 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3298 && errno == EINTR && n > 0)
3299 --n;
3300 }
3301# else
3302 ioctl(read_cmd_fd, TCSETA, &tnew);
3303# endif
3304
3305#else
3306
3307 /*
3308 * for "old" tty systems
3309 */
3310# ifndef TIOCSETN
3311# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3312# endif
3313 static struct sgttyb ttybold;
3314 struct sgttyb ttybnew;
3315
3316 if (first)
3317 {
3318 first = FALSE;
3319 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3320 }
3321
3322 ttybnew = ttybold;
3323 if (tmode == TMODE_RAW)
3324 {
3325 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3326 ttybnew.sg_flags |= RAW;
3327 }
3328 else if (tmode == TMODE_SLEEP)
3329 ttybnew.sg_flags &= ~(ECHO);
3330 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3331#endif
3332 curr_tmode = tmode;
3333}
3334
3335/*
3336 * Try to get the code for "t_kb" from the stty setting
3337 *
3338 * Even if termcap claims a backspace key, the user's setting *should*
3339 * prevail. stty knows more about reality than termcap does, and if
3340 * somebody's usual erase key is DEL (which, for most BSD users, it will
3341 * be), they're going to get really annoyed if their erase key starts
3342 * doing forward deletes for no reason. (Eric Fischer)
3343 */
3344 void
3345get_stty()
3346{
3347 char_u buf[2];
3348 char_u *p;
3349
3350 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3351#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3352 /* for "new" tty systems */
3353# ifdef HAVE_TERMIOS_H
3354 struct termios keys;
3355# else
3356 struct termio keys;
3357# endif
3358
3359# if defined(HAVE_TERMIOS_H)
3360 if (tcgetattr(read_cmd_fd, &keys) != -1)
3361# else
3362 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3363# endif
3364 {
3365 buf[0] = keys.c_cc[VERASE];
3366 intr_char = keys.c_cc[VINTR];
3367#else
3368 /* for "old" tty systems */
3369 struct sgttyb keys;
3370
3371 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3372 {
3373 buf[0] = keys.sg_erase;
3374 intr_char = keys.sg_kill;
3375#endif
3376 buf[1] = NUL;
3377 add_termcode((char_u *)"kb", buf, FALSE);
3378
3379 /*
3380 * If <BS> and <DEL> are now the same, redefine <DEL>.
3381 */
3382 p = find_termcode((char_u *)"kD");
3383 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3384 do_fixdel(NULL);
3385 }
3386#if 0
3387 } /* to keep cindent happy */
3388#endif
3389}
3390
3391#endif /* VMS */
3392
3393#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3394/*
3395 * Set mouse clicks on or off.
3396 */
3397 void
3398mch_setmouse(on)
3399 int on;
3400{
3401 static int ison = FALSE;
3402 int xterm_mouse_vers;
3403
3404 if (on == ison) /* return quickly if nothing to do */
3405 return;
3406
3407 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003408
3409# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003410 if (ttym_flags == TTYM_URXVT)
3411 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003412 out_str_nf((char_u *)
3413 (on
3414 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3415 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3416 ison = on;
3417 }
3418# endif
3419
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003420# ifdef FEAT_MOUSE_SGR
3421 if (ttym_flags == TTYM_SGR)
3422 {
3423 out_str_nf((char_u *)
3424 (on
3425 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3426 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3427 ison = on;
3428 }
3429# endif
3430
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431 if (xterm_mouse_vers > 0)
3432 {
3433 if (on) /* enable mouse events, use mouse tracking if available */
3434 out_str_nf((char_u *)
3435 (xterm_mouse_vers > 1
3436 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3437 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3438 else /* disable mouse events, could probably always send the same */
3439 out_str_nf((char_u *)
3440 (xterm_mouse_vers > 1
3441 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3442 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3443 ison = on;
3444 }
3445
3446# ifdef FEAT_MOUSE_DEC
3447 else if (ttym_flags == TTYM_DEC)
3448 {
3449 if (on) /* enable mouse events */
3450 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3451 else /* disable mouse events */
3452 out_str_nf((char_u *)"\033['z");
3453 ison = on;
3454 }
3455# endif
3456
3457# ifdef FEAT_MOUSE_GPM
3458 else
3459 {
3460 if (on)
3461 {
3462 if (gpm_open())
3463 ison = TRUE;
3464 }
3465 else
3466 {
3467 gpm_close();
3468 ison = FALSE;
3469 }
3470 }
3471# endif
3472
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003473# ifdef FEAT_SYSMOUSE
3474 else
3475 {
3476 if (on)
3477 {
3478 if (sysmouse_open() == OK)
3479 ison = TRUE;
3480 }
3481 else
3482 {
3483 sysmouse_close();
3484 ison = FALSE;
3485 }
3486 }
3487# endif
3488
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489# ifdef FEAT_MOUSE_JSB
3490 else
3491 {
3492 if (on)
3493 {
3494 /* D - Enable Mouse up/down messages
3495 * L - Enable Left Button Reporting
3496 * M - Enable Middle Button Reporting
3497 * R - Enable Right Button Reporting
3498 * K - Enable SHIFT and CTRL key Reporting
3499 * + - Enable Advanced messaging of mouse moves and up/down messages
3500 * Q - Quiet No Ack
3501 * # - Numeric value of mouse pointer required
3502 * 0 = Multiview 2000 cursor, used as standard
3503 * 1 = Windows Arrow
3504 * 2 = Windows I Beam
3505 * 3 = Windows Hour Glass
3506 * 4 = Windows Cross Hair
3507 * 5 = Windows UP Arrow
3508 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003509# ifdef JSBTERM_MOUSE_NONADVANCED
3510 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3512 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003513# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3515 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 ison = TRUE;
3518 }
3519 else
3520 {
3521 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3522 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3523 ison = FALSE;
3524 }
3525 }
3526# endif
3527# ifdef FEAT_MOUSE_PTERM
3528 else
3529 {
3530 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3531 if (on)
3532 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3533 else
3534 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3535 ison = on;
3536 }
3537# endif
3538}
3539
3540/*
3541 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3542 */
3543 void
3544check_mouse_termcode()
3545{
3546# ifdef FEAT_MOUSE_XTERM
3547 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003548# ifdef FEAT_MOUSE_URXVT
3549 && use_xterm_mouse() != 3
3550# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551# ifdef FEAT_GUI
3552 && !gui.in_use
3553# endif
3554 )
3555 {
3556 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003557 ? IF_EB("\233M", CSI_STR "M")
3558 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 if (*p_mouse != NUL)
3560 {
3561 /* force mouse off and maybe on to send possibly new mouse
3562 * activation sequence to the xterm, with(out) drag tracing. */
3563 mch_setmouse(FALSE);
3564 setmouse();
3565 }
3566 }
3567 else
3568 del_mouse_termcode(KS_MOUSE);
3569# endif
3570
3571# ifdef FEAT_MOUSE_GPM
3572 if (!use_xterm_mouse()
3573# ifdef FEAT_GUI
3574 && !gui.in_use
3575# endif
3576 )
3577 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3578# endif
3579
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003580# ifdef FEAT_SYSMOUSE
3581 if (!use_xterm_mouse()
3582# ifdef FEAT_GUI
3583 && !gui.in_use
3584# endif
3585 )
3586 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3587# endif
3588
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589# ifdef FEAT_MOUSE_JSB
3590 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3591 if (!use_xterm_mouse()
3592# ifdef FEAT_GUI
3593 && !gui.in_use
3594# endif
3595 )
3596 set_mouse_termcode(KS_JSBTERM_MOUSE,
3597 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3598 else
3599 del_mouse_termcode(KS_JSBTERM_MOUSE);
3600# endif
3601
3602# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003603 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 * define it in the GUI or when using an xterm. */
3605 if (!use_xterm_mouse()
3606# ifdef FEAT_GUI
3607 && !gui.in_use
3608# endif
3609 )
3610 set_mouse_termcode(KS_NETTERM_MOUSE,
3611 (char_u *)IF_EB("\033}", ESC_STR "}"));
3612 else
3613 del_mouse_termcode(KS_NETTERM_MOUSE);
3614# endif
3615
3616# ifdef FEAT_MOUSE_DEC
3617 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3618 if (!use_xterm_mouse()
3619# ifdef FEAT_GUI
3620 && !gui.in_use
3621# endif
3622 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003623 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3624 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 else
3626 del_mouse_termcode(KS_DEC_MOUSE);
3627# endif
3628# ifdef FEAT_MOUSE_PTERM
3629 /* same as the dec mouse */
3630 if (!use_xterm_mouse()
3631# ifdef FEAT_GUI
3632 && !gui.in_use
3633# endif
3634 )
3635 set_mouse_termcode(KS_PTERM_MOUSE,
3636 (char_u *) IF_EB("\033[", ESC_STR "["));
3637 else
3638 del_mouse_termcode(KS_PTERM_MOUSE);
3639# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003640# ifdef FEAT_MOUSE_URXVT
3641 /* same as the dec mouse */
3642 if (use_xterm_mouse() == 3
3643# ifdef FEAT_GUI
3644 && !gui.in_use
3645# endif
3646 )
3647 {
3648 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3649 ? IF_EB("\233", CSI_STR)
3650 : IF_EB("\033[", ESC_STR "[")));
3651
3652 if (*p_mouse != NUL)
3653 {
3654 mch_setmouse(FALSE);
3655 setmouse();
3656 }
3657 }
3658 else
3659 del_mouse_termcode(KS_URXVT_MOUSE);
3660# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003661# ifdef FEAT_MOUSE_SGR
3662 /* same as the dec mouse */
3663 if (use_xterm_mouse() == 4
3664# ifdef FEAT_GUI
3665 && !gui.in_use
3666# endif
3667 )
3668 {
3669 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3670 ? IF_EB("\233<", CSI_STR "<")
3671 : IF_EB("\033[<", ESC_STR "[<")));
3672
3673 if (*p_mouse != NUL)
3674 {
3675 mch_setmouse(FALSE);
3676 setmouse();
3677 }
3678 }
3679 else
3680 del_mouse_termcode(KS_SGR_MOUSE);
3681# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682}
3683#endif
3684
3685/*
3686 * set screen mode, always fails.
3687 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688 int
3689mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003690 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691{
3692 EMSG(_(e_screenmode));
3693 return FAIL;
3694}
3695
3696#ifndef VMS
3697
3698/*
3699 * Try to get the current window size:
3700 * 1. with an ioctl(), most accurate method
3701 * 2. from the environment variables LINES and COLUMNS
3702 * 3. from the termcap
3703 * 4. keep using the old values
3704 * Return OK when size could be determined, FAIL otherwise.
3705 */
3706 int
3707mch_get_shellsize()
3708{
3709 long rows = 0;
3710 long columns = 0;
3711 char_u *p;
3712
3713 /*
3714 * For OS/2 use _scrsize().
3715 */
3716# ifdef __EMX__
3717 {
3718 int s[2];
3719
3720 _scrsize(s);
3721 columns = s[0];
3722 rows = s[1];
3723 }
3724# endif
3725
3726 /*
3727 * 1. try using an ioctl. It is the most accurate method.
3728 *
3729 * Try using TIOCGWINSZ first, some systems that have it also define
3730 * TIOCGSIZE but don't have a struct ttysize.
3731 */
3732# ifdef TIOCGWINSZ
3733 {
3734 struct winsize ws;
3735 int fd = 1;
3736
3737 /* When stdout is not a tty, use stdin for the ioctl(). */
3738 if (!isatty(fd) && isatty(read_cmd_fd))
3739 fd = read_cmd_fd;
3740 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3741 {
3742 columns = ws.ws_col;
3743 rows = ws.ws_row;
3744 }
3745 }
3746# else /* TIOCGWINSZ */
3747# ifdef TIOCGSIZE
3748 {
3749 struct ttysize ts;
3750 int fd = 1;
3751
3752 /* When stdout is not a tty, use stdin for the ioctl(). */
3753 if (!isatty(fd) && isatty(read_cmd_fd))
3754 fd = read_cmd_fd;
3755 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3756 {
3757 columns = ts.ts_cols;
3758 rows = ts.ts_lines;
3759 }
3760 }
3761# endif /* TIOCGSIZE */
3762# endif /* TIOCGWINSZ */
3763
3764 /*
3765 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003766 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3767 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003769 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 {
3771 if ((p = (char_u *)getenv("LINES")))
3772 rows = atoi((char *)p);
3773 if ((p = (char_u *)getenv("COLUMNS")))
3774 columns = atoi((char *)p);
3775 }
3776
3777#ifdef HAVE_TGETENT
3778 /*
3779 * 3. try reading "co" and "li" entries from termcap
3780 */
3781 if (columns == 0 || rows == 0)
3782 getlinecol(&columns, &rows);
3783#endif
3784
3785 /*
3786 * 4. If everything fails, use the old values
3787 */
3788 if (columns <= 0 || rows <= 0)
3789 return FAIL;
3790
3791 Rows = rows;
3792 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003793 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 return OK;
3795}
3796
3797/*
3798 * Try to set the window size to Rows and Columns.
3799 */
3800 void
3801mch_set_shellsize()
3802{
3803 if (*T_CWS)
3804 {
3805 /*
3806 * NOTE: if you get an error here that term_set_winsize() is
3807 * undefined, check the output of configure. It could probably not
3808 * find a ncurses, termcap or termlib library.
3809 */
3810 term_set_winsize((int)Rows, (int)Columns);
3811 out_flush();
3812 screen_start(); /* don't know where cursor is now */
3813 }
3814}
3815
3816#endif /* VMS */
3817
3818/*
3819 * Rows and/or Columns has changed.
3820 */
3821 void
3822mch_new_shellsize()
3823{
3824 /* Nothing to do. */
3825}
3826
Bram Moolenaar205b8862011-09-07 15:04:31 +02003827/*
3828 * Wait for process "child" to end.
3829 * Return "child" if it exited properly, <= 0 on error.
3830 */
3831 static pid_t
3832wait4pid(child, status)
3833 pid_t child;
3834 waitstatus *status;
3835{
3836 pid_t wait_pid = 0;
3837
3838 while (wait_pid != child)
3839 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003840 /* When compiled with Python threads are probably used, in which case
3841 * wait() sometimes hangs for no obvious reason. Use waitpid()
3842 * instead and loop (like the GUI). Also needed for other interfaces,
3843 * they might call system(). */
3844# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003845 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003846# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003847 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003848# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003849 if (wait_pid == 0)
3850 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003851 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003852 mch_delay(10L, TRUE);
3853 continue;
3854 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003855 if (wait_pid <= 0
3856# ifdef ECHILD
3857 && errno == ECHILD
3858# endif
3859 )
3860 break;
3861 }
3862 return wait_pid;
3863}
3864
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 int
3866mch_call_shell(cmd, options)
3867 char_u *cmd;
3868 int options; /* SHELL_*, see vim.h */
3869{
3870#ifdef VMS
3871 char *ifn = NULL;
3872 char *ofn = NULL;
3873#endif
3874 int tmode = cur_tmode;
3875#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3876 int x;
3877# ifndef __EMX__
3878 char_u *newcmd; /* only needed for unix */
3879# else
3880 /*
3881 * Set the preferred shell in the EMXSHELL environment variable (but
3882 * only if it is different from what is already in the environment).
3883 * Emx then takes care of whether to use "/c" or "-c" in an
3884 * intelligent way. Simply pass the whole thing to emx's system() call.
3885 * Emx also starts an interactive shell if system() is passed an empty
3886 * string.
3887 */
3888 char_u *p, *old;
3889
3890 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3891 {
3892 /* should check HAVE_SETENV, but I know we don't have it. */
3893 p = alloc(10 + strlen(p_sh));
3894 if (p)
3895 {
3896 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3897 putenv((char *)p); /* don't free the pointer! */
3898 }
3899 }
3900# endif
3901
3902 out_flush();
3903
3904 if (options & SHELL_COOKED)
3905 settmode(TMODE_COOK); /* set to normal mode */
3906
Bram Moolenaar62b42182010-09-21 22:09:37 +02003907# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003908 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02003909 loose_clipboard();
3910# endif
3911
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912# ifdef __EMX__
3913 if (cmd == NULL)
3914 x = system(""); /* this starts an interactive shell in emx */
3915 else
3916 x = system((char *)cmd);
3917 /* system() returns -1 when error occurs in starting shell */
3918 if (x == -1 && !emsg_silent)
3919 {
3920 MSG_PUTS(_("\nCannot execute shell "));
3921 msg_outtrans(p_sh);
3922 msg_putchar('\n');
3923 }
3924# else /* not __EMX__ */
3925 if (cmd == NULL)
3926 x = system((char *)p_sh);
3927 else
3928 {
3929# ifdef VMS
3930 if (ofn = strchr((char *)cmd, '>'))
3931 *ofn++ = '\0';
3932 if (ifn = strchr((char *)cmd, '<'))
3933 {
3934 char *p;
3935
3936 *ifn++ = '\0';
3937 p = strchr(ifn,' '); /* chop off any trailing spaces */
3938 if (p)
3939 *p = '\0';
3940 }
3941 if (ofn)
3942 x = vms_sys((char *)cmd, ofn, ifn);
3943 else
3944 x = system((char *)cmd);
3945# else
3946 newcmd = lalloc(STRLEN(p_sh)
3947 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3948 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3949 if (newcmd == NULL)
3950 x = 0;
3951 else
3952 {
3953 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3954 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3955 (char *)p_shcf,
3956 (char *)cmd);
3957 x = system((char *)newcmd);
3958 vim_free(newcmd);
3959 }
3960# endif
3961 }
3962# ifdef VMS
3963 x = vms_sys_status(x);
3964# endif
3965 if (emsg_silent)
3966 ;
3967 else if (x == 127)
3968 MSG_PUTS(_("\nCannot execute shell sh\n"));
3969# endif /* __EMX__ */
3970 else if (x && !(options & SHELL_SILENT))
3971 {
3972 MSG_PUTS(_("\nshell returned "));
3973 msg_outnum((long)x);
3974 msg_putchar('\n');
3975 }
3976
3977 if (tmode == TMODE_RAW)
3978 settmode(TMODE_RAW); /* set to raw mode */
3979# ifdef FEAT_TITLE
3980 resettitle();
3981# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01003982# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3983 restore_clipboard();
3984# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985 return x;
3986
3987#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3988
Bram Moolenaardf177f62005-02-22 08:39:57 +00003989# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3990 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991
3992 char_u *newcmd = NULL;
3993 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003994 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 pid_t wait_pid = 0;
3996# ifdef HAVE_UNION_WAIT
3997 union wait status;
3998# else
3999 int status = -1;
4000# endif
4001 int retval = -1;
4002 char **argv = NULL;
4003 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004004 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005 int i;
4006 char_u *p;
4007 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004009# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 int pty_slave_fd = -1;
4011 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004012# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004013 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014 int fd_fromshell[2];
4015 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004016# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004018# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019 static char envbuf_Rows[20];
4020 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004022 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023
Bram Moolenaar62b42182010-09-21 22:09:37 +02004024 newcmd = vim_strsave(p_sh);
4025 if (newcmd == NULL) /* out of memory */
4026 goto error;
4027
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 out_flush();
4029 if (options & SHELL_COOKED)
4030 settmode(TMODE_COOK); /* set to normal mode */
4031
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004032 /*
4033 * Do this loop twice:
4034 * 1: find number of arguments
4035 * 2: separate them and build argv[]
4036 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004037 for (i = 0; i < 2; ++i)
4038 {
4039 p = newcmd;
4040 inquote = FALSE;
4041 argc = 0;
4042 for (;;)
4043 {
4044 if (i == 1)
4045 argv[argc] = (char *)p;
4046 ++argc;
4047 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4048 {
4049 if (*p == '"')
4050 inquote = !inquote;
4051 ++p;
4052 }
4053 if (*p == NUL)
4054 break;
4055 if (i == 1)
4056 *p++ = NUL;
4057 p = skipwhite(p);
4058 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004059 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004061 /*
4062 * Account for possible multiple args in p_shcf.
4063 */
4064 p = p_shcf;
4065 for (;;)
4066 {
4067 p = skiptowhite(p);
4068 if (*p == NUL)
4069 break;
4070 ++argc;
4071 p = skipwhite(p);
4072 }
4073
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4075 if (argv == NULL) /* out of memory */
4076 goto error;
4077 }
4078 }
4079 if (cmd != NULL)
4080 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004081 char_u *s;
4082
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083 if (extra_shell_arg != NULL)
4084 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004085
4086 /* Break 'shellcmdflag' into white separated parts. This doesn't
4087 * handle quoted strings, they are very unlikely to appear. */
4088 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4089 if (p_shcf_copy == NULL) /* out of memory */
4090 goto error;
4091 s = p_shcf_copy;
4092 p = p_shcf;
4093 while (*p != NUL)
4094 {
4095 argv[argc++] = (char *)s;
4096 while (*p && *p != ' ' && *p != TAB)
4097 *s++ = *p++;
4098 *s++ = NUL;
4099 p = skipwhite(p);
4100 }
4101
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 argv[argc++] = (char *)cmd;
4103 }
4104 argv[argc] = NULL;
4105
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004107 * For the GUI, when writing the output into the buffer and when reading
4108 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4109 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004111 if ((options & (SHELL_READ|SHELL_WRITE))
4112# ifdef FEAT_GUI
4113 || (gui.in_use && show_shell_mess)
4114# endif
4115 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004117# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 /*
4119 * Try to open a master pty.
4120 * If this works, open the slave pty.
4121 * If the slave can't be opened, close the master pty.
4122 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004123 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 {
4125 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004126 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004128 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4129 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4130 * adding O_NOCTTY always works when defined. */
4131#ifdef O_NOCTTY
4132 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4133#else
4134 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4135#endif
4136 if (pty_slave_fd < 0)
4137 {
4138 close(pty_master_fd);
4139 pty_master_fd = -1;
4140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 }
4142 }
4143 /*
4144 * If not opening a pty or it didn't work, try using pipes.
4145 */
4146 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004147# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 {
4149 pipe_error = (pipe(fd_toshell) < 0);
4150 if (!pipe_error) /* pipe create OK */
4151 {
4152 pipe_error = (pipe(fd_fromshell) < 0);
4153 if (pipe_error) /* pipe create failed */
4154 {
4155 close(fd_toshell[0]);
4156 close(fd_toshell[1]);
4157 }
4158 }
4159 if (pipe_error)
4160 {
4161 MSG_PUTS(_("\nCannot create pipes\n"));
4162 out_flush();
4163 }
4164 }
4165 }
4166
4167 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 {
4169# ifdef __BEOS__
4170 beos_cleanup_read_thread();
4171# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004172
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4174 {
4175 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004176 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004178 || (gui.in_use && show_shell_mess)
4179# endif
4180 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004182# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 if (pty_master_fd >= 0) /* close the pseudo tty */
4184 {
4185 close(pty_master_fd);
4186 close(pty_slave_fd);
4187 }
4188 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004189# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 {
4191 close(fd_toshell[0]);
4192 close(fd_toshell[1]);
4193 close(fd_fromshell[0]);
4194 close(fd_fromshell[1]);
4195 }
4196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 }
4198 else if (pid == 0) /* child */
4199 {
4200 reset_signals(); /* handle signals normally */
4201
4202 if (!show_shell_mess || (options & SHELL_EXPAND))
4203 {
4204 int fd;
4205
4206 /*
4207 * Don't want to show any message from the shell. Can't just
4208 * close stdout and stderr though, because some systems will
4209 * break if you try to write to them after that, so we must
4210 * use dup() to replace them with something else -- webb
4211 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4212 * waiting for input.
4213 */
4214 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4215 fclose(stdin);
4216 fclose(stdout);
4217 fclose(stderr);
4218
4219 /*
4220 * If any of these open()'s and dup()'s fail, we just continue
4221 * anyway. It's not fatal, and on most systems it will make
4222 * no difference at all. On a few it will cause the execvp()
4223 * to exit with a non-zero status even when the completion
4224 * could be done, which is nothing too serious. If the open()
4225 * or dup() failed we'd just do the same thing ourselves
4226 * anyway -- webb
4227 */
4228 if (fd >= 0)
4229 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004230 ignored = dup(fd); /* To replace stdin (fd 0) */
4231 ignored = dup(fd); /* To replace stdout (fd 1) */
4232 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233
4234 /* Don't need this now that we've duplicated it */
4235 close(fd);
4236 }
4237 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004238 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004240 || gui.in_use
4241# endif
4242 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 {
4244
Bram Moolenaardf177f62005-02-22 08:39:57 +00004245# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004246 /* Create our own process group, so that the child and all its
4247 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004248 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004249 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004250 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004251 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004252# if defined(SIGHUP)
4253 /* When doing "!xterm&" and 'shell' is bash: the shell
4254 * will exit and send SIGHUP to all processes in its
4255 * group, killing the just started process. Ignore SIGHUP
4256 * to avoid that. (suggested by Simon Schubert)
4257 */
4258 signal(SIGHUP, SIG_IGN);
4259# endif
4260 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004261# endif
4262# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004263 if (pty_slave_fd >= 0)
4264 {
4265 /* push stream discipline modules */
4266 if (options & SHELL_COOKED)
4267 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004269 /* Try to become controlling tty (probably doesn't work,
4270 * unless run by root) */
4271 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004273 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004274# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004276# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 setenv("TERM", "dumb", 1);
4278 sprintf((char *)envbuf, "%ld", Rows);
4279 setenv("ROWS", (char *)envbuf, 1);
4280 sprintf((char *)envbuf, "%ld", Rows);
4281 setenv("LINES", (char *)envbuf, 1);
4282 sprintf((char *)envbuf, "%ld", Columns);
4283 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004284# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 /*
4286 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004287 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288 */
4289 putenv("TERM=dumb");
4290 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4291 putenv(envbuf_Rows);
4292 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4293 putenv(envbuf_Rows);
4294 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4295 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004296# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297
Bram Moolenaara5792f52005-11-23 21:25:05 +00004298 /*
4299 * stderr is only redirected when using the GUI, so that a
4300 * program like gpg can still access the terminal to get a
4301 * passphrase using stderr.
4302 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004303# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 if (pty_master_fd >= 0)
4305 {
4306 close(pty_master_fd); /* close master side of pty */
4307
4308 /* set up stdin/stdout/stderr for the child */
4309 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004310 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004312 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004313 if (gui.in_use)
4314 {
4315 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004316 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318
4319 close(pty_slave_fd); /* has been dupped, close it now */
4320 }
4321 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004322# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004323 {
4324 /* set up stdin for the child */
4325 close(fd_toshell[1]);
4326 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004327 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328 close(fd_toshell[0]);
4329
4330 /* set up stdout for the child */
4331 close(fd_fromshell[0]);
4332 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004333 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 close(fd_fromshell[1]);
4335
Bram Moolenaara5792f52005-11-23 21:25:05 +00004336# ifdef FEAT_GUI
4337 if (gui.in_use)
4338 {
4339 /* set up stderr for the child */
4340 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004341 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004342 }
4343# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 }
4345 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004346
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347 /*
4348 * There is no type cast for the argv, because the type may be
4349 * different on different machines. This may cause a warning
4350 * message with strict compilers, don't worry about it.
4351 * Call _exit() instead of exit() to avoid closing the connection
4352 * to the X server (esp. with GTK, which uses atexit()).
4353 */
4354 execvp(argv[0], argv);
4355 _exit(EXEC_FAILED); /* exec failed, return failure code */
4356 }
4357 else /* parent */
4358 {
4359 /*
4360 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004361 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362 */
4363 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004364 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365
4366 /*
4367 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004368 * This is also used to pipe stdin/stdout to/from the external
4369 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004371 if ((options & (SHELL_READ|SHELL_WRITE))
4372# ifdef FEAT_GUI
4373 || (gui.in_use && show_shell_mess)
4374# endif
4375 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004377# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004379# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004381# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4383 int ta_len = 0; /* valid bytes in ta_buf[] */
4384 int len;
4385 int p_more_save;
4386 int old_State;
4387 int c;
4388 int toshell_fd;
4389 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004390 garray_T ga;
4391 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004392# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4393 struct timeval start_tv;
4394# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395
Bram Moolenaardf177f62005-02-22 08:39:57 +00004396# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004397 if (pty_master_fd >= 0)
4398 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399 fromshell_fd = pty_master_fd;
4400 toshell_fd = dup(pty_master_fd);
4401 }
4402 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004403# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404 {
4405 close(fd_toshell[0]);
4406 close(fd_fromshell[1]);
4407 toshell_fd = fd_toshell[1];
4408 fromshell_fd = fd_fromshell[0];
4409 }
4410
4411 /*
4412 * Write to the child if there are typed characters.
4413 * Read from the child if there are characters available.
4414 * Repeat the reading a few times if more characters are
4415 * available. Need to check for typed keys now and then, but
4416 * not too often (delays when no chars are available).
4417 * This loop is quit if no characters can be read from the pty
4418 * (WaitForChar detected special condition), or there are no
4419 * characters available and the child has exited.
4420 * Only check if the child has exited when there is no more
4421 * output. The child may exit before all the output has
4422 * been printed.
4423 *
4424 * Currently this busy loops!
4425 * This can probably dead-lock when the write blocks!
4426 */
4427 p_more_save = p_more;
4428 p_more = FALSE;
4429 old_State = State;
4430 State = EXTERNCMD; /* don't redraw at window resize */
4431
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004432 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004433 {
4434 /* Fork a process that will write the lines to the
4435 * external program. */
4436 if ((wpid = fork()) == -1)
4437 {
4438 MSG_PUTS(_("\nCannot fork\n"));
4439 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004440 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004441 {
4442 linenr_T lnum = curbuf->b_op_start.lnum;
4443 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004444 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004445 size_t l;
4446
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004447 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004448 for (;;)
4449 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004450 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004451 if (l == 0)
4452 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004453 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004454 /* NL -> NUL translation */
4455 len = write(toshell_fd, "", (size_t)1);
4456 else
4457 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004458 char_u *s = vim_strchr(lp + written, NL);
4459
Bram Moolenaar89d40322006-08-29 15:30:07 +00004460 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004461 s == NULL ? l
4462 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004463 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004464 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004465 {
4466 /* Finished a line, add a NL, unless this line
4467 * should not have one. */
4468 if (lnum != curbuf->b_op_end.lnum
4469 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004470 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004471 && (lnum !=
4472 curbuf->b_ml.ml_line_count
4473 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004474 ignored = write(toshell_fd, "\n",
4475 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004476 ++lnum;
4477 if (lnum > curbuf->b_op_end.lnum)
4478 {
4479 /* finished all the lines, close pipe */
4480 close(toshell_fd);
4481 toshell_fd = -1;
4482 break;
4483 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004484 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004485 written = 0;
4486 }
4487 else if (len > 0)
4488 written += len;
4489 }
4490 _exit(0);
4491 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004492 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004493 {
4494 close(toshell_fd);
4495 toshell_fd = -1;
4496 }
4497 }
4498
4499 if (options & SHELL_READ)
4500 ga_init2(&ga, 1, BUFLEN);
4501
4502 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004503# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4504 gettimeofday(&start_tv, NULL);
4505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 for (;;)
4507 {
4508 /*
4509 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004510 * if there are any.
4511 * Don't do this if we are expanding wild cards (would eat
4512 * typeahead).
4513 * Don't do this when filtering and terminal is in cooked
4514 * mode, the shell command will handle the I/O. Avoids
4515 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004516 * Don't get characters when the child has already
4517 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004518 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004519 * while (noread_cnt > 4), avoids that ":r !ls" eats
4520 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 */
4522 len = 0;
4523 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004524 && ((options &
4525 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4526 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004527# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004528 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004529# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004530 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004531 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004532 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004534 if (ta_len == 0)
4535 {
4536 /* Get extra characters when we don't have any.
4537 * Reset the counter and timer. */
4538 noread_cnt = 0;
4539# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4540 gettimeofday(&start_tv, NULL);
4541# endif
4542 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4543 }
4544 if (ta_len > 0 || len > 0)
4545 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 /*
4547 * For pipes:
4548 * Check for CTRL-C: send interrupt signal to child.
4549 * Check for CTRL-D: EOF, close pipe to child.
4550 */
4551 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4552 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004553# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004554 /*
4555 * Send SIGINT to the child's group or all
4556 * processes in our group.
4557 */
4558 if (ta_buf[ta_len] == Ctrl_C
4559 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004560 {
4561# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004563# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004566 if (wpid > 0)
4567 kill(wpid, SIGINT);
4568 }
4569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 if (pty_master_fd < 0 && toshell_fd >= 0
4571 && ta_buf[ta_len] == Ctrl_D)
4572 {
4573 close(toshell_fd);
4574 toshell_fd = -1;
4575 }
4576 }
4577
4578 /* replace K_BS by <BS> and K_DEL by <DEL> */
4579 for (i = ta_len; i < ta_len + len; ++i)
4580 {
4581 if (ta_buf[i] == CSI && len - i > 2)
4582 {
4583 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4584 if (c == K_DEL || c == K_KDEL || c == K_BS)
4585 {
4586 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4587 (size_t)(len - i - 2));
4588 if (c == K_DEL || c == K_KDEL)
4589 ta_buf[i] = DEL;
4590 else
4591 ta_buf[i] = Ctrl_H;
4592 len -= 2;
4593 }
4594 }
4595 else if (ta_buf[i] == '\r')
4596 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004597# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004599 i += (*mb_ptr2len_len)(ta_buf + i,
4600 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004601# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 }
4603
4604 /*
4605 * For pipes: echo the typed characters.
4606 * For a pty this does not seem to work.
4607 */
4608 if (pty_master_fd < 0)
4609 {
4610 for (i = ta_len; i < ta_len + len; ++i)
4611 {
4612 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4613 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004614# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 else if (has_mbyte)
4616 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004617 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618
4619 msg_outtrans_len(ta_buf + i, l);
4620 i += l - 1;
4621 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 else
4624 msg_outtrans_len(ta_buf + i, 1);
4625 }
4626 windgoto(msg_row, msg_col);
4627 out_flush();
4628 }
4629
4630 ta_len += len;
4631
4632 /*
4633 * Write the characters to the child, unless EOF has
4634 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004635 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004636 * When writing buffer lines, drop the typed
4637 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004639 if (options & SHELL_WRITE)
4640 ta_len = 0;
4641 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 {
4643 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4644 if (len > 0)
4645 {
4646 ta_len -= len;
4647 mch_memmove(ta_buf, ta_buf + len, ta_len);
4648 }
4649 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004650 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651 }
4652
Bram Moolenaardf177f62005-02-22 08:39:57 +00004653 if (got_int)
4654 {
4655 /* CTRL-C sends a signal to the child, we ignore it
4656 * ourselves */
4657# ifdef HAVE_SETSID
4658 kill(-pid, SIGINT);
4659# else
4660 kill(0, SIGINT);
4661# endif
4662 if (wpid > 0)
4663 kill(wpid, SIGINT);
4664 got_int = FALSE;
4665 }
4666
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 /*
4668 * Check if the child has any characters to be printed.
4669 * Read them and write them to our window. Repeat this as
4670 * long as there is something to do, avoid the 10ms wait
4671 * for mch_inchar(), or sending typeahead characters to
4672 * the external process.
4673 * TODO: This should handle escape sequences, compatible
4674 * to some terminal (vt52?).
4675 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004676 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4678 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004679 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004680# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004682# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004684# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 );
4686 if (len <= 0) /* end of file or error */
4687 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004688
4689 noread_cnt = 0;
4690 if (options & SHELL_READ)
4691 {
4692 /* Do NUL -> NL translation, append NL separated
4693 * lines to the current buffer. */
4694 for (i = 0; i < len; ++i)
4695 {
4696 if (buffer[i] == NL)
4697 append_ga_line(&ga);
4698 else if (buffer[i] == NUL)
4699 ga_append(&ga, NL);
4700 else
4701 ga_append(&ga, buffer[i]);
4702 }
4703 }
4704# ifdef FEAT_MBYTE
4705 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706 {
4707 int l;
4708
Bram Moolenaardf177f62005-02-22 08:39:57 +00004709 len += buffer_off;
4710 buffer[len] = NUL;
4711
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712 /* Check if the last character in buffer[] is
4713 * incomplete, keep these bytes for the next
4714 * round. */
4715 for (p = buffer; p < buffer + len; p += l)
4716 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004717 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 if (l == 0)
4719 l = 1; /* NUL byte? */
4720 else if (MB_BYTE2LEN(*p) != l)
4721 break;
4722 }
4723 if (p == buffer) /* no complete character */
4724 {
4725 /* avoid getting stuck at an illegal byte */
4726 if (len >= 12)
4727 ++p;
4728 else
4729 {
4730 buffer_off = len;
4731 continue;
4732 }
4733 }
4734 c = *p;
4735 *p = NUL;
4736 msg_puts(buffer);
4737 if (p < buffer + len)
4738 {
4739 *p = c;
4740 buffer_off = (buffer + len) - p;
4741 mch_memmove(buffer, p, buffer_off);
4742 continue;
4743 }
4744 buffer_off = 0;
4745 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004746# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 {
4749 buffer[len] = NUL;
4750 msg_puts(buffer);
4751 }
4752
4753 windgoto(msg_row, msg_col);
4754 cursor_on();
4755 out_flush();
4756 if (got_int)
4757 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004758
4759# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4760 {
4761 struct timeval now_tv;
4762 long msec;
4763
4764 /* Avoid that we keep looping here without
4765 * checking for a CTRL-C for a long time. Don't
4766 * break out too often to avoid losing typeahead. */
4767 gettimeofday(&now_tv, NULL);
4768 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4769 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4770 if (msec > 2000)
4771 {
4772 noread_cnt = 5;
4773 break;
4774 }
4775 }
4776# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 }
4778
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004779 /* If we already detected the child has finished break the
4780 * loop now. */
4781 if (wait_pid == pid)
4782 break;
4783
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784 /*
4785 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004786 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004788# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004789 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004790# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004792# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4794 || (wait_pid == pid && WIFEXITED(status)))
4795 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004796 /* Don't break the loop yet, try reading more
4797 * characters from "fromshell_fd" first. When using
4798 * pipes there might still be something to read and
4799 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004802 else
4803 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004804
Bram Moolenaar95a51352013-03-21 22:53:50 +01004805# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004806 /* Handle any X events, e.g. serving the clipboard. */
4807 clip_update();
4808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 }
4810finished:
4811 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004812 if (options & SHELL_READ)
4813 {
4814 if (ga.ga_len > 0)
4815 {
4816 append_ga_line(&ga);
4817 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004818 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004819 }
4820 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004821 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004822 ga_clear(&ga);
4823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 /*
4826 * Give all typeahead that wasn't used back to ui_inchar().
4827 */
4828 if (ta_len)
4829 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 State = old_State;
4831 if (toshell_fd >= 0)
4832 close(toshell_fd);
4833 close(fromshell_fd);
4834 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004835# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004836 else
4837 {
4838 /*
4839 * Similar to the loop above, but only handle X events, no
4840 * I/O.
4841 */
4842 for (;;)
4843 {
4844 if (got_int)
4845 {
4846 /* CTRL-C sends a signal to the child, we ignore it
4847 * ourselves */
4848# ifdef HAVE_SETSID
4849 kill(-pid, SIGINT);
4850# else
4851 kill(0, SIGINT);
4852# endif
4853 got_int = FALSE;
4854 }
4855# ifdef __NeXT__
4856 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4857# else
4858 wait_pid = waitpid(pid, &status, WNOHANG);
4859# endif
4860 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4861 || (wait_pid == pid && WIFEXITED(status)))
4862 {
4863 wait_pid = pid;
4864 break;
4865 }
4866
4867 /* Handle any X events, e.g. serving the clipboard. */
4868 clip_update();
4869
4870 mch_delay(10L, TRUE);
4871 }
4872 }
4873# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874
4875 /*
4876 * Wait until our child has exited.
4877 * Ignore wait() returning pids of other children and returning
4878 * because of some signal like SIGWINCH.
4879 * Don't wait if wait_pid was already set above, indicating the
4880 * child already exited.
4881 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004882 if (wait_pid != pid)
4883 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884
Bram Moolenaar624891f2010-10-13 16:22:09 +02004885# ifdef FEAT_GUI
4886 /* Close slave side of pty. Only do this after the child has
4887 * exited, otherwise the child may hang when it tries to write on
4888 * the pty. */
4889 if (pty_master_fd >= 0)
4890 close(pty_slave_fd);
4891# endif
4892
Bram Moolenaardf177f62005-02-22 08:39:57 +00004893 /* Make sure the child that writes to the external program is
4894 * dead. */
4895 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004896 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004897 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004898 wait4pid(wpid, NULL);
4899 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004900
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 /*
4902 * Set to raw mode right now, otherwise a CTRL-C after
4903 * catch_signals() will kill Vim.
4904 */
4905 if (tmode == TMODE_RAW)
4906 settmode(TMODE_RAW);
4907 did_settmode = TRUE;
4908 set_signals();
4909
4910 if (WIFEXITED(status))
4911 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004912 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01004914 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 {
4916 if (retval == EXEC_FAILED)
4917 {
4918 MSG_PUTS(_("\nCannot execute shell "));
4919 msg_outtrans(p_sh);
4920 msg_putchar('\n');
4921 }
4922 else if (!(options & SHELL_SILENT))
4923 {
4924 MSG_PUTS(_("\nshell returned "));
4925 msg_outnum((long)retval);
4926 msg_putchar('\n');
4927 }
4928 }
4929 }
4930 else
4931 MSG_PUTS(_("\nCommand terminated\n"));
4932 }
4933 }
4934 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004935 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936
4937error:
4938 if (!did_settmode)
4939 if (tmode == TMODE_RAW)
4940 settmode(TMODE_RAW); /* set to raw mode */
4941# ifdef FEAT_TITLE
4942 resettitle();
4943# endif
4944 vim_free(newcmd);
4945
4946 return retval;
4947
4948#endif /* USE_SYSTEM */
4949}
4950
4951/*
4952 * Check for CTRL-C typed by reading all available characters.
4953 * In cooked mode we should get SIGINT, no need to check.
4954 */
4955 void
4956mch_breakcheck()
4957{
4958 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4959 fill_input_buf(FALSE);
4960}
4961
4962/*
4963 * Wait "msec" msec until a character is available from the keyboard or from
4964 * inbuf[]. msec == -1 will block forever.
4965 * When a GUI is being used, this will never get called -- webb
4966 */
4967 static int
4968WaitForChar(msec)
4969 long msec;
4970{
4971#ifdef FEAT_MOUSE_GPM
4972 int gpm_process_wanted;
4973#endif
4974#ifdef FEAT_XCLIPBOARD
4975 int rest;
4976#endif
4977 int avail;
4978
4979 if (input_available()) /* something in inbuf[] */
4980 return 1;
4981
4982#if defined(FEAT_MOUSE_DEC)
4983 /* May need to query the mouse position. */
4984 if (WantQueryMouse)
4985 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004986 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4988 }
4989#endif
4990
4991 /*
4992 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4993 * events. This is a bit complicated, because they might both be defined.
4994 */
4995#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4996# ifdef FEAT_XCLIPBOARD
4997 rest = 0;
4998 if (do_xterm_trace())
4999 rest = msec;
5000# endif
5001 do
5002 {
5003# ifdef FEAT_XCLIPBOARD
5004 if (rest != 0)
5005 {
5006 msec = XT_TRACE_DELAY;
5007 if (rest >= 0 && rest < XT_TRACE_DELAY)
5008 msec = rest;
5009 if (rest >= 0)
5010 rest -= msec;
5011 }
5012# endif
5013# ifdef FEAT_MOUSE_GPM
5014 gpm_process_wanted = 0;
5015 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5016# else
5017 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5018# endif
5019 if (!avail)
5020 {
5021 if (input_available())
5022 return 1;
5023# ifdef FEAT_XCLIPBOARD
5024 if (rest == 0 || !do_xterm_trace())
5025# endif
5026 break;
5027 }
5028 }
5029 while (FALSE
5030# ifdef FEAT_MOUSE_GPM
5031 || (gpm_process_wanted && mch_gpm_process() == 0)
5032# endif
5033# ifdef FEAT_XCLIPBOARD
5034 || (!avail && rest != 0)
5035# endif
5036 );
5037
5038#else
5039 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5040#endif
5041 return avail;
5042}
5043
5044/*
5045 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005046 * "msec" == 0 will check for characters once.
5047 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 * When a GUI is being used, this will not be used for input -- webb
5049 * Returns also, when a request from Sniff is waiting -- toni.
5050 * Or when a Linux GPM mouse event is waiting.
5051 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052#if defined(__BEOS__)
5053 int
5054#else
5055 static int
5056#endif
5057RealWaitForChar(fd, msec, check_for_gpm)
5058 int fd;
5059 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005060 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061{
5062 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005063#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005064 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005065#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005066#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067 static int busy = FALSE;
5068
5069 /* May retry getting characters after an event was handled. */
5070# define MAY_LOOP
5071
5072# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5073 /* Remember at what time we started, so that we know how much longer we
5074 * should wait after being interrupted. */
5075# define USE_START_TV
5076 struct timeval start_tv;
5077
5078 if (msec > 0 && (
5079# ifdef FEAT_XCLIPBOARD
5080 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005081# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 ||
5083# endif
5084# endif
5085# ifdef USE_XSMP
5086 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005087# ifdef FEAT_MZSCHEME
5088 ||
5089# endif
5090# endif
5091# ifdef FEAT_MZSCHEME
5092 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093# endif
5094 ))
5095 gettimeofday(&start_tv, NULL);
5096# endif
5097
5098 /* Handle being called recursively. This may happen for the session
5099 * manager stuff, it may save the file, which does a breakcheck. */
5100 if (busy)
5101 return 0;
5102#endif
5103
5104#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005105 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106#endif
5107 {
5108#ifdef MAY_LOOP
5109 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005110# ifdef FEAT_MZSCHEME
5111 int mzquantum_used = FALSE;
5112# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113#endif
5114#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005115 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 int nfd;
5117# ifdef FEAT_XCLIPBOARD
5118 int xterm_idx = -1;
5119# endif
5120# ifdef FEAT_MOUSE_GPM
5121 int gpm_idx = -1;
5122# endif
5123# ifdef USE_XSMP
5124 int xsmp_idx = -1;
5125# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005126# ifdef FEAT_NETBEANS_INTG
5127 int nb_idx = -1;
5128# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005129 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005131# ifdef FEAT_MZSCHEME
5132 mzvim_check_threads();
5133 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5134 {
5135 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5136 mzquantum_used = TRUE;
5137 }
5138# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005139 fds[0].fd = fd;
5140 fds[0].events = POLLIN;
5141 nfd = 1;
5142
5143# ifdef FEAT_SNIFF
5144# define SNIFF_IDX 1
5145 if (want_sniff_request)
5146 {
5147 fds[SNIFF_IDX].fd = fd_from_sniff;
5148 fds[SNIFF_IDX].events = POLLIN;
5149 nfd++;
5150 }
5151# endif
5152# ifdef FEAT_XCLIPBOARD
5153 if (xterm_Shell != (Widget)0)
5154 {
5155 xterm_idx = nfd;
5156 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5157 fds[nfd].events = POLLIN;
5158 nfd++;
5159 }
5160# endif
5161# ifdef FEAT_MOUSE_GPM
5162 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5163 {
5164 gpm_idx = nfd;
5165 fds[nfd].fd = gpm_fd;
5166 fds[nfd].events = POLLIN;
5167 nfd++;
5168 }
5169# endif
5170# ifdef USE_XSMP
5171 if (xsmp_icefd != -1)
5172 {
5173 xsmp_idx = nfd;
5174 fds[nfd].fd = xsmp_icefd;
5175 fds[nfd].events = POLLIN;
5176 nfd++;
5177 }
5178# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005179#ifdef FEAT_NETBEANS_INTG
5180 if (nb_fd != -1)
5181 {
5182 nb_idx = nfd;
5183 fds[nfd].fd = nb_fd;
5184 fds[nfd].events = POLLIN;
5185 nfd++;
5186 }
5187#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005189 ret = poll(fds, nfd, towait);
5190# ifdef FEAT_MZSCHEME
5191 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005192 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005193 finished = FALSE;
5194# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195
5196# ifdef FEAT_SNIFF
5197 if (ret < 0)
5198 sniff_disconnect(1);
5199 else if (want_sniff_request)
5200 {
5201 if (fds[SNIFF_IDX].revents & POLLHUP)
5202 sniff_disconnect(1);
5203 if (fds[SNIFF_IDX].revents & POLLIN)
5204 sniff_request_waiting = 1;
5205 }
5206# endif
5207# ifdef FEAT_XCLIPBOARD
5208 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5209 {
5210 xterm_update(); /* Maybe we should hand out clipboard */
5211 if (--ret == 0 && !input_available())
5212 /* Try again */
5213 finished = FALSE;
5214 }
5215# endif
5216# ifdef FEAT_MOUSE_GPM
5217 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5218 {
5219 *check_for_gpm = 1;
5220 }
5221# endif
5222# ifdef USE_XSMP
5223 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5224 {
5225 if (fds[xsmp_idx].revents & POLLIN)
5226 {
5227 busy = TRUE;
5228 xsmp_handle_requests();
5229 busy = FALSE;
5230 }
5231 else if (fds[xsmp_idx].revents & POLLHUP)
5232 {
5233 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005234 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235 xsmp_close();
5236 }
5237 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005238 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239 }
5240# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005241#ifdef FEAT_NETBEANS_INTG
5242 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5243 {
5244 netbeans_read();
5245 --ret;
5246 }
5247#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248
5249
5250#else /* HAVE_SELECT */
5251
5252 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005253 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254 fd_set rfds, efds;
5255 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005256 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005258# ifdef FEAT_MZSCHEME
5259 mzvim_check_threads();
5260 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5261 {
5262 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5263 mzquantum_used = TRUE;
5264 }
5265# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266# ifdef __EMX__
5267 /* don't check for incoming chars if not in raw mode, because select()
5268 * always returns TRUE then (in some version of emx.dll) */
5269 if (curr_tmode != TMODE_RAW)
5270 return 0;
5271# endif
5272
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005273 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005275 tv.tv_sec = towait / 1000;
5276 tv.tv_usec = (towait % 1000) * (1000000/1000);
5277 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005279 else
5280 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281
5282 /*
5283 * Select on ready for reading and exceptional condition (end of file).
5284 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005285select_eintr:
5286 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287 FD_ZERO(&efds);
5288 FD_SET(fd, &rfds);
5289# if !defined(__QNX__) && !defined(__CYGWIN32__)
5290 /* For QNX select() always returns 1 if this is set. Why? */
5291 FD_SET(fd, &efds);
5292# endif
5293 maxfd = fd;
5294
5295# ifdef FEAT_SNIFF
5296 if (want_sniff_request)
5297 {
5298 FD_SET(fd_from_sniff, &rfds);
5299 FD_SET(fd_from_sniff, &efds);
5300 if (maxfd < fd_from_sniff)
5301 maxfd = fd_from_sniff;
5302 }
5303# endif
5304# ifdef FEAT_XCLIPBOARD
5305 if (xterm_Shell != (Widget)0)
5306 {
5307 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5308 if (maxfd < ConnectionNumber(xterm_dpy))
5309 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005310
5311 /* An event may have already been read but not handled. In
5312 * particulary, XFlush may cause this. */
5313 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314 }
5315# endif
5316# ifdef FEAT_MOUSE_GPM
5317 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5318 {
5319 FD_SET(gpm_fd, &rfds);
5320 FD_SET(gpm_fd, &efds);
5321 if (maxfd < gpm_fd)
5322 maxfd = gpm_fd;
5323 }
5324# endif
5325# ifdef USE_XSMP
5326 if (xsmp_icefd != -1)
5327 {
5328 FD_SET(xsmp_icefd, &rfds);
5329 FD_SET(xsmp_icefd, &efds);
5330 if (maxfd < xsmp_icefd)
5331 maxfd = xsmp_icefd;
5332 }
5333# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005334# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005335 if (nb_fd != -1)
5336 {
5337 FD_SET(nb_fd, &rfds);
5338 if (maxfd < nb_fd)
5339 maxfd = nb_fd;
5340 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005341# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342
5343# ifdef OLD_VMS
5344 /* Old VMS as v6.2 and older have broken select(). It waits more than
5345 * required. Should not be used */
5346 ret = 0;
5347# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005348 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5349# endif
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005350# ifdef EINTR
5351 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005352 {
5353 /* Check whether window has been resized, EINTR may be caused by
5354 * SIGWINCH. */
5355 if (do_resize)
5356 handle_resize();
5357
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005358 /* Interrupted by a signal, need to try again. We ignore msec
5359 * here, because we do want to check even after a timeout if
5360 * characters are available. Needed for reading output of an
5361 * external command after the process has finished. */
5362 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005363 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005364# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005365# ifdef __TANDEM
5366 if (ret == -1 && errno == ENOTSUP)
5367 {
5368 FD_ZERO(&rfds);
5369 FD_ZERO(&efds);
5370 ret = 0;
5371 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005372# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005373# ifdef FEAT_MZSCHEME
5374 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005375 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005376 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377# endif
5378
5379# ifdef FEAT_SNIFF
5380 if (ret < 0 )
5381 sniff_disconnect(1);
5382 else if (ret > 0 && want_sniff_request)
5383 {
5384 if (FD_ISSET(fd_from_sniff, &efds))
5385 sniff_disconnect(1);
5386 if (FD_ISSET(fd_from_sniff, &rfds))
5387 sniff_request_waiting = 1;
5388 }
5389# endif
5390# ifdef FEAT_XCLIPBOARD
5391 if (ret > 0 && xterm_Shell != (Widget)0
5392 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5393 {
5394 xterm_update(); /* Maybe we should hand out clipboard */
5395 /* continue looping when we only got the X event and the input
5396 * buffer is empty */
5397 if (--ret == 0 && !input_available())
5398 {
5399 /* Try again */
5400 finished = FALSE;
5401 }
5402 }
5403# endif
5404# ifdef FEAT_MOUSE_GPM
5405 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5406 {
5407 if (FD_ISSET(gpm_fd, &efds))
5408 gpm_close();
5409 else if (FD_ISSET(gpm_fd, &rfds))
5410 *check_for_gpm = 1;
5411 }
5412# endif
5413# ifdef USE_XSMP
5414 if (ret > 0 && xsmp_icefd != -1)
5415 {
5416 if (FD_ISSET(xsmp_icefd, &efds))
5417 {
5418 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005419 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 xsmp_close();
5421 if (--ret == 0)
5422 finished = FALSE; /* keep going if event was only one */
5423 }
5424 else if (FD_ISSET(xsmp_icefd, &rfds))
5425 {
5426 busy = TRUE;
5427 xsmp_handle_requests();
5428 busy = FALSE;
5429 if (--ret == 0)
5430 finished = FALSE; /* keep going if event was only one */
5431 }
5432 }
5433# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005434#ifdef FEAT_NETBEANS_INTG
5435 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5436 {
5437 netbeans_read();
5438 --ret;
5439 }
5440#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441
5442#endif /* HAVE_SELECT */
5443
5444#ifdef MAY_LOOP
5445 if (finished || msec == 0)
5446 break;
5447
5448 /* We're going to loop around again, find out for how long */
5449 if (msec > 0)
5450 {
5451# ifdef USE_START_TV
5452 struct timeval mtv;
5453
5454 /* Compute remaining wait time. */
5455 gettimeofday(&mtv, NULL);
5456 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5457 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5458# else
5459 /* Guess we got interrupted halfway. */
5460 msec = msec / 2;
5461# endif
5462 if (msec <= 0)
5463 break; /* waited long enough */
5464 }
5465#endif
5466 }
5467
5468 return (ret > 0);
5469}
5470
5471#ifndef VMS
5472
5473#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005475 * Expand a path into all matching files and/or directories. Handles "*",
5476 * "?", "[a-z]", "**", etc.
5477 * "path" has backslashes before chars that are not to be expanded.
5478 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479 */
5480 int
5481mch_expandpath(gap, path, flags)
5482 garray_T *gap;
5483 char_u *path;
5484 int flags; /* EW_* flags */
5485{
Bram Moolenaar02743632005-07-25 20:42:36 +00005486 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005487}
5488#endif
5489
5490/*
5491 * mch_expand_wildcards() - this code does wild-card pattern matching using
5492 * the shell
5493 *
5494 * return OK for success, FAIL for error (you may lose some memory) and put
5495 * an error message in *file.
5496 *
5497 * num_pat is number of input patterns
5498 * pat is array of pointers to input patterns
5499 * num_file is pointer to number of matched file names
5500 * file is pointer to array of pointers to matched file names
5501 */
5502
5503#ifndef SEEK_SET
5504# define SEEK_SET 0
5505#endif
5506#ifndef SEEK_END
5507# define SEEK_END 2
5508#endif
5509
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005510#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005511
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 int
5513mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5514 int num_pat;
5515 char_u **pat;
5516 int *num_file;
5517 char_u ***file;
5518 int flags; /* EW_* flags */
5519{
5520 int i;
5521 size_t len;
5522 char_u *p;
5523 int dir;
5524#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005525 /*
5526 * This is the OS/2 implementation.
5527 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528# define EXPL_ALLOC_INC 16
5529 char_u **expl_files;
5530 size_t files_alloced, files_free;
5531 char_u *buf;
5532 int has_wildcard;
5533
5534 *num_file = 0; /* default: no files found */
5535 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5536 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5537 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5538 if (*file == NULL)
5539 return FAIL;
5540
5541 for (; num_pat > 0; num_pat--, pat++)
5542 {
5543 expl_files = NULL;
5544 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5545 /* expand environment var or home dir */
5546 buf = expand_env_save(*pat);
5547 else
5548 buf = vim_strsave(*pat);
5549 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005550 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551 if (has_wildcard) /* yes, so expand them */
5552 expl_files = (char_u **)_fnexplode(buf);
5553
5554 /*
5555 * return value of buf if no wildcards left,
5556 * OR if no match AND EW_NOTFOUND is set.
5557 */
5558 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5559 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5560 { /* simply save the current contents of *buf */
5561 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5562 if (expl_files != NULL)
5563 {
5564 expl_files[0] = vim_strsave(buf);
5565 expl_files[1] = NULL;
5566 }
5567 }
5568 vim_free(buf);
5569
5570 /*
5571 * Count number of names resulting from expansion,
5572 * At the same time add a backslash to the end of names that happen to
5573 * be directories, and replace slashes with backslashes.
5574 */
5575 if (expl_files)
5576 {
5577 for (i = 0; (p = expl_files[i]) != NULL; i++)
5578 {
5579 dir = mch_isdir(p);
5580 /* If we don't want dirs and this is one, skip it */
5581 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5582 continue;
5583
Bram Moolenaara2031822006-03-07 22:29:51 +00005584 /* Skip files that are not executable if we check for that. */
5585 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5586 continue;
5587
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 if (--files_free == 0)
5589 {
5590 /* need more room in table of pointers */
5591 files_alloced += EXPL_ALLOC_INC;
5592 *file = (char_u **)vim_realloc(*file,
5593 sizeof(char_u **) * files_alloced);
5594 if (*file == NULL)
5595 {
5596 EMSG(_(e_outofmem));
5597 *num_file = 0;
5598 return FAIL;
5599 }
5600 files_free = EXPL_ALLOC_INC;
5601 }
5602 slash_adjust(p);
5603 if (dir)
5604 {
5605 /* For a directory we add a '/', unless it's already
5606 * there. */
5607 len = STRLEN(p);
5608 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5609 {
5610 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005611 if (!after_pathsep((*file)[*num_file],
5612 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 {
5614 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005615 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 }
5617 }
5618 }
5619 else
5620 {
5621 (*file)[*num_file] = vim_strsave(p);
5622 }
5623
5624 /*
5625 * Error message already given by either alloc or vim_strsave.
5626 * Should return FAIL, but returning OK works also.
5627 */
5628 if ((*file)[*num_file] == NULL)
5629 break;
5630 (*num_file)++;
5631 }
5632 _fnexplodefree((char **)expl_files);
5633 }
5634 }
5635 return OK;
5636
5637#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005638 /*
5639 * This is the non-OS/2 implementation (really Unix).
5640 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 int j;
5642 char_u *tempname;
5643 char_u *command;
5644 FILE *fd;
5645 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005646#define STYLE_ECHO 0 /* use "echo", the default */
5647#define STYLE_GLOB 1 /* use "glob", for csh */
5648#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5649#define STYLE_PRINT 3 /* use "print -N", for zsh */
5650#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5651 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 int shell_style = STYLE_ECHO;
5653 int check_spaces;
5654 static int did_find_nul = FALSE;
5655 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005656 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005657 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658
5659 *num_file = 0; /* default: no files found */
5660 *file = NULL;
5661
5662 /*
5663 * If there are no wildcards, just copy the names to allocated memory.
5664 * Saves a lot of time, because we don't have to start a new shell.
5665 */
5666 if (!have_wildcard(num_pat, pat))
5667 return save_patterns(num_pat, pat, num_file, file);
5668
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005669# ifdef HAVE_SANDBOX
5670 /* Don't allow any shell command in the sandbox. */
5671 if (sandbox != 0 && check_secure())
5672 return FAIL;
5673# endif
5674
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 /*
5676 * Don't allow the use of backticks in secure and restricted mode.
5677 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005678 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679 for (i = 0; i < num_pat; ++i)
5680 if (vim_strchr(pat[i], '`') != NULL
5681 && (check_restricted() || check_secure()))
5682 return FAIL;
5683
5684 /*
5685 * get a name for the temp file
5686 */
5687 if ((tempname = vim_tempname('o')) == NULL)
5688 {
5689 EMSG(_(e_notmp));
5690 return FAIL;
5691 }
5692
5693 /*
5694 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005695 * file.
5696 * STYLE_BT: NL separated
5697 * If expanding `cmd` execute it directly.
5698 * STYLE_GLOB: NUL separated
5699 * If we use *csh, "glob" will work better than "echo".
5700 * STYLE_PRINT: NL or NUL separated
5701 * If we use *zsh, "print -N" will work better than "glob".
5702 * STYLE_VIMGLOB: NL separated
5703 * If we use *sh*, we define "vimglob()".
5704 * STYLE_ECHO: space separated.
5705 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 */
5707 if (num_pat == 1 && *pat[0] == '`'
5708 && (len = STRLEN(pat[0])) > 2
5709 && *(pat[0] + len - 1) == '`')
5710 shell_style = STYLE_BT;
5711 else if ((len = STRLEN(p_sh)) >= 3)
5712 {
5713 if (STRCMP(p_sh + len - 3, "csh") == 0)
5714 shell_style = STYLE_GLOB;
5715 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5716 shell_style = STYLE_PRINT;
5717 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005718 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5719 "sh") != NULL)
5720 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721
Bram Moolenaarc7247912008-01-13 12:54:11 +00005722 /* Compute the length of the command. We need 2 extra bytes: for the
5723 * optional '&' and for the NUL.
5724 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005726 if (shell_style == STYLE_VIMGLOB)
5727 len += STRLEN(sh_vimglob_func);
5728
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005729 for (i = 0; i < num_pat; ++i)
5730 {
5731 /* Count the length of the patterns in the same way as they are put in
5732 * "command" below. */
5733#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005735#else
5736 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005737 for (j = 0; pat[i][j] != NUL; ++j)
5738 {
5739 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5740 ++len; /* may add a backslash */
5741 ++len;
5742 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005743#endif
5744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 command = alloc(len);
5746 if (command == NULL)
5747 {
5748 /* out of memory */
5749 vim_free(tempname);
5750 return FAIL;
5751 }
5752
5753 /*
5754 * Build the shell command:
5755 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5756 * recognizes this).
5757 * - Add the shell command to print the expanded names.
5758 * - Add the temp file name.
5759 * - Add the file name patterns.
5760 */
5761 if (shell_style == STYLE_BT)
5762 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005763 /* change `command; command& ` to (command; command ) */
5764 STRCPY(command, "(");
5765 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005767 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 while (p > command && vim_iswhite(*p))
5769 --p;
5770 if (*p == '&') /* remove trailing '&' */
5771 {
5772 ampersent = TRUE;
5773 *p = ' ';
5774 }
5775 STRCAT(command, ">");
5776 }
5777 else
5778 {
5779 if (flags & EW_NOTFOUND)
5780 STRCPY(command, "set nonomatch; ");
5781 else
5782 STRCPY(command, "unset nonomatch; ");
5783 if (shell_style == STYLE_GLOB)
5784 STRCAT(command, "glob >");
5785 else if (shell_style == STYLE_PRINT)
5786 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005787 else if (shell_style == STYLE_VIMGLOB)
5788 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 else
5790 STRCAT(command, "echo >");
5791 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005792
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005794
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 if (shell_style != STYLE_BT)
5796 for (i = 0; i < num_pat; ++i)
5797 {
5798 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005799 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005800 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801#ifdef USE_SYSTEM
5802 STRCAT(command, " \"");
5803 STRCAT(command, pat[i]);
5804 STRCAT(command, "\"");
5805#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005806 int intick = FALSE;
5807
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 p = command + STRLEN(command);
5809 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005810 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005811 {
5812 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005813 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005814 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5815 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005816 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005817 * backslash inside backticks, before a special character
5818 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005819 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005820 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5821 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005822 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005823 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005824 }
5825 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005826 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005827 /* Put a backslash before a special character, but not
5828 * when inside ``. */
5829 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005830
5831 /* Copy one character. */
5832 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834 *p = NUL;
5835#endif
5836 }
5837 if (flags & EW_SILENT)
5838 show_shell_mess = FALSE;
5839 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005840 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841
5842 /*
5843 * Using zsh -G: If a pattern has no matches, it is just deleted from
5844 * the argument list, otherwise zsh gives an error message and doesn't
5845 * expand any other pattern.
5846 */
5847 if (shell_style == STYLE_PRINT)
5848 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5849
5850 /*
5851 * If we use -f then shell variables set in .cshrc won't get expanded.
5852 * vi can do it, so we will too, but it is only necessary if there is a "$"
5853 * in one of the patterns, otherwise we can still use the fast option.
5854 */
5855 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5856 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5857
5858 /*
5859 * execute the shell command
5860 */
5861 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5862
5863 /* When running in the background, give it some time to create the temp
5864 * file, but don't wait for it to finish. */
5865 if (ampersent)
5866 mch_delay(10L, TRUE);
5867
5868 extra_shell_arg = NULL; /* cleanup */
5869 show_shell_mess = TRUE;
5870 vim_free(command);
5871
Bram Moolenaarc7247912008-01-13 12:54:11 +00005872 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 {
5874 mch_remove(tempname);
5875 vim_free(tempname);
5876 /*
5877 * With interactive completion, the error message is not printed.
5878 * However with USE_SYSTEM, I don't know how to turn off error messages
5879 * from the shell, so screen may still get messed up -- webb.
5880 */
5881#ifndef USE_SYSTEM
5882 if (!(flags & EW_SILENT))
5883#endif
5884 {
5885 redraw_later_clear(); /* probably messed up screen */
5886 msg_putchar('\n'); /* clear bottom line quickly */
5887 cmdline_row = Rows - 1; /* continue on last line */
5888#ifdef USE_SYSTEM
5889 if (!(flags & EW_SILENT))
5890#endif
5891 {
5892 MSG(_(e_wildexpand));
5893 msg_start(); /* don't overwrite this message */
5894 }
5895 }
5896 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5897 * EW_NOTFOUND is given */
5898 if (shell_style == STYLE_BT)
5899 return FAIL;
5900 goto notfound;
5901 }
5902
5903 /*
5904 * read the names from the file into memory
5905 */
5906 fd = fopen((char *)tempname, READBIN);
5907 if (fd == NULL)
5908 {
5909 /* Something went wrong, perhaps a file name with a special char. */
5910 if (!(flags & EW_SILENT))
5911 {
5912 MSG(_(e_wildexpand));
5913 msg_start(); /* don't overwrite this message */
5914 }
5915 vim_free(tempname);
5916 goto notfound;
5917 }
5918 fseek(fd, 0L, SEEK_END);
5919 len = ftell(fd); /* get size of temp file */
5920 fseek(fd, 0L, SEEK_SET);
5921 buffer = alloc(len + 1);
5922 if (buffer == NULL)
5923 {
5924 /* out of memory */
5925 mch_remove(tempname);
5926 vim_free(tempname);
5927 fclose(fd);
5928 return FAIL;
5929 }
5930 i = fread((char *)buffer, 1, len, fd);
5931 fclose(fd);
5932 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005933 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 {
5935 /* unexpected read error */
5936 EMSG2(_(e_notread), tempname);
5937 vim_free(tempname);
5938 vim_free(buffer);
5939 return FAIL;
5940 }
5941 vim_free(tempname);
5942
Bram Moolenaarc7247912008-01-13 12:54:11 +00005943# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5945 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02005946 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5948 *p++ = buffer[i];
5949 len = p - buffer;
5950# endif
5951
5952
5953 /* file names are separated with Space */
5954 if (shell_style == STYLE_ECHO)
5955 {
5956 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5957 p = buffer;
5958 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5959 {
5960 while (*p != ' ' && *p != '\n')
5961 ++p;
5962 p = skipwhite(p); /* skip to next entry */
5963 }
5964 }
5965 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005966 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 {
5968 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5969 p = buffer;
5970 for (i = 0; *p != NUL; ++i) /* count number of entries */
5971 {
5972 while (*p != '\n' && *p != NUL)
5973 ++p;
5974 if (*p != NUL)
5975 ++p;
5976 p = skipwhite(p); /* skip leading white space */
5977 }
5978 }
5979 /* file names are separated with NUL */
5980 else
5981 {
5982 /*
5983 * Some versions of zsh use spaces instead of NULs to separate
5984 * results. Only do this when there is no NUL before the end of the
5985 * buffer, otherwise we would never be able to use file names with
5986 * embedded spaces when zsh does use NULs.
5987 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5988 * don't check for spaces again.
5989 */
5990 check_spaces = FALSE;
5991 if (shell_style == STYLE_PRINT && !did_find_nul)
5992 {
5993 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005994 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005995 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996 did_find_nul = TRUE;
5997 else
5998 check_spaces = TRUE;
5999 }
6000
6001 /*
6002 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6003 * already is one, for STYLE_GLOB it needs to be added.
6004 */
6005 if (len && buffer[len - 1] == NUL)
6006 --len;
6007 else
6008 buffer[len] = NUL;
6009 i = 0;
6010 for (p = buffer; p < buffer + len; ++p)
6011 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6012 {
6013 ++i;
6014 *p = NUL;
6015 }
6016 if (len)
6017 ++i; /* count last entry */
6018 }
6019 if (i == 0)
6020 {
6021 /*
6022 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6023 * /bin/sh will happily expand it to nothing rather than returning an
6024 * error; and hey, it's good to check anyway -- webb.
6025 */
6026 vim_free(buffer);
6027 goto notfound;
6028 }
6029 *num_file = i;
6030 *file = (char_u **)alloc(sizeof(char_u *) * i);
6031 if (*file == NULL)
6032 {
6033 /* out of memory */
6034 vim_free(buffer);
6035 return FAIL;
6036 }
6037
6038 /*
6039 * Isolate the individual file names.
6040 */
6041 p = buffer;
6042 for (i = 0; i < *num_file; ++i)
6043 {
6044 (*file)[i] = p;
6045 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006046 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6047 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006049 while (!(shell_style == STYLE_ECHO && *p == ' ')
6050 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 ++p;
6052 if (p == buffer + len) /* last entry */
6053 *p = NUL;
6054 else
6055 {
6056 *p++ = NUL;
6057 p = skipwhite(p); /* skip to next entry */
6058 }
6059 }
6060 else /* NUL separates */
6061 {
6062 while (*p && p < buffer + len) /* skip entry */
6063 ++p;
6064 ++p; /* skip NUL */
6065 }
6066 }
6067
6068 /*
6069 * Move the file names to allocated memory.
6070 */
6071 for (j = 0, i = 0; i < *num_file; ++i)
6072 {
6073 /* Require the files to exist. Helps when using /bin/sh */
6074 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6075 continue;
6076
6077 /* check if this entry should be included */
6078 dir = (mch_isdir((*file)[i]));
6079 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6080 continue;
6081
Bram Moolenaara2031822006-03-07 22:29:51 +00006082 /* Skip files that are not executable if we check for that. */
6083 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
6084 continue;
6085
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6087 if (p)
6088 {
6089 STRCPY(p, (*file)[i]);
6090 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006091 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 (*file)[j++] = p;
6093 }
6094 }
6095 vim_free(buffer);
6096 *num_file = j;
6097
6098 if (*num_file == 0) /* rejected all entries */
6099 {
6100 vim_free(*file);
6101 *file = NULL;
6102 goto notfound;
6103 }
6104
6105 return OK;
6106
6107notfound:
6108 if (flags & EW_NOTFOUND)
6109 return save_patterns(num_pat, pat, num_file, file);
6110 return FAIL;
6111
6112#endif /* __EMX__ */
6113}
6114
6115#endif /* VMS */
6116
6117#ifndef __EMX__
6118 static int
6119save_patterns(num_pat, pat, num_file, file)
6120 int num_pat;
6121 char_u **pat;
6122 int *num_file;
6123 char_u ***file;
6124{
6125 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006126 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127
6128 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6129 if (*file == NULL)
6130 return FAIL;
6131 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006132 {
6133 s = vim_strsave(pat[i]);
6134 if (s != NULL)
6135 /* Be compatible with expand_filename(): halve the number of
6136 * backslashes. */
6137 backslash_halve(s);
6138 (*file)[i] = s;
6139 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140 *num_file = num_pat;
6141 return OK;
6142}
6143#endif
6144
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145/*
6146 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6147 * expand.
6148 */
6149 int
6150mch_has_exp_wildcard(p)
6151 char_u *p;
6152{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006153 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 {
6155#ifndef OS2
6156 if (*p == '\\' && p[1] != NUL)
6157 ++p;
6158 else
6159#endif
6160 if (vim_strchr((char_u *)
6161#ifdef VMS
6162 "*?%"
6163#else
6164# ifdef OS2
6165 "*?"
6166# else
6167 "*?[{'"
6168# endif
6169#endif
6170 , *p) != NULL)
6171 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 }
6173 return FALSE;
6174}
6175
6176/*
6177 * Return TRUE if the string "p" contains a wildcard.
6178 * Don't recognize '~' at the end as a wildcard.
6179 */
6180 int
6181mch_has_wildcard(p)
6182 char_u *p;
6183{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006184 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 {
6186#ifndef OS2
6187 if (*p == '\\' && p[1] != NUL)
6188 ++p;
6189 else
6190#endif
6191 if (vim_strchr((char_u *)
6192#ifdef VMS
6193 "*?%$"
6194#else
6195# ifdef OS2
6196# ifdef VIM_BACKTICK
6197 "*?$`"
6198# else
6199 "*?$"
6200# endif
6201# else
6202 "*?[{`'$"
6203# endif
6204#endif
6205 , *p) != NULL
6206 || (*p == '~' && p[1] != NUL))
6207 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 }
6209 return FALSE;
6210}
6211
6212#ifndef __EMX__
6213 static int
6214have_wildcard(num, file)
6215 int num;
6216 char_u **file;
6217{
6218 int i;
6219
6220 for (i = 0; i < num; i++)
6221 if (mch_has_wildcard(file[i]))
6222 return 1;
6223 return 0;
6224}
6225
6226 static int
6227have_dollars(num, file)
6228 int num;
6229 char_u **file;
6230{
6231 int i;
6232
6233 for (i = 0; i < num; i++)
6234 if (vim_strchr(file[i], '$') != NULL)
6235 return TRUE;
6236 return FALSE;
6237}
6238#endif /* ifndef __EMX__ */
6239
6240#ifndef HAVE_RENAME
6241/*
6242 * Scaled-down version of rename(), which is missing in Xenix.
6243 * This version can only move regular files and will fail if the
6244 * destination exists.
6245 */
6246 int
6247mch_rename(src, dest)
6248 const char *src, *dest;
6249{
6250 struct stat st;
6251
6252 if (stat(dest, &st) >= 0) /* fail if destination exists */
6253 return -1;
6254 if (link(src, dest) != 0) /* link file to new name */
6255 return -1;
6256 if (mch_remove(src) == 0) /* delete link to old name */
6257 return 0;
6258 return -1;
6259}
6260#endif /* !HAVE_RENAME */
6261
6262#ifdef FEAT_MOUSE_GPM
6263/*
6264 * Initializes connection with gpm (if it isn't already opened)
6265 * Return 1 if succeeded (or connection already opened), 0 if failed
6266 */
6267 static int
6268gpm_open()
6269{
6270 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6271
6272 if (!gpm_flag)
6273 {
6274 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6275 gpm_connect.defaultMask = ~GPM_HARD;
6276 /* Default handling for mouse move*/
6277 gpm_connect.minMod = 0; /* Handle any modifier keys */
6278 gpm_connect.maxMod = 0xffff;
6279 if (Gpm_Open(&gpm_connect, 0) > 0)
6280 {
6281 /* gpm library tries to handling TSTP causes
6282 * problems. Anyways, we close connection to Gpm whenever
6283 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006284 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006286# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006288# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 return 1; /* succeed */
6290 }
6291 if (gpm_fd == -2)
6292 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6293 return 0;
6294 }
6295 return 1; /* already open */
6296}
6297
6298/*
6299 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 */
6301 static void
6302gpm_close()
6303{
6304 if (gpm_flag && gpm_fd >= 0) /* if Open */
6305 Gpm_Close();
6306}
6307
6308/* Reads gpm event and adds special keys to input buf. Returns length of
6309 * generated key sequence.
6310 * This function is made after gui_send_mouse_event
6311 */
6312 static int
6313mch_gpm_process()
6314{
6315 int button;
6316 static Gpm_Event gpm_event;
6317 char_u string[6];
6318 int_u vim_modifiers;
6319 int row,col;
6320 unsigned char buttons_mask;
6321 unsigned char gpm_modifiers;
6322 static unsigned char old_buttons = 0;
6323
6324 Gpm_GetEvent(&gpm_event);
6325
6326#ifdef FEAT_GUI
6327 /* Don't put events in the input queue now. */
6328 if (hold_gui_events)
6329 return 0;
6330#endif
6331
6332 row = gpm_event.y - 1;
6333 col = gpm_event.x - 1;
6334
6335 string[0] = ESC; /* Our termcode */
6336 string[1] = 'M';
6337 string[2] = 'G';
6338 switch (GPM_BARE_EVENTS(gpm_event.type))
6339 {
6340 case GPM_DRAG:
6341 string[3] = MOUSE_DRAG;
6342 break;
6343 case GPM_DOWN:
6344 buttons_mask = gpm_event.buttons & ~old_buttons;
6345 old_buttons = gpm_event.buttons;
6346 switch (buttons_mask)
6347 {
6348 case GPM_B_LEFT:
6349 button = MOUSE_LEFT;
6350 break;
6351 case GPM_B_MIDDLE:
6352 button = MOUSE_MIDDLE;
6353 break;
6354 case GPM_B_RIGHT:
6355 button = MOUSE_RIGHT;
6356 break;
6357 default:
6358 return 0;
6359 /*Don't know what to do. Can more than one button be
6360 * reported in one event? */
6361 }
6362 string[3] = (char_u)(button | 0x20);
6363 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6364 break;
6365 case GPM_UP:
6366 string[3] = MOUSE_RELEASE;
6367 old_buttons &= ~gpm_event.buttons;
6368 break;
6369 default:
6370 return 0;
6371 }
6372 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6373 gpm_modifiers = gpm_event.modifiers;
6374 vim_modifiers = 0x0;
6375 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6376 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6377 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6378 */
6379 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6380 vim_modifiers |= MOUSE_SHIFT;
6381
6382 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6383 vim_modifiers |= MOUSE_CTRL;
6384 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6385 vim_modifiers |= MOUSE_ALT;
6386 string[3] |= vim_modifiers;
6387 string[4] = (char_u)(col + ' ' + 1);
6388 string[5] = (char_u)(row + ' ' + 1);
6389 add_to_input_buf(string, 6);
6390 return 6;
6391}
6392#endif /* FEAT_MOUSE_GPM */
6393
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006394#ifdef FEAT_SYSMOUSE
6395/*
6396 * Initialize connection with sysmouse.
6397 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6398 * output, any sysmouse output than will be processed via sig_sysmouse().
6399 * Return OK if succeeded, FAIL if failed.
6400 */
6401 static int
6402sysmouse_open()
6403{
6404 struct mouse_info mouse;
6405
6406 mouse.operation = MOUSE_MODE;
6407 mouse.u.mode.mode = 0;
6408 mouse.u.mode.signal = SIGUSR2;
6409 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6410 {
6411 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6412 mouse.operation = MOUSE_SHOW;
6413 ioctl(1, CONS_MOUSECTL, &mouse);
6414 return OK;
6415 }
6416 return FAIL;
6417}
6418
6419/*
6420 * Stop processing SIGUSR2 signals, and also make sure that
6421 * virtual console do not send us any sysmouse related signal.
6422 */
6423 static void
6424sysmouse_close()
6425{
6426 struct mouse_info mouse;
6427
6428 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6429 mouse.operation = MOUSE_MODE;
6430 mouse.u.mode.mode = 0;
6431 mouse.u.mode.signal = 0;
6432 ioctl(1, CONS_MOUSECTL, &mouse);
6433}
6434
6435/*
6436 * Gets info from sysmouse and adds special keys to input buf.
6437 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006438 static RETSIGTYPE
6439sig_sysmouse SIGDEFARG(sigarg)
6440{
6441 struct mouse_info mouse;
6442 struct video_info video;
6443 char_u string[6];
6444 int row, col;
6445 int button;
6446 int buttons;
6447 static int oldbuttons = 0;
6448
6449#ifdef FEAT_GUI
6450 /* Don't put events in the input queue now. */
6451 if (hold_gui_events)
6452 return;
6453#endif
6454
6455 mouse.operation = MOUSE_GETINFO;
6456 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6457 && ioctl(1, FBIO_MODEINFO, &video) != -1
6458 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6459 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6460 {
6461 row = mouse.u.data.y / video.vi_cheight;
6462 col = mouse.u.data.x / video.vi_cwidth;
6463 buttons = mouse.u.data.buttons;
6464 string[0] = ESC; /* Our termcode */
6465 string[1] = 'M';
6466 string[2] = 'S';
6467 if (oldbuttons == buttons && buttons != 0)
6468 {
6469 button = MOUSE_DRAG;
6470 }
6471 else
6472 {
6473 switch (buttons)
6474 {
6475 case 0:
6476 button = MOUSE_RELEASE;
6477 break;
6478 case 1:
6479 button = MOUSE_LEFT;
6480 break;
6481 case 2:
6482 button = MOUSE_MIDDLE;
6483 break;
6484 case 4:
6485 button = MOUSE_RIGHT;
6486 break;
6487 default:
6488 return;
6489 }
6490 oldbuttons = buttons;
6491 }
6492 string[3] = (char_u)(button);
6493 string[4] = (char_u)(col + ' ' + 1);
6494 string[5] = (char_u)(row + ' ' + 1);
6495 add_to_input_buf(string, 6);
6496 }
6497 return;
6498}
6499#endif /* FEAT_SYSMOUSE */
6500
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501#if defined(FEAT_LIBCALL) || defined(PROTO)
6502typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6503typedef char_u * (*INTPROCSTR)__ARGS((int));
6504typedef int (*STRPROCINT)__ARGS((char_u *));
6505typedef int (*INTPROCINT)__ARGS((int));
6506
6507/*
6508 * Call a DLL routine which takes either a string or int param
6509 * and returns an allocated string.
6510 */
6511 int
6512mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6513 char_u *libname;
6514 char_u *funcname;
6515 char_u *argstring; /* NULL when using a argint */
6516 int argint;
6517 char_u **string_result;/* NULL when using number_result */
6518 int *number_result;
6519{
6520# if defined(USE_DLOPEN)
6521 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006522 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523# else
6524 shl_t hinstLib;
6525# endif
6526 STRPROCSTR ProcAdd;
6527 INTPROCSTR ProcAddI;
6528 char_u *retval_str = NULL;
6529 int retval_int = 0;
6530 int success = FALSE;
6531
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006532 /*
6533 * Get a handle to the DLL module.
6534 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006536 /* First clear any error, it's not cleared by the dlopen() call. */
6537 (void)dlerror();
6538
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 hinstLib = dlopen((char *)libname, RTLD_LAZY
6540# ifdef RTLD_LOCAL
6541 | RTLD_LOCAL
6542# endif
6543 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006544 if (hinstLib == NULL)
6545 {
6546 /* "dlerr" must be used before dlclose() */
6547 dlerr = (char *)dlerror();
6548 if (dlerr != NULL)
6549 EMSG2(_("dlerror = \"%s\""), dlerr);
6550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551# else
6552 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6553# endif
6554
6555 /* If the handle is valid, try to get the function address. */
6556 if (hinstLib != NULL)
6557 {
6558# ifdef HAVE_SETJMP_H
6559 /*
6560 * Catch a crash when calling the library function. For example when
6561 * using a number where a string pointer is expected.
6562 */
6563 mch_startjmp();
6564 if (SETJMP(lc_jump_env) != 0)
6565 {
6566 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006567# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006568 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006569# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 mch_didjmp();
6571 }
6572 else
6573# endif
6574 {
6575 retval_str = NULL;
6576 retval_int = 0;
6577
6578 if (argstring != NULL)
6579 {
6580# if defined(USE_DLOPEN)
6581 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006582 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583# else
6584 if (shl_findsym(&hinstLib, (const char *)funcname,
6585 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6586 ProcAdd = NULL;
6587# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006588 if ((success = (ProcAdd != NULL
6589# if defined(USE_DLOPEN)
6590 && dlerr == NULL
6591# endif
6592 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 {
6594 if (string_result == NULL)
6595 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6596 else
6597 retval_str = (ProcAdd)(argstring);
6598 }
6599 }
6600 else
6601 {
6602# if defined(USE_DLOPEN)
6603 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006604 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605# else
6606 if (shl_findsym(&hinstLib, (const char *)funcname,
6607 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6608 ProcAddI = NULL;
6609# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006610 if ((success = (ProcAddI != NULL
6611# if defined(USE_DLOPEN)
6612 && dlerr == NULL
6613# endif
6614 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 {
6616 if (string_result == NULL)
6617 retval_int = ((INTPROCINT)ProcAddI)(argint);
6618 else
6619 retval_str = (ProcAddI)(argint);
6620 }
6621 }
6622
6623 /* Save the string before we free the library. */
6624 /* Assume that a "1" or "-1" result is an illegal pointer. */
6625 if (string_result == NULL)
6626 *number_result = retval_int;
6627 else if (retval_str != NULL
6628 && retval_str != (char_u *)1
6629 && retval_str != (char_u *)-1)
6630 *string_result = vim_strsave(retval_str);
6631 }
6632
6633# ifdef HAVE_SETJMP_H
6634 mch_endjmp();
6635# ifdef SIGHASARG
6636 if (lc_signal != 0)
6637 {
6638 int i;
6639
6640 /* try to find the name of this signal */
6641 for (i = 0; signal_info[i].sig != -1; i++)
6642 if (lc_signal == signal_info[i].sig)
6643 break;
6644 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6645 }
6646# endif
6647# endif
6648
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006650 /* "dlerr" must be used before dlclose() */
6651 if (dlerr != NULL)
6652 EMSG2(_("dlerror = \"%s\""), dlerr);
6653
6654 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 (void)dlclose(hinstLib);
6656# else
6657 (void)shl_unload(hinstLib);
6658# endif
6659 }
6660
6661 if (!success)
6662 {
6663 EMSG2(_(e_libcall), funcname);
6664 return FAIL;
6665 }
6666
6667 return OK;
6668}
6669#endif
6670
6671#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6672static int xterm_trace = -1; /* default: disabled */
6673static int xterm_button;
6674
6675/*
6676 * Setup a dummy window for X selections in a terminal.
6677 */
6678 void
6679setup_term_clip()
6680{
6681 int z = 0;
6682 char *strp = "";
6683 Widget AppShell;
6684
6685 if (!x_connect_to_server())
6686 return;
6687
6688 open_app_context();
6689 if (app_context != NULL && xterm_Shell == (Widget)0)
6690 {
6691 int (*oldhandler)();
6692#if defined(HAVE_SETJMP_H)
6693 int (*oldIOhandler)();
6694#endif
6695# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6696 struct timeval start_tv;
6697
6698 if (p_verbose > 0)
6699 gettimeofday(&start_tv, NULL);
6700# endif
6701
6702 /* Ignore X errors while opening the display */
6703 oldhandler = XSetErrorHandler(x_error_check);
6704
6705#if defined(HAVE_SETJMP_H)
6706 /* Ignore X IO errors while opening the display */
6707 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6708 mch_startjmp();
6709 if (SETJMP(lc_jump_env) != 0)
6710 {
6711 mch_didjmp();
6712 xterm_dpy = NULL;
6713 }
6714 else
6715#endif
6716 {
6717 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6718 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6719#if defined(HAVE_SETJMP_H)
6720 mch_endjmp();
6721#endif
6722 }
6723
6724#if defined(HAVE_SETJMP_H)
6725 /* Now handle X IO errors normally. */
6726 (void)XSetIOErrorHandler(oldIOhandler);
6727#endif
6728 /* Now handle X errors normally. */
6729 (void)XSetErrorHandler(oldhandler);
6730
6731 if (xterm_dpy == NULL)
6732 {
6733 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006734 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 return;
6736 }
6737
6738 /* Catch terminating error of the X server connection. */
6739 (void)XSetIOErrorHandler(x_IOerror_handler);
6740
6741# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6742 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006743 {
6744 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006746 verbose_leave();
6747 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748# endif
6749
6750 /* Create a Shell to make converters work. */
6751 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6752 applicationShellWidgetClass, xterm_dpy,
6753 NULL);
6754 if (AppShell == (Widget)0)
6755 return;
6756 xterm_Shell = XtVaCreatePopupShell("VIM",
6757 topLevelShellWidgetClass, AppShell,
6758 XtNmappedWhenManaged, 0,
6759 XtNwidth, 1,
6760 XtNheight, 1,
6761 NULL);
6762 if (xterm_Shell == (Widget)0)
6763 return;
6764
6765 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006766 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 if (x11_display == NULL)
6768 x11_display = xterm_dpy;
6769
6770 XtRealizeWidget(xterm_Shell);
6771 XSync(xterm_dpy, False);
6772 xterm_update();
6773 }
6774 if (xterm_Shell != (Widget)0)
6775 {
6776 clip_init(TRUE);
6777 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6778 x11_window = (Window)atol(strp);
6779 /* Check if $WINDOWID is valid. */
6780 if (test_x11_window(xterm_dpy) == FAIL)
6781 x11_window = 0;
6782 if (x11_window != 0)
6783 xterm_trace = 0;
6784 }
6785}
6786
6787 void
6788start_xterm_trace(button)
6789 int button;
6790{
6791 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6792 return;
6793 xterm_trace = 1;
6794 xterm_button = button;
6795 do_xterm_trace();
6796}
6797
6798
6799 void
6800stop_xterm_trace()
6801{
6802 if (xterm_trace < 0)
6803 return;
6804 xterm_trace = 0;
6805}
6806
6807/*
6808 * Query the xterm pointer and generate mouse termcodes if necessary
6809 * return TRUE if dragging is active, else FALSE
6810 */
6811 static int
6812do_xterm_trace()
6813{
6814 Window root, child;
6815 int root_x, root_y;
6816 int win_x, win_y;
6817 int row, col;
6818 int_u mask_return;
6819 char_u buf[50];
6820 char_u *strp;
6821 long got_hints;
6822 static char_u *mouse_code;
6823 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6824 static int prev_row = 0, prev_col = 0;
6825 static XSizeHints xterm_hints;
6826
6827 if (xterm_trace <= 0)
6828 return FALSE;
6829
6830 if (xterm_trace == 1)
6831 {
6832 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006833 * have changed recently. */
6834 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6835 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 || xterm_hints.width_inc <= 1
6837 || xterm_hints.height_inc <= 1)
6838 {
6839 xterm_trace = -1; /* Not enough data -- disable tracing */
6840 return FALSE;
6841 }
6842
6843 /* Rely on the same mouse code for the duration of this */
6844 mouse_code = find_termcode(mouse_name);
6845 prev_row = mouse_row;
6846 prev_row = mouse_col;
6847 xterm_trace = 2;
6848
6849 /* Find the offset of the chars, there might be a scrollbar on the
6850 * left of the window and/or a menu on the top (eterm etc.) */
6851 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6852 &win_x, &win_y, &mask_return);
6853 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6854 - (xterm_hints.height_inc / 2);
6855 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6856 xterm_hints.y = 2;
6857 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6858 - (xterm_hints.width_inc / 2);
6859 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6860 xterm_hints.x = 2;
6861 return TRUE;
6862 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006863 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 {
6865 xterm_trace = 0;
6866 return FALSE;
6867 }
6868
6869 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6870 &win_x, &win_y, &mask_return);
6871
6872 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6873 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6874 if (row == prev_row && col == prev_col)
6875 return TRUE;
6876
6877 STRCPY(buf, mouse_code);
6878 strp = buf + STRLEN(buf);
6879 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6880 *strp++ = (char_u)(col + ' ' + 1);
6881 *strp++ = (char_u)(row + ' ' + 1);
6882 *strp = 0;
6883 add_to_input_buf(buf, STRLEN(buf));
6884
6885 prev_row = row;
6886 prev_col = col;
6887 return TRUE;
6888}
6889
6890# if defined(FEAT_GUI) || defined(PROTO)
6891/*
6892 * Destroy the display, window and app_context. Required for GTK.
6893 */
6894 void
6895clear_xterm_clip()
6896{
6897 if (xterm_Shell != (Widget)0)
6898 {
6899 XtDestroyWidget(xterm_Shell);
6900 xterm_Shell = (Widget)0;
6901 }
6902 if (xterm_dpy != NULL)
6903 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006904# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 /* Lesstif and Solaris crash here, lose some memory */
6906 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006907# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 if (x11_display == xterm_dpy)
6909 x11_display = NULL;
6910 xterm_dpy = NULL;
6911 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006912# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 if (app_context != (XtAppContext)NULL)
6914 {
6915 /* Lesstif and Solaris crash here, lose some memory */
6916 XtDestroyApplicationContext(app_context);
6917 app_context = (XtAppContext)NULL;
6918 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006919# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920}
6921# endif
6922
6923/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01006924 * Catch up with GUI or X events.
6925 */
6926 static void
6927clip_update()
6928{
6929# ifdef FEAT_GUI
6930 if (gui.in_use)
6931 gui_mch_update();
6932 else
6933# endif
6934 if (xterm_Shell != (Widget)0)
6935 xterm_update();
6936}
6937
6938/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 * Catch up with any queued X events. This may put keyboard input into the
6940 * input buffer, call resize call-backs, trigger timers etc. If there is
6941 * nothing in the X event queue (& no timers pending), then we return
6942 * immediately.
6943 */
6944 static void
6945xterm_update()
6946{
6947 XEvent event;
6948
6949 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6950 {
6951 XtAppNextEvent(app_context, &event);
6952#ifdef FEAT_CLIENTSERVER
6953 {
6954 XPropertyEvent *e = (XPropertyEvent *)&event;
6955
6956 if (e->type == PropertyNotify && e->window == commWindow
6957 && e->atom == commProperty && e->state == PropertyNewValue)
6958 serverEventProc(xterm_dpy, &event);
6959 }
6960#endif
6961 XtDispatchEvent(&event);
6962 }
6963}
6964
6965 int
6966clip_xterm_own_selection(cbd)
6967 VimClipboard *cbd;
6968{
6969 if (xterm_Shell != (Widget)0)
6970 return clip_x11_own_selection(xterm_Shell, cbd);
6971 return FAIL;
6972}
6973
6974 void
6975clip_xterm_lose_selection(cbd)
6976 VimClipboard *cbd;
6977{
6978 if (xterm_Shell != (Widget)0)
6979 clip_x11_lose_selection(xterm_Shell, cbd);
6980}
6981
6982 void
6983clip_xterm_request_selection(cbd)
6984 VimClipboard *cbd;
6985{
6986 if (xterm_Shell != (Widget)0)
6987 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6988}
6989
6990 void
6991clip_xterm_set_selection(cbd)
6992 VimClipboard *cbd;
6993{
6994 clip_x11_set_selection(cbd);
6995}
6996#endif
6997
6998
6999#if defined(USE_XSMP) || defined(PROTO)
7000/*
7001 * Code for X Session Management Protocol.
7002 */
7003static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
7004static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
7005static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
7006static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
7007static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
7008
7009
7010# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7011static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7012
7013/*
7014 * This is our chance to ask the user if they want to save,
7015 * or abort the logout
7016 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 static void
7018xsmp_handle_interaction(smc_conn, client_data)
7019 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007020 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021{
7022 cmdmod_T save_cmdmod;
7023 int cancel_shutdown = False;
7024
7025 save_cmdmod = cmdmod;
7026 cmdmod.confirm = TRUE;
7027 if (check_changed_any(FALSE))
7028 /* Mustn't logout */
7029 cancel_shutdown = True;
7030 cmdmod = save_cmdmod;
7031 setcursor(); /* position cursor */
7032 out_flush();
7033
7034 /* Done interaction */
7035 SmcInteractDone(smc_conn, cancel_shutdown);
7036
7037 /* Finish off
7038 * Only end save-yourself here if we're not cancelling shutdown;
7039 * we'll get a cancelled callback later in which we'll end it.
7040 * Hopefully get around glitchy SMs (like GNOME-1)
7041 */
7042 if (!cancel_shutdown)
7043 {
7044 xsmp.save_yourself = False;
7045 SmcSaveYourselfDone(smc_conn, True);
7046 }
7047}
7048# endif
7049
7050/*
7051 * Callback that starts save-yourself.
7052 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 static void
7054xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7055 shutdown, interact_style, fast)
7056 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007057 SmPointer client_data UNUSED;
7058 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007060 int interact_style UNUSED;
7061 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062{
7063 /* Handle already being in saveyourself */
7064 if (xsmp.save_yourself)
7065 SmcSaveYourselfDone(smc_conn, True);
7066 xsmp.save_yourself = True;
7067 xsmp.shutdown = shutdown;
7068
7069 /* First up, preserve all files */
7070 out_flush();
7071 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7072
7073 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007074 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075
7076# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7077 /* Now see if we can ask about unsaved files */
7078 if (shutdown && !fast && gui.in_use)
7079 /* Need to interact with user, but need SM's permission */
7080 SmcInteractRequest(smc_conn, SmDialogError,
7081 xsmp_handle_interaction, client_data);
7082 else
7083# endif
7084 {
7085 /* Can stop the cycle here */
7086 SmcSaveYourselfDone(smc_conn, True);
7087 xsmp.save_yourself = False;
7088 }
7089}
7090
7091
7092/*
7093 * Callback to warn us of imminent death.
7094 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 static void
7096xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007097 SmcConn smc_conn UNUSED;
7098 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099{
7100 xsmp_close();
7101
7102 /* quit quickly leaving swapfiles for modified buffers behind */
7103 getout_preserve_modified(0);
7104}
7105
7106
7107/*
7108 * Callback to tell us that save-yourself has completed.
7109 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110 static void
7111xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007112 SmcConn smc_conn UNUSED;
7113 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114{
7115 xsmp.save_yourself = False;
7116}
7117
7118
7119/*
7120 * Callback to tell us that an instigated shutdown was cancelled
7121 * (maybe even by us)
7122 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 static void
7124xsmp_shutdown_cancelled(smc_conn, client_data)
7125 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007126 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127{
7128 if (xsmp.save_yourself)
7129 SmcSaveYourselfDone(smc_conn, True);
7130 xsmp.save_yourself = False;
7131 xsmp.shutdown = False;
7132}
7133
7134
7135/*
7136 * Callback to tell us that a new ICE connection has been established.
7137 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 static void
7139xsmp_ice_connection(iceConn, clientData, opening, watchData)
7140 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007141 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007143 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144{
7145 /* Intercept creation of ICE connection fd */
7146 if (opening)
7147 {
7148 xsmp_icefd = IceConnectionNumber(iceConn);
7149 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7150 }
7151}
7152
7153
7154/* Handle any ICE processing that's required; return FAIL if SM lost */
7155 int
7156xsmp_handle_requests()
7157{
7158 Bool rep;
7159
7160 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7161 == IceProcessMessagesIOError)
7162 {
7163 /* Lost ICE */
7164 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007165 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166 xsmp_close();
7167 return FAIL;
7168 }
7169 else
7170 return OK;
7171}
7172
7173static int dummy;
7174
7175/* Set up X Session Management Protocol */
7176 void
7177xsmp_init(void)
7178{
7179 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 SmcCallbacks smcallbacks;
7181#if 0
7182 SmPropValue smname;
7183 SmProp smnameprop;
7184 SmProp *smprops[1];
7185#endif
7186
7187 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007188 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189
7190 xsmp.save_yourself = xsmp.shutdown = False;
7191
7192 /* Set up SM callbacks - must have all, even if they're not used */
7193 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7194 smcallbacks.save_yourself.client_data = NULL;
7195 smcallbacks.die.callback = xsmp_die;
7196 smcallbacks.die.client_data = NULL;
7197 smcallbacks.save_complete.callback = xsmp_save_complete;
7198 smcallbacks.save_complete.client_data = NULL;
7199 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7200 smcallbacks.shutdown_cancelled.client_data = NULL;
7201
7202 /* Set up a watch on ICE connection creations. The "dummy" argument is
7203 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7204 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7205 {
7206 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007207 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208 return;
7209 }
7210
7211 /* Create an SM connection */
7212 xsmp.smcconn = SmcOpenConnection(
7213 NULL,
7214 NULL,
7215 SmProtoMajor,
7216 SmProtoMinor,
7217 SmcSaveYourselfProcMask | SmcDieProcMask
7218 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7219 &smcallbacks,
7220 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007221 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222 sizeof(errorstring),
7223 errorstring);
7224 if (xsmp.smcconn == NULL)
7225 {
7226 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007227
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007229 {
7230 vim_snprintf(errorreport, sizeof(errorreport),
7231 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7232 verb_msg((char_u *)errorreport);
7233 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 return;
7235 }
7236 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7237
7238#if 0
7239 /* ID ourselves */
7240 smname.value = "vim";
7241 smname.length = 3;
7242 smnameprop.name = "SmProgram";
7243 smnameprop.type = "SmARRAY8";
7244 smnameprop.num_vals = 1;
7245 smnameprop.vals = &smname;
7246
7247 smprops[0] = &smnameprop;
7248 SmcSetProperties(xsmp.smcconn, 1, smprops);
7249#endif
7250}
7251
7252
7253/* Shut down XSMP comms. */
7254 void
7255xsmp_close()
7256{
7257 if (xsmp_icefd != -1)
7258 {
7259 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007260 if (xsmp.clientid != NULL)
7261 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007262 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263 xsmp_icefd = -1;
7264 }
7265}
7266#endif /* USE_XSMP */
7267
7268
7269#ifdef EBCDIC
7270/* Translate character to its CTRL- value */
7271char CtrlTable[] =
7272{
7273/* 00 - 5E */
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, 0,
7278 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7280/* ^ */ 0x1E,
7281/* - */ 0x1F,
7282/* 61 - 6C */
7283 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7284/* _ */ 0x1F,
7285/* 6E - 80 */
7286 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7287/* a */ 0x01,
7288/* b */ 0x02,
7289/* c */ 0x03,
7290/* d */ 0x37,
7291/* e */ 0x2D,
7292/* f */ 0x2E,
7293/* g */ 0x2F,
7294/* h */ 0x16,
7295/* i */ 0x05,
7296/* 8A - 90 */
7297 0, 0, 0, 0, 0, 0, 0,
7298/* j */ 0x15,
7299/* k */ 0x0B,
7300/* l */ 0x0C,
7301/* m */ 0x0D,
7302/* n */ 0x0E,
7303/* o */ 0x0F,
7304/* p */ 0x10,
7305/* q */ 0x11,
7306/* r */ 0x12,
7307/* 9A - A1 */
7308 0, 0, 0, 0, 0, 0, 0, 0,
7309/* s */ 0x13,
7310/* t */ 0x3C,
7311/* u */ 0x3D,
7312/* v */ 0x32,
7313/* w */ 0x26,
7314/* x */ 0x18,
7315/* y */ 0x19,
7316/* z */ 0x3F,
7317/* AA - AC */
7318 0, 0, 0,
7319/* [ */ 0x27,
7320/* AE - BC */
7321 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7322/* ] */ 0x1D,
7323/* BE - C0 */ 0, 0, 0,
7324/* A */ 0x01,
7325/* B */ 0x02,
7326/* C */ 0x03,
7327/* D */ 0x37,
7328/* E */ 0x2D,
7329/* F */ 0x2E,
7330/* G */ 0x2F,
7331/* H */ 0x16,
7332/* I */ 0x05,
7333/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7334/* J */ 0x15,
7335/* K */ 0x0B,
7336/* L */ 0x0C,
7337/* M */ 0x0D,
7338/* N */ 0x0E,
7339/* O */ 0x0F,
7340/* P */ 0x10,
7341/* Q */ 0x11,
7342/* R */ 0x12,
7343/* DA - DF */ 0, 0, 0, 0, 0, 0,
7344/* \ */ 0x1C,
7345/* E1 */ 0,
7346/* S */ 0x13,
7347/* T */ 0x3C,
7348/* U */ 0x3D,
7349/* V */ 0x32,
7350/* W */ 0x26,
7351/* X */ 0x18,
7352/* Y */ 0x19,
7353/* Z */ 0x3F,
7354/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7355 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7356};
7357
7358char MetaCharTable[]=
7359{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7360 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7361 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7362 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7363 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7364};
7365
7366
7367/* TODO: Use characters NOT numbers!!! */
7368char CtrlCharTable[]=
7369{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7370 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7371 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7372 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7373 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7374};
7375
7376
7377#endif