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