blob: 48176e1803e2f5570df6f317c0251612894b428f [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 Moolenaara2442432007-04-26 14:26:37 +000064# endif
65#endif
66
Bram Moolenaar071d4272004-06-13 20:20:40 +000067#if defined(HAVE_SELECT)
68extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
69#endif
70
71#ifdef FEAT_MOUSE_GPM
72# include <gpm.h>
73/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
74 * I just copied relevant defines here. A cleaner solution would be to put gpm
75 * code into separate file and include there linux/keyboard.h
76 */
77/* #include <linux/keyboard.h> */
78# define KG_SHIFT 0
79# define KG_CTRL 2
80# define KG_ALT 3
81# define KG_ALTGR 1
82# define KG_SHIFTL 4
83# define KG_SHIFTR 5
84# define KG_CTRLL 6
85# define KG_CTRLR 7
86# define KG_CAPSSHIFT 8
87
88static void gpm_close __ARGS((void));
89static int gpm_open __ARGS((void));
90static int mch_gpm_process __ARGS((void));
91#endif
92
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000093#ifdef FEAT_SYSMOUSE
94# include <sys/consio.h>
95# include <sys/fbio.h>
96
97static int sysmouse_open __ARGS((void));
98static void sysmouse_close __ARGS((void));
99static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG);
100#endif
101
Bram Moolenaar071d4272004-06-13 20:20:40 +0000102/*
103 * end of autoconf section. To be extended...
104 */
105
106/* Are the following #ifdefs still required? And why? Is that for X11? */
107
108#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
109# ifdef SIGWINCH
110# undef SIGWINCH
111# endif
112# ifdef TIOCGWINSZ
113# undef TIOCGWINSZ
114# endif
115#endif
116
117#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
118# define SIGWINCH SIGWINDOW
119#endif
120
121#ifdef FEAT_X11
122# include <X11/Xlib.h>
123# include <X11/Xutil.h>
124# include <X11/Xatom.h>
125# ifdef FEAT_XCLIPBOARD
126# include <X11/Intrinsic.h>
127# include <X11/Shell.h>
128# include <X11/StringDefs.h>
129static Widget xterm_Shell = (Widget)0;
130static void xterm_update __ARGS((void));
131# endif
132
133# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
134Window x11_window = 0;
135# endif
136Display *x11_display = NULL;
137
138# ifdef FEAT_TITLE
139static int get_x11_windis __ARGS((void));
140static void set_x11_title __ARGS((char_u *));
141static void set_x11_icon __ARGS((char_u *));
142# endif
143#endif
144
145#ifdef FEAT_TITLE
146static int get_x11_title __ARGS((int));
147static int get_x11_icon __ARGS((int));
148
149static char_u *oldtitle = NULL;
150static int did_set_title = FALSE;
151static char_u *oldicon = NULL;
152static int did_set_icon = FALSE;
153#endif
154
155static void may_core_dump __ARGS((void));
156
Bram Moolenaar205b8862011-09-07 15:04:31 +0200157#ifdef HAVE_UNION_WAIT
158typedef union wait waitstatus;
159#else
160typedef int waitstatus;
161#endif
Bram Moolenaar9f118812011-09-08 23:24:14 +0200162static pid_t wait4pid __ARGS((pid_t, waitstatus *));
Bram Moolenaar205b8862011-09-07 15:04:31 +0200163
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164static int WaitForChar __ARGS((long));
165#if defined(__BEOS__)
166int RealWaitForChar __ARGS((int, long, int *));
167#else
168static int RealWaitForChar __ARGS((int, long, int *));
169#endif
170
171#ifdef FEAT_XCLIPBOARD
172static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000173# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174#endif
175
176static void handle_resize __ARGS((void));
177
178#if defined(SIGWINCH)
179static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
180#endif
181#if defined(SIGINT)
182static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
183#endif
184#if defined(SIGPWR)
185static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
186#endif
187#if defined(SIGALRM) && defined(FEAT_X11) \
188 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
189# define SET_SIG_ALARM
190static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000191/* volatile because it is used in signal handler sig_alarm(). */
192static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193#endif
194static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
195
Bram Moolenaardf177f62005-02-22 08:39:57 +0000196static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197static void set_signals __ARGS((void));
198static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
199#ifndef __EMX__
200static int have_wildcard __ARGS((int, char_u **));
201static int have_dollars __ARGS((int, char_u **));
202#endif
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef __EMX__
205static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
206#endif
207
208#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000209# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210#endif
211
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000212/* volatile because it is used in signal handler sig_winch(). */
213static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214#ifndef __EMX__
215static char_u *extra_shell_arg = NULL;
216static int show_shell_mess = TRUE;
217#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000218/* volatile because it is used in signal handler deathtrap(). */
219static volatile int deadly_signal = 0; /* The signal we caught */
220/* volatile because it is used in signal handler deathtrap(). */
221static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222
223static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
224
225#ifdef USE_XSMP
226typedef struct
227{
228 SmcConn smcconn; /* The SM connection ID */
229 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200230 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231 Bool save_yourself; /* If we're in the middle of a save_yourself */
232 Bool shutdown; /* If we're in shutdown mode */
233} xsmp_config_T;
234
235static xsmp_config_T xsmp;
236#endif
237
238#ifdef SYS_SIGLIST_DECLARED
239/*
240 * I have seen
241 * extern char *_sys_siglist[NSIG];
242 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
243 * that describe the signals. That is nearly what we want here. But
244 * autoconf does only check for sys_siglist (without the underscore), I
245 * do not want to change everything today.... jw.
246 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
247 */
248#endif
249
250static struct signalinfo
251{
252 int sig; /* Signal number, eg. SIGSEGV etc */
253 char *name; /* Signal name (not char_u!). */
254 char deadly; /* Catch as a deadly signal? */
255} signal_info[] =
256{
257#ifdef SIGHUP
258 {SIGHUP, "HUP", TRUE},
259#endif
260#ifdef SIGQUIT
261 {SIGQUIT, "QUIT", TRUE},
262#endif
263#ifdef SIGILL
264 {SIGILL, "ILL", TRUE},
265#endif
266#ifdef SIGTRAP
267 {SIGTRAP, "TRAP", TRUE},
268#endif
269#ifdef SIGABRT
270 {SIGABRT, "ABRT", TRUE},
271#endif
272#ifdef SIGEMT
273 {SIGEMT, "EMT", TRUE},
274#endif
275#ifdef SIGFPE
276 {SIGFPE, "FPE", TRUE},
277#endif
278#ifdef SIGBUS
279 {SIGBUS, "BUS", TRUE},
280#endif
281#ifdef SIGSEGV
282 {SIGSEGV, "SEGV", TRUE},
283#endif
284#ifdef SIGSYS
285 {SIGSYS, "SYS", TRUE},
286#endif
287#ifdef SIGALRM
288 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
289#endif
290#ifdef SIGTERM
291 {SIGTERM, "TERM", TRUE},
292#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100293#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 {SIGVTALRM, "VTALRM", TRUE},
295#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000296#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
297 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
298 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299 {SIGPROF, "PROF", TRUE},
300#endif
301#ifdef SIGXCPU
302 {SIGXCPU, "XCPU", TRUE},
303#endif
304#ifdef SIGXFSZ
305 {SIGXFSZ, "XFSZ", TRUE},
306#endif
307#ifdef SIGUSR1
308 {SIGUSR1, "USR1", TRUE},
309#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000310#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
311 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312 {SIGUSR2, "USR2", TRUE},
313#endif
314#ifdef SIGINT
315 {SIGINT, "INT", FALSE},
316#endif
317#ifdef SIGWINCH
318 {SIGWINCH, "WINCH", FALSE},
319#endif
320#ifdef SIGTSTP
321 {SIGTSTP, "TSTP", FALSE},
322#endif
323#ifdef SIGPIPE
324 {SIGPIPE, "PIPE", FALSE},
325#endif
326 {-1, "Unknown!", FALSE}
327};
328
Bram Moolenaar25724922009-07-14 15:38:41 +0000329 int
330mch_chdir(path)
331 char *path;
332{
333 if (p_verbose >= 5)
334 {
335 verbose_enter();
336 smsg((char_u *)"chdir(%s)", path);
337 verbose_leave();
338 }
339# ifdef VMS
340 return chdir(vms_fixfilename(path));
341# else
342 return chdir(path);
343# endif
344}
345
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000346/*
347 * Write s[len] to the screen.
348 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 void
350mch_write(s, len)
351 char_u *s;
352 int len;
353{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000354 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355 if (p_wd) /* Unix is too fast, slow down a bit more */
356 RealWaitForChar(read_cmd_fd, p_wd, NULL);
357}
358
359/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000360 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361 * Get a characters from the keyboard.
362 * Return the number of characters that are available.
363 * If wtime == 0 do not wait for characters.
364 * If wtime == n wait a short time for characters.
365 * If wtime == -1 wait forever for characters.
366 */
367 int
368mch_inchar(buf, maxlen, wtime, tb_change_cnt)
369 char_u *buf;
370 int maxlen;
371 long wtime; /* don't use "time", MIPS cannot handle it */
372 int tb_change_cnt;
373{
374 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000375
Bram Moolenaar67c53842010-05-22 18:28:27 +0200376#ifdef FEAT_NETBEANS_INTG
377 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200378 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200379#endif
380
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 /* Check if window changed size while we were busy, perhaps the ":set
382 * columns=99" command was used. */
383 while (do_resize)
384 handle_resize();
385
386 if (wtime >= 0)
387 {
388 while (WaitForChar(wtime) == 0) /* no character available */
389 {
390 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000391 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200393#ifdef FEAT_NETBEANS_INTG
394 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200395 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 }
398 }
399 else /* wtime == -1 */
400 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 /*
402 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000403 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 * Also done when interrupted by SIGWINCH.
405 */
406 if (WaitForChar(p_ut) == 0)
407 {
408#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000409 if (trigger_cursorhold() && maxlen >= 3
410 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000412 buf[0] = K_SPECIAL;
413 buf[1] = KS_EXTRA;
414 buf[2] = (int)KE_CURSORHOLD;
415 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000418 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 }
420 }
421
422 for (;;) /* repeat until we got a character */
423 {
424 while (do_resize) /* window changed size */
425 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200426
427#ifdef FEAT_NETBEANS_INTG
428 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200429 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200430#endif
Bram Moolenaar48bae372010-07-29 23:12:15 +0200431#ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200433 * We want to be interrupted by the winch signal
434 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200436 if (WaitForChar(-1L) == 0)
437 {
438 if (do_resize) /* interrupted by SIGWINCH signal */
439 handle_resize();
440 return 0;
441 }
Bram Moolenaar48bae372010-07-29 23:12:15 +0200442#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443
444 /* If input was put directly in typeahead buffer bail out here. */
445 if (typebuf_changed(tb_change_cnt))
446 return 0;
447
448 /*
449 * For some terminals we only get one character at a time.
450 * We want the get all available characters, so we could keep on
451 * trying until none is available
452 * For some other terminals this is quite slow, that's why we don't do
453 * it.
454 */
455 len = read_from_input_buf(buf, (long)maxlen);
456 if (len > 0)
457 {
458#ifdef OS2
459 int i;
460
461 for (i = 0; i < len; i++)
462 if (buf[i] == 0)
463 buf[i] = K_NUL;
464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 return len;
466 }
467 }
468}
469
470 static void
471handle_resize()
472{
473 do_resize = FALSE;
474 shell_resized();
475}
476
477/*
478 * return non-zero if a character is available
479 */
480 int
481mch_char_avail()
482{
483 return WaitForChar(0L);
484}
485
486#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
487# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000488# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489# endif
490# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
491# include <sys/sysctl.h>
492# endif
493# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
494# include <sys/sysinfo.h>
495# endif
496
497/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000498 * Return total amount of memory available in Kbyte.
499 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501 long_u
502mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000503 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504{
505# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000506 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507# else
508 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000509 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510
511# ifdef HAVE_SYSCTL
512 int mib[2], physmem;
513 size_t len;
514
515 /* BSD way of getting the amount of RAM available. */
516 mib[0] = CTL_HW;
517 mib[1] = HW_USERMEM;
518 len = sizeof(physmem);
519 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
520 mem = (long_u)physmem;
521# endif
522
523# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
524 if (mem == 0)
525 {
526 struct sysinfo sinfo;
527
528 /* Linux way of getting amount of RAM available */
529 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000530 {
531# ifdef HAVE_SYSINFO_MEM_UNIT
532 /* avoid overflow as much as possible */
533 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
534 {
535 sinfo.mem_unit = sinfo.mem_unit >> 1;
536 --shiftright;
537 }
538 mem = sinfo.totalram * sinfo.mem_unit;
539# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000541# endif
542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543 }
544# endif
545
546# ifdef HAVE_SYSCONF
547 if (mem == 0)
548 {
549 long pagesize, pagecount;
550
551 /* Solaris way of getting amount of RAM available */
552 pagesize = sysconf(_SC_PAGESIZE);
553 pagecount = sysconf(_SC_PHYS_PAGES);
554 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000555 {
556 /* avoid overflow as much as possible */
557 while (shiftright > 0 && (pagesize & 1) == 0)
558 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000559 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000560 --shiftright;
561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000563 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564 }
565# endif
566
567 /* Return the minimum of the physical memory and the user limit, because
568 * using more than the user limit may cause Vim to be terminated. */
569# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
570 {
571 struct rlimit rlp;
572
573 if (getrlimit(RLIMIT_DATA, &rlp) == 0
574 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
575# ifdef RLIM_INFINITY
576 && rlp.rlim_cur != RLIM_INFINITY
577# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000578 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000580 {
581 mem = (long_u)rlp.rlim_cur;
582 shiftright = 10;
583 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 }
585# endif
586
587 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000588 return mem >> shiftright;
589 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590# endif
591}
592#endif
593
594 void
595mch_delay(msec, ignoreinput)
596 long msec;
597 int ignoreinput;
598{
599 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000600#ifdef FEAT_MZSCHEME
601 long total = msec; /* remember original value */
602#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 if (ignoreinput)
605 {
606 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000607 * here. But we don't want QUIT to kill us (CTRL-\ used in a
608 * shell may produce SIGQUIT). */
609 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 old_tmode = curr_tmode;
611 if (curr_tmode == TMODE_RAW)
612 settmode(TMODE_SLEEP);
613
614 /*
615 * Everybody sleeps in a different way...
616 * Prefer nanosleep(), some versions of usleep() can only sleep up to
617 * one second.
618 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000619#ifdef FEAT_MZSCHEME
620 do
621 {
622 /* if total is large enough, wait by portions in p_mzq */
623 if (total > p_mzq)
624 msec = p_mzq;
625 else
626 msec = total;
627 total -= msec;
628#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#ifdef HAVE_NANOSLEEP
630 {
631 struct timespec ts;
632
633 ts.tv_sec = msec / 1000;
634 ts.tv_nsec = (msec % 1000) * 1000000;
635 (void)nanosleep(&ts, NULL);
636 }
637#else
638# ifdef HAVE_USLEEP
639 while (msec >= 1000)
640 {
641 usleep((unsigned int)(999 * 1000));
642 msec -= 999;
643 }
644 usleep((unsigned int)(msec * 1000));
645# else
646# ifndef HAVE_SELECT
647 poll(NULL, 0, (int)msec);
648# else
649# ifdef __EMX__
650 _sleep2(msec);
651# else
652 {
653 struct timeval tv;
654
655 tv.tv_sec = msec / 1000;
656 tv.tv_usec = (msec % 1000) * 1000;
657 /*
658 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
659 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
660 */
661 select(0, NULL, NULL, NULL, &tv);
662 }
663# endif /* __EMX__ */
664# endif /* HAVE_SELECT */
665# endif /* HAVE_NANOSLEEP */
666#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000667#ifdef FEAT_MZSCHEME
668 }
669 while (total > 0);
670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671
672 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000673 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674 }
675 else
676 WaitForChar(msec);
677}
678
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000679#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
681# define HAVE_CHECK_STACK_GROWTH
682/*
683 * Support for checking for an almost-out-of-stack-space situation.
684 */
685
686/*
687 * Return a pointer to an item on the stack. Used to find out if the stack
688 * grows up or down.
689 */
690static void check_stack_growth __ARGS((char *p));
691static int stack_grows_downwards;
692
693/*
694 * Find out if the stack grows upwards or downwards.
695 * "p" points to a variable on the stack of the caller.
696 */
697 static void
698check_stack_growth(p)
699 char *p;
700{
701 int i;
702
703 stack_grows_downwards = (p > (char *)&i);
704}
705#endif
706
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000707#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708static char *stack_limit = NULL;
709
710#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
711# include <pthread.h>
712# include <pthread_np.h>
713#endif
714
715/*
716 * Find out until how var the stack can grow without getting into trouble.
717 * Called when starting up and when switching to the signal stack in
718 * deathtrap().
719 */
720 static void
721get_stack_limit()
722{
723 struct rlimit rlp;
724 int i;
725 long lim;
726
727 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
728 * limit doesn't fit in a long (rlim_cur might be "long long"). */
729 if (getrlimit(RLIMIT_STACK, &rlp) == 0
730 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
731# ifdef RLIM_INFINITY
732 && rlp.rlim_cur != RLIM_INFINITY
733# endif
734 )
735 {
736 lim = (long)rlp.rlim_cur;
737#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
738 {
739 pthread_attr_t attr;
740 size_t size;
741
742 /* On FreeBSD the initial thread always has a fixed stack size, no
743 * matter what the limits are set to. Normally it's 1 Mbyte. */
744 pthread_attr_init(&attr);
745 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
746 {
747 pthread_attr_getstacksize(&attr, &size);
748 if (lim > (long)size)
749 lim = (long)size;
750 }
751 pthread_attr_destroy(&attr);
752 }
753#endif
754 if (stack_grows_downwards)
755 {
756 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
757 if (stack_limit >= (char *)&i)
758 /* overflow, set to 1/16 of current stack position */
759 stack_limit = (char *)((long)&i / 16L);
760 }
761 else
762 {
763 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
764 if (stack_limit <= (char *)&i)
765 stack_limit = NULL; /* overflow */
766 }
767 }
768}
769
770/*
771 * Return FAIL when running out of stack space.
772 * "p" must point to any variable local to the caller that's on the stack.
773 */
774 int
775mch_stackcheck(p)
776 char *p;
777{
778 if (stack_limit != NULL)
779 {
780 if (stack_grows_downwards)
781 {
782 if (p < stack_limit)
783 return FAIL;
784 }
785 else if (p > stack_limit)
786 return FAIL;
787 }
788 return OK;
789}
790#endif
791
792#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
793/*
794 * Support for using the signal stack.
795 * This helps when we run out of stack space, which causes a SIGSEGV. The
796 * signal handler then must run on another stack, since the normal stack is
797 * completely full.
798 */
799
800#ifndef SIGSTKSZ
801# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
802#endif
803
804# ifdef HAVE_SIGALTSTACK
805static stack_t sigstk; /* for sigaltstack() */
806# else
807static struct sigstack sigstk; /* for sigstack() */
808# endif
809
810static void init_signal_stack __ARGS((void));
811static char *signal_stack;
812
813 static void
814init_signal_stack()
815{
816 if (signal_stack != NULL)
817 {
818# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000819# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
820 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
822 * "struct sigaltstack" needs to be declared. */
823 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
824# endif
825
826# ifdef HAVE_SS_BASE
827 sigstk.ss_base = signal_stack;
828# else
829 sigstk.ss_sp = signal_stack;
830# endif
831 sigstk.ss_size = SIGSTKSZ;
832 sigstk.ss_flags = 0;
833 (void)sigaltstack(&sigstk, NULL);
834# else
835 sigstk.ss_sp = signal_stack;
836 if (stack_grows_downwards)
837 sigstk.ss_sp += SIGSTKSZ - 1;
838 sigstk.ss_onstack = 0;
839 (void)sigstack(&sigstk, NULL);
840# endif
841 }
842}
843#endif
844
845/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000846 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 * will barf when the second argument to signal() is ``wrong''.
848 * Let me try it with a few tricky defines from my own osdef.h (jw).
849 */
850#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851 static RETSIGTYPE
852sig_winch SIGDEFARG(sigarg)
853{
854 /* this is not required on all systems, but it doesn't hurt anybody */
855 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
856 do_resize = TRUE;
857 SIGRETURN;
858}
859#endif
860
861#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 static RETSIGTYPE
863catch_sigint SIGDEFARG(sigarg)
864{
865 /* this is not required on all systems, but it doesn't hurt anybody */
866 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
867 got_int = TRUE;
868 SIGRETURN;
869}
870#endif
871
872#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 static RETSIGTYPE
874catch_sigpwr SIGDEFARG(sigarg)
875{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000876 /* this is not required on all systems, but it doesn't hurt anybody */
877 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878 /*
879 * I'm not sure we get the SIGPWR signal when the system is really going
880 * down or when the batteries are almost empty. Just preserve the swap
881 * files and don't exit, that can't do any harm.
882 */
883 ml_sync_all(FALSE, FALSE);
884 SIGRETURN;
885}
886#endif
887
888#ifdef SET_SIG_ALARM
889/*
890 * signal function for alarm().
891 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 static RETSIGTYPE
893sig_alarm SIGDEFARG(sigarg)
894{
895 /* doesn't do anything, just to break a system call */
896 sig_alarm_called = TRUE;
897 SIGRETURN;
898}
899#endif
900
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000901#if (defined(HAVE_SETJMP_H) \
902 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
903 || defined(FEAT_LIBCALL))) \
904 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905/*
906 * A simplistic version of setjmp() that only allows one level of using.
907 * Don't call twice before calling mch_endjmp()!.
908 * Usage:
909 * mch_startjmp();
910 * if (SETJMP(lc_jump_env) != 0)
911 * {
912 * mch_didjmp();
913 * EMSG("crash!");
914 * }
915 * else
916 * {
917 * do_the_work;
918 * mch_endjmp();
919 * }
920 * Note: Can't move SETJMP() here, because a function calling setjmp() must
921 * not return before the saved environment is used.
922 * Returns OK for normal return, FAIL when the protected code caused a
923 * problem and LONGJMP() was used.
924 */
925 void
926mch_startjmp()
927{
928#ifdef SIGHASARG
929 lc_signal = 0;
930#endif
931 lc_active = TRUE;
932}
933
934 void
935mch_endjmp()
936{
937 lc_active = FALSE;
938}
939
940 void
941mch_didjmp()
942{
943# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
944 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
945 * otherwise catching the signal only works once. */
946 init_signal_stack();
947# endif
948}
949#endif
950
951/*
952 * This function handles deadly signals.
953 * It tries to preserve any swap file and exit properly.
954 * (partly from Elvis).
955 */
956 static RETSIGTYPE
957deathtrap SIGDEFARG(sigarg)
958{
959 static int entered = 0; /* count the number of times we got here.
960 Note: when memory has been corrupted
961 this may get an arbitrary value! */
962#ifdef SIGHASARG
963 int i;
964#endif
965
966#if defined(HAVE_SETJMP_H)
967 /*
968 * Catch a crash in protected code.
969 * Restores the environment saved in lc_jump_env, which looks like
970 * SETJMP() returns 1.
971 */
972 if (lc_active)
973 {
974# if defined(SIGHASARG)
975 lc_signal = sigarg;
976# endif
977 lc_active = FALSE; /* don't jump again */
978 LONGJMP(lc_jump_env, 1);
979 /* NOTREACHED */
980 }
981#endif
982
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000983#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000984# ifdef SIGQUIT
985 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
986 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
987 * pressing CTRL-\, but we don't want Vim to exit then. */
988 if (in_mch_delay && sigarg == SIGQUIT)
989 SIGRETURN;
990# endif
991
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000992 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
993 * here. This avoids that a non-reentrant function is interrupted, e.g.,
994 * free(). Calling free() again may then cause a crash. */
995 if (entered == 0
996 && (0
997# ifdef SIGHUP
998 || sigarg == SIGHUP
999# endif
1000# ifdef SIGQUIT
1001 || sigarg == SIGQUIT
1002# endif
1003# ifdef SIGTERM
1004 || sigarg == SIGTERM
1005# endif
1006# ifdef SIGPWR
1007 || sigarg == SIGPWR
1008# endif
1009# ifdef SIGUSR1
1010 || sigarg == SIGUSR1
1011# endif
1012# ifdef SIGUSR2
1013 || sigarg == SIGUSR2
1014# endif
1015 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001016 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001017 SIGRETURN;
1018#endif
1019
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 /* Remember how often we have been called. */
1021 ++entered;
1022
1023#ifdef FEAT_EVAL
1024 /* Set the v:dying variable. */
1025 set_vim_var_nr(VV_DYING, (long)entered);
1026#endif
1027
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001028#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 /* Since we are now using the signal stack, need to reset the stack
1030 * limit. Otherwise using a regexp will fail. */
1031 get_stack_limit();
1032#endif
1033
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001034#if 0
1035 /* This is for opening gdb the moment Vim crashes.
1036 * You need to manually adjust the file name and Vim executable name.
1037 * Suggested by SungHyun Nam. */
1038 {
1039# define VI_GDB_FILE "/tmp/vimgdb"
1040# define VIM_NAME "/usr/bin/vim"
1041 FILE *fp = fopen(VI_GDB_FILE, "w");
1042 if (fp)
1043 {
1044 fprintf(fp,
1045 "file %s\n"
1046 "attach %d\n"
1047 "set height 1000\n"
1048 "bt full\n"
1049 , VIM_NAME, getpid());
1050 fclose(fp);
1051 system("xterm -e gdb -x "VI_GDB_FILE);
1052 unlink(VI_GDB_FILE);
1053 }
1054 }
1055#endif
1056
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057#ifdef SIGHASARG
1058 /* try to find the name of this signal */
1059 for (i = 0; signal_info[i].sig != -1; i++)
1060 if (sigarg == signal_info[i].sig)
1061 break;
1062 deadly_signal = sigarg;
1063#endif
1064
1065 full_screen = FALSE; /* don't write message to the GUI, it might be
1066 * part of the problem... */
1067 /*
1068 * If something goes wrong after entering here, we may get here again.
1069 * When this happens, give a message and try to exit nicely (resetting the
1070 * terminal mode, etc.)
1071 * When this happens twice, just exit, don't even try to give a message,
1072 * stack may be corrupt or something weird.
1073 * When this still happens again (or memory was corrupted in such a way
1074 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1075 */
1076 if (entered >= 3)
1077 {
1078 reset_signals(); /* don't catch any signals anymore */
1079 may_core_dump();
1080 if (entered >= 4)
1081 _exit(8);
1082 exit(7);
1083 }
1084 if (entered == 2)
1085 {
1086 OUT_STR(_("Vim: Double signal, exiting\n"));
1087 out_flush();
1088 getout(1);
1089 }
1090
1091#ifdef SIGHASARG
1092 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
1093 signal_info[i].name);
1094#else
1095 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
1096#endif
1097 preserve_exit(); /* preserve files and exit */
1098
Bram Moolenaar009b2592004-10-24 19:18:58 +00001099#ifdef NBDEBUG
1100 reset_signals();
1101 may_core_dump();
1102 abort();
1103#endif
1104
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 SIGRETURN;
1106}
1107
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001108#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109/*
1110 * On Solaris with multi-threading, suspending might not work immediately.
1111 * Catch the SIGCONT signal, which will be used as an indication whether the
1112 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001113 *
1114 * On Linux, signal is not always handled immediately either.
1115 * See https://bugs.launchpad.net/bugs/291373
1116 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001117 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001119static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1121
1122/*
1123 * signal handler for SIGCONT
1124 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 static RETSIGTYPE
1126sigcont_handler SIGDEFARG(sigarg)
1127{
1128 sigcont_received = TRUE;
1129 SIGRETURN;
1130}
1131#endif
1132
Bram Moolenaar62b42182010-09-21 22:09:37 +02001133# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1134static void loose_clipboard __ARGS((void));
1135
1136/*
1137 * Called when Vim is going to sleep or execute a shell command.
1138 * We can't respond to requests for the X selections. Lose them, otherwise
1139 * other applications will hang. But first copy the text to cut buffer 0.
1140 */
1141 static void
1142loose_clipboard()
1143{
1144 if (clip_star.owned || clip_plus.owned)
1145 {
1146 x11_export_final_selection();
1147 if (clip_star.owned)
1148 clip_lose_selection(&clip_star);
1149 if (clip_plus.owned)
1150 clip_lose_selection(&clip_plus);
1151 if (x11_display != NULL)
1152 XFlush(x11_display);
1153 }
1154}
1155#endif
1156
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157/*
1158 * If the machine has job control, use it to suspend the program,
1159 * otherwise fake it by starting a new shell.
1160 */
1161 void
1162mch_suspend()
1163{
1164 /* BeOS does have SIGTSTP, but it doesn't work. */
1165#if defined(SIGTSTP) && !defined(__BEOS__)
1166 out_flush(); /* needed to make cursor visible on some systems */
1167 settmode(TMODE_COOK);
1168 out_flush(); /* needed to disable mouse on some systems */
1169
1170# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001171 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172# endif
1173
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001174# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 sigcont_received = FALSE;
1176# endif
1177 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001178# if defined(_REENTRANT) && defined(SIGCONT)
1179 /*
1180 * Wait for the SIGCONT signal to be handled. It generally happens
1181 * immediately, but somehow not all the time. Do not call pause()
1182 * because there would be race condition which would hang Vim if
1183 * signal happened in between the test of sigcont_received and the
1184 * call to pause(). If signal is not yet received, call sleep(0)
1185 * to just yield CPU. Signal should then be received. If somehow
1186 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1187 * further if signal is not received after 1+2+3+4 ms (not expected
1188 * to happen).
1189 */
1190 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001191 long wait_time;
1192 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001193 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001194 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001195 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196# endif
1197
1198# ifdef FEAT_TITLE
1199 /*
1200 * Set oldtitle to NULL, so the current title is obtained again.
1201 */
1202 vim_free(oldtitle);
1203 oldtitle = NULL;
1204# endif
1205 settmode(TMODE_RAW);
1206 need_check_timestamps = TRUE;
1207 did_check_timestamps = FALSE;
1208#else
1209 suspend_shell();
1210#endif
1211}
1212
1213 void
1214mch_init()
1215{
1216 Columns = 80;
1217 Rows = 24;
1218
1219 out_flush();
1220 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001221
Bram Moolenaar56718732006-03-15 22:53:57 +00001222#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001223 mac_conv_init();
1224#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001225}
1226
1227 static void
1228set_signals()
1229{
1230#if defined(SIGWINCH)
1231 /*
1232 * WINDOW CHANGE signal is handled with sig_winch().
1233 */
1234 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1235#endif
1236
1237 /*
1238 * We want the STOP signal to work, to make mch_suspend() work.
1239 * For "rvim" the STOP signal is ignored.
1240 */
1241#ifdef SIGTSTP
1242 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1243#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001244#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 signal(SIGCONT, sigcont_handler);
1246#endif
1247
1248 /*
1249 * We want to ignore breaking of PIPEs.
1250 */
1251#ifdef SIGPIPE
1252 signal(SIGPIPE, SIG_IGN);
1253#endif
1254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001256 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257#endif
1258
1259 /*
1260 * Ignore alarm signals (Perl's alarm() generates it).
1261 */
1262#ifdef SIGALRM
1263 signal(SIGALRM, SIG_IGN);
1264#endif
1265
1266 /*
1267 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1268 * work will be lost.
1269 */
1270#ifdef SIGPWR
1271 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1272#endif
1273
1274 /*
1275 * Arrange for other signals to gracefully shutdown Vim.
1276 */
1277 catch_signals(deathtrap, SIG_ERR);
1278
1279#if defined(FEAT_GUI) && defined(SIGHUP)
1280 /*
1281 * When the GUI is running, ignore the hangup signal.
1282 */
1283 if (gui.in_use)
1284 signal(SIGHUP, SIG_IGN);
1285#endif
1286}
1287
Bram Moolenaardf177f62005-02-22 08:39:57 +00001288#if defined(SIGINT) || defined(PROTO)
1289/*
1290 * Catch CTRL-C (only works while in Cooked mode).
1291 */
1292 static void
1293catch_int_signal()
1294{
1295 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1296}
1297#endif
1298
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 void
1300reset_signals()
1301{
1302 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001303#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 /* SIGCONT isn't in the list, because its default action is ignore */
1305 signal(SIGCONT, SIG_DFL);
1306#endif
1307}
1308
1309 static void
1310catch_signals(func_deadly, func_other)
1311 RETSIGTYPE (*func_deadly)();
1312 RETSIGTYPE (*func_other)();
1313{
1314 int i;
1315
1316 for (i = 0; signal_info[i].sig != -1; i++)
1317 if (signal_info[i].deadly)
1318 {
1319#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1320 struct sigaction sa;
1321
1322 /* Setup to use the alternate stack for the signal function. */
1323 sa.sa_handler = func_deadly;
1324 sigemptyset(&sa.sa_mask);
1325# if defined(__linux__) && defined(_REENTRANT)
1326 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1327 * thread handling in combination with using the alternate stack:
1328 * pthread library functions try to use the stack pointer to
1329 * identify the current thread, causing a SEGV signal, which
1330 * recursively calls deathtrap() and hangs. */
1331 sa.sa_flags = 0;
1332# else
1333 sa.sa_flags = SA_ONSTACK;
1334# endif
1335 sigaction(signal_info[i].sig, &sa, NULL);
1336#else
1337# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1338 struct sigvec sv;
1339
1340 /* Setup to use the alternate stack for the signal function. */
1341 sv.sv_handler = func_deadly;
1342 sv.sv_mask = 0;
1343 sv.sv_flags = SV_ONSTACK;
1344 sigvec(signal_info[i].sig, &sv, NULL);
1345# else
1346 signal(signal_info[i].sig, func_deadly);
1347# endif
1348#endif
1349 }
1350 else if (func_other != SIG_ERR)
1351 signal(signal_info[i].sig, func_other);
1352}
1353
1354/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001355 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001356 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1357 * return TRUE
1358 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1359 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001360 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001361 * Returns TRUE when Vim should exit.
1362 */
1363 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001364vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001365 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001366{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001367 static int got_signal = 0;
1368 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001369
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001370 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001371 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001372 case SIGNAL_BLOCK: blocked = TRUE;
1373 break;
1374
1375 case SIGNAL_UNBLOCK: blocked = FALSE;
1376 if (got_signal != 0)
1377 {
1378 kill(getpid(), got_signal);
1379 got_signal = 0;
1380 }
1381 break;
1382
1383 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001384 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001385 got_signal = sig;
1386#ifdef SIGPWR
1387 if (sig != SIGPWR)
1388#endif
1389 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001390 break;
1391 }
1392 return FALSE;
1393}
1394
1395/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396 * Check_win checks whether we have an interactive stdout.
1397 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 int
1399mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001400 int argc UNUSED;
1401 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402{
1403#ifdef OS2
1404 /*
1405 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1406 * name, mostly it's just "vim" and found in the path, which is unusable.
1407 */
1408 if (mch_isFullName(argv[0]))
1409 exe_name = vim_strsave((char_u *)argv[0]);
1410#endif
1411 if (isatty(1))
1412 return OK;
1413 return FAIL;
1414}
1415
1416/*
1417 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1418 */
1419 int
1420mch_input_isatty()
1421{
1422 if (isatty(read_cmd_fd))
1423 return TRUE;
1424 return FALSE;
1425}
1426
1427#ifdef FEAT_X11
1428
1429# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1430 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1431
1432static void xopen_message __ARGS((struct timeval *tvp));
1433
1434/*
1435 * Give a message about the elapsed time for opening the X window.
1436 */
1437 static void
1438xopen_message(tvp)
1439 struct timeval *tvp; /* must contain start time */
1440{
1441 struct timeval end_tv;
1442
1443 /* Compute elapsed time. */
1444 gettimeofday(&end_tv, NULL);
1445 smsg((char_u *)_("Opening the X display took %ld msec"),
1446 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001447 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448}
1449# endif
1450#endif
1451
1452#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1453/*
1454 * A few functions shared by X11 title and clipboard code.
1455 */
1456static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1457static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1458static int x_connect_to_server __ARGS((void));
1459static int test_x11_window __ARGS((Display *dpy));
1460
1461static int got_x_error = FALSE;
1462
1463/*
1464 * X Error handler, otherwise X just exits! (very rude) -- webb
1465 */
1466 static int
1467x_error_handler(dpy, error_event)
1468 Display *dpy;
1469 XErrorEvent *error_event;
1470{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001471 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 STRCAT(IObuff, _("\nVim: Got X error\n"));
1473
1474 /* We cannot print a message and continue, because no X calls are allowed
1475 * here (causes my system to hang). Silently continuing might be an
1476 * alternative... */
1477 preserve_exit(); /* preserve files and exit */
1478
1479 return 0; /* NOTREACHED */
1480}
1481
1482/*
1483 * Another X Error handler, just used to check for errors.
1484 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485 static int
1486x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001487 Display *dpy UNUSED;
1488 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489{
1490 got_x_error = TRUE;
1491 return 0;
1492}
1493
1494#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1495# if defined(HAVE_SETJMP_H)
1496/*
1497 * An X IO Error handler, used to catch error while opening the display.
1498 */
1499static int x_IOerror_check __ARGS((Display *dpy));
1500
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 static int
1502x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001503 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504{
1505 /* This function should not return, it causes exit(). Longjump instead. */
1506 LONGJMP(lc_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001507# ifdef VMS
1508 return 0; /* avoid the compiler complains about missing return value */
1509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510}
1511# endif
1512
1513/*
1514 * An X IO Error handler, used to catch terminal errors.
1515 */
1516static int x_IOerror_handler __ARGS((Display *dpy));
1517
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 static int
1519x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001520 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521{
1522 xterm_dpy = NULL;
1523 x11_window = 0;
1524 x11_display = NULL;
1525 xterm_Shell = (Widget)0;
1526
1527 /* This function should not return, it causes exit(). Longjump instead. */
1528 LONGJMP(x_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001529# ifdef VMS
1530 return 0; /* avoid the compiler complains about missing return value */
1531# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532}
1533#endif
1534
1535/*
1536 * Return TRUE when connection to the X server is desired.
1537 */
1538 static int
1539x_connect_to_server()
1540{
1541 regmatch_T regmatch;
1542
1543#if defined(FEAT_CLIENTSERVER)
1544 if (x_force_connect)
1545 return TRUE;
1546#endif
1547 if (x_no_connect)
1548 return FALSE;
1549
1550 /* Check for a match with "exclude:" from 'clipboard'. */
1551 if (clip_exclude_prog != NULL)
1552 {
1553 regmatch.rm_ic = FALSE; /* Don't ignore case */
1554 regmatch.regprog = clip_exclude_prog;
1555 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1556 return FALSE;
1557 }
1558 return TRUE;
1559}
1560
1561/*
1562 * Test if "dpy" and x11_window are valid by getting the window title.
1563 * I don't actually want it yet, so there may be a simpler call to use, but
1564 * this will cause the error handler x_error_check() to be called if anything
1565 * is wrong, such as the window pointer being invalid (as can happen when the
1566 * user changes his DISPLAY, but not his WINDOWID) -- webb
1567 */
1568 static int
1569test_x11_window(dpy)
1570 Display *dpy;
1571{
1572 int (*old_handler)();
1573 XTextProperty text_prop;
1574
1575 old_handler = XSetErrorHandler(x_error_check);
1576 got_x_error = FALSE;
1577 if (XGetWMName(dpy, x11_window, &text_prop))
1578 XFree((void *)text_prop.value);
1579 XSync(dpy, False);
1580 (void)XSetErrorHandler(old_handler);
1581
1582 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001583 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584
1585 return (got_x_error ? FAIL : OK);
1586}
1587#endif
1588
1589#ifdef FEAT_TITLE
1590
1591#ifdef FEAT_X11
1592
1593static int get_x11_thing __ARGS((int get_title, int test_only));
1594
1595/*
1596 * try to get x11 window and display
1597 *
1598 * return FAIL for failure, OK otherwise
1599 */
1600 static int
1601get_x11_windis()
1602{
1603 char *winid;
1604 static int result = -1;
1605#define XD_NONE 0 /* x11_display not set here */
1606#define XD_HERE 1 /* x11_display opened here */
1607#define XD_GUI 2 /* x11_display used from gui.dpy */
1608#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1609 static int x11_display_from = XD_NONE;
1610 static int did_set_error_handler = FALSE;
1611
1612 if (!did_set_error_handler)
1613 {
1614 /* X just exits if it finds an error otherwise! */
1615 (void)XSetErrorHandler(x_error_handler);
1616 did_set_error_handler = TRUE;
1617 }
1618
Bram Moolenaar9372a112005-12-06 19:59:18 +00001619#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 if (gui.in_use)
1621 {
1622 /*
1623 * If the X11 display was opened here before, for the window where Vim
1624 * was started, close that one now to avoid a memory leak.
1625 */
1626 if (x11_display_from == XD_HERE && x11_display != NULL)
1627 {
1628 XCloseDisplay(x11_display);
1629 x11_display_from = XD_NONE;
1630 }
1631 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1632 {
1633 x11_display_from = XD_GUI;
1634 return OK;
1635 }
1636 x11_display = NULL;
1637 return FAIL;
1638 }
1639 else if (x11_display_from == XD_GUI)
1640 {
1641 /* GUI must have stopped somehow, clear x11_display */
1642 x11_window = 0;
1643 x11_display = NULL;
1644 x11_display_from = XD_NONE;
1645 }
1646#endif
1647
1648 /* When started with the "-X" argument, don't try connecting. */
1649 if (!x_connect_to_server())
1650 return FAIL;
1651
1652 /*
1653 * If WINDOWID not set, should try another method to find out
1654 * what the current window number is. The only code I know for
1655 * this is very complicated.
1656 * We assume that zero is invalid for WINDOWID.
1657 */
1658 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1659 x11_window = (Window)atol(winid);
1660
1661#ifdef FEAT_XCLIPBOARD
1662 if (xterm_dpy != NULL && x11_window != 0)
1663 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001664 /* We may have checked it already, but Gnome terminal can move us to
1665 * another window, so we need to check every time. */
1666 if (x11_display_from != XD_XTERM)
1667 {
1668 /*
1669 * If the X11 display was opened here before, for the window where
1670 * Vim was started, close that one now to avoid a memory leak.
1671 */
1672 if (x11_display_from == XD_HERE && x11_display != NULL)
1673 XCloseDisplay(x11_display);
1674 x11_display = xterm_dpy;
1675 x11_display_from = XD_XTERM;
1676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 if (test_x11_window(x11_display) == FAIL)
1678 {
1679 /* probably bad $WINDOWID */
1680 x11_window = 0;
1681 x11_display = NULL;
1682 x11_display_from = XD_NONE;
1683 return FAIL;
1684 }
1685 return OK;
1686 }
1687#endif
1688
1689 if (x11_window == 0 || x11_display == NULL)
1690 result = -1;
1691
1692 if (result != -1) /* Have already been here and set this */
1693 return result; /* Don't do all these X calls again */
1694
1695 if (x11_window != 0 && x11_display == NULL)
1696 {
1697#ifdef SET_SIG_ALARM
1698 RETSIGTYPE (*sig_save)();
1699#endif
1700#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1701 struct timeval start_tv;
1702
1703 if (p_verbose > 0)
1704 gettimeofday(&start_tv, NULL);
1705#endif
1706
1707#ifdef SET_SIG_ALARM
1708 /*
1709 * Opening the Display may hang if the DISPLAY setting is wrong, or
1710 * the network connection is bad. Set an alarm timer to get out.
1711 */
1712 sig_alarm_called = FALSE;
1713 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1714 (RETSIGTYPE (*)())sig_alarm);
1715 alarm(2);
1716#endif
1717 x11_display = XOpenDisplay(NULL);
1718
1719#ifdef SET_SIG_ALARM
1720 alarm(0);
1721 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1722 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001723 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724#endif
1725 if (x11_display != NULL)
1726 {
1727# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1728 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001729 {
1730 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001732 verbose_leave();
1733 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734# endif
1735 if (test_x11_window(x11_display) == FAIL)
1736 {
1737 /* Maybe window id is bad */
1738 x11_window = 0;
1739 XCloseDisplay(x11_display);
1740 x11_display = NULL;
1741 }
1742 else
1743 x11_display_from = XD_HERE;
1744 }
1745 }
1746 if (x11_window == 0 || x11_display == NULL)
1747 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001748
1749# ifdef FEAT_EVAL
1750 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1751# endif
1752
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 return (result = OK);
1754}
1755
1756/*
1757 * Determine original x11 Window Title
1758 */
1759 static int
1760get_x11_title(test_only)
1761 int test_only;
1762{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001763 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764}
1765
1766/*
1767 * Determine original x11 Window icon
1768 */
1769 static int
1770get_x11_icon(test_only)
1771 int test_only;
1772{
1773 int retval = FALSE;
1774
1775 retval = get_x11_thing(FALSE, test_only);
1776
1777 /* could not get old icon, use terminal name */
1778 if (oldicon == NULL && !test_only)
1779 {
1780 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001781 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001783 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 }
1785
1786 return retval;
1787}
1788
1789 static int
1790get_x11_thing(get_title, test_only)
1791 int get_title; /* get title string */
1792 int test_only;
1793{
1794 XTextProperty text_prop;
1795 int retval = FALSE;
1796 Status status;
1797
1798 if (get_x11_windis() == OK)
1799 {
1800 /* Get window/icon name if any */
1801 if (get_title)
1802 status = XGetWMName(x11_display, x11_window, &text_prop);
1803 else
1804 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1805
1806 /*
1807 * If terminal is xterm, then x11_window may be a child window of the
1808 * outer xterm window that actually contains the window/icon name, so
1809 * keep traversing up the tree until a window with a title/icon is
1810 * found.
1811 */
1812 /* Previously this was only done for xterm and alikes. I don't see a
1813 * reason why it would fail for other terminal emulators.
1814 * if (term_is_xterm) */
1815 {
1816 Window root;
1817 Window parent;
1818 Window win = x11_window;
1819 Window *children;
1820 unsigned int num_children;
1821
1822 while (!status || text_prop.value == NULL)
1823 {
1824 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1825 &num_children))
1826 break;
1827 if (children)
1828 XFree((void *)children);
1829 if (parent == root || parent == 0)
1830 break;
1831
1832 win = parent;
1833 if (get_title)
1834 status = XGetWMName(x11_display, win, &text_prop);
1835 else
1836 status = XGetWMIconName(x11_display, win, &text_prop);
1837 }
1838 }
1839 if (status && text_prop.value != NULL)
1840 {
1841 retval = TRUE;
1842 if (!test_only)
1843 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001844#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1845 if (text_prop.encoding == XA_STRING
1846# ifdef FEAT_MBYTE
1847 && !has_mbyte
1848# endif
1849 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 {
1851#endif
1852 if (get_title)
1853 oldtitle = vim_strsave((char_u *)text_prop.value);
1854 else
1855 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001856#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 }
1858 else
1859 {
1860 char **cl;
1861 Status transform_status;
1862 int n = 0;
1863
1864 transform_status = XmbTextPropertyToTextList(x11_display,
1865 &text_prop,
1866 &cl, &n);
1867 if (transform_status >= Success && n > 0 && cl[0])
1868 {
1869 if (get_title)
1870 oldtitle = vim_strsave((char_u *) cl[0]);
1871 else
1872 oldicon = vim_strsave((char_u *) cl[0]);
1873 XFreeStringList(cl);
1874 }
1875 else
1876 {
1877 if (get_title)
1878 oldtitle = vim_strsave((char_u *)text_prop.value);
1879 else
1880 oldicon = vim_strsave((char_u *)text_prop.value);
1881 }
1882 }
1883#endif
1884 }
1885 XFree((void *)text_prop.value);
1886 }
1887 }
1888 return retval;
1889}
1890
1891/* Are Xutf8 functions available? Avoid error from old compilers. */
1892#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1893# if X_HAVE_UTF8_STRING
1894# define USE_UTF8_STRING
1895# endif
1896#endif
1897
1898/*
1899 * Set x11 Window Title
1900 *
1901 * get_x11_windis() must be called before this and have returned OK
1902 */
1903 static void
1904set_x11_title(title)
1905 char_u *title;
1906{
1907 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1908 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1909 * supported everywhere and STRING doesn't work for multi-byte titles.
1910 */
1911#ifdef USE_UTF8_STRING
1912 if (enc_utf8)
1913 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1914 NULL, NULL, 0, NULL, NULL, NULL);
1915 else
1916#endif
1917 {
1918#if XtSpecificationRelease >= 4
1919# ifdef FEAT_XFONTSET
1920 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1921 NULL, NULL, 0, NULL, NULL, NULL);
1922# else
1923 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001924 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925
1926 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001927 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 XSetWMProperties(x11_display, x11_window, &text_prop,
1929 NULL, NULL, 0, NULL, NULL, NULL);
1930# endif
1931#else
1932 XStoreName(x11_display, x11_window, (char *)title);
1933#endif
1934 }
1935 XFlush(x11_display);
1936}
1937
1938/*
1939 * Set x11 Window icon
1940 *
1941 * get_x11_windis() must be called before this and have returned OK
1942 */
1943 static void
1944set_x11_icon(icon)
1945 char_u *icon;
1946{
1947 /* See above for comments about using X*SetWMProperties(). */
1948#ifdef USE_UTF8_STRING
1949 if (enc_utf8)
1950 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1951 NULL, 0, NULL, NULL, NULL);
1952 else
1953#endif
1954 {
1955#if XtSpecificationRelease >= 4
1956# ifdef FEAT_XFONTSET
1957 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1958 NULL, 0, NULL, NULL, NULL);
1959# else
1960 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001961 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001963 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1965 NULL, 0, NULL, NULL, NULL);
1966# endif
1967#else
1968 XSetIconName(x11_display, x11_window, (char *)icon);
1969#endif
1970 }
1971 XFlush(x11_display);
1972}
1973
1974#else /* FEAT_X11 */
1975
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 static int
1977get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001978 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979{
1980 return FALSE;
1981}
1982
1983 static int
1984get_x11_icon(test_only)
1985 int test_only;
1986{
1987 if (!test_only)
1988 {
1989 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001990 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001992 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 }
1994 return FALSE;
1995}
1996
1997#endif /* FEAT_X11 */
1998
1999 int
2000mch_can_restore_title()
2001{
2002 return get_x11_title(TRUE);
2003}
2004
2005 int
2006mch_can_restore_icon()
2007{
2008 return get_x11_icon(TRUE);
2009}
2010
2011/*
2012 * Set the window title and icon.
2013 */
2014 void
2015mch_settitle(title, icon)
2016 char_u *title;
2017 char_u *icon;
2018{
2019 int type = 0;
2020 static int recursive = 0;
2021
2022 if (T_NAME == NULL) /* no terminal name (yet) */
2023 return;
2024 if (title == NULL && icon == NULL) /* nothing to do */
2025 return;
2026
2027 /* When one of the X11 functions causes a deadly signal, we get here again
2028 * recursively. Avoid hanging then (something is probably locked). */
2029 if (recursive)
2030 return;
2031 ++recursive;
2032
2033 /*
2034 * if the window ID and the display is known, we may use X11 calls
2035 */
2036#ifdef FEAT_X11
2037 if (get_x11_windis() == OK)
2038 type = 1;
2039#else
2040# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2041 if (gui.in_use)
2042 type = 1;
2043# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044#endif
2045
2046 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002047 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 * than x11 calls, because the x11 calls don't always work
2049 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 if ((type || *T_TS != NUL) && title != NULL)
2051 {
2052 if (oldtitle == NULL
2053#ifdef FEAT_GUI
2054 && !gui.in_use
2055#endif
2056 ) /* first call but not in GUI, save title */
2057 (void)get_x11_title(FALSE);
2058
2059 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2060 term_settitle(title);
2061#ifdef FEAT_X11
2062 else
2063# ifdef FEAT_GUI_GTK
2064 if (!gui.in_use) /* don't do this if GTK+ is running */
2065# endif
2066 set_x11_title(title); /* x11 */
2067#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002068#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2070 else
2071 gui_mch_settitle(title, icon);
2072#endif
2073 did_set_title = TRUE;
2074 }
2075
2076 if ((type || *T_CIS != NUL) && icon != NULL)
2077 {
2078 if (oldicon == NULL
2079#ifdef FEAT_GUI
2080 && !gui.in_use
2081#endif
2082 ) /* first call, save icon */
2083 get_x11_icon(FALSE);
2084
2085 if (*T_CIS != NUL)
2086 {
2087 out_str(T_CIS); /* set icon start */
2088 out_str_nf(icon);
2089 out_str(T_CIE); /* set icon end */
2090 out_flush();
2091 }
2092#ifdef FEAT_X11
2093 else
2094# ifdef FEAT_GUI_GTK
2095 if (!gui.in_use) /* don't do this if GTK+ is running */
2096# endif
2097 set_x11_icon(icon); /* x11 */
2098#endif
2099 did_set_icon = TRUE;
2100 }
2101 --recursive;
2102}
2103
2104/*
2105 * Restore the window/icon title.
2106 * "which" is one of:
2107 * 1 only restore title
2108 * 2 only restore icon
2109 * 3 restore title and icon
2110 */
2111 void
2112mch_restore_title(which)
2113 int which;
2114{
2115 /* only restore the title or icon when it has been set */
2116 mch_settitle(((which & 1) && did_set_title) ?
2117 (oldtitle ? oldtitle : p_titleold) : NULL,
2118 ((which & 2) && did_set_icon) ? oldicon : NULL);
2119}
2120
2121#endif /* FEAT_TITLE */
2122
2123/*
2124 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002125 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 */
2127 int
2128vim_is_xterm(name)
2129 char_u *name;
2130{
2131 if (name == NULL)
2132 return FALSE;
2133 return (STRNICMP(name, "xterm", 5) == 0
2134 || STRNICMP(name, "nxterm", 6) == 0
2135 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002136 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 || STRNICMP(name, "rxvt", 4) == 0
2138 || STRCMP(name, "builtin_xterm") == 0);
2139}
2140
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002141#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2142/*
2143 * Return TRUE if "name" appears to be that of a terminal
2144 * known to support the xterm-style mouse protocol.
2145 * Relies on term_is_xterm having been set to its correct value.
2146 */
2147 int
2148use_xterm_like_mouse(name)
2149 char_u *name;
2150{
2151 return (name != NULL
2152 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2153}
2154#endif
2155
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2157/*
2158 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2159 * Return 1 for "xterm".
2160 * Return 2 for "xterm2".
2161 */
2162 int
2163use_xterm_mouse()
2164{
2165 if (ttym_flags == TTYM_XTERM2)
2166 return 2;
2167 if (ttym_flags == TTYM_XTERM)
2168 return 1;
2169 return 0;
2170}
2171#endif
2172
2173 int
2174vim_is_iris(name)
2175 char_u *name;
2176{
2177 if (name == NULL)
2178 return FALSE;
2179 return (STRNICMP(name, "iris-ansi", 9) == 0
2180 || STRCMP(name, "builtin_iris-ansi") == 0);
2181}
2182
2183 int
2184vim_is_vt300(name)
2185 char_u *name;
2186{
2187 if (name == NULL)
2188 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002189 /* catch VT100 - VT5xx */
2190 return ((STRNICMP(name, "vt", 2) == 0
2191 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 || STRCMP(name, "builtin_vt320") == 0);
2193}
2194
2195/*
2196 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2197 * This should include all windowed terminal emulators.
2198 */
2199 int
2200vim_is_fastterm(name)
2201 char_u *name;
2202{
2203 if (name == NULL)
2204 return FALSE;
2205 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2206 return TRUE;
2207 return ( STRNICMP(name, "hpterm", 6) == 0
2208 || STRNICMP(name, "sun-cmd", 7) == 0
2209 || STRNICMP(name, "screen", 6) == 0
2210 || STRNICMP(name, "dtterm", 6) == 0);
2211}
2212
2213/*
2214 * Insert user name in s[len].
2215 * Return OK if a name found.
2216 */
2217 int
2218mch_get_user_name(s, len)
2219 char_u *s;
2220 int len;
2221{
2222#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002223 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 return OK;
2225#else
2226 return mch_get_uname(getuid(), s, len);
2227#endif
2228}
2229
2230/*
2231 * Insert user name for "uid" in s[len].
2232 * Return OK if a name found.
2233 */
2234 int
2235mch_get_uname(uid, s, len)
2236 uid_t uid;
2237 char_u *s;
2238 int len;
2239{
2240#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2241 struct passwd *pw;
2242
2243 if ((pw = getpwuid(uid)) != NULL
2244 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2245 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002246 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 return OK;
2248 }
2249#endif
2250 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2251 return FAIL; /* a number is not a name */
2252}
2253
2254/*
2255 * Insert host name is s[len].
2256 */
2257
2258#ifdef HAVE_SYS_UTSNAME_H
2259 void
2260mch_get_host_name(s, len)
2261 char_u *s;
2262 int len;
2263{
2264 struct utsname vutsname;
2265
2266 if (uname(&vutsname) < 0)
2267 *s = NUL;
2268 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002269 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270}
2271#else /* HAVE_SYS_UTSNAME_H */
2272
2273# ifdef HAVE_SYS_SYSTEMINFO_H
2274# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2275# endif
2276
2277 void
2278mch_get_host_name(s, len)
2279 char_u *s;
2280 int len;
2281{
2282# ifdef VAXC
2283 vaxc$gethostname((char *)s, len);
2284# else
2285 gethostname((char *)s, len);
2286# endif
2287 s[len - 1] = NUL; /* make sure it's terminated */
2288}
2289#endif /* HAVE_SYS_UTSNAME_H */
2290
2291/*
2292 * return process ID
2293 */
2294 long
2295mch_get_pid()
2296{
2297 return (long)getpid();
2298}
2299
2300#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2301static char *strerror __ARGS((int));
2302
2303 static char *
2304strerror(err)
2305 int err;
2306{
2307 extern int sys_nerr;
2308 extern char *sys_errlist[];
2309 static char er[20];
2310
2311 if (err > 0 && err < sys_nerr)
2312 return (sys_errlist[err]);
2313 sprintf(er, "Error %d", err);
2314 return er;
2315}
2316#endif
2317
2318/*
2319 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2320 * Return OK for success, FAIL for failure.
2321 */
2322 int
2323mch_dirname(buf, len)
2324 char_u *buf;
2325 int len;
2326{
2327#if defined(USE_GETCWD)
2328 if (getcwd((char *)buf, len) == NULL)
2329 {
2330 STRCPY(buf, strerror(errno));
2331 return FAIL;
2332 }
2333 return OK;
2334#else
2335 return (getwd((char *)buf) != NULL ? OK : FAIL);
2336#endif
2337}
2338
2339#if defined(OS2) || defined(PROTO)
2340/*
2341 * Replace all slashes by backslashes.
2342 * When 'shellslash' set do it the other way around.
2343 */
2344 void
2345slash_adjust(p)
2346 char_u *p;
2347{
2348 while (*p)
2349 {
2350 if (*p == psepcN)
2351 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002352 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 }
2354}
2355#endif
2356
2357/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002358 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 *
2360 * return FAIL for failure, OK for success
2361 */
2362 int
2363mch_FullName(fname, buf, len, force)
2364 char_u *fname, *buf;
2365 int len;
2366 int force; /* also expand when already absolute path */
2367{
2368 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002369#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002371#endif
2372#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 int fd = -1;
2374 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002375#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 char_u olddir[MAXPATHL];
2377 char_u *p;
2378 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002379#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002380 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2381 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002382#endif
2383
Bram Moolenaar38323e42007-03-06 19:22:53 +00002384#ifdef VMS
2385 fname = vms_fixfilename(fname);
2386#endif
2387
Bram Moolenaara2442432007-04-26 14:26:37 +00002388#ifdef __CYGWIN__
2389 /*
2390 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2391 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002392# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2393 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2394# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002395 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002396# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002397 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002398#endif
2399
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 /* expand it if forced or not an absolute path */
2401 if (force || !mch_isFullName(fname))
2402 {
2403 /*
2404 * If the file name has a path, change to that directory for a moment,
2405 * and then do the getwd() (and get back to where we were).
2406 * This will get the correct path name with "../" things.
2407 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002408#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 only_drive = 0;
2410 if (((p = vim_strrchr(fname, '/')) != NULL)
2411 || ((p = vim_strrchr(fname, '\\')) != NULL)
2412 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002413#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002417#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 /*
2419 * Use fchdir() if possible, it's said to be faster and more
2420 * reliable. But on SunOS 4 it might not work. Check this by
2421 * doing a fchdir() right now.
2422 */
2423 if (!dont_fchdir)
2424 {
2425 fd = open(".", O_RDONLY | O_EXTRA, 0);
2426 if (fd >= 0 && fchdir(fd) < 0)
2427 {
2428 close(fd);
2429 fd = -1;
2430 dont_fchdir = TRUE; /* don't try again */
2431 }
2432 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002433#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434
2435 /* Only change directory when we are sure we can return to where
2436 * we are now. After doing "su" chdir(".") might not work. */
2437 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002438#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002440#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 (mch_dirname(olddir, MAXPATHL) == FAIL
2442 || mch_chdir((char *)olddir) != 0))
2443 {
2444 p = NULL; /* can't get current dir: don't chdir */
2445 retval = FAIL;
2446 }
2447 else
2448 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002449#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 /*
2451 * compensate for case where ':' from "D:" was the only
2452 * path separator detected in the file name; the _next_
2453 * character has to be removed, and then restored later.
2454 */
2455 if (only_drive)
2456 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002457#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 /* The directory is copied into buf[], to be able to remove
2459 * the file name without changing it (could be a string in
2460 * read-only memory) */
2461 if (p - fname >= len)
2462 retval = FAIL;
2463 else
2464 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002465 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 if (mch_chdir((char *)buf))
2467 retval = FAIL;
2468 else
2469 fname = p + 1;
2470 *buf = NUL;
2471 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002472#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 if (only_drive)
2474 {
2475 p--;
2476 if (retval != FAIL)
2477 fname--;
2478 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002479#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 }
2481 }
2482 if (mch_dirname(buf, len) == FAIL)
2483 {
2484 retval = FAIL;
2485 *buf = NUL;
2486 }
2487 if (p != NULL)
2488 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002489#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 if (fd >= 0)
2491 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002492 if (p_verbose >= 5)
2493 {
2494 verbose_enter();
2495 MSG("fchdir() to previous dir");
2496 verbose_leave();
2497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498 l = fchdir(fd);
2499 close(fd);
2500 }
2501 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 l = mch_chdir((char *)olddir);
2504 if (l != 0)
2505 EMSG(_(e_prev_dir));
2506 }
2507
2508 l = STRLEN(buf);
2509 if (l >= len)
2510 retval = FAIL;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002511#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 else
2513 {
2514 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2515 && STRCMP(fname, ".") != 0)
2516 STRCAT(buf, "/");
2517 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002520
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002522 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 return FAIL;
2524
2525 /* Do not append ".", "/dir/." is equal to "/dir". */
2526 if (STRCMP(fname, ".") != 0)
2527 STRCAT(buf, fname);
2528
2529 return OK;
2530}
2531
2532/*
2533 * Return TRUE if "fname" does not depend on the current directory.
2534 */
2535 int
2536mch_isFullName(fname)
2537 char_u *fname;
2538{
2539#ifdef __EMX__
2540 return _fnisabs(fname);
2541#else
2542# ifdef VMS
2543 return ( fname[0] == '/' || fname[0] == '.' ||
2544 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2545 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2546 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2547# else
2548 return (*fname == '/' || *fname == '~');
2549# endif
2550#endif
2551}
2552
Bram Moolenaar24552be2005-12-10 20:17:30 +00002553#if defined(USE_FNAME_CASE) || defined(PROTO)
2554/*
2555 * Set the case of the file name, if it already exists. This will cause the
2556 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002557 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002558 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002559 void
2560fname_case(name, len)
2561 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002562 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002563{
2564 struct stat st;
2565 char_u *slash, *tail;
2566 DIR *dirp;
2567 struct dirent *dp;
2568
2569 if (lstat((char *)name, &st) >= 0)
2570 {
2571 /* Open the directory where the file is located. */
2572 slash = vim_strrchr(name, '/');
2573 if (slash == NULL)
2574 {
2575 dirp = opendir(".");
2576 tail = name;
2577 }
2578 else
2579 {
2580 *slash = NUL;
2581 dirp = opendir((char *)name);
2582 *slash = '/';
2583 tail = slash + 1;
2584 }
2585
2586 if (dirp != NULL)
2587 {
2588 while ((dp = readdir(dirp)) != NULL)
2589 {
2590 /* Only accept names that differ in case and are the same byte
2591 * length. TODO: accept different length name. */
2592 if (STRICMP(tail, dp->d_name) == 0
2593 && STRLEN(tail) == STRLEN(dp->d_name))
2594 {
2595 char_u newname[MAXPATHL + 1];
2596 struct stat st2;
2597
2598 /* Verify the inode is equal. */
2599 vim_strncpy(newname, name, MAXPATHL);
2600 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2601 MAXPATHL - (tail - name));
2602 if (lstat((char *)newname, &st2) >= 0
2603 && st.st_ino == st2.st_ino
2604 && st.st_dev == st2.st_dev)
2605 {
2606 STRCPY(tail, dp->d_name);
2607 break;
2608 }
2609 }
2610 }
2611
2612 closedir(dirp);
2613 }
2614 }
2615}
2616#endif
2617
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618/*
2619 * Get file permissions for 'name'.
2620 * Returns -1 when it doesn't exist.
2621 */
2622 long
2623mch_getperm(name)
2624 char_u *name;
2625{
2626 struct stat statb;
2627
2628 /* Keep the #ifdef outside of stat(), it may be a macro. */
2629#ifdef VMS
2630 if (stat((char *)vms_fixfilename(name), &statb))
2631#else
2632 if (stat((char *)name, &statb))
2633#endif
2634 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002635#ifdef __INTERIX
2636 /* The top bit makes the value negative, which means the file doesn't
2637 * exist. Remove the bit, we don't use it. */
2638 return statb.st_mode & ~S_ADDACE;
2639#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002641#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642}
2643
2644/*
2645 * set file permission for 'name' to 'perm'
2646 *
2647 * return FAIL for failure, OK otherwise
2648 */
2649 int
2650mch_setperm(name, perm)
2651 char_u *name;
2652 long perm;
2653{
2654 return (chmod((char *)
2655#ifdef VMS
2656 vms_fixfilename(name),
2657#else
2658 name,
2659#endif
2660 (mode_t)perm) == 0 ? OK : FAIL);
2661}
2662
2663#if defined(HAVE_ACL) || defined(PROTO)
2664# ifdef HAVE_SYS_ACL_H
2665# include <sys/acl.h>
2666# endif
2667# ifdef HAVE_SYS_ACCESS_H
2668# include <sys/access.h>
2669# endif
2670
2671# ifdef HAVE_SOLARIS_ACL
2672typedef struct vim_acl_solaris_T {
2673 int acl_cnt;
2674 aclent_t *acl_entry;
2675} vim_acl_solaris_T;
2676# endif
2677
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002678#if defined(HAVE_SELINUX) || defined(PROTO)
2679/*
2680 * Copy security info from "from_file" to "to_file".
2681 */
2682 void
2683mch_copy_sec(from_file, to_file)
2684 char_u *from_file;
2685 char_u *to_file;
2686{
2687 if (from_file == NULL)
2688 return;
2689
2690 if (selinux_enabled == -1)
2691 selinux_enabled = is_selinux_enabled();
2692
2693 if (selinux_enabled > 0)
2694 {
2695 security_context_t from_context = NULL;
2696 security_context_t to_context = NULL;
2697
2698 if (getfilecon((char *)from_file, &from_context) < 0)
2699 {
2700 /* If the filesystem doesn't support extended attributes,
2701 the original had no special security context and the
2702 target cannot have one either. */
2703 if (errno == EOPNOTSUPP)
2704 return;
2705
2706 MSG_PUTS(_("\nCould not get security context for "));
2707 msg_outtrans(from_file);
2708 msg_putchar('\n');
2709 return;
2710 }
2711 if (getfilecon((char *)to_file, &to_context) < 0)
2712 {
2713 MSG_PUTS(_("\nCould not get security context for "));
2714 msg_outtrans(to_file);
2715 msg_putchar('\n');
2716 freecon (from_context);
2717 return ;
2718 }
2719 if (strcmp(from_context, to_context) != 0)
2720 {
2721 if (setfilecon((char *)to_file, from_context) < 0)
2722 {
2723 MSG_PUTS(_("\nCould not set security context for "));
2724 msg_outtrans(to_file);
2725 msg_putchar('\n');
2726 }
2727 }
2728 freecon(to_context);
2729 freecon(from_context);
2730 }
2731}
2732#endif /* HAVE_SELINUX */
2733
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734/*
2735 * Return a pointer to the ACL of file "fname" in allocated memory.
2736 * Return NULL if the ACL is not available for whatever reason.
2737 */
2738 vim_acl_T
2739mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002740 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741{
2742 vim_acl_T ret = NULL;
2743#ifdef HAVE_POSIX_ACL
2744 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2745#else
2746#ifdef HAVE_SOLARIS_ACL
2747 vim_acl_solaris_T *aclent;
2748
2749 aclent = malloc(sizeof(vim_acl_solaris_T));
2750 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2751 {
2752 free(aclent);
2753 return NULL;
2754 }
2755 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2756 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2757 {
2758 free(aclent->acl_entry);
2759 free(aclent);
2760 return NULL;
2761 }
2762 ret = (vim_acl_T)aclent;
2763#else
2764#if defined(HAVE_AIX_ACL)
2765 int aclsize;
2766 struct acl *aclent;
2767
2768 aclsize = sizeof(struct acl);
2769 aclent = malloc(aclsize);
2770 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2771 {
2772 if (errno == ENOSPC)
2773 {
2774 aclsize = aclent->acl_len;
2775 aclent = realloc(aclent, aclsize);
2776 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2777 {
2778 free(aclent);
2779 return NULL;
2780 }
2781 }
2782 else
2783 {
2784 free(aclent);
2785 return NULL;
2786 }
2787 }
2788 ret = (vim_acl_T)aclent;
2789#endif /* HAVE_AIX_ACL */
2790#endif /* HAVE_SOLARIS_ACL */
2791#endif /* HAVE_POSIX_ACL */
2792 return ret;
2793}
2794
2795/*
2796 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2797 */
2798 void
2799mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002800 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 vim_acl_T aclent;
2802{
2803 if (aclent == NULL)
2804 return;
2805#ifdef HAVE_POSIX_ACL
2806 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2807#else
2808#ifdef HAVE_SOLARIS_ACL
2809 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2810 ((vim_acl_solaris_T *)aclent)->acl_entry);
2811#else
2812#ifdef HAVE_AIX_ACL
2813 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2814#endif /* HAVE_AIX_ACL */
2815#endif /* HAVE_SOLARIS_ACL */
2816#endif /* HAVE_POSIX_ACL */
2817}
2818
2819 void
2820mch_free_acl(aclent)
2821 vim_acl_T aclent;
2822{
2823 if (aclent == NULL)
2824 return;
2825#ifdef HAVE_POSIX_ACL
2826 acl_free((acl_t)aclent);
2827#else
2828#ifdef HAVE_SOLARIS_ACL
2829 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2830 free(aclent);
2831#else
2832#ifdef HAVE_AIX_ACL
2833 free(aclent);
2834#endif /* HAVE_AIX_ACL */
2835#endif /* HAVE_SOLARIS_ACL */
2836#endif /* HAVE_POSIX_ACL */
2837}
2838#endif
2839
2840/*
2841 * Set hidden flag for "name".
2842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843 void
2844mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002845 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846{
2847 /* can't hide a file */
2848}
2849
2850/*
2851 * return TRUE if "name" is a directory
2852 * return FALSE if "name" is not a directory
2853 * return FALSE for error
2854 */
2855 int
2856mch_isdir(name)
2857 char_u *name;
2858{
2859 struct stat statb;
2860
2861 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2862 return FALSE;
2863 if (stat((char *)name, &statb))
2864 return FALSE;
2865#ifdef _POSIX_SOURCE
2866 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2867#else
2868 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2869#endif
2870}
2871
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872static int executable_file __ARGS((char_u *name));
2873
2874/*
2875 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2876 */
2877 static int
2878executable_file(name)
2879 char_u *name;
2880{
2881 struct stat st;
2882
2883 if (stat((char *)name, &st))
2884 return 0;
2885 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2886}
2887
2888/*
2889 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2890 * Return -1 if unknown.
2891 */
2892 int
2893mch_can_exe(name)
2894 char_u *name;
2895{
2896 char_u *buf;
2897 char_u *p, *e;
2898 int retval;
2899
2900 /* If it's an absolute or relative path don't need to use $PATH. */
2901 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2902 || (name[1] == '.' && name[2] == '/'))))
2903 return executable_file(name);
2904
2905 p = (char_u *)getenv("PATH");
2906 if (p == NULL || *p == NUL)
2907 return -1;
2908 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2909 if (buf == NULL)
2910 return -1;
2911
2912 /*
2913 * Walk through all entries in $PATH to check if "name" exists there and
2914 * is an executable file.
2915 */
2916 for (;;)
2917 {
2918 e = (char_u *)strchr((char *)p, ':');
2919 if (e == NULL)
2920 e = p + STRLEN(p);
2921 if (e - p <= 1) /* empty entry means current dir */
2922 STRCPY(buf, "./");
2923 else
2924 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002925 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 add_pathsep(buf);
2927 }
2928 STRCAT(buf, name);
2929 retval = executable_file(buf);
2930 if (retval == 1)
2931 break;
2932
2933 if (*e != ':')
2934 break;
2935 p = e + 1;
2936 }
2937
2938 vim_free(buf);
2939 return retval;
2940}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941
2942/*
2943 * Check what "name" is:
2944 * NODE_NORMAL: file or directory (or doesn't exist)
2945 * NODE_WRITABLE: writable device, socket, fifo, etc.
2946 * NODE_OTHER: non-writable things
2947 */
2948 int
2949mch_nodetype(name)
2950 char_u *name;
2951{
2952 struct stat st;
2953
2954 if (stat((char *)name, &st))
2955 return NODE_NORMAL;
2956 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2957 return NODE_NORMAL;
2958#ifndef OS2
2959 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2960 return NODE_OTHER;
2961#endif
2962 /* Everything else is writable? */
2963 return NODE_WRITABLE;
2964}
2965
2966 void
2967mch_early_init()
2968{
2969#ifdef HAVE_CHECK_STACK_GROWTH
2970 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 check_stack_growth((char *)&i);
2973
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002974# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 get_stack_limit();
2976# endif
2977
2978#endif
2979
2980 /*
2981 * Setup an alternative stack for signals. Helps to catch signals when
2982 * running out of stack space.
2983 * Use of sigaltstack() is preferred, it's more portable.
2984 * Ignore any errors.
2985 */
2986#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00002987 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 init_signal_stack();
2989#endif
2990}
2991
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002992#if defined(EXITFREE) || defined(PROTO)
2993 void
2994mch_free_mem()
2995{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00002996# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2997 if (clip_star.owned)
2998 clip_lose_selection(&clip_star);
2999 if (clip_plus.owned)
3000 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003001# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003002# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003003 if (xterm_Shell != (Widget)0)
3004 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003005# ifndef LESSTIF_VERSION
3006 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003007 if (xterm_dpy != NULL)
3008 XtCloseDisplay(xterm_dpy);
3009 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003010 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003011 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003012# ifdef FEAT_X11
3013 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3014# endif
3015 }
3016# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003017# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003018# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003019 if (x11_display != NULL
3020# ifdef FEAT_XCLIPBOARD
3021 && x11_display != xterm_dpy
3022# endif
3023 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003024 XCloseDisplay(x11_display);
3025# endif
3026# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3027 vim_free(signal_stack);
3028 signal_stack = NULL;
3029# endif
3030# ifdef FEAT_TITLE
3031 vim_free(oldtitle);
3032 vim_free(oldicon);
3033# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003034}
3035#endif
3036
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037static void exit_scroll __ARGS((void));
3038
3039/*
3040 * Output a newline when exiting.
3041 * Make sure the newline goes to the same stream as the text.
3042 */
3043 static void
3044exit_scroll()
3045{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003046 if (silent_mode)
3047 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 if (newline_on_exit || msg_didout)
3049 {
3050 if (msg_use_printf())
3051 {
3052 if (info_message)
3053 mch_msg("\n");
3054 else
3055 mch_errmsg("\r\n");
3056 }
3057 else
3058 out_char('\n');
3059 }
3060 else
3061 {
3062 restore_cterm_colors(); /* get original colors back */
3063 msg_clr_eos_force(); /* clear the rest of the display */
3064 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3065 }
3066}
3067
3068 void
3069mch_exit(r)
3070 int r;
3071{
3072 exiting = TRUE;
3073
3074#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3075 x11_export_final_selection();
3076#endif
3077
3078#ifdef FEAT_GUI
3079 if (!gui.in_use)
3080#endif
3081 {
3082 settmode(TMODE_COOK);
3083#ifdef FEAT_TITLE
3084 mch_restore_title(3); /* restore xterm title and icon name */
3085#endif
3086 /*
3087 * When t_ti is not empty but it doesn't cause swapping terminal
3088 * pages, need to output a newline when msg_didout is set. But when
3089 * t_ti does swap pages it should not go to the shell page. Do this
3090 * before stoptermcap().
3091 */
3092 if (swapping_screen() && !newline_on_exit)
3093 exit_scroll();
3094
3095 /* Stop termcap: May need to check for T_CRV response, which
3096 * requires RAW mode. */
3097 stoptermcap();
3098
3099 /*
3100 * A newline is only required after a message in the alternate screen.
3101 * This is set to TRUE by wait_return().
3102 */
3103 if (!swapping_screen() || newline_on_exit)
3104 exit_scroll();
3105
3106 /* Cursor may have been switched off without calling starttermcap()
3107 * when doing "vim -u vimrc" and vimrc contains ":q". */
3108 if (full_screen)
3109 cursor_on();
3110 }
3111 out_flush();
3112 ml_close_all(TRUE); /* remove all memfiles */
3113 may_core_dump();
3114#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 gui_exit(r);
3117#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003118
Bram Moolenaar56718732006-03-15 22:53:57 +00003119#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003120 mac_conv_cleanup();
3121#endif
3122
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123#ifdef __QNX__
3124 /* A core dump won't be created if the signal handler
3125 * doesn't return, so we can't call exit() */
3126 if (deadly_signal != 0)
3127 return;
3128#endif
3129
Bram Moolenaar009b2592004-10-24 19:18:58 +00003130#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003131 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003132#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003133
3134#ifdef EXITFREE
3135 free_all_mem();
3136#endif
3137
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 exit(r);
3139}
3140
3141 static void
3142may_core_dump()
3143{
3144 if (deadly_signal != 0)
3145 {
3146 signal(deadly_signal, SIG_DFL);
3147 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3148 }
3149}
3150
3151#ifndef VMS
3152
3153 void
3154mch_settmode(tmode)
3155 int tmode;
3156{
3157 static int first = TRUE;
3158
3159 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3160#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3161 /*
3162 * for "new" tty systems
3163 */
3164# ifdef HAVE_TERMIOS_H
3165 static struct termios told;
3166 struct termios tnew;
3167# else
3168 static struct termio told;
3169 struct termio tnew;
3170# endif
3171
3172 if (first)
3173 {
3174 first = FALSE;
3175# if defined(HAVE_TERMIOS_H)
3176 tcgetattr(read_cmd_fd, &told);
3177# else
3178 ioctl(read_cmd_fd, TCGETA, &told);
3179# endif
3180 }
3181
3182 tnew = told;
3183 if (tmode == TMODE_RAW)
3184 {
3185 /*
3186 * ~ICRNL enables typing ^V^M
3187 */
3188 tnew.c_iflag &= ~ICRNL;
3189 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3190# if defined(IEXTEN) && !defined(__MINT__)
3191 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3192 /* but it breaks function keys on MINT */
3193# endif
3194 );
3195# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3196 tnew.c_oflag &= ~ONLCR;
3197# endif
3198 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3199 tnew.c_cc[VTIME] = 0; /* don't wait */
3200 }
3201 else if (tmode == TMODE_SLEEP)
3202 tnew.c_lflag &= ~(ECHO);
3203
3204# if defined(HAVE_TERMIOS_H)
3205 {
3206 int n = 10;
3207
3208 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3209 * few times. */
3210 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3211 && errno == EINTR && n > 0)
3212 --n;
3213 }
3214# else
3215 ioctl(read_cmd_fd, TCSETA, &tnew);
3216# endif
3217
3218#else
3219
3220 /*
3221 * for "old" tty systems
3222 */
3223# ifndef TIOCSETN
3224# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3225# endif
3226 static struct sgttyb ttybold;
3227 struct sgttyb ttybnew;
3228
3229 if (first)
3230 {
3231 first = FALSE;
3232 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3233 }
3234
3235 ttybnew = ttybold;
3236 if (tmode == TMODE_RAW)
3237 {
3238 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3239 ttybnew.sg_flags |= RAW;
3240 }
3241 else if (tmode == TMODE_SLEEP)
3242 ttybnew.sg_flags &= ~(ECHO);
3243 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3244#endif
3245 curr_tmode = tmode;
3246}
3247
3248/*
3249 * Try to get the code for "t_kb" from the stty setting
3250 *
3251 * Even if termcap claims a backspace key, the user's setting *should*
3252 * prevail. stty knows more about reality than termcap does, and if
3253 * somebody's usual erase key is DEL (which, for most BSD users, it will
3254 * be), they're going to get really annoyed if their erase key starts
3255 * doing forward deletes for no reason. (Eric Fischer)
3256 */
3257 void
3258get_stty()
3259{
3260 char_u buf[2];
3261 char_u *p;
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 /* for "new" tty systems */
3266# ifdef HAVE_TERMIOS_H
3267 struct termios keys;
3268# else
3269 struct termio keys;
3270# endif
3271
3272# if defined(HAVE_TERMIOS_H)
3273 if (tcgetattr(read_cmd_fd, &keys) != -1)
3274# else
3275 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3276# endif
3277 {
3278 buf[0] = keys.c_cc[VERASE];
3279 intr_char = keys.c_cc[VINTR];
3280#else
3281 /* for "old" tty systems */
3282 struct sgttyb keys;
3283
3284 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3285 {
3286 buf[0] = keys.sg_erase;
3287 intr_char = keys.sg_kill;
3288#endif
3289 buf[1] = NUL;
3290 add_termcode((char_u *)"kb", buf, FALSE);
3291
3292 /*
3293 * If <BS> and <DEL> are now the same, redefine <DEL>.
3294 */
3295 p = find_termcode((char_u *)"kD");
3296 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3297 do_fixdel(NULL);
3298 }
3299#if 0
3300 } /* to keep cindent happy */
3301#endif
3302}
3303
3304#endif /* VMS */
3305
3306#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3307/*
3308 * Set mouse clicks on or off.
3309 */
3310 void
3311mch_setmouse(on)
3312 int on;
3313{
3314 static int ison = FALSE;
3315 int xterm_mouse_vers;
3316
3317 if (on == ison) /* return quickly if nothing to do */
3318 return;
3319
3320 xterm_mouse_vers = use_xterm_mouse();
3321 if (xterm_mouse_vers > 0)
3322 {
3323 if (on) /* enable mouse events, use mouse tracking if available */
3324 out_str_nf((char_u *)
3325 (xterm_mouse_vers > 1
3326 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3327 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3328 else /* disable mouse events, could probably always send the same */
3329 out_str_nf((char_u *)
3330 (xterm_mouse_vers > 1
3331 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3332 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3333 ison = on;
3334 }
3335
3336# ifdef FEAT_MOUSE_DEC
3337 else if (ttym_flags == TTYM_DEC)
3338 {
3339 if (on) /* enable mouse events */
3340 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3341 else /* disable mouse events */
3342 out_str_nf((char_u *)"\033['z");
3343 ison = on;
3344 }
3345# endif
3346
3347# ifdef FEAT_MOUSE_GPM
3348 else
3349 {
3350 if (on)
3351 {
3352 if (gpm_open())
3353 ison = TRUE;
3354 }
3355 else
3356 {
3357 gpm_close();
3358 ison = FALSE;
3359 }
3360 }
3361# endif
3362
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003363# ifdef FEAT_SYSMOUSE
3364 else
3365 {
3366 if (on)
3367 {
3368 if (sysmouse_open() == OK)
3369 ison = TRUE;
3370 }
3371 else
3372 {
3373 sysmouse_close();
3374 ison = FALSE;
3375 }
3376 }
3377# endif
3378
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379# ifdef FEAT_MOUSE_JSB
3380 else
3381 {
3382 if (on)
3383 {
3384 /* D - Enable Mouse up/down messages
3385 * L - Enable Left Button Reporting
3386 * M - Enable Middle Button Reporting
3387 * R - Enable Right Button Reporting
3388 * K - Enable SHIFT and CTRL key Reporting
3389 * + - Enable Advanced messaging of mouse moves and up/down messages
3390 * Q - Quiet No Ack
3391 * # - Numeric value of mouse pointer required
3392 * 0 = Multiview 2000 cursor, used as standard
3393 * 1 = Windows Arrow
3394 * 2 = Windows I Beam
3395 * 3 = Windows Hour Glass
3396 * 4 = Windows Cross Hair
3397 * 5 = Windows UP Arrow
3398 */
3399#ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3400 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3401 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3402#else
3403 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3404 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3405#endif
3406 ison = TRUE;
3407 }
3408 else
3409 {
3410 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3411 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3412 ison = FALSE;
3413 }
3414 }
3415# endif
3416# ifdef FEAT_MOUSE_PTERM
3417 else
3418 {
3419 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3420 if (on)
3421 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3422 else
3423 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3424 ison = on;
3425 }
3426# endif
3427}
3428
3429/*
3430 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3431 */
3432 void
3433check_mouse_termcode()
3434{
3435# ifdef FEAT_MOUSE_XTERM
3436 if (use_xterm_mouse()
3437# ifdef FEAT_GUI
3438 && !gui.in_use
3439# endif
3440 )
3441 {
3442 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003443 ? IF_EB("\233M", CSI_STR "M")
3444 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 if (*p_mouse != NUL)
3446 {
3447 /* force mouse off and maybe on to send possibly new mouse
3448 * activation sequence to the xterm, with(out) drag tracing. */
3449 mch_setmouse(FALSE);
3450 setmouse();
3451 }
3452 }
3453 else
3454 del_mouse_termcode(KS_MOUSE);
3455# endif
3456
3457# ifdef FEAT_MOUSE_GPM
3458 if (!use_xterm_mouse()
3459# ifdef FEAT_GUI
3460 && !gui.in_use
3461# endif
3462 )
3463 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3464# endif
3465
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003466# ifdef FEAT_SYSMOUSE
3467 if (!use_xterm_mouse()
3468# ifdef FEAT_GUI
3469 && !gui.in_use
3470# endif
3471 )
3472 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3473# endif
3474
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475# ifdef FEAT_MOUSE_JSB
3476 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3477 if (!use_xterm_mouse()
3478# ifdef FEAT_GUI
3479 && !gui.in_use
3480# endif
3481 )
3482 set_mouse_termcode(KS_JSBTERM_MOUSE,
3483 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3484 else
3485 del_mouse_termcode(KS_JSBTERM_MOUSE);
3486# endif
3487
3488# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003489 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 * define it in the GUI or when using an xterm. */
3491 if (!use_xterm_mouse()
3492# ifdef FEAT_GUI
3493 && !gui.in_use
3494# endif
3495 )
3496 set_mouse_termcode(KS_NETTERM_MOUSE,
3497 (char_u *)IF_EB("\033}", ESC_STR "}"));
3498 else
3499 del_mouse_termcode(KS_NETTERM_MOUSE);
3500# endif
3501
3502# ifdef FEAT_MOUSE_DEC
3503 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3504 if (!use_xterm_mouse()
3505# ifdef FEAT_GUI
3506 && !gui.in_use
3507# endif
3508 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003509 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3510 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 else
3512 del_mouse_termcode(KS_DEC_MOUSE);
3513# endif
3514# ifdef FEAT_MOUSE_PTERM
3515 /* same as the dec mouse */
3516 if (!use_xterm_mouse()
3517# ifdef FEAT_GUI
3518 && !gui.in_use
3519# endif
3520 )
3521 set_mouse_termcode(KS_PTERM_MOUSE,
3522 (char_u *) IF_EB("\033[", ESC_STR "["));
3523 else
3524 del_mouse_termcode(KS_PTERM_MOUSE);
3525# endif
3526}
3527#endif
3528
3529/*
3530 * set screen mode, always fails.
3531 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 int
3533mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003534 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535{
3536 EMSG(_(e_screenmode));
3537 return FAIL;
3538}
3539
3540#ifndef VMS
3541
3542/*
3543 * Try to get the current window size:
3544 * 1. with an ioctl(), most accurate method
3545 * 2. from the environment variables LINES and COLUMNS
3546 * 3. from the termcap
3547 * 4. keep using the old values
3548 * Return OK when size could be determined, FAIL otherwise.
3549 */
3550 int
3551mch_get_shellsize()
3552{
3553 long rows = 0;
3554 long columns = 0;
3555 char_u *p;
3556
3557 /*
3558 * For OS/2 use _scrsize().
3559 */
3560# ifdef __EMX__
3561 {
3562 int s[2];
3563
3564 _scrsize(s);
3565 columns = s[0];
3566 rows = s[1];
3567 }
3568# endif
3569
3570 /*
3571 * 1. try using an ioctl. It is the most accurate method.
3572 *
3573 * Try using TIOCGWINSZ first, some systems that have it also define
3574 * TIOCGSIZE but don't have a struct ttysize.
3575 */
3576# ifdef TIOCGWINSZ
3577 {
3578 struct winsize ws;
3579 int fd = 1;
3580
3581 /* When stdout is not a tty, use stdin for the ioctl(). */
3582 if (!isatty(fd) && isatty(read_cmd_fd))
3583 fd = read_cmd_fd;
3584 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3585 {
3586 columns = ws.ws_col;
3587 rows = ws.ws_row;
3588 }
3589 }
3590# else /* TIOCGWINSZ */
3591# ifdef TIOCGSIZE
3592 {
3593 struct ttysize ts;
3594 int fd = 1;
3595
3596 /* When stdout is not a tty, use stdin for the ioctl(). */
3597 if (!isatty(fd) && isatty(read_cmd_fd))
3598 fd = read_cmd_fd;
3599 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3600 {
3601 columns = ts.ts_cols;
3602 rows = ts.ts_lines;
3603 }
3604 }
3605# endif /* TIOCGSIZE */
3606# endif /* TIOCGWINSZ */
3607
3608 /*
3609 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003610 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3611 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003613 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 {
3615 if ((p = (char_u *)getenv("LINES")))
3616 rows = atoi((char *)p);
3617 if ((p = (char_u *)getenv("COLUMNS")))
3618 columns = atoi((char *)p);
3619 }
3620
3621#ifdef HAVE_TGETENT
3622 /*
3623 * 3. try reading "co" and "li" entries from termcap
3624 */
3625 if (columns == 0 || rows == 0)
3626 getlinecol(&columns, &rows);
3627#endif
3628
3629 /*
3630 * 4. If everything fails, use the old values
3631 */
3632 if (columns <= 0 || rows <= 0)
3633 return FAIL;
3634
3635 Rows = rows;
3636 Columns = columns;
3637 return OK;
3638}
3639
3640/*
3641 * Try to set the window size to Rows and Columns.
3642 */
3643 void
3644mch_set_shellsize()
3645{
3646 if (*T_CWS)
3647 {
3648 /*
3649 * NOTE: if you get an error here that term_set_winsize() is
3650 * undefined, check the output of configure. It could probably not
3651 * find a ncurses, termcap or termlib library.
3652 */
3653 term_set_winsize((int)Rows, (int)Columns);
3654 out_flush();
3655 screen_start(); /* don't know where cursor is now */
3656 }
3657}
3658
3659#endif /* VMS */
3660
3661/*
3662 * Rows and/or Columns has changed.
3663 */
3664 void
3665mch_new_shellsize()
3666{
3667 /* Nothing to do. */
3668}
3669
Bram Moolenaar205b8862011-09-07 15:04:31 +02003670/*
3671 * Wait for process "child" to end.
3672 * Return "child" if it exited properly, <= 0 on error.
3673 */
3674 static pid_t
3675wait4pid(child, status)
3676 pid_t child;
3677 waitstatus *status;
3678{
3679 pid_t wait_pid = 0;
3680
3681 while (wait_pid != child)
3682 {
3683# ifdef _THREAD_SAFE
3684 /* Ugly hack: when compiled with Python threads are probably
3685 * used, in which case wait() sometimes hangs for no obvious
3686 * reason. Use waitpid() instead and loop (like the GUI). */
3687# ifdef __NeXT__
3688 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
3689# else
3690 wait_pid = waitpid(child, status, WNOHANG);
3691# endif
3692 if (wait_pid == 0)
3693 {
3694 /* Wait for 1/100 sec before trying again. */
3695 mch_delay(10L, TRUE);
3696 continue;
3697 }
3698# else
3699 wait_pid = wait(status);
3700# endif
3701 if (wait_pid <= 0
3702# ifdef ECHILD
3703 && errno == ECHILD
3704# endif
3705 )
3706 break;
3707 }
3708 return wait_pid;
3709}
3710
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711 int
3712mch_call_shell(cmd, options)
3713 char_u *cmd;
3714 int options; /* SHELL_*, see vim.h */
3715{
3716#ifdef VMS
3717 char *ifn = NULL;
3718 char *ofn = NULL;
3719#endif
3720 int tmode = cur_tmode;
3721#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3722 int x;
3723# ifndef __EMX__
3724 char_u *newcmd; /* only needed for unix */
3725# else
3726 /*
3727 * Set the preferred shell in the EMXSHELL environment variable (but
3728 * only if it is different from what is already in the environment).
3729 * Emx then takes care of whether to use "/c" or "-c" in an
3730 * intelligent way. Simply pass the whole thing to emx's system() call.
3731 * Emx also starts an interactive shell if system() is passed an empty
3732 * string.
3733 */
3734 char_u *p, *old;
3735
3736 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3737 {
3738 /* should check HAVE_SETENV, but I know we don't have it. */
3739 p = alloc(10 + strlen(p_sh));
3740 if (p)
3741 {
3742 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3743 putenv((char *)p); /* don't free the pointer! */
3744 }
3745 }
3746# endif
3747
3748 out_flush();
3749
3750 if (options & SHELL_COOKED)
3751 settmode(TMODE_COOK); /* set to normal mode */
3752
Bram Moolenaar62b42182010-09-21 22:09:37 +02003753# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3754 loose_clipboard();
3755# endif
3756
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757# ifdef __EMX__
3758 if (cmd == NULL)
3759 x = system(""); /* this starts an interactive shell in emx */
3760 else
3761 x = system((char *)cmd);
3762 /* system() returns -1 when error occurs in starting shell */
3763 if (x == -1 && !emsg_silent)
3764 {
3765 MSG_PUTS(_("\nCannot execute shell "));
3766 msg_outtrans(p_sh);
3767 msg_putchar('\n');
3768 }
3769# else /* not __EMX__ */
3770 if (cmd == NULL)
3771 x = system((char *)p_sh);
3772 else
3773 {
3774# ifdef VMS
3775 if (ofn = strchr((char *)cmd, '>'))
3776 *ofn++ = '\0';
3777 if (ifn = strchr((char *)cmd, '<'))
3778 {
3779 char *p;
3780
3781 *ifn++ = '\0';
3782 p = strchr(ifn,' '); /* chop off any trailing spaces */
3783 if (p)
3784 *p = '\0';
3785 }
3786 if (ofn)
3787 x = vms_sys((char *)cmd, ofn, ifn);
3788 else
3789 x = system((char *)cmd);
3790# else
3791 newcmd = lalloc(STRLEN(p_sh)
3792 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3793 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3794 if (newcmd == NULL)
3795 x = 0;
3796 else
3797 {
3798 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3799 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3800 (char *)p_shcf,
3801 (char *)cmd);
3802 x = system((char *)newcmd);
3803 vim_free(newcmd);
3804 }
3805# endif
3806 }
3807# ifdef VMS
3808 x = vms_sys_status(x);
3809# endif
3810 if (emsg_silent)
3811 ;
3812 else if (x == 127)
3813 MSG_PUTS(_("\nCannot execute shell sh\n"));
3814# endif /* __EMX__ */
3815 else if (x && !(options & SHELL_SILENT))
3816 {
3817 MSG_PUTS(_("\nshell returned "));
3818 msg_outnum((long)x);
3819 msg_putchar('\n');
3820 }
3821
3822 if (tmode == TMODE_RAW)
3823 settmode(TMODE_RAW); /* set to raw mode */
3824# ifdef FEAT_TITLE
3825 resettitle();
3826# endif
3827 return x;
3828
3829#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3830
Bram Moolenaardf177f62005-02-22 08:39:57 +00003831# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3832 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833
3834 char_u *newcmd = NULL;
3835 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003836 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 pid_t wait_pid = 0;
3838# ifdef HAVE_UNION_WAIT
3839 union wait status;
3840# else
3841 int status = -1;
3842# endif
3843 int retval = -1;
3844 char **argv = NULL;
3845 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003846 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 int i;
3848 char_u *p;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003849 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003850 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003852# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853 int pty_slave_fd = -1;
3854 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003855# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003856 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 int fd_fromshell[2];
3858 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003859# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003861# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862 static char envbuf_Rows[20];
3863 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003865 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866
Bram Moolenaar62b42182010-09-21 22:09:37 +02003867 newcmd = vim_strsave(p_sh);
3868 if (newcmd == NULL) /* out of memory */
3869 goto error;
3870
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 out_flush();
3872 if (options & SHELL_COOKED)
3873 settmode(TMODE_COOK); /* set to normal mode */
3874
Bram Moolenaar62b42182010-09-21 22:09:37 +02003875# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3876 loose_clipboard();
3877# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003878
3879 /*
3880 * Do this loop twice:
3881 * 1: find number of arguments
3882 * 2: separate them and build argv[]
3883 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 for (i = 0; i < 2; ++i)
3885 {
3886 p = newcmd;
3887 inquote = FALSE;
3888 argc = 0;
3889 for (;;)
3890 {
3891 if (i == 1)
3892 argv[argc] = (char *)p;
3893 ++argc;
3894 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3895 {
3896 if (*p == '"')
3897 inquote = !inquote;
3898 ++p;
3899 }
3900 if (*p == NUL)
3901 break;
3902 if (i == 1)
3903 *p++ = NUL;
3904 p = skipwhite(p);
3905 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003906 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003908 /*
3909 * Account for possible multiple args in p_shcf.
3910 */
3911 p = p_shcf;
3912 for (;;)
3913 {
3914 p = skiptowhite(p);
3915 if (*p == NUL)
3916 break;
3917 ++argc;
3918 p = skipwhite(p);
3919 }
3920
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3922 if (argv == NULL) /* out of memory */
3923 goto error;
3924 }
3925 }
3926 if (cmd != NULL)
3927 {
3928 if (extra_shell_arg != NULL)
3929 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003930
3931 /* Break 'shellcmdflag' into white separated parts. This doesn't
3932 * handle quoted strings, they are very unlikely to appear. */
3933 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
3934 if (p_shcf_copy == NULL) /* out of memory */
3935 goto error;
3936 s = p_shcf_copy;
3937 p = p_shcf;
3938 while (*p != NUL)
3939 {
3940 argv[argc++] = (char *)s;
3941 while (*p && *p != ' ' && *p != TAB)
3942 *s++ = *p++;
3943 *s++ = NUL;
3944 p = skipwhite(p);
3945 }
3946
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 argv[argc++] = (char *)cmd;
3948 }
3949 argv[argc] = NULL;
3950
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003952 * For the GUI, when writing the output into the buffer and when reading
3953 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3954 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003956 if ((options & (SHELL_READ|SHELL_WRITE))
3957# ifdef FEAT_GUI
3958 || (gui.in_use && show_shell_mess)
3959# endif
3960 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003962# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963 /*
3964 * Try to open a master pty.
3965 * If this works, open the slave pty.
3966 * If the slave can't be opened, close the master pty.
3967 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003968 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 {
3970 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02003971 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02003973 /* Leaving out O_NOCTTY may lead to waitpid() always returning
3974 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
3975 * adding O_NOCTTY always works when defined. */
3976#ifdef O_NOCTTY
3977 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
3978#else
3979 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
3980#endif
3981 if (pty_slave_fd < 0)
3982 {
3983 close(pty_master_fd);
3984 pty_master_fd = -1;
3985 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 }
3987 }
3988 /*
3989 * If not opening a pty or it didn't work, try using pipes.
3990 */
3991 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 {
3994 pipe_error = (pipe(fd_toshell) < 0);
3995 if (!pipe_error) /* pipe create OK */
3996 {
3997 pipe_error = (pipe(fd_fromshell) < 0);
3998 if (pipe_error) /* pipe create failed */
3999 {
4000 close(fd_toshell[0]);
4001 close(fd_toshell[1]);
4002 }
4003 }
4004 if (pipe_error)
4005 {
4006 MSG_PUTS(_("\nCannot create pipes\n"));
4007 out_flush();
4008 }
4009 }
4010 }
4011
4012 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 {
4014# ifdef __BEOS__
4015 beos_cleanup_read_thread();
4016# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004017
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4019 {
4020 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004021 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004023 || (gui.in_use && show_shell_mess)
4024# endif
4025 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004027# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 if (pty_master_fd >= 0) /* close the pseudo tty */
4029 {
4030 close(pty_master_fd);
4031 close(pty_slave_fd);
4032 }
4033 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004034# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 {
4036 close(fd_toshell[0]);
4037 close(fd_toshell[1]);
4038 close(fd_fromshell[0]);
4039 close(fd_fromshell[1]);
4040 }
4041 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042 }
4043 else if (pid == 0) /* child */
4044 {
4045 reset_signals(); /* handle signals normally */
4046
4047 if (!show_shell_mess || (options & SHELL_EXPAND))
4048 {
4049 int fd;
4050
4051 /*
4052 * Don't want to show any message from the shell. Can't just
4053 * close stdout and stderr though, because some systems will
4054 * break if you try to write to them after that, so we must
4055 * use dup() to replace them with something else -- webb
4056 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4057 * waiting for input.
4058 */
4059 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4060 fclose(stdin);
4061 fclose(stdout);
4062 fclose(stderr);
4063
4064 /*
4065 * If any of these open()'s and dup()'s fail, we just continue
4066 * anyway. It's not fatal, and on most systems it will make
4067 * no difference at all. On a few it will cause the execvp()
4068 * to exit with a non-zero status even when the completion
4069 * could be done, which is nothing too serious. If the open()
4070 * or dup() failed we'd just do the same thing ourselves
4071 * anyway -- webb
4072 */
4073 if (fd >= 0)
4074 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004075 ignored = dup(fd); /* To replace stdin (fd 0) */
4076 ignored = dup(fd); /* To replace stdout (fd 1) */
4077 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078
4079 /* Don't need this now that we've duplicated it */
4080 close(fd);
4081 }
4082 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004083 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004085 || gui.in_use
4086# endif
4087 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 {
4089
Bram Moolenaardf177f62005-02-22 08:39:57 +00004090# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004091 /* Create our own process group, so that the child and all its
4092 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004093 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004094 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004095 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004096 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004097# if defined(SIGHUP)
4098 /* When doing "!xterm&" and 'shell' is bash: the shell
4099 * will exit and send SIGHUP to all processes in its
4100 * group, killing the just started process. Ignore SIGHUP
4101 * to avoid that. (suggested by Simon Schubert)
4102 */
4103 signal(SIGHUP, SIG_IGN);
4104# endif
4105 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004106# endif
4107# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004108 if (pty_slave_fd >= 0)
4109 {
4110 /* push stream discipline modules */
4111 if (options & SHELL_COOKED)
4112 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004114 /* Try to become controlling tty (probably doesn't work,
4115 * unless run by root) */
4116 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004118 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004121# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 setenv("TERM", "dumb", 1);
4123 sprintf((char *)envbuf, "%ld", Rows);
4124 setenv("ROWS", (char *)envbuf, 1);
4125 sprintf((char *)envbuf, "%ld", Rows);
4126 setenv("LINES", (char *)envbuf, 1);
4127 sprintf((char *)envbuf, "%ld", Columns);
4128 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004129# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 /*
4131 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004132 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 */
4134 putenv("TERM=dumb");
4135 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4136 putenv(envbuf_Rows);
4137 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4138 putenv(envbuf_Rows);
4139 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4140 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004141# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142
Bram Moolenaara5792f52005-11-23 21:25:05 +00004143 /*
4144 * stderr is only redirected when using the GUI, so that a
4145 * program like gpg can still access the terminal to get a
4146 * passphrase using stderr.
4147 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004148# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 if (pty_master_fd >= 0)
4150 {
4151 close(pty_master_fd); /* close master side of pty */
4152
4153 /* set up stdin/stdout/stderr for the child */
4154 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004155 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004157 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004158 if (gui.in_use)
4159 {
4160 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004161 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163
4164 close(pty_slave_fd); /* has been dupped, close it now */
4165 }
4166 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004167# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 {
4169 /* set up stdin for the child */
4170 close(fd_toshell[1]);
4171 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004172 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 close(fd_toshell[0]);
4174
4175 /* set up stdout for the child */
4176 close(fd_fromshell[0]);
4177 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004178 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 close(fd_fromshell[1]);
4180
Bram Moolenaara5792f52005-11-23 21:25:05 +00004181# ifdef FEAT_GUI
4182 if (gui.in_use)
4183 {
4184 /* set up stderr for the child */
4185 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004186 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004187 }
4188# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 }
4190 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004191
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 /*
4193 * There is no type cast for the argv, because the type may be
4194 * different on different machines. This may cause a warning
4195 * message with strict compilers, don't worry about it.
4196 * Call _exit() instead of exit() to avoid closing the connection
4197 * to the X server (esp. with GTK, which uses atexit()).
4198 */
4199 execvp(argv[0], argv);
4200 _exit(EXEC_FAILED); /* exec failed, return failure code */
4201 }
4202 else /* parent */
4203 {
4204 /*
4205 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004206 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 */
4208 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004209 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210
4211 /*
4212 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004213 * This is also used to pipe stdin/stdout to/from the external
4214 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004216 if ((options & (SHELL_READ|SHELL_WRITE))
4217# ifdef FEAT_GUI
4218 || (gui.in_use && show_shell_mess)
4219# endif
4220 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004222# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004224# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004226# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4228 int ta_len = 0; /* valid bytes in ta_buf[] */
4229 int len;
4230 int p_more_save;
4231 int old_State;
4232 int c;
4233 int toshell_fd;
4234 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004235 garray_T ga;
4236 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004237# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4238 struct timeval start_tv;
4239# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240
Bram Moolenaardf177f62005-02-22 08:39:57 +00004241# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242 if (pty_master_fd >= 0)
4243 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 fromshell_fd = pty_master_fd;
4245 toshell_fd = dup(pty_master_fd);
4246 }
4247 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004248# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249 {
4250 close(fd_toshell[0]);
4251 close(fd_fromshell[1]);
4252 toshell_fd = fd_toshell[1];
4253 fromshell_fd = fd_fromshell[0];
4254 }
4255
4256 /*
4257 * Write to the child if there are typed characters.
4258 * Read from the child if there are characters available.
4259 * Repeat the reading a few times if more characters are
4260 * available. Need to check for typed keys now and then, but
4261 * not too often (delays when no chars are available).
4262 * This loop is quit if no characters can be read from the pty
4263 * (WaitForChar detected special condition), or there are no
4264 * characters available and the child has exited.
4265 * Only check if the child has exited when there is no more
4266 * output. The child may exit before all the output has
4267 * been printed.
4268 *
4269 * Currently this busy loops!
4270 * This can probably dead-lock when the write blocks!
4271 */
4272 p_more_save = p_more;
4273 p_more = FALSE;
4274 old_State = State;
4275 State = EXTERNCMD; /* don't redraw at window resize */
4276
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004277 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004278 {
4279 /* Fork a process that will write the lines to the
4280 * external program. */
4281 if ((wpid = fork()) == -1)
4282 {
4283 MSG_PUTS(_("\nCannot fork\n"));
4284 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004285 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004286 {
4287 linenr_T lnum = curbuf->b_op_start.lnum;
4288 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004289 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004290 char_u *s;
4291 size_t l;
4292
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004293 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004294 for (;;)
4295 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004296 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004297 if (l == 0)
4298 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004299 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004300 /* NL -> NUL translation */
4301 len = write(toshell_fd, "", (size_t)1);
4302 else
4303 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004304 s = vim_strchr(lp + written, NL);
4305 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004306 s == NULL ? l
4307 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004308 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004309 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004310 {
4311 /* Finished a line, add a NL, unless this line
4312 * should not have one. */
4313 if (lnum != curbuf->b_op_end.lnum
4314 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004315 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004316 && (lnum !=
4317 curbuf->b_ml.ml_line_count
4318 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004319 ignored = write(toshell_fd, "\n",
4320 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004321 ++lnum;
4322 if (lnum > curbuf->b_op_end.lnum)
4323 {
4324 /* finished all the lines, close pipe */
4325 close(toshell_fd);
4326 toshell_fd = -1;
4327 break;
4328 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004329 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004330 written = 0;
4331 }
4332 else if (len > 0)
4333 written += len;
4334 }
4335 _exit(0);
4336 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004337 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004338 {
4339 close(toshell_fd);
4340 toshell_fd = -1;
4341 }
4342 }
4343
4344 if (options & SHELL_READ)
4345 ga_init2(&ga, 1, BUFLEN);
4346
4347 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004348# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4349 gettimeofday(&start_tv, NULL);
4350# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 for (;;)
4352 {
4353 /*
4354 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004355 * if there are any.
4356 * Don't do this if we are expanding wild cards (would eat
4357 * typeahead).
4358 * Don't do this when filtering and terminal is in cooked
4359 * mode, the shell command will handle the I/O. Avoids
4360 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004361 * Don't get characters when the child has already
4362 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004363 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004364 * while (noread_cnt > 4), avoids that ":r !ls" eats
4365 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 */
4367 len = 0;
4368 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004369 && ((options &
4370 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4371 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004372# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004373 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004374# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004375 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004376 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004377 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004379 if (ta_len == 0)
4380 {
4381 /* Get extra characters when we don't have any.
4382 * Reset the counter and timer. */
4383 noread_cnt = 0;
4384# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4385 gettimeofday(&start_tv, NULL);
4386# endif
4387 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4388 }
4389 if (ta_len > 0 || len > 0)
4390 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391 /*
4392 * For pipes:
4393 * Check for CTRL-C: send interrupt signal to child.
4394 * Check for CTRL-D: EOF, close pipe to child.
4395 */
4396 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4397 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004398# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399 /*
4400 * Send SIGINT to the child's group or all
4401 * processes in our group.
4402 */
4403 if (ta_buf[ta_len] == Ctrl_C
4404 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004405 {
4406# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004408# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004411 if (wpid > 0)
4412 kill(wpid, SIGINT);
4413 }
4414# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 if (pty_master_fd < 0 && toshell_fd >= 0
4416 && ta_buf[ta_len] == Ctrl_D)
4417 {
4418 close(toshell_fd);
4419 toshell_fd = -1;
4420 }
4421 }
4422
4423 /* replace K_BS by <BS> and K_DEL by <DEL> */
4424 for (i = ta_len; i < ta_len + len; ++i)
4425 {
4426 if (ta_buf[i] == CSI && len - i > 2)
4427 {
4428 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4429 if (c == K_DEL || c == K_KDEL || c == K_BS)
4430 {
4431 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4432 (size_t)(len - i - 2));
4433 if (c == K_DEL || c == K_KDEL)
4434 ta_buf[i] = DEL;
4435 else
4436 ta_buf[i] = Ctrl_H;
4437 len -= 2;
4438 }
4439 }
4440 else if (ta_buf[i] == '\r')
4441 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004442# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004444 i += (*mb_ptr2len_len)(ta_buf + i,
4445 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004446# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 }
4448
4449 /*
4450 * For pipes: echo the typed characters.
4451 * For a pty this does not seem to work.
4452 */
4453 if (pty_master_fd < 0)
4454 {
4455 for (i = ta_len; i < ta_len + len; ++i)
4456 {
4457 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4458 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004459# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460 else if (has_mbyte)
4461 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004462 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463
4464 msg_outtrans_len(ta_buf + i, l);
4465 i += l - 1;
4466 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004467# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 else
4469 msg_outtrans_len(ta_buf + i, 1);
4470 }
4471 windgoto(msg_row, msg_col);
4472 out_flush();
4473 }
4474
4475 ta_len += len;
4476
4477 /*
4478 * Write the characters to the child, unless EOF has
4479 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004480 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004481 * When writing buffer lines, drop the typed
4482 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004484 if (options & SHELL_WRITE)
4485 ta_len = 0;
4486 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 {
4488 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4489 if (len > 0)
4490 {
4491 ta_len -= len;
4492 mch_memmove(ta_buf, ta_buf + len, ta_len);
4493 }
4494 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 }
4497
Bram Moolenaardf177f62005-02-22 08:39:57 +00004498 if (got_int)
4499 {
4500 /* CTRL-C sends a signal to the child, we ignore it
4501 * ourselves */
4502# ifdef HAVE_SETSID
4503 kill(-pid, SIGINT);
4504# else
4505 kill(0, SIGINT);
4506# endif
4507 if (wpid > 0)
4508 kill(wpid, SIGINT);
4509 got_int = FALSE;
4510 }
4511
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512 /*
4513 * Check if the child has any characters to be printed.
4514 * Read them and write them to our window. Repeat this as
4515 * long as there is something to do, avoid the 10ms wait
4516 * for mch_inchar(), or sending typeahead characters to
4517 * the external process.
4518 * TODO: This should handle escape sequences, compatible
4519 * to some terminal (vt52?).
4520 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004521 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4523 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004524 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004525# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004527# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 );
4531 if (len <= 0) /* end of file or error */
4532 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004533
4534 noread_cnt = 0;
4535 if (options & SHELL_READ)
4536 {
4537 /* Do NUL -> NL translation, append NL separated
4538 * lines to the current buffer. */
4539 for (i = 0; i < len; ++i)
4540 {
4541 if (buffer[i] == NL)
4542 append_ga_line(&ga);
4543 else if (buffer[i] == NUL)
4544 ga_append(&ga, NL);
4545 else
4546 ga_append(&ga, buffer[i]);
4547 }
4548 }
4549# ifdef FEAT_MBYTE
4550 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 {
4552 int l;
4553
Bram Moolenaardf177f62005-02-22 08:39:57 +00004554 len += buffer_off;
4555 buffer[len] = NUL;
4556
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 /* Check if the last character in buffer[] is
4558 * incomplete, keep these bytes for the next
4559 * round. */
4560 for (p = buffer; p < buffer + len; p += l)
4561 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004562 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 if (l == 0)
4564 l = 1; /* NUL byte? */
4565 else if (MB_BYTE2LEN(*p) != l)
4566 break;
4567 }
4568 if (p == buffer) /* no complete character */
4569 {
4570 /* avoid getting stuck at an illegal byte */
4571 if (len >= 12)
4572 ++p;
4573 else
4574 {
4575 buffer_off = len;
4576 continue;
4577 }
4578 }
4579 c = *p;
4580 *p = NUL;
4581 msg_puts(buffer);
4582 if (p < buffer + len)
4583 {
4584 *p = c;
4585 buffer_off = (buffer + len) - p;
4586 mch_memmove(buffer, p, buffer_off);
4587 continue;
4588 }
4589 buffer_off = 0;
4590 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004591# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004593 {
4594 buffer[len] = NUL;
4595 msg_puts(buffer);
4596 }
4597
4598 windgoto(msg_row, msg_col);
4599 cursor_on();
4600 out_flush();
4601 if (got_int)
4602 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004603
4604# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4605 {
4606 struct timeval now_tv;
4607 long msec;
4608
4609 /* Avoid that we keep looping here without
4610 * checking for a CTRL-C for a long time. Don't
4611 * break out too often to avoid losing typeahead. */
4612 gettimeofday(&now_tv, NULL);
4613 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4614 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4615 if (msec > 2000)
4616 {
4617 noread_cnt = 5;
4618 break;
4619 }
4620 }
4621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004622 }
4623
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004624 /* If we already detected the child has finished break the
4625 * loop now. */
4626 if (wait_pid == pid)
4627 break;
4628
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 /*
4630 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004631 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004633# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004634 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004635# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004637# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4639 || (wait_pid == pid && WIFEXITED(status)))
4640 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004641 /* Don't break the loop yet, try reading more
4642 * characters from "fromshell_fd" first. When using
4643 * pipes there might still be something to read and
4644 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004647 else
4648 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 }
4650finished:
4651 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004652 if (options & SHELL_READ)
4653 {
4654 if (ga.ga_len > 0)
4655 {
4656 append_ga_line(&ga);
4657 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004658 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004659 }
4660 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004661 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004662 ga_clear(&ga);
4663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665 /*
4666 * Give all typeahead that wasn't used back to ui_inchar().
4667 */
4668 if (ta_len)
4669 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004670 State = old_State;
4671 if (toshell_fd >= 0)
4672 close(toshell_fd);
4673 close(fromshell_fd);
4674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676 /*
4677 * Wait until our child has exited.
4678 * Ignore wait() returning pids of other children and returning
4679 * because of some signal like SIGWINCH.
4680 * Don't wait if wait_pid was already set above, indicating the
4681 * child already exited.
4682 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004683 if (wait_pid != pid)
4684 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685
Bram Moolenaar624891f2010-10-13 16:22:09 +02004686# ifdef FEAT_GUI
4687 /* Close slave side of pty. Only do this after the child has
4688 * exited, otherwise the child may hang when it tries to write on
4689 * the pty. */
4690 if (pty_master_fd >= 0)
4691 close(pty_slave_fd);
4692# endif
4693
Bram Moolenaardf177f62005-02-22 08:39:57 +00004694 /* Make sure the child that writes to the external program is
4695 * dead. */
4696 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004697 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004698 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004699 wait4pid(wpid, NULL);
4700 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004701
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 /*
4703 * Set to raw mode right now, otherwise a CTRL-C after
4704 * catch_signals() will kill Vim.
4705 */
4706 if (tmode == TMODE_RAW)
4707 settmode(TMODE_RAW);
4708 did_settmode = TRUE;
4709 set_signals();
4710
4711 if (WIFEXITED(status))
4712 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004713 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714 retval = WEXITSTATUS(status);
4715 if (retval && !emsg_silent)
4716 {
4717 if (retval == EXEC_FAILED)
4718 {
4719 MSG_PUTS(_("\nCannot execute shell "));
4720 msg_outtrans(p_sh);
4721 msg_putchar('\n');
4722 }
4723 else if (!(options & SHELL_SILENT))
4724 {
4725 MSG_PUTS(_("\nshell returned "));
4726 msg_outnum((long)retval);
4727 msg_putchar('\n');
4728 }
4729 }
4730 }
4731 else
4732 MSG_PUTS(_("\nCommand terminated\n"));
4733 }
4734 }
4735 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004736 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737
4738error:
4739 if (!did_settmode)
4740 if (tmode == TMODE_RAW)
4741 settmode(TMODE_RAW); /* set to raw mode */
4742# ifdef FEAT_TITLE
4743 resettitle();
4744# endif
4745 vim_free(newcmd);
4746
4747 return retval;
4748
4749#endif /* USE_SYSTEM */
4750}
4751
4752/*
4753 * Check for CTRL-C typed by reading all available characters.
4754 * In cooked mode we should get SIGINT, no need to check.
4755 */
4756 void
4757mch_breakcheck()
4758{
4759 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4760 fill_input_buf(FALSE);
4761}
4762
4763/*
4764 * Wait "msec" msec until a character is available from the keyboard or from
4765 * inbuf[]. msec == -1 will block forever.
4766 * When a GUI is being used, this will never get called -- webb
4767 */
4768 static int
4769WaitForChar(msec)
4770 long msec;
4771{
4772#ifdef FEAT_MOUSE_GPM
4773 int gpm_process_wanted;
4774#endif
4775#ifdef FEAT_XCLIPBOARD
4776 int rest;
4777#endif
4778 int avail;
4779
4780 if (input_available()) /* something in inbuf[] */
4781 return 1;
4782
4783#if defined(FEAT_MOUSE_DEC)
4784 /* May need to query the mouse position. */
4785 if (WantQueryMouse)
4786 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004787 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4789 }
4790#endif
4791
4792 /*
4793 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4794 * events. This is a bit complicated, because they might both be defined.
4795 */
4796#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4797# ifdef FEAT_XCLIPBOARD
4798 rest = 0;
4799 if (do_xterm_trace())
4800 rest = msec;
4801# endif
4802 do
4803 {
4804# ifdef FEAT_XCLIPBOARD
4805 if (rest != 0)
4806 {
4807 msec = XT_TRACE_DELAY;
4808 if (rest >= 0 && rest < XT_TRACE_DELAY)
4809 msec = rest;
4810 if (rest >= 0)
4811 rest -= msec;
4812 }
4813# endif
4814# ifdef FEAT_MOUSE_GPM
4815 gpm_process_wanted = 0;
4816 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4817# else
4818 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4819# endif
4820 if (!avail)
4821 {
4822 if (input_available())
4823 return 1;
4824# ifdef FEAT_XCLIPBOARD
4825 if (rest == 0 || !do_xterm_trace())
4826# endif
4827 break;
4828 }
4829 }
4830 while (FALSE
4831# ifdef FEAT_MOUSE_GPM
4832 || (gpm_process_wanted && mch_gpm_process() == 0)
4833# endif
4834# ifdef FEAT_XCLIPBOARD
4835 || (!avail && rest != 0)
4836# endif
4837 );
4838
4839#else
4840 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4841#endif
4842 return avail;
4843}
4844
4845/*
4846 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02004847 * "msec" == 0 will check for characters once.
4848 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 * When a GUI is being used, this will not be used for input -- webb
4850 * Returns also, when a request from Sniff is waiting -- toni.
4851 * Or when a Linux GPM mouse event is waiting.
4852 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853#if defined(__BEOS__)
4854 int
4855#else
4856 static int
4857#endif
4858RealWaitForChar(fd, msec, check_for_gpm)
4859 int fd;
4860 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004861 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862{
4863 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004864#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004865 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004866#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004867#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868 static int busy = FALSE;
4869
4870 /* May retry getting characters after an event was handled. */
4871# define MAY_LOOP
4872
4873# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4874 /* Remember at what time we started, so that we know how much longer we
4875 * should wait after being interrupted. */
4876# define USE_START_TV
4877 struct timeval start_tv;
4878
4879 if (msec > 0 && (
4880# ifdef FEAT_XCLIPBOARD
4881 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004882# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 ||
4884# endif
4885# endif
4886# ifdef USE_XSMP
4887 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004888# ifdef FEAT_MZSCHEME
4889 ||
4890# endif
4891# endif
4892# ifdef FEAT_MZSCHEME
4893 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894# endif
4895 ))
4896 gettimeofday(&start_tv, NULL);
4897# endif
4898
4899 /* Handle being called recursively. This may happen for the session
4900 * manager stuff, it may save the file, which does a breakcheck. */
4901 if (busy)
4902 return 0;
4903#endif
4904
4905#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004906 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907#endif
4908 {
4909#ifdef MAY_LOOP
4910 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004911# ifdef FEAT_MZSCHEME
4912 int mzquantum_used = FALSE;
4913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914#endif
4915#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004916 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 int nfd;
4918# ifdef FEAT_XCLIPBOARD
4919 int xterm_idx = -1;
4920# endif
4921# ifdef FEAT_MOUSE_GPM
4922 int gpm_idx = -1;
4923# endif
4924# ifdef USE_XSMP
4925 int xsmp_idx = -1;
4926# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004927# ifdef FEAT_NETBEANS_INTG
4928 int nb_idx = -1;
4929# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004930 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004932# ifdef FEAT_MZSCHEME
4933 mzvim_check_threads();
4934 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4935 {
4936 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4937 mzquantum_used = TRUE;
4938 }
4939# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 fds[0].fd = fd;
4941 fds[0].events = POLLIN;
4942 nfd = 1;
4943
4944# ifdef FEAT_SNIFF
4945# define SNIFF_IDX 1
4946 if (want_sniff_request)
4947 {
4948 fds[SNIFF_IDX].fd = fd_from_sniff;
4949 fds[SNIFF_IDX].events = POLLIN;
4950 nfd++;
4951 }
4952# endif
4953# ifdef FEAT_XCLIPBOARD
4954 if (xterm_Shell != (Widget)0)
4955 {
4956 xterm_idx = nfd;
4957 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4958 fds[nfd].events = POLLIN;
4959 nfd++;
4960 }
4961# endif
4962# ifdef FEAT_MOUSE_GPM
4963 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4964 {
4965 gpm_idx = nfd;
4966 fds[nfd].fd = gpm_fd;
4967 fds[nfd].events = POLLIN;
4968 nfd++;
4969 }
4970# endif
4971# ifdef USE_XSMP
4972 if (xsmp_icefd != -1)
4973 {
4974 xsmp_idx = nfd;
4975 fds[nfd].fd = xsmp_icefd;
4976 fds[nfd].events = POLLIN;
4977 nfd++;
4978 }
4979# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004980#ifdef FEAT_NETBEANS_INTG
4981 if (nb_fd != -1)
4982 {
4983 nb_idx = nfd;
4984 fds[nfd].fd = nb_fd;
4985 fds[nfd].events = POLLIN;
4986 nfd++;
4987 }
4988#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004990 ret = poll(fds, nfd, towait);
4991# ifdef FEAT_MZSCHEME
4992 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004993 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004994 finished = FALSE;
4995# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996
4997# ifdef FEAT_SNIFF
4998 if (ret < 0)
4999 sniff_disconnect(1);
5000 else if (want_sniff_request)
5001 {
5002 if (fds[SNIFF_IDX].revents & POLLHUP)
5003 sniff_disconnect(1);
5004 if (fds[SNIFF_IDX].revents & POLLIN)
5005 sniff_request_waiting = 1;
5006 }
5007# endif
5008# ifdef FEAT_XCLIPBOARD
5009 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5010 {
5011 xterm_update(); /* Maybe we should hand out clipboard */
5012 if (--ret == 0 && !input_available())
5013 /* Try again */
5014 finished = FALSE;
5015 }
5016# endif
5017# ifdef FEAT_MOUSE_GPM
5018 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5019 {
5020 *check_for_gpm = 1;
5021 }
5022# endif
5023# ifdef USE_XSMP
5024 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5025 {
5026 if (fds[xsmp_idx].revents & POLLIN)
5027 {
5028 busy = TRUE;
5029 xsmp_handle_requests();
5030 busy = FALSE;
5031 }
5032 else if (fds[xsmp_idx].revents & POLLHUP)
5033 {
5034 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005035 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036 xsmp_close();
5037 }
5038 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005039 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 }
5041# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005042#ifdef FEAT_NETBEANS_INTG
5043 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5044 {
5045 netbeans_read();
5046 --ret;
5047 }
5048#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049
5050
5051#else /* HAVE_SELECT */
5052
5053 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005054 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 fd_set rfds, efds;
5056 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005057 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005059# ifdef FEAT_MZSCHEME
5060 mzvim_check_threads();
5061 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5062 {
5063 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5064 mzquantum_used = TRUE;
5065 }
5066# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067# ifdef __EMX__
5068 /* don't check for incoming chars if not in raw mode, because select()
5069 * always returns TRUE then (in some version of emx.dll) */
5070 if (curr_tmode != TMODE_RAW)
5071 return 0;
5072# endif
5073
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005074 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005075 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005076 tv.tv_sec = towait / 1000;
5077 tv.tv_usec = (towait % 1000) * (1000000/1000);
5078 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005079 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005080 else
5081 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082
5083 /*
5084 * Select on ready for reading and exceptional condition (end of file).
5085 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005086select_eintr:
5087 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088 FD_ZERO(&efds);
5089 FD_SET(fd, &rfds);
5090# if !defined(__QNX__) && !defined(__CYGWIN32__)
5091 /* For QNX select() always returns 1 if this is set. Why? */
5092 FD_SET(fd, &efds);
5093# endif
5094 maxfd = fd;
5095
5096# ifdef FEAT_SNIFF
5097 if (want_sniff_request)
5098 {
5099 FD_SET(fd_from_sniff, &rfds);
5100 FD_SET(fd_from_sniff, &efds);
5101 if (maxfd < fd_from_sniff)
5102 maxfd = fd_from_sniff;
5103 }
5104# endif
5105# ifdef FEAT_XCLIPBOARD
5106 if (xterm_Shell != (Widget)0)
5107 {
5108 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5109 if (maxfd < ConnectionNumber(xterm_dpy))
5110 maxfd = ConnectionNumber(xterm_dpy);
5111 }
5112# endif
5113# ifdef FEAT_MOUSE_GPM
5114 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5115 {
5116 FD_SET(gpm_fd, &rfds);
5117 FD_SET(gpm_fd, &efds);
5118 if (maxfd < gpm_fd)
5119 maxfd = gpm_fd;
5120 }
5121# endif
5122# ifdef USE_XSMP
5123 if (xsmp_icefd != -1)
5124 {
5125 FD_SET(xsmp_icefd, &rfds);
5126 FD_SET(xsmp_icefd, &efds);
5127 if (maxfd < xsmp_icefd)
5128 maxfd = xsmp_icefd;
5129 }
5130# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005131#ifdef FEAT_NETBEANS_INTG
5132 if (nb_fd != -1)
5133 {
5134 FD_SET(nb_fd, &rfds);
5135 if (maxfd < nb_fd)
5136 maxfd = nb_fd;
5137 }
5138#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005139
5140# ifdef OLD_VMS
5141 /* Old VMS as v6.2 and older have broken select(). It waits more than
5142 * required. Should not be used */
5143 ret = 0;
5144# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005145 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5146# endif
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005147# ifdef EINTR
5148 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005149 {
5150 /* Check whether window has been resized, EINTR may be caused by
5151 * SIGWINCH. */
5152 if (do_resize)
5153 handle_resize();
5154
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005155 /* Interrupted by a signal, need to try again. We ignore msec
5156 * here, because we do want to check even after a timeout if
5157 * characters are available. Needed for reading output of an
5158 * external command after the process has finished. */
5159 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005160 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005161# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005162# ifdef __TANDEM
5163 if (ret == -1 && errno == ENOTSUP)
5164 {
5165 FD_ZERO(&rfds);
5166 FD_ZERO(&efds);
5167 ret = 0;
5168 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005169# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005170# ifdef FEAT_MZSCHEME
5171 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005172 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005173 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174# endif
5175
5176# ifdef FEAT_SNIFF
5177 if (ret < 0 )
5178 sniff_disconnect(1);
5179 else if (ret > 0 && want_sniff_request)
5180 {
5181 if (FD_ISSET(fd_from_sniff, &efds))
5182 sniff_disconnect(1);
5183 if (FD_ISSET(fd_from_sniff, &rfds))
5184 sniff_request_waiting = 1;
5185 }
5186# endif
5187# ifdef FEAT_XCLIPBOARD
5188 if (ret > 0 && xterm_Shell != (Widget)0
5189 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5190 {
5191 xterm_update(); /* Maybe we should hand out clipboard */
5192 /* continue looping when we only got the X event and the input
5193 * buffer is empty */
5194 if (--ret == 0 && !input_available())
5195 {
5196 /* Try again */
5197 finished = FALSE;
5198 }
5199 }
5200# endif
5201# ifdef FEAT_MOUSE_GPM
5202 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5203 {
5204 if (FD_ISSET(gpm_fd, &efds))
5205 gpm_close();
5206 else if (FD_ISSET(gpm_fd, &rfds))
5207 *check_for_gpm = 1;
5208 }
5209# endif
5210# ifdef USE_XSMP
5211 if (ret > 0 && xsmp_icefd != -1)
5212 {
5213 if (FD_ISSET(xsmp_icefd, &efds))
5214 {
5215 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005216 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 xsmp_close();
5218 if (--ret == 0)
5219 finished = FALSE; /* keep going if event was only one */
5220 }
5221 else if (FD_ISSET(xsmp_icefd, &rfds))
5222 {
5223 busy = TRUE;
5224 xsmp_handle_requests();
5225 busy = FALSE;
5226 if (--ret == 0)
5227 finished = FALSE; /* keep going if event was only one */
5228 }
5229 }
5230# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005231#ifdef FEAT_NETBEANS_INTG
5232 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5233 {
5234 netbeans_read();
5235 --ret;
5236 }
5237#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238
5239#endif /* HAVE_SELECT */
5240
5241#ifdef MAY_LOOP
5242 if (finished || msec == 0)
5243 break;
5244
5245 /* We're going to loop around again, find out for how long */
5246 if (msec > 0)
5247 {
5248# ifdef USE_START_TV
5249 struct timeval mtv;
5250
5251 /* Compute remaining wait time. */
5252 gettimeofday(&mtv, NULL);
5253 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5254 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5255# else
5256 /* Guess we got interrupted halfway. */
5257 msec = msec / 2;
5258# endif
5259 if (msec <= 0)
5260 break; /* waited long enough */
5261 }
5262#endif
5263 }
5264
5265 return (ret > 0);
5266}
5267
5268#ifndef VMS
5269
5270#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005272 * Expand a path into all matching files and/or directories. Handles "*",
5273 * "?", "[a-z]", "**", etc.
5274 * "path" has backslashes before chars that are not to be expanded.
5275 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276 */
5277 int
5278mch_expandpath(gap, path, flags)
5279 garray_T *gap;
5280 char_u *path;
5281 int flags; /* EW_* flags */
5282{
Bram Moolenaar02743632005-07-25 20:42:36 +00005283 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284}
5285#endif
5286
5287/*
5288 * mch_expand_wildcards() - this code does wild-card pattern matching using
5289 * the shell
5290 *
5291 * return OK for success, FAIL for error (you may lose some memory) and put
5292 * an error message in *file.
5293 *
5294 * num_pat is number of input patterns
5295 * pat is array of pointers to input patterns
5296 * num_file is pointer to number of matched file names
5297 * file is pointer to array of pointers to matched file names
5298 */
5299
5300#ifndef SEEK_SET
5301# define SEEK_SET 0
5302#endif
5303#ifndef SEEK_END
5304# define SEEK_END 2
5305#endif
5306
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005307#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005308
Bram Moolenaar071d4272004-06-13 20:20:40 +00005309 int
5310mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5311 int num_pat;
5312 char_u **pat;
5313 int *num_file;
5314 char_u ***file;
5315 int flags; /* EW_* flags */
5316{
5317 int i;
5318 size_t len;
5319 char_u *p;
5320 int dir;
5321#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005322 /*
5323 * This is the OS/2 implementation.
5324 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325# define EXPL_ALLOC_INC 16
5326 char_u **expl_files;
5327 size_t files_alloced, files_free;
5328 char_u *buf;
5329 int has_wildcard;
5330
5331 *num_file = 0; /* default: no files found */
5332 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5333 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5334 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5335 if (*file == NULL)
5336 return FAIL;
5337
5338 for (; num_pat > 0; num_pat--, pat++)
5339 {
5340 expl_files = NULL;
5341 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5342 /* expand environment var or home dir */
5343 buf = expand_env_save(*pat);
5344 else
5345 buf = vim_strsave(*pat);
5346 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005347 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348 if (has_wildcard) /* yes, so expand them */
5349 expl_files = (char_u **)_fnexplode(buf);
5350
5351 /*
5352 * return value of buf if no wildcards left,
5353 * OR if no match AND EW_NOTFOUND is set.
5354 */
5355 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5356 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5357 { /* simply save the current contents of *buf */
5358 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5359 if (expl_files != NULL)
5360 {
5361 expl_files[0] = vim_strsave(buf);
5362 expl_files[1] = NULL;
5363 }
5364 }
5365 vim_free(buf);
5366
5367 /*
5368 * Count number of names resulting from expansion,
5369 * At the same time add a backslash to the end of names that happen to
5370 * be directories, and replace slashes with backslashes.
5371 */
5372 if (expl_files)
5373 {
5374 for (i = 0; (p = expl_files[i]) != NULL; i++)
5375 {
5376 dir = mch_isdir(p);
5377 /* If we don't want dirs and this is one, skip it */
5378 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5379 continue;
5380
Bram Moolenaara2031822006-03-07 22:29:51 +00005381 /* Skip files that are not executable if we check for that. */
5382 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5383 continue;
5384
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385 if (--files_free == 0)
5386 {
5387 /* need more room in table of pointers */
5388 files_alloced += EXPL_ALLOC_INC;
5389 *file = (char_u **)vim_realloc(*file,
5390 sizeof(char_u **) * files_alloced);
5391 if (*file == NULL)
5392 {
5393 EMSG(_(e_outofmem));
5394 *num_file = 0;
5395 return FAIL;
5396 }
5397 files_free = EXPL_ALLOC_INC;
5398 }
5399 slash_adjust(p);
5400 if (dir)
5401 {
5402 /* For a directory we add a '/', unless it's already
5403 * there. */
5404 len = STRLEN(p);
5405 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5406 {
5407 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005408 if (!after_pathsep((*file)[*num_file],
5409 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005410 {
5411 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005412 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413 }
5414 }
5415 }
5416 else
5417 {
5418 (*file)[*num_file] = vim_strsave(p);
5419 }
5420
5421 /*
5422 * Error message already given by either alloc or vim_strsave.
5423 * Should return FAIL, but returning OK works also.
5424 */
5425 if ((*file)[*num_file] == NULL)
5426 break;
5427 (*num_file)++;
5428 }
5429 _fnexplodefree((char **)expl_files);
5430 }
5431 }
5432 return OK;
5433
5434#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005435 /*
5436 * This is the non-OS/2 implementation (really Unix).
5437 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 int j;
5439 char_u *tempname;
5440 char_u *command;
5441 FILE *fd;
5442 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005443#define STYLE_ECHO 0 /* use "echo", the default */
5444#define STYLE_GLOB 1 /* use "glob", for csh */
5445#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5446#define STYLE_PRINT 3 /* use "print -N", for zsh */
5447#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5448 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005449 int shell_style = STYLE_ECHO;
5450 int check_spaces;
5451 static int did_find_nul = FALSE;
5452 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005453 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005454 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455
5456 *num_file = 0; /* default: no files found */
5457 *file = NULL;
5458
5459 /*
5460 * If there are no wildcards, just copy the names to allocated memory.
5461 * Saves a lot of time, because we don't have to start a new shell.
5462 */
5463 if (!have_wildcard(num_pat, pat))
5464 return save_patterns(num_pat, pat, num_file, file);
5465
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005466# ifdef HAVE_SANDBOX
5467 /* Don't allow any shell command in the sandbox. */
5468 if (sandbox != 0 && check_secure())
5469 return FAIL;
5470# endif
5471
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 /*
5473 * Don't allow the use of backticks in secure and restricted mode.
5474 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005475 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 for (i = 0; i < num_pat; ++i)
5477 if (vim_strchr(pat[i], '`') != NULL
5478 && (check_restricted() || check_secure()))
5479 return FAIL;
5480
5481 /*
5482 * get a name for the temp file
5483 */
5484 if ((tempname = vim_tempname('o')) == NULL)
5485 {
5486 EMSG(_(e_notmp));
5487 return FAIL;
5488 }
5489
5490 /*
5491 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005492 * file.
5493 * STYLE_BT: NL separated
5494 * If expanding `cmd` execute it directly.
5495 * STYLE_GLOB: NUL separated
5496 * If we use *csh, "glob" will work better than "echo".
5497 * STYLE_PRINT: NL or NUL separated
5498 * If we use *zsh, "print -N" will work better than "glob".
5499 * STYLE_VIMGLOB: NL separated
5500 * If we use *sh*, we define "vimglob()".
5501 * STYLE_ECHO: space separated.
5502 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503 */
5504 if (num_pat == 1 && *pat[0] == '`'
5505 && (len = STRLEN(pat[0])) > 2
5506 && *(pat[0] + len - 1) == '`')
5507 shell_style = STYLE_BT;
5508 else if ((len = STRLEN(p_sh)) >= 3)
5509 {
5510 if (STRCMP(p_sh + len - 3, "csh") == 0)
5511 shell_style = STYLE_GLOB;
5512 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5513 shell_style = STYLE_PRINT;
5514 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005515 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5516 "sh") != NULL)
5517 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518
Bram Moolenaarc7247912008-01-13 12:54:11 +00005519 /* Compute the length of the command. We need 2 extra bytes: for the
5520 * optional '&' and for the NUL.
5521 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005523 if (shell_style == STYLE_VIMGLOB)
5524 len += STRLEN(sh_vimglob_func);
5525
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005526 for (i = 0; i < num_pat; ++i)
5527 {
5528 /* Count the length of the patterns in the same way as they are put in
5529 * "command" below. */
5530#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005532#else
5533 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005534 for (j = 0; pat[i][j] != NUL; ++j)
5535 {
5536 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5537 ++len; /* may add a backslash */
5538 ++len;
5539 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005540#endif
5541 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 command = alloc(len);
5543 if (command == NULL)
5544 {
5545 /* out of memory */
5546 vim_free(tempname);
5547 return FAIL;
5548 }
5549
5550 /*
5551 * Build the shell command:
5552 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5553 * recognizes this).
5554 * - Add the shell command to print the expanded names.
5555 * - Add the temp file name.
5556 * - Add the file name patterns.
5557 */
5558 if (shell_style == STYLE_BT)
5559 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005560 /* change `command; command& ` to (command; command ) */
5561 STRCPY(command, "(");
5562 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005564 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565 while (p > command && vim_iswhite(*p))
5566 --p;
5567 if (*p == '&') /* remove trailing '&' */
5568 {
5569 ampersent = TRUE;
5570 *p = ' ';
5571 }
5572 STRCAT(command, ">");
5573 }
5574 else
5575 {
5576 if (flags & EW_NOTFOUND)
5577 STRCPY(command, "set nonomatch; ");
5578 else
5579 STRCPY(command, "unset nonomatch; ");
5580 if (shell_style == STYLE_GLOB)
5581 STRCAT(command, "glob >");
5582 else if (shell_style == STYLE_PRINT)
5583 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005584 else if (shell_style == STYLE_VIMGLOB)
5585 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 else
5587 STRCAT(command, "echo >");
5588 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005589
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005591
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 if (shell_style != STYLE_BT)
5593 for (i = 0; i < num_pat; ++i)
5594 {
5595 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005596 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005597 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598#ifdef USE_SYSTEM
5599 STRCAT(command, " \"");
5600 STRCAT(command, pat[i]);
5601 STRCAT(command, "\"");
5602#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005603 int intick = FALSE;
5604
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 p = command + STRLEN(command);
5606 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005607 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005608 {
5609 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005610 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005611 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5612 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005613 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005614 * backslash inside backticks, before a special character
5615 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005616 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005617 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5618 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005619 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005620 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005621 }
5622 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005623 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005624 /* Put a backslash before a special character, but not
5625 * when inside ``. */
5626 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005627
5628 /* Copy one character. */
5629 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 *p = NUL;
5632#endif
5633 }
5634 if (flags & EW_SILENT)
5635 show_shell_mess = FALSE;
5636 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005637 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638
5639 /*
5640 * Using zsh -G: If a pattern has no matches, it is just deleted from
5641 * the argument list, otherwise zsh gives an error message and doesn't
5642 * expand any other pattern.
5643 */
5644 if (shell_style == STYLE_PRINT)
5645 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5646
5647 /*
5648 * If we use -f then shell variables set in .cshrc won't get expanded.
5649 * vi can do it, so we will too, but it is only necessary if there is a "$"
5650 * in one of the patterns, otherwise we can still use the fast option.
5651 */
5652 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5653 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5654
5655 /*
5656 * execute the shell command
5657 */
5658 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5659
5660 /* When running in the background, give it some time to create the temp
5661 * file, but don't wait for it to finish. */
5662 if (ampersent)
5663 mch_delay(10L, TRUE);
5664
5665 extra_shell_arg = NULL; /* cleanup */
5666 show_shell_mess = TRUE;
5667 vim_free(command);
5668
Bram Moolenaarc7247912008-01-13 12:54:11 +00005669 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 {
5671 mch_remove(tempname);
5672 vim_free(tempname);
5673 /*
5674 * With interactive completion, the error message is not printed.
5675 * However with USE_SYSTEM, I don't know how to turn off error messages
5676 * from the shell, so screen may still get messed up -- webb.
5677 */
5678#ifndef USE_SYSTEM
5679 if (!(flags & EW_SILENT))
5680#endif
5681 {
5682 redraw_later_clear(); /* probably messed up screen */
5683 msg_putchar('\n'); /* clear bottom line quickly */
5684 cmdline_row = Rows - 1; /* continue on last line */
5685#ifdef USE_SYSTEM
5686 if (!(flags & EW_SILENT))
5687#endif
5688 {
5689 MSG(_(e_wildexpand));
5690 msg_start(); /* don't overwrite this message */
5691 }
5692 }
5693 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5694 * EW_NOTFOUND is given */
5695 if (shell_style == STYLE_BT)
5696 return FAIL;
5697 goto notfound;
5698 }
5699
5700 /*
5701 * read the names from the file into memory
5702 */
5703 fd = fopen((char *)tempname, READBIN);
5704 if (fd == NULL)
5705 {
5706 /* Something went wrong, perhaps a file name with a special char. */
5707 if (!(flags & EW_SILENT))
5708 {
5709 MSG(_(e_wildexpand));
5710 msg_start(); /* don't overwrite this message */
5711 }
5712 vim_free(tempname);
5713 goto notfound;
5714 }
5715 fseek(fd, 0L, SEEK_END);
5716 len = ftell(fd); /* get size of temp file */
5717 fseek(fd, 0L, SEEK_SET);
5718 buffer = alloc(len + 1);
5719 if (buffer == NULL)
5720 {
5721 /* out of memory */
5722 mch_remove(tempname);
5723 vim_free(tempname);
5724 fclose(fd);
5725 return FAIL;
5726 }
5727 i = fread((char *)buffer, 1, len, fd);
5728 fclose(fd);
5729 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005730 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 {
5732 /* unexpected read error */
5733 EMSG2(_(e_notread), tempname);
5734 vim_free(tempname);
5735 vim_free(buffer);
5736 return FAIL;
5737 }
5738 vim_free(tempname);
5739
Bram Moolenaarc7247912008-01-13 12:54:11 +00005740# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5742 p = buffer;
5743 for (i = 0; i < len; ++i)
5744 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5745 *p++ = buffer[i];
5746 len = p - buffer;
5747# endif
5748
5749
5750 /* file names are separated with Space */
5751 if (shell_style == STYLE_ECHO)
5752 {
5753 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5754 p = buffer;
5755 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5756 {
5757 while (*p != ' ' && *p != '\n')
5758 ++p;
5759 p = skipwhite(p); /* skip to next entry */
5760 }
5761 }
5762 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005763 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 {
5765 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5766 p = buffer;
5767 for (i = 0; *p != NUL; ++i) /* count number of entries */
5768 {
5769 while (*p != '\n' && *p != NUL)
5770 ++p;
5771 if (*p != NUL)
5772 ++p;
5773 p = skipwhite(p); /* skip leading white space */
5774 }
5775 }
5776 /* file names are separated with NUL */
5777 else
5778 {
5779 /*
5780 * Some versions of zsh use spaces instead of NULs to separate
5781 * results. Only do this when there is no NUL before the end of the
5782 * buffer, otherwise we would never be able to use file names with
5783 * embedded spaces when zsh does use NULs.
5784 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5785 * don't check for spaces again.
5786 */
5787 check_spaces = FALSE;
5788 if (shell_style == STYLE_PRINT && !did_find_nul)
5789 {
5790 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005791 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005792 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 did_find_nul = TRUE;
5794 else
5795 check_spaces = TRUE;
5796 }
5797
5798 /*
5799 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5800 * already is one, for STYLE_GLOB it needs to be added.
5801 */
5802 if (len && buffer[len - 1] == NUL)
5803 --len;
5804 else
5805 buffer[len] = NUL;
5806 i = 0;
5807 for (p = buffer; p < buffer + len; ++p)
5808 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5809 {
5810 ++i;
5811 *p = NUL;
5812 }
5813 if (len)
5814 ++i; /* count last entry */
5815 }
5816 if (i == 0)
5817 {
5818 /*
5819 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5820 * /bin/sh will happily expand it to nothing rather than returning an
5821 * error; and hey, it's good to check anyway -- webb.
5822 */
5823 vim_free(buffer);
5824 goto notfound;
5825 }
5826 *num_file = i;
5827 *file = (char_u **)alloc(sizeof(char_u *) * i);
5828 if (*file == NULL)
5829 {
5830 /* out of memory */
5831 vim_free(buffer);
5832 return FAIL;
5833 }
5834
5835 /*
5836 * Isolate the individual file names.
5837 */
5838 p = buffer;
5839 for (i = 0; i < *num_file; ++i)
5840 {
5841 (*file)[i] = p;
5842 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005843 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5844 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005846 while (!(shell_style == STYLE_ECHO && *p == ' ')
5847 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 ++p;
5849 if (p == buffer + len) /* last entry */
5850 *p = NUL;
5851 else
5852 {
5853 *p++ = NUL;
5854 p = skipwhite(p); /* skip to next entry */
5855 }
5856 }
5857 else /* NUL separates */
5858 {
5859 while (*p && p < buffer + len) /* skip entry */
5860 ++p;
5861 ++p; /* skip NUL */
5862 }
5863 }
5864
5865 /*
5866 * Move the file names to allocated memory.
5867 */
5868 for (j = 0, i = 0; i < *num_file; ++i)
5869 {
5870 /* Require the files to exist. Helps when using /bin/sh */
5871 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5872 continue;
5873
5874 /* check if this entry should be included */
5875 dir = (mch_isdir((*file)[i]));
5876 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5877 continue;
5878
Bram Moolenaara2031822006-03-07 22:29:51 +00005879 /* Skip files that are not executable if we check for that. */
5880 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5881 continue;
5882
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5884 if (p)
5885 {
5886 STRCPY(p, (*file)[i]);
5887 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005888 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889 (*file)[j++] = p;
5890 }
5891 }
5892 vim_free(buffer);
5893 *num_file = j;
5894
5895 if (*num_file == 0) /* rejected all entries */
5896 {
5897 vim_free(*file);
5898 *file = NULL;
5899 goto notfound;
5900 }
5901
5902 return OK;
5903
5904notfound:
5905 if (flags & EW_NOTFOUND)
5906 return save_patterns(num_pat, pat, num_file, file);
5907 return FAIL;
5908
5909#endif /* __EMX__ */
5910}
5911
5912#endif /* VMS */
5913
5914#ifndef __EMX__
5915 static int
5916save_patterns(num_pat, pat, num_file, file)
5917 int num_pat;
5918 char_u **pat;
5919 int *num_file;
5920 char_u ***file;
5921{
5922 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005923 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924
5925 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5926 if (*file == NULL)
5927 return FAIL;
5928 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005929 {
5930 s = vim_strsave(pat[i]);
5931 if (s != NULL)
5932 /* Be compatible with expand_filename(): halve the number of
5933 * backslashes. */
5934 backslash_halve(s);
5935 (*file)[i] = s;
5936 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 *num_file = num_pat;
5938 return OK;
5939}
5940#endif
5941
5942
5943/*
5944 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5945 * expand.
5946 */
5947 int
5948mch_has_exp_wildcard(p)
5949 char_u *p;
5950{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005951 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 {
5953#ifndef OS2
5954 if (*p == '\\' && p[1] != NUL)
5955 ++p;
5956 else
5957#endif
5958 if (vim_strchr((char_u *)
5959#ifdef VMS
5960 "*?%"
5961#else
5962# ifdef OS2
5963 "*?"
5964# else
5965 "*?[{'"
5966# endif
5967#endif
5968 , *p) != NULL)
5969 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 }
5971 return FALSE;
5972}
5973
5974/*
5975 * Return TRUE if the string "p" contains a wildcard.
5976 * Don't recognize '~' at the end as a wildcard.
5977 */
5978 int
5979mch_has_wildcard(p)
5980 char_u *p;
5981{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005982 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983 {
5984#ifndef OS2
5985 if (*p == '\\' && p[1] != NUL)
5986 ++p;
5987 else
5988#endif
5989 if (vim_strchr((char_u *)
5990#ifdef VMS
5991 "*?%$"
5992#else
5993# ifdef OS2
5994# ifdef VIM_BACKTICK
5995 "*?$`"
5996# else
5997 "*?$"
5998# endif
5999# else
6000 "*?[{`'$"
6001# endif
6002#endif
6003 , *p) != NULL
6004 || (*p == '~' && p[1] != NUL))
6005 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 }
6007 return FALSE;
6008}
6009
6010#ifndef __EMX__
6011 static int
6012have_wildcard(num, file)
6013 int num;
6014 char_u **file;
6015{
6016 int i;
6017
6018 for (i = 0; i < num; i++)
6019 if (mch_has_wildcard(file[i]))
6020 return 1;
6021 return 0;
6022}
6023
6024 static int
6025have_dollars(num, file)
6026 int num;
6027 char_u **file;
6028{
6029 int i;
6030
6031 for (i = 0; i < num; i++)
6032 if (vim_strchr(file[i], '$') != NULL)
6033 return TRUE;
6034 return FALSE;
6035}
6036#endif /* ifndef __EMX__ */
6037
6038#ifndef HAVE_RENAME
6039/*
6040 * Scaled-down version of rename(), which is missing in Xenix.
6041 * This version can only move regular files and will fail if the
6042 * destination exists.
6043 */
6044 int
6045mch_rename(src, dest)
6046 const char *src, *dest;
6047{
6048 struct stat st;
6049
6050 if (stat(dest, &st) >= 0) /* fail if destination exists */
6051 return -1;
6052 if (link(src, dest) != 0) /* link file to new name */
6053 return -1;
6054 if (mch_remove(src) == 0) /* delete link to old name */
6055 return 0;
6056 return -1;
6057}
6058#endif /* !HAVE_RENAME */
6059
6060#ifdef FEAT_MOUSE_GPM
6061/*
6062 * Initializes connection with gpm (if it isn't already opened)
6063 * Return 1 if succeeded (or connection already opened), 0 if failed
6064 */
6065 static int
6066gpm_open()
6067{
6068 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6069
6070 if (!gpm_flag)
6071 {
6072 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6073 gpm_connect.defaultMask = ~GPM_HARD;
6074 /* Default handling for mouse move*/
6075 gpm_connect.minMod = 0; /* Handle any modifier keys */
6076 gpm_connect.maxMod = 0xffff;
6077 if (Gpm_Open(&gpm_connect, 0) > 0)
6078 {
6079 /* gpm library tries to handling TSTP causes
6080 * problems. Anyways, we close connection to Gpm whenever
6081 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006082 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006084# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006086# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006087 return 1; /* succeed */
6088 }
6089 if (gpm_fd == -2)
6090 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6091 return 0;
6092 }
6093 return 1; /* already open */
6094}
6095
6096/*
6097 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098 */
6099 static void
6100gpm_close()
6101{
6102 if (gpm_flag && gpm_fd >= 0) /* if Open */
6103 Gpm_Close();
6104}
6105
6106/* Reads gpm event and adds special keys to input buf. Returns length of
6107 * generated key sequence.
6108 * This function is made after gui_send_mouse_event
6109 */
6110 static int
6111mch_gpm_process()
6112{
6113 int button;
6114 static Gpm_Event gpm_event;
6115 char_u string[6];
6116 int_u vim_modifiers;
6117 int row,col;
6118 unsigned char buttons_mask;
6119 unsigned char gpm_modifiers;
6120 static unsigned char old_buttons = 0;
6121
6122 Gpm_GetEvent(&gpm_event);
6123
6124#ifdef FEAT_GUI
6125 /* Don't put events in the input queue now. */
6126 if (hold_gui_events)
6127 return 0;
6128#endif
6129
6130 row = gpm_event.y - 1;
6131 col = gpm_event.x - 1;
6132
6133 string[0] = ESC; /* Our termcode */
6134 string[1] = 'M';
6135 string[2] = 'G';
6136 switch (GPM_BARE_EVENTS(gpm_event.type))
6137 {
6138 case GPM_DRAG:
6139 string[3] = MOUSE_DRAG;
6140 break;
6141 case GPM_DOWN:
6142 buttons_mask = gpm_event.buttons & ~old_buttons;
6143 old_buttons = gpm_event.buttons;
6144 switch (buttons_mask)
6145 {
6146 case GPM_B_LEFT:
6147 button = MOUSE_LEFT;
6148 break;
6149 case GPM_B_MIDDLE:
6150 button = MOUSE_MIDDLE;
6151 break;
6152 case GPM_B_RIGHT:
6153 button = MOUSE_RIGHT;
6154 break;
6155 default:
6156 return 0;
6157 /*Don't know what to do. Can more than one button be
6158 * reported in one event? */
6159 }
6160 string[3] = (char_u)(button | 0x20);
6161 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6162 break;
6163 case GPM_UP:
6164 string[3] = MOUSE_RELEASE;
6165 old_buttons &= ~gpm_event.buttons;
6166 break;
6167 default:
6168 return 0;
6169 }
6170 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6171 gpm_modifiers = gpm_event.modifiers;
6172 vim_modifiers = 0x0;
6173 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6174 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6175 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6176 */
6177 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6178 vim_modifiers |= MOUSE_SHIFT;
6179
6180 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6181 vim_modifiers |= MOUSE_CTRL;
6182 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6183 vim_modifiers |= MOUSE_ALT;
6184 string[3] |= vim_modifiers;
6185 string[4] = (char_u)(col + ' ' + 1);
6186 string[5] = (char_u)(row + ' ' + 1);
6187 add_to_input_buf(string, 6);
6188 return 6;
6189}
6190#endif /* FEAT_MOUSE_GPM */
6191
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006192#ifdef FEAT_SYSMOUSE
6193/*
6194 * Initialize connection with sysmouse.
6195 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6196 * output, any sysmouse output than will be processed via sig_sysmouse().
6197 * Return OK if succeeded, FAIL if failed.
6198 */
6199 static int
6200sysmouse_open()
6201{
6202 struct mouse_info mouse;
6203
6204 mouse.operation = MOUSE_MODE;
6205 mouse.u.mode.mode = 0;
6206 mouse.u.mode.signal = SIGUSR2;
6207 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6208 {
6209 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6210 mouse.operation = MOUSE_SHOW;
6211 ioctl(1, CONS_MOUSECTL, &mouse);
6212 return OK;
6213 }
6214 return FAIL;
6215}
6216
6217/*
6218 * Stop processing SIGUSR2 signals, and also make sure that
6219 * virtual console do not send us any sysmouse related signal.
6220 */
6221 static void
6222sysmouse_close()
6223{
6224 struct mouse_info mouse;
6225
6226 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6227 mouse.operation = MOUSE_MODE;
6228 mouse.u.mode.mode = 0;
6229 mouse.u.mode.signal = 0;
6230 ioctl(1, CONS_MOUSECTL, &mouse);
6231}
6232
6233/*
6234 * Gets info from sysmouse and adds special keys to input buf.
6235 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006236 static RETSIGTYPE
6237sig_sysmouse SIGDEFARG(sigarg)
6238{
6239 struct mouse_info mouse;
6240 struct video_info video;
6241 char_u string[6];
6242 int row, col;
6243 int button;
6244 int buttons;
6245 static int oldbuttons = 0;
6246
6247#ifdef FEAT_GUI
6248 /* Don't put events in the input queue now. */
6249 if (hold_gui_events)
6250 return;
6251#endif
6252
6253 mouse.operation = MOUSE_GETINFO;
6254 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6255 && ioctl(1, FBIO_MODEINFO, &video) != -1
6256 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6257 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6258 {
6259 row = mouse.u.data.y / video.vi_cheight;
6260 col = mouse.u.data.x / video.vi_cwidth;
6261 buttons = mouse.u.data.buttons;
6262 string[0] = ESC; /* Our termcode */
6263 string[1] = 'M';
6264 string[2] = 'S';
6265 if (oldbuttons == buttons && buttons != 0)
6266 {
6267 button = MOUSE_DRAG;
6268 }
6269 else
6270 {
6271 switch (buttons)
6272 {
6273 case 0:
6274 button = MOUSE_RELEASE;
6275 break;
6276 case 1:
6277 button = MOUSE_LEFT;
6278 break;
6279 case 2:
6280 button = MOUSE_MIDDLE;
6281 break;
6282 case 4:
6283 button = MOUSE_RIGHT;
6284 break;
6285 default:
6286 return;
6287 }
6288 oldbuttons = buttons;
6289 }
6290 string[3] = (char_u)(button);
6291 string[4] = (char_u)(col + ' ' + 1);
6292 string[5] = (char_u)(row + ' ' + 1);
6293 add_to_input_buf(string, 6);
6294 }
6295 return;
6296}
6297#endif /* FEAT_SYSMOUSE */
6298
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299#if defined(FEAT_LIBCALL) || defined(PROTO)
6300typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6301typedef char_u * (*INTPROCSTR)__ARGS((int));
6302typedef int (*STRPROCINT)__ARGS((char_u *));
6303typedef int (*INTPROCINT)__ARGS((int));
6304
6305/*
6306 * Call a DLL routine which takes either a string or int param
6307 * and returns an allocated string.
6308 */
6309 int
6310mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6311 char_u *libname;
6312 char_u *funcname;
6313 char_u *argstring; /* NULL when using a argint */
6314 int argint;
6315 char_u **string_result;/* NULL when using number_result */
6316 int *number_result;
6317{
6318# if defined(USE_DLOPEN)
6319 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006320 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321# else
6322 shl_t hinstLib;
6323# endif
6324 STRPROCSTR ProcAdd;
6325 INTPROCSTR ProcAddI;
6326 char_u *retval_str = NULL;
6327 int retval_int = 0;
6328 int success = FALSE;
6329
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006330 /*
6331 * Get a handle to the DLL module.
6332 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006334 /* First clear any error, it's not cleared by the dlopen() call. */
6335 (void)dlerror();
6336
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 hinstLib = dlopen((char *)libname, RTLD_LAZY
6338# ifdef RTLD_LOCAL
6339 | RTLD_LOCAL
6340# endif
6341 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006342 if (hinstLib == NULL)
6343 {
6344 /* "dlerr" must be used before dlclose() */
6345 dlerr = (char *)dlerror();
6346 if (dlerr != NULL)
6347 EMSG2(_("dlerror = \"%s\""), dlerr);
6348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349# else
6350 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6351# endif
6352
6353 /* If the handle is valid, try to get the function address. */
6354 if (hinstLib != NULL)
6355 {
6356# ifdef HAVE_SETJMP_H
6357 /*
6358 * Catch a crash when calling the library function. For example when
6359 * using a number where a string pointer is expected.
6360 */
6361 mch_startjmp();
6362 if (SETJMP(lc_jump_env) != 0)
6363 {
6364 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006365# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006366 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006367# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 mch_didjmp();
6369 }
6370 else
6371# endif
6372 {
6373 retval_str = NULL;
6374 retval_int = 0;
6375
6376 if (argstring != NULL)
6377 {
6378# if defined(USE_DLOPEN)
6379 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006380 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381# else
6382 if (shl_findsym(&hinstLib, (const char *)funcname,
6383 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6384 ProcAdd = NULL;
6385# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006386 if ((success = (ProcAdd != NULL
6387# if defined(USE_DLOPEN)
6388 && dlerr == NULL
6389# endif
6390 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 {
6392 if (string_result == NULL)
6393 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6394 else
6395 retval_str = (ProcAdd)(argstring);
6396 }
6397 }
6398 else
6399 {
6400# if defined(USE_DLOPEN)
6401 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006402 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403# else
6404 if (shl_findsym(&hinstLib, (const char *)funcname,
6405 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6406 ProcAddI = NULL;
6407# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006408 if ((success = (ProcAddI != NULL
6409# if defined(USE_DLOPEN)
6410 && dlerr == NULL
6411# endif
6412 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 {
6414 if (string_result == NULL)
6415 retval_int = ((INTPROCINT)ProcAddI)(argint);
6416 else
6417 retval_str = (ProcAddI)(argint);
6418 }
6419 }
6420
6421 /* Save the string before we free the library. */
6422 /* Assume that a "1" or "-1" result is an illegal pointer. */
6423 if (string_result == NULL)
6424 *number_result = retval_int;
6425 else if (retval_str != NULL
6426 && retval_str != (char_u *)1
6427 && retval_str != (char_u *)-1)
6428 *string_result = vim_strsave(retval_str);
6429 }
6430
6431# ifdef HAVE_SETJMP_H
6432 mch_endjmp();
6433# ifdef SIGHASARG
6434 if (lc_signal != 0)
6435 {
6436 int i;
6437
6438 /* try to find the name of this signal */
6439 for (i = 0; signal_info[i].sig != -1; i++)
6440 if (lc_signal == signal_info[i].sig)
6441 break;
6442 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6443 }
6444# endif
6445# endif
6446
Bram Moolenaar071d4272004-06-13 20:20:40 +00006447# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006448 /* "dlerr" must be used before dlclose() */
6449 if (dlerr != NULL)
6450 EMSG2(_("dlerror = \"%s\""), dlerr);
6451
6452 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 (void)dlclose(hinstLib);
6454# else
6455 (void)shl_unload(hinstLib);
6456# endif
6457 }
6458
6459 if (!success)
6460 {
6461 EMSG2(_(e_libcall), funcname);
6462 return FAIL;
6463 }
6464
6465 return OK;
6466}
6467#endif
6468
6469#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6470static int xterm_trace = -1; /* default: disabled */
6471static int xterm_button;
6472
6473/*
6474 * Setup a dummy window for X selections in a terminal.
6475 */
6476 void
6477setup_term_clip()
6478{
6479 int z = 0;
6480 char *strp = "";
6481 Widget AppShell;
6482
6483 if (!x_connect_to_server())
6484 return;
6485
6486 open_app_context();
6487 if (app_context != NULL && xterm_Shell == (Widget)0)
6488 {
6489 int (*oldhandler)();
6490#if defined(HAVE_SETJMP_H)
6491 int (*oldIOhandler)();
6492#endif
6493# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6494 struct timeval start_tv;
6495
6496 if (p_verbose > 0)
6497 gettimeofday(&start_tv, NULL);
6498# endif
6499
6500 /* Ignore X errors while opening the display */
6501 oldhandler = XSetErrorHandler(x_error_check);
6502
6503#if defined(HAVE_SETJMP_H)
6504 /* Ignore X IO errors while opening the display */
6505 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6506 mch_startjmp();
6507 if (SETJMP(lc_jump_env) != 0)
6508 {
6509 mch_didjmp();
6510 xterm_dpy = NULL;
6511 }
6512 else
6513#endif
6514 {
6515 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6516 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6517#if defined(HAVE_SETJMP_H)
6518 mch_endjmp();
6519#endif
6520 }
6521
6522#if defined(HAVE_SETJMP_H)
6523 /* Now handle X IO errors normally. */
6524 (void)XSetIOErrorHandler(oldIOhandler);
6525#endif
6526 /* Now handle X errors normally. */
6527 (void)XSetErrorHandler(oldhandler);
6528
6529 if (xterm_dpy == NULL)
6530 {
6531 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006532 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 return;
6534 }
6535
6536 /* Catch terminating error of the X server connection. */
6537 (void)XSetIOErrorHandler(x_IOerror_handler);
6538
6539# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6540 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006541 {
6542 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006544 verbose_leave();
6545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546# endif
6547
6548 /* Create a Shell to make converters work. */
6549 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6550 applicationShellWidgetClass, xterm_dpy,
6551 NULL);
6552 if (AppShell == (Widget)0)
6553 return;
6554 xterm_Shell = XtVaCreatePopupShell("VIM",
6555 topLevelShellWidgetClass, AppShell,
6556 XtNmappedWhenManaged, 0,
6557 XtNwidth, 1,
6558 XtNheight, 1,
6559 NULL);
6560 if (xterm_Shell == (Widget)0)
6561 return;
6562
6563 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006564 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 if (x11_display == NULL)
6566 x11_display = xterm_dpy;
6567
6568 XtRealizeWidget(xterm_Shell);
6569 XSync(xterm_dpy, False);
6570 xterm_update();
6571 }
6572 if (xterm_Shell != (Widget)0)
6573 {
6574 clip_init(TRUE);
6575 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6576 x11_window = (Window)atol(strp);
6577 /* Check if $WINDOWID is valid. */
6578 if (test_x11_window(xterm_dpy) == FAIL)
6579 x11_window = 0;
6580 if (x11_window != 0)
6581 xterm_trace = 0;
6582 }
6583}
6584
6585 void
6586start_xterm_trace(button)
6587 int button;
6588{
6589 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6590 return;
6591 xterm_trace = 1;
6592 xterm_button = button;
6593 do_xterm_trace();
6594}
6595
6596
6597 void
6598stop_xterm_trace()
6599{
6600 if (xterm_trace < 0)
6601 return;
6602 xterm_trace = 0;
6603}
6604
6605/*
6606 * Query the xterm pointer and generate mouse termcodes if necessary
6607 * return TRUE if dragging is active, else FALSE
6608 */
6609 static int
6610do_xterm_trace()
6611{
6612 Window root, child;
6613 int root_x, root_y;
6614 int win_x, win_y;
6615 int row, col;
6616 int_u mask_return;
6617 char_u buf[50];
6618 char_u *strp;
6619 long got_hints;
6620 static char_u *mouse_code;
6621 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6622 static int prev_row = 0, prev_col = 0;
6623 static XSizeHints xterm_hints;
6624
6625 if (xterm_trace <= 0)
6626 return FALSE;
6627
6628 if (xterm_trace == 1)
6629 {
6630 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006631 * have changed recently. */
6632 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6633 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 || xterm_hints.width_inc <= 1
6635 || xterm_hints.height_inc <= 1)
6636 {
6637 xterm_trace = -1; /* Not enough data -- disable tracing */
6638 return FALSE;
6639 }
6640
6641 /* Rely on the same mouse code for the duration of this */
6642 mouse_code = find_termcode(mouse_name);
6643 prev_row = mouse_row;
6644 prev_row = mouse_col;
6645 xterm_trace = 2;
6646
6647 /* Find the offset of the chars, there might be a scrollbar on the
6648 * left of the window and/or a menu on the top (eterm etc.) */
6649 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6650 &win_x, &win_y, &mask_return);
6651 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6652 - (xterm_hints.height_inc / 2);
6653 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6654 xterm_hints.y = 2;
6655 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6656 - (xterm_hints.width_inc / 2);
6657 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6658 xterm_hints.x = 2;
6659 return TRUE;
6660 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006661 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 {
6663 xterm_trace = 0;
6664 return FALSE;
6665 }
6666
6667 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6668 &win_x, &win_y, &mask_return);
6669
6670 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6671 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6672 if (row == prev_row && col == prev_col)
6673 return TRUE;
6674
6675 STRCPY(buf, mouse_code);
6676 strp = buf + STRLEN(buf);
6677 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6678 *strp++ = (char_u)(col + ' ' + 1);
6679 *strp++ = (char_u)(row + ' ' + 1);
6680 *strp = 0;
6681 add_to_input_buf(buf, STRLEN(buf));
6682
6683 prev_row = row;
6684 prev_col = col;
6685 return TRUE;
6686}
6687
6688# if defined(FEAT_GUI) || defined(PROTO)
6689/*
6690 * Destroy the display, window and app_context. Required for GTK.
6691 */
6692 void
6693clear_xterm_clip()
6694{
6695 if (xterm_Shell != (Widget)0)
6696 {
6697 XtDestroyWidget(xterm_Shell);
6698 xterm_Shell = (Widget)0;
6699 }
6700 if (xterm_dpy != NULL)
6701 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006702# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 /* Lesstif and Solaris crash here, lose some memory */
6704 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006705# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 if (x11_display == xterm_dpy)
6707 x11_display = NULL;
6708 xterm_dpy = NULL;
6709 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006710# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 if (app_context != (XtAppContext)NULL)
6712 {
6713 /* Lesstif and Solaris crash here, lose some memory */
6714 XtDestroyApplicationContext(app_context);
6715 app_context = (XtAppContext)NULL;
6716 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718}
6719# endif
6720
6721/*
6722 * Catch up with any queued X events. This may put keyboard input into the
6723 * input buffer, call resize call-backs, trigger timers etc. If there is
6724 * nothing in the X event queue (& no timers pending), then we return
6725 * immediately.
6726 */
6727 static void
6728xterm_update()
6729{
6730 XEvent event;
6731
6732 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6733 {
6734 XtAppNextEvent(app_context, &event);
6735#ifdef FEAT_CLIENTSERVER
6736 {
6737 XPropertyEvent *e = (XPropertyEvent *)&event;
6738
6739 if (e->type == PropertyNotify && e->window == commWindow
6740 && e->atom == commProperty && e->state == PropertyNewValue)
6741 serverEventProc(xterm_dpy, &event);
6742 }
6743#endif
6744 XtDispatchEvent(&event);
6745 }
6746}
6747
6748 int
6749clip_xterm_own_selection(cbd)
6750 VimClipboard *cbd;
6751{
6752 if (xterm_Shell != (Widget)0)
6753 return clip_x11_own_selection(xterm_Shell, cbd);
6754 return FAIL;
6755}
6756
6757 void
6758clip_xterm_lose_selection(cbd)
6759 VimClipboard *cbd;
6760{
6761 if (xterm_Shell != (Widget)0)
6762 clip_x11_lose_selection(xterm_Shell, cbd);
6763}
6764
6765 void
6766clip_xterm_request_selection(cbd)
6767 VimClipboard *cbd;
6768{
6769 if (xterm_Shell != (Widget)0)
6770 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6771}
6772
6773 void
6774clip_xterm_set_selection(cbd)
6775 VimClipboard *cbd;
6776{
6777 clip_x11_set_selection(cbd);
6778}
6779#endif
6780
6781
6782#if defined(USE_XSMP) || defined(PROTO)
6783/*
6784 * Code for X Session Management Protocol.
6785 */
6786static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6787static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6788static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6789static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6790static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6791
6792
6793# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6794static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6795
6796/*
6797 * This is our chance to ask the user if they want to save,
6798 * or abort the logout
6799 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800 static void
6801xsmp_handle_interaction(smc_conn, client_data)
6802 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006803 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804{
6805 cmdmod_T save_cmdmod;
6806 int cancel_shutdown = False;
6807
6808 save_cmdmod = cmdmod;
6809 cmdmod.confirm = TRUE;
6810 if (check_changed_any(FALSE))
6811 /* Mustn't logout */
6812 cancel_shutdown = True;
6813 cmdmod = save_cmdmod;
6814 setcursor(); /* position cursor */
6815 out_flush();
6816
6817 /* Done interaction */
6818 SmcInteractDone(smc_conn, cancel_shutdown);
6819
6820 /* Finish off
6821 * Only end save-yourself here if we're not cancelling shutdown;
6822 * we'll get a cancelled callback later in which we'll end it.
6823 * Hopefully get around glitchy SMs (like GNOME-1)
6824 */
6825 if (!cancel_shutdown)
6826 {
6827 xsmp.save_yourself = False;
6828 SmcSaveYourselfDone(smc_conn, True);
6829 }
6830}
6831# endif
6832
6833/*
6834 * Callback that starts save-yourself.
6835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 static void
6837xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6838 shutdown, interact_style, fast)
6839 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006840 SmPointer client_data UNUSED;
6841 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006843 int interact_style UNUSED;
6844 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845{
6846 /* Handle already being in saveyourself */
6847 if (xsmp.save_yourself)
6848 SmcSaveYourselfDone(smc_conn, True);
6849 xsmp.save_yourself = True;
6850 xsmp.shutdown = shutdown;
6851
6852 /* First up, preserve all files */
6853 out_flush();
6854 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6855
6856 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006857 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858
6859# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6860 /* Now see if we can ask about unsaved files */
6861 if (shutdown && !fast && gui.in_use)
6862 /* Need to interact with user, but need SM's permission */
6863 SmcInteractRequest(smc_conn, SmDialogError,
6864 xsmp_handle_interaction, client_data);
6865 else
6866# endif
6867 {
6868 /* Can stop the cycle here */
6869 SmcSaveYourselfDone(smc_conn, True);
6870 xsmp.save_yourself = False;
6871 }
6872}
6873
6874
6875/*
6876 * Callback to warn us of imminent death.
6877 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 static void
6879xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006880 SmcConn smc_conn UNUSED;
6881 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882{
6883 xsmp_close();
6884
6885 /* quit quickly leaving swapfiles for modified buffers behind */
6886 getout_preserve_modified(0);
6887}
6888
6889
6890/*
6891 * Callback to tell us that save-yourself has completed.
6892 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893 static void
6894xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006895 SmcConn smc_conn UNUSED;
6896 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897{
6898 xsmp.save_yourself = False;
6899}
6900
6901
6902/*
6903 * Callback to tell us that an instigated shutdown was cancelled
6904 * (maybe even by us)
6905 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 static void
6907xsmp_shutdown_cancelled(smc_conn, client_data)
6908 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006909 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910{
6911 if (xsmp.save_yourself)
6912 SmcSaveYourselfDone(smc_conn, True);
6913 xsmp.save_yourself = False;
6914 xsmp.shutdown = False;
6915}
6916
6917
6918/*
6919 * Callback to tell us that a new ICE connection has been established.
6920 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 static void
6922xsmp_ice_connection(iceConn, clientData, opening, watchData)
6923 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006924 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006926 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927{
6928 /* Intercept creation of ICE connection fd */
6929 if (opening)
6930 {
6931 xsmp_icefd = IceConnectionNumber(iceConn);
6932 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6933 }
6934}
6935
6936
6937/* Handle any ICE processing that's required; return FAIL if SM lost */
6938 int
6939xsmp_handle_requests()
6940{
6941 Bool rep;
6942
6943 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6944 == IceProcessMessagesIOError)
6945 {
6946 /* Lost ICE */
6947 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006948 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 xsmp_close();
6950 return FAIL;
6951 }
6952 else
6953 return OK;
6954}
6955
6956static int dummy;
6957
6958/* Set up X Session Management Protocol */
6959 void
6960xsmp_init(void)
6961{
6962 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 SmcCallbacks smcallbacks;
6964#if 0
6965 SmPropValue smname;
6966 SmProp smnameprop;
6967 SmProp *smprops[1];
6968#endif
6969
6970 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006971 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972
6973 xsmp.save_yourself = xsmp.shutdown = False;
6974
6975 /* Set up SM callbacks - must have all, even if they're not used */
6976 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6977 smcallbacks.save_yourself.client_data = NULL;
6978 smcallbacks.die.callback = xsmp_die;
6979 smcallbacks.die.client_data = NULL;
6980 smcallbacks.save_complete.callback = xsmp_save_complete;
6981 smcallbacks.save_complete.client_data = NULL;
6982 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6983 smcallbacks.shutdown_cancelled.client_data = NULL;
6984
6985 /* Set up a watch on ICE connection creations. The "dummy" argument is
6986 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6987 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6988 {
6989 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006990 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 return;
6992 }
6993
6994 /* Create an SM connection */
6995 xsmp.smcconn = SmcOpenConnection(
6996 NULL,
6997 NULL,
6998 SmProtoMajor,
6999 SmProtoMinor,
7000 SmcSaveYourselfProcMask | SmcDieProcMask
7001 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7002 &smcallbacks,
7003 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007004 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005 sizeof(errorstring),
7006 errorstring);
7007 if (xsmp.smcconn == NULL)
7008 {
7009 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007010
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007012 {
7013 vim_snprintf(errorreport, sizeof(errorreport),
7014 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7015 verb_msg((char_u *)errorreport);
7016 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 return;
7018 }
7019 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7020
7021#if 0
7022 /* ID ourselves */
7023 smname.value = "vim";
7024 smname.length = 3;
7025 smnameprop.name = "SmProgram";
7026 smnameprop.type = "SmARRAY8";
7027 smnameprop.num_vals = 1;
7028 smnameprop.vals = &smname;
7029
7030 smprops[0] = &smnameprop;
7031 SmcSetProperties(xsmp.smcconn, 1, smprops);
7032#endif
7033}
7034
7035
7036/* Shut down XSMP comms. */
7037 void
7038xsmp_close()
7039{
7040 if (xsmp_icefd != -1)
7041 {
7042 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007043 if (xsmp.clientid != NULL)
7044 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007045 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 xsmp_icefd = -1;
7047 }
7048}
7049#endif /* USE_XSMP */
7050
7051
7052#ifdef EBCDIC
7053/* Translate character to its CTRL- value */
7054char CtrlTable[] =
7055{
7056/* 00 - 5E */
7057 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7058 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7059 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7060 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7061 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7062 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7063/* ^ */ 0x1E,
7064/* - */ 0x1F,
7065/* 61 - 6C */
7066 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7067/* _ */ 0x1F,
7068/* 6E - 80 */
7069 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7070/* a */ 0x01,
7071/* b */ 0x02,
7072/* c */ 0x03,
7073/* d */ 0x37,
7074/* e */ 0x2D,
7075/* f */ 0x2E,
7076/* g */ 0x2F,
7077/* h */ 0x16,
7078/* i */ 0x05,
7079/* 8A - 90 */
7080 0, 0, 0, 0, 0, 0, 0,
7081/* j */ 0x15,
7082/* k */ 0x0B,
7083/* l */ 0x0C,
7084/* m */ 0x0D,
7085/* n */ 0x0E,
7086/* o */ 0x0F,
7087/* p */ 0x10,
7088/* q */ 0x11,
7089/* r */ 0x12,
7090/* 9A - A1 */
7091 0, 0, 0, 0, 0, 0, 0, 0,
7092/* s */ 0x13,
7093/* t */ 0x3C,
7094/* u */ 0x3D,
7095/* v */ 0x32,
7096/* w */ 0x26,
7097/* x */ 0x18,
7098/* y */ 0x19,
7099/* z */ 0x3F,
7100/* AA - AC */
7101 0, 0, 0,
7102/* [ */ 0x27,
7103/* AE - BC */
7104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7105/* ] */ 0x1D,
7106/* BE - C0 */ 0, 0, 0,
7107/* A */ 0x01,
7108/* B */ 0x02,
7109/* C */ 0x03,
7110/* D */ 0x37,
7111/* E */ 0x2D,
7112/* F */ 0x2E,
7113/* G */ 0x2F,
7114/* H */ 0x16,
7115/* I */ 0x05,
7116/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7117/* J */ 0x15,
7118/* K */ 0x0B,
7119/* L */ 0x0C,
7120/* M */ 0x0D,
7121/* N */ 0x0E,
7122/* O */ 0x0F,
7123/* P */ 0x10,
7124/* Q */ 0x11,
7125/* R */ 0x12,
7126/* DA - DF */ 0, 0, 0, 0, 0, 0,
7127/* \ */ 0x1C,
7128/* E1 */ 0,
7129/* S */ 0x13,
7130/* T */ 0x3C,
7131/* U */ 0x3D,
7132/* V */ 0x32,
7133/* W */ 0x26,
7134/* X */ 0x18,
7135/* Y */ 0x19,
7136/* Z */ 0x3F,
7137/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7138 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7139};
7140
7141char MetaCharTable[]=
7142{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7143 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7144 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7145 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7146 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7147};
7148
7149
7150/* TODO: Use characters NOT numbers!!! */
7151char CtrlCharTable[]=
7152{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7153 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7154 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7155 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7156 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7157};
7158
7159
7160#endif