blob: 391af9cb13ffd9077655b4aa97cfdb4b1a55c2e4 [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
157static int WaitForChar __ARGS((long));
158#if defined(__BEOS__)
159int RealWaitForChar __ARGS((int, long, int *));
160#else
161static int RealWaitForChar __ARGS((int, long, int *));
162#endif
163
164#ifdef FEAT_XCLIPBOARD
165static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000166# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167#endif
168
169static void handle_resize __ARGS((void));
170
171#if defined(SIGWINCH)
172static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
173#endif
174#if defined(SIGINT)
175static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
176#endif
177#if defined(SIGPWR)
178static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
179#endif
180#if defined(SIGALRM) && defined(FEAT_X11) \
181 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
182# define SET_SIG_ALARM
183static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000184/* volatile because it is used in signal handler sig_alarm(). */
185static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000186#endif
187static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
188
Bram Moolenaardf177f62005-02-22 08:39:57 +0000189static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190static void set_signals __ARGS((void));
191static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
192#ifndef __EMX__
193static int have_wildcard __ARGS((int, char_u **));
194static int have_dollars __ARGS((int, char_u **));
195#endif
196
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197#ifndef __EMX__
198static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
199#endif
200
201#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000202# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203#endif
204
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000205/* volatile because it is used in signal handler sig_winch(). */
206static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207#ifndef __EMX__
208static char_u *extra_shell_arg = NULL;
209static int show_shell_mess = TRUE;
210#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000211/* volatile because it is used in signal handler deathtrap(). */
212static volatile int deadly_signal = 0; /* The signal we caught */
213/* volatile because it is used in signal handler deathtrap(). */
214static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215
216static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
217
218#ifdef USE_XSMP
219typedef struct
220{
221 SmcConn smcconn; /* The SM connection ID */
222 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200223 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224 Bool save_yourself; /* If we're in the middle of a save_yourself */
225 Bool shutdown; /* If we're in shutdown mode */
226} xsmp_config_T;
227
228static xsmp_config_T xsmp;
229#endif
230
231#ifdef SYS_SIGLIST_DECLARED
232/*
233 * I have seen
234 * extern char *_sys_siglist[NSIG];
235 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
236 * that describe the signals. That is nearly what we want here. But
237 * autoconf does only check for sys_siglist (without the underscore), I
238 * do not want to change everything today.... jw.
239 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
240 */
241#endif
242
243static struct signalinfo
244{
245 int sig; /* Signal number, eg. SIGSEGV etc */
246 char *name; /* Signal name (not char_u!). */
247 char deadly; /* Catch as a deadly signal? */
248} signal_info[] =
249{
250#ifdef SIGHUP
251 {SIGHUP, "HUP", TRUE},
252#endif
253#ifdef SIGQUIT
254 {SIGQUIT, "QUIT", TRUE},
255#endif
256#ifdef SIGILL
257 {SIGILL, "ILL", TRUE},
258#endif
259#ifdef SIGTRAP
260 {SIGTRAP, "TRAP", TRUE},
261#endif
262#ifdef SIGABRT
263 {SIGABRT, "ABRT", TRUE},
264#endif
265#ifdef SIGEMT
266 {SIGEMT, "EMT", TRUE},
267#endif
268#ifdef SIGFPE
269 {SIGFPE, "FPE", TRUE},
270#endif
271#ifdef SIGBUS
272 {SIGBUS, "BUS", TRUE},
273#endif
274#ifdef SIGSEGV
275 {SIGSEGV, "SEGV", TRUE},
276#endif
277#ifdef SIGSYS
278 {SIGSYS, "SYS", TRUE},
279#endif
280#ifdef SIGALRM
281 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
282#endif
283#ifdef SIGTERM
284 {SIGTERM, "TERM", TRUE},
285#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100286#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 {SIGVTALRM, "VTALRM", TRUE},
288#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000289#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
290 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
291 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 {SIGPROF, "PROF", TRUE},
293#endif
294#ifdef SIGXCPU
295 {SIGXCPU, "XCPU", TRUE},
296#endif
297#ifdef SIGXFSZ
298 {SIGXFSZ, "XFSZ", TRUE},
299#endif
300#ifdef SIGUSR1
301 {SIGUSR1, "USR1", TRUE},
302#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000303#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
304 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305 {SIGUSR2, "USR2", TRUE},
306#endif
307#ifdef SIGINT
308 {SIGINT, "INT", FALSE},
309#endif
310#ifdef SIGWINCH
311 {SIGWINCH, "WINCH", FALSE},
312#endif
313#ifdef SIGTSTP
314 {SIGTSTP, "TSTP", FALSE},
315#endif
316#ifdef SIGPIPE
317 {SIGPIPE, "PIPE", FALSE},
318#endif
319 {-1, "Unknown!", FALSE}
320};
321
Bram Moolenaar25724922009-07-14 15:38:41 +0000322 int
323mch_chdir(path)
324 char *path;
325{
326 if (p_verbose >= 5)
327 {
328 verbose_enter();
329 smsg((char_u *)"chdir(%s)", path);
330 verbose_leave();
331 }
332# ifdef VMS
333 return chdir(vms_fixfilename(path));
334# else
335 return chdir(path);
336# endif
337}
338
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000339/*
340 * Write s[len] to the screen.
341 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000342 void
343mch_write(s, len)
344 char_u *s;
345 int len;
346{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000347 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348 if (p_wd) /* Unix is too fast, slow down a bit more */
349 RealWaitForChar(read_cmd_fd, p_wd, NULL);
350}
351
352/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000353 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000354 * Get a characters from the keyboard.
355 * Return the number of characters that are available.
356 * If wtime == 0 do not wait for characters.
357 * If wtime == n wait a short time for characters.
358 * If wtime == -1 wait forever for characters.
359 */
360 int
361mch_inchar(buf, maxlen, wtime, tb_change_cnt)
362 char_u *buf;
363 int maxlen;
364 long wtime; /* don't use "time", MIPS cannot handle it */
365 int tb_change_cnt;
366{
367 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368
Bram Moolenaar67c53842010-05-22 18:28:27 +0200369#ifdef FEAT_NETBEANS_INTG
370 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200371 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200372#endif
373
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 /* Check if window changed size while we were busy, perhaps the ":set
375 * columns=99" command was used. */
376 while (do_resize)
377 handle_resize();
378
379 if (wtime >= 0)
380 {
381 while (WaitForChar(wtime) == 0) /* no character available */
382 {
383 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000384 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200386#ifdef FEAT_NETBEANS_INTG
387 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200388 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200389#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390 }
391 }
392 else /* wtime == -1 */
393 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 /*
395 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000396 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 * Also done when interrupted by SIGWINCH.
398 */
399 if (WaitForChar(p_ut) == 0)
400 {
401#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000402 if (trigger_cursorhold() && maxlen >= 3
403 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000405 buf[0] = K_SPECIAL;
406 buf[1] = KS_EXTRA;
407 buf[2] = (int)KE_CURSORHOLD;
408 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000411 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 }
413 }
414
415 for (;;) /* repeat until we got a character */
416 {
417 while (do_resize) /* window changed size */
418 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200419
420#ifdef FEAT_NETBEANS_INTG
421 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200422 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200423#endif
Bram Moolenaar48bae372010-07-29 23:12:15 +0200424#ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200426 * We want to be interrupted by the winch signal
427 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200429 if (WaitForChar(-1L) == 0)
430 {
431 if (do_resize) /* interrupted by SIGWINCH signal */
432 handle_resize();
433 return 0;
434 }
Bram Moolenaar48bae372010-07-29 23:12:15 +0200435#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436
437 /* If input was put directly in typeahead buffer bail out here. */
438 if (typebuf_changed(tb_change_cnt))
439 return 0;
440
441 /*
442 * For some terminals we only get one character at a time.
443 * We want the get all available characters, so we could keep on
444 * trying until none is available
445 * For some other terminals this is quite slow, that's why we don't do
446 * it.
447 */
448 len = read_from_input_buf(buf, (long)maxlen);
449 if (len > 0)
450 {
451#ifdef OS2
452 int i;
453
454 for (i = 0; i < len; i++)
455 if (buf[i] == 0)
456 buf[i] = K_NUL;
457#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 return len;
459 }
460 }
461}
462
463 static void
464handle_resize()
465{
466 do_resize = FALSE;
467 shell_resized();
468}
469
470/*
471 * return non-zero if a character is available
472 */
473 int
474mch_char_avail()
475{
476 return WaitForChar(0L);
477}
478
479#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
480# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000481# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482# endif
483# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
484# include <sys/sysctl.h>
485# endif
486# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
487# include <sys/sysinfo.h>
488# endif
489
490/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000491 * Return total amount of memory available in Kbyte.
492 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000494 long_u
495mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000496 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497{
498# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000499 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500# else
501 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000502 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503
504# ifdef HAVE_SYSCTL
505 int mib[2], physmem;
506 size_t len;
507
508 /* BSD way of getting the amount of RAM available. */
509 mib[0] = CTL_HW;
510 mib[1] = HW_USERMEM;
511 len = sizeof(physmem);
512 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
513 mem = (long_u)physmem;
514# endif
515
516# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
517 if (mem == 0)
518 {
519 struct sysinfo sinfo;
520
521 /* Linux way of getting amount of RAM available */
522 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000523 {
524# ifdef HAVE_SYSINFO_MEM_UNIT
525 /* avoid overflow as much as possible */
526 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
527 {
528 sinfo.mem_unit = sinfo.mem_unit >> 1;
529 --shiftright;
530 }
531 mem = sinfo.totalram * sinfo.mem_unit;
532# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000534# endif
535 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 }
537# endif
538
539# ifdef HAVE_SYSCONF
540 if (mem == 0)
541 {
542 long pagesize, pagecount;
543
544 /* Solaris way of getting amount of RAM available */
545 pagesize = sysconf(_SC_PAGESIZE);
546 pagecount = sysconf(_SC_PHYS_PAGES);
547 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000548 {
549 /* avoid overflow as much as possible */
550 while (shiftright > 0 && (pagesize & 1) == 0)
551 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000552 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000553 --shiftright;
554 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557 }
558# endif
559
560 /* Return the minimum of the physical memory and the user limit, because
561 * using more than the user limit may cause Vim to be terminated. */
562# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
563 {
564 struct rlimit rlp;
565
566 if (getrlimit(RLIMIT_DATA, &rlp) == 0
567 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
568# ifdef RLIM_INFINITY
569 && rlp.rlim_cur != RLIM_INFINITY
570# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000571 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000573 {
574 mem = (long_u)rlp.rlim_cur;
575 shiftright = 10;
576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 }
578# endif
579
580 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000581 return mem >> shiftright;
582 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583# endif
584}
585#endif
586
587 void
588mch_delay(msec, ignoreinput)
589 long msec;
590 int ignoreinput;
591{
592 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000593#ifdef FEAT_MZSCHEME
594 long total = msec; /* remember original value */
595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596
597 if (ignoreinput)
598 {
599 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000600 * here. But we don't want QUIT to kill us (CTRL-\ used in a
601 * shell may produce SIGQUIT). */
602 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 old_tmode = curr_tmode;
604 if (curr_tmode == TMODE_RAW)
605 settmode(TMODE_SLEEP);
606
607 /*
608 * Everybody sleeps in a different way...
609 * Prefer nanosleep(), some versions of usleep() can only sleep up to
610 * one second.
611 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000612#ifdef FEAT_MZSCHEME
613 do
614 {
615 /* if total is large enough, wait by portions in p_mzq */
616 if (total > p_mzq)
617 msec = p_mzq;
618 else
619 msec = total;
620 total -= msec;
621#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622#ifdef HAVE_NANOSLEEP
623 {
624 struct timespec ts;
625
626 ts.tv_sec = msec / 1000;
627 ts.tv_nsec = (msec % 1000) * 1000000;
628 (void)nanosleep(&ts, NULL);
629 }
630#else
631# ifdef HAVE_USLEEP
632 while (msec >= 1000)
633 {
634 usleep((unsigned int)(999 * 1000));
635 msec -= 999;
636 }
637 usleep((unsigned int)(msec * 1000));
638# else
639# ifndef HAVE_SELECT
640 poll(NULL, 0, (int)msec);
641# else
642# ifdef __EMX__
643 _sleep2(msec);
644# else
645 {
646 struct timeval tv;
647
648 tv.tv_sec = msec / 1000;
649 tv.tv_usec = (msec % 1000) * 1000;
650 /*
651 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
652 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
653 */
654 select(0, NULL, NULL, NULL, &tv);
655 }
656# endif /* __EMX__ */
657# endif /* HAVE_SELECT */
658# endif /* HAVE_NANOSLEEP */
659#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000660#ifdef FEAT_MZSCHEME
661 }
662 while (total > 0);
663#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664
665 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000666 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 }
668 else
669 WaitForChar(msec);
670}
671
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000672#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
674# define HAVE_CHECK_STACK_GROWTH
675/*
676 * Support for checking for an almost-out-of-stack-space situation.
677 */
678
679/*
680 * Return a pointer to an item on the stack. Used to find out if the stack
681 * grows up or down.
682 */
683static void check_stack_growth __ARGS((char *p));
684static int stack_grows_downwards;
685
686/*
687 * Find out if the stack grows upwards or downwards.
688 * "p" points to a variable on the stack of the caller.
689 */
690 static void
691check_stack_growth(p)
692 char *p;
693{
694 int i;
695
696 stack_grows_downwards = (p > (char *)&i);
697}
698#endif
699
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000700#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701static char *stack_limit = NULL;
702
703#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
704# include <pthread.h>
705# include <pthread_np.h>
706#endif
707
708/*
709 * Find out until how var the stack can grow without getting into trouble.
710 * Called when starting up and when switching to the signal stack in
711 * deathtrap().
712 */
713 static void
714get_stack_limit()
715{
716 struct rlimit rlp;
717 int i;
718 long lim;
719
720 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
721 * limit doesn't fit in a long (rlim_cur might be "long long"). */
722 if (getrlimit(RLIMIT_STACK, &rlp) == 0
723 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
724# ifdef RLIM_INFINITY
725 && rlp.rlim_cur != RLIM_INFINITY
726# endif
727 )
728 {
729 lim = (long)rlp.rlim_cur;
730#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
731 {
732 pthread_attr_t attr;
733 size_t size;
734
735 /* On FreeBSD the initial thread always has a fixed stack size, no
736 * matter what the limits are set to. Normally it's 1 Mbyte. */
737 pthread_attr_init(&attr);
738 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
739 {
740 pthread_attr_getstacksize(&attr, &size);
741 if (lim > (long)size)
742 lim = (long)size;
743 }
744 pthread_attr_destroy(&attr);
745 }
746#endif
747 if (stack_grows_downwards)
748 {
749 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
750 if (stack_limit >= (char *)&i)
751 /* overflow, set to 1/16 of current stack position */
752 stack_limit = (char *)((long)&i / 16L);
753 }
754 else
755 {
756 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
757 if (stack_limit <= (char *)&i)
758 stack_limit = NULL; /* overflow */
759 }
760 }
761}
762
763/*
764 * Return FAIL when running out of stack space.
765 * "p" must point to any variable local to the caller that's on the stack.
766 */
767 int
768mch_stackcheck(p)
769 char *p;
770{
771 if (stack_limit != NULL)
772 {
773 if (stack_grows_downwards)
774 {
775 if (p < stack_limit)
776 return FAIL;
777 }
778 else if (p > stack_limit)
779 return FAIL;
780 }
781 return OK;
782}
783#endif
784
785#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
786/*
787 * Support for using the signal stack.
788 * This helps when we run out of stack space, which causes a SIGSEGV. The
789 * signal handler then must run on another stack, since the normal stack is
790 * completely full.
791 */
792
793#ifndef SIGSTKSZ
794# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
795#endif
796
797# ifdef HAVE_SIGALTSTACK
798static stack_t sigstk; /* for sigaltstack() */
799# else
800static struct sigstack sigstk; /* for sigstack() */
801# endif
802
803static void init_signal_stack __ARGS((void));
804static char *signal_stack;
805
806 static void
807init_signal_stack()
808{
809 if (signal_stack != NULL)
810 {
811# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000812# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
813 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
815 * "struct sigaltstack" needs to be declared. */
816 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
817# endif
818
819# ifdef HAVE_SS_BASE
820 sigstk.ss_base = signal_stack;
821# else
822 sigstk.ss_sp = signal_stack;
823# endif
824 sigstk.ss_size = SIGSTKSZ;
825 sigstk.ss_flags = 0;
826 (void)sigaltstack(&sigstk, NULL);
827# else
828 sigstk.ss_sp = signal_stack;
829 if (stack_grows_downwards)
830 sigstk.ss_sp += SIGSTKSZ - 1;
831 sigstk.ss_onstack = 0;
832 (void)sigstack(&sigstk, NULL);
833# endif
834 }
835}
836#endif
837
838/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000839 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840 * will barf when the second argument to signal() is ``wrong''.
841 * Let me try it with a few tricky defines from my own osdef.h (jw).
842 */
843#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844 static RETSIGTYPE
845sig_winch SIGDEFARG(sigarg)
846{
847 /* this is not required on all systems, but it doesn't hurt anybody */
848 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
849 do_resize = TRUE;
850 SIGRETURN;
851}
852#endif
853
854#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855 static RETSIGTYPE
856catch_sigint SIGDEFARG(sigarg)
857{
858 /* this is not required on all systems, but it doesn't hurt anybody */
859 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
860 got_int = TRUE;
861 SIGRETURN;
862}
863#endif
864
865#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 static RETSIGTYPE
867catch_sigpwr SIGDEFARG(sigarg)
868{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000869 /* this is not required on all systems, but it doesn't hurt anybody */
870 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871 /*
872 * I'm not sure we get the SIGPWR signal when the system is really going
873 * down or when the batteries are almost empty. Just preserve the swap
874 * files and don't exit, that can't do any harm.
875 */
876 ml_sync_all(FALSE, FALSE);
877 SIGRETURN;
878}
879#endif
880
881#ifdef SET_SIG_ALARM
882/*
883 * signal function for alarm().
884 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885 static RETSIGTYPE
886sig_alarm SIGDEFARG(sigarg)
887{
888 /* doesn't do anything, just to break a system call */
889 sig_alarm_called = TRUE;
890 SIGRETURN;
891}
892#endif
893
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000894#if (defined(HAVE_SETJMP_H) \
895 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
896 || defined(FEAT_LIBCALL))) \
897 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898/*
899 * A simplistic version of setjmp() that only allows one level of using.
900 * Don't call twice before calling mch_endjmp()!.
901 * Usage:
902 * mch_startjmp();
903 * if (SETJMP(lc_jump_env) != 0)
904 * {
905 * mch_didjmp();
906 * EMSG("crash!");
907 * }
908 * else
909 * {
910 * do_the_work;
911 * mch_endjmp();
912 * }
913 * Note: Can't move SETJMP() here, because a function calling setjmp() must
914 * not return before the saved environment is used.
915 * Returns OK for normal return, FAIL when the protected code caused a
916 * problem and LONGJMP() was used.
917 */
918 void
919mch_startjmp()
920{
921#ifdef SIGHASARG
922 lc_signal = 0;
923#endif
924 lc_active = TRUE;
925}
926
927 void
928mch_endjmp()
929{
930 lc_active = FALSE;
931}
932
933 void
934mch_didjmp()
935{
936# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
937 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
938 * otherwise catching the signal only works once. */
939 init_signal_stack();
940# endif
941}
942#endif
943
944/*
945 * This function handles deadly signals.
946 * It tries to preserve any swap file and exit properly.
947 * (partly from Elvis).
948 */
949 static RETSIGTYPE
950deathtrap SIGDEFARG(sigarg)
951{
952 static int entered = 0; /* count the number of times we got here.
953 Note: when memory has been corrupted
954 this may get an arbitrary value! */
955#ifdef SIGHASARG
956 int i;
957#endif
958
959#if defined(HAVE_SETJMP_H)
960 /*
961 * Catch a crash in protected code.
962 * Restores the environment saved in lc_jump_env, which looks like
963 * SETJMP() returns 1.
964 */
965 if (lc_active)
966 {
967# if defined(SIGHASARG)
968 lc_signal = sigarg;
969# endif
970 lc_active = FALSE; /* don't jump again */
971 LONGJMP(lc_jump_env, 1);
972 /* NOTREACHED */
973 }
974#endif
975
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000976#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000977# ifdef SIGQUIT
978 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
979 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
980 * pressing CTRL-\, but we don't want Vim to exit then. */
981 if (in_mch_delay && sigarg == SIGQUIT)
982 SIGRETURN;
983# endif
984
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000985 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
986 * here. This avoids that a non-reentrant function is interrupted, e.g.,
987 * free(). Calling free() again may then cause a crash. */
988 if (entered == 0
989 && (0
990# ifdef SIGHUP
991 || sigarg == SIGHUP
992# endif
993# ifdef SIGQUIT
994 || sigarg == SIGQUIT
995# endif
996# ifdef SIGTERM
997 || sigarg == SIGTERM
998# endif
999# ifdef SIGPWR
1000 || sigarg == SIGPWR
1001# endif
1002# ifdef SIGUSR1
1003 || sigarg == SIGUSR1
1004# endif
1005# ifdef SIGUSR2
1006 || sigarg == SIGUSR2
1007# endif
1008 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001009 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001010 SIGRETURN;
1011#endif
1012
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 /* Remember how often we have been called. */
1014 ++entered;
1015
1016#ifdef FEAT_EVAL
1017 /* Set the v:dying variable. */
1018 set_vim_var_nr(VV_DYING, (long)entered);
1019#endif
1020
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001021#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 /* Since we are now using the signal stack, need to reset the stack
1023 * limit. Otherwise using a regexp will fail. */
1024 get_stack_limit();
1025#endif
1026
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001027#if 0
1028 /* This is for opening gdb the moment Vim crashes.
1029 * You need to manually adjust the file name and Vim executable name.
1030 * Suggested by SungHyun Nam. */
1031 {
1032# define VI_GDB_FILE "/tmp/vimgdb"
1033# define VIM_NAME "/usr/bin/vim"
1034 FILE *fp = fopen(VI_GDB_FILE, "w");
1035 if (fp)
1036 {
1037 fprintf(fp,
1038 "file %s\n"
1039 "attach %d\n"
1040 "set height 1000\n"
1041 "bt full\n"
1042 , VIM_NAME, getpid());
1043 fclose(fp);
1044 system("xterm -e gdb -x "VI_GDB_FILE);
1045 unlink(VI_GDB_FILE);
1046 }
1047 }
1048#endif
1049
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050#ifdef SIGHASARG
1051 /* try to find the name of this signal */
1052 for (i = 0; signal_info[i].sig != -1; i++)
1053 if (sigarg == signal_info[i].sig)
1054 break;
1055 deadly_signal = sigarg;
1056#endif
1057
1058 full_screen = FALSE; /* don't write message to the GUI, it might be
1059 * part of the problem... */
1060 /*
1061 * If something goes wrong after entering here, we may get here again.
1062 * When this happens, give a message and try to exit nicely (resetting the
1063 * terminal mode, etc.)
1064 * When this happens twice, just exit, don't even try to give a message,
1065 * stack may be corrupt or something weird.
1066 * When this still happens again (or memory was corrupted in such a way
1067 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1068 */
1069 if (entered >= 3)
1070 {
1071 reset_signals(); /* don't catch any signals anymore */
1072 may_core_dump();
1073 if (entered >= 4)
1074 _exit(8);
1075 exit(7);
1076 }
1077 if (entered == 2)
1078 {
1079 OUT_STR(_("Vim: Double signal, exiting\n"));
1080 out_flush();
1081 getout(1);
1082 }
1083
1084#ifdef SIGHASARG
1085 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
1086 signal_info[i].name);
1087#else
1088 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
1089#endif
1090 preserve_exit(); /* preserve files and exit */
1091
Bram Moolenaar009b2592004-10-24 19:18:58 +00001092#ifdef NBDEBUG
1093 reset_signals();
1094 may_core_dump();
1095 abort();
1096#endif
1097
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 SIGRETURN;
1099}
1100
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001101#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102/*
1103 * On Solaris with multi-threading, suspending might not work immediately.
1104 * Catch the SIGCONT signal, which will be used as an indication whether the
1105 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001106 *
1107 * On Linux, signal is not always handled immediately either.
1108 * See https://bugs.launchpad.net/bugs/291373
1109 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001110 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001112static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1114
1115/*
1116 * signal handler for SIGCONT
1117 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 static RETSIGTYPE
1119sigcont_handler SIGDEFARG(sigarg)
1120{
1121 sigcont_received = TRUE;
1122 SIGRETURN;
1123}
1124#endif
1125
Bram Moolenaar62b42182010-09-21 22:09:37 +02001126# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1127static void loose_clipboard __ARGS((void));
1128
1129/*
1130 * Called when Vim is going to sleep or execute a shell command.
1131 * We can't respond to requests for the X selections. Lose them, otherwise
1132 * other applications will hang. But first copy the text to cut buffer 0.
1133 */
1134 static void
1135loose_clipboard()
1136{
1137 if (clip_star.owned || clip_plus.owned)
1138 {
1139 x11_export_final_selection();
1140 if (clip_star.owned)
1141 clip_lose_selection(&clip_star);
1142 if (clip_plus.owned)
1143 clip_lose_selection(&clip_plus);
1144 if (x11_display != NULL)
1145 XFlush(x11_display);
1146 }
1147}
1148#endif
1149
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150/*
1151 * If the machine has job control, use it to suspend the program,
1152 * otherwise fake it by starting a new shell.
1153 */
1154 void
1155mch_suspend()
1156{
1157 /* BeOS does have SIGTSTP, but it doesn't work. */
1158#if defined(SIGTSTP) && !defined(__BEOS__)
1159 out_flush(); /* needed to make cursor visible on some systems */
1160 settmode(TMODE_COOK);
1161 out_flush(); /* needed to disable mouse on some systems */
1162
1163# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001164 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165# endif
1166
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001167# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168 sigcont_received = FALSE;
1169# endif
1170 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001171# if defined(_REENTRANT) && defined(SIGCONT)
1172 /*
1173 * Wait for the SIGCONT signal to be handled. It generally happens
1174 * immediately, but somehow not all the time. Do not call pause()
1175 * because there would be race condition which would hang Vim if
1176 * signal happened in between the test of sigcont_received and the
1177 * call to pause(). If signal is not yet received, call sleep(0)
1178 * to just yield CPU. Signal should then be received. If somehow
1179 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1180 * further if signal is not received after 1+2+3+4 ms (not expected
1181 * to happen).
1182 */
1183 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001184 long wait_time;
1185 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001186 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001187 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189# endif
1190
1191# ifdef FEAT_TITLE
1192 /*
1193 * Set oldtitle to NULL, so the current title is obtained again.
1194 */
1195 vim_free(oldtitle);
1196 oldtitle = NULL;
1197# endif
1198 settmode(TMODE_RAW);
1199 need_check_timestamps = TRUE;
1200 did_check_timestamps = FALSE;
1201#else
1202 suspend_shell();
1203#endif
1204}
1205
1206 void
1207mch_init()
1208{
1209 Columns = 80;
1210 Rows = 24;
1211
1212 out_flush();
1213 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001214
Bram Moolenaar56718732006-03-15 22:53:57 +00001215#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001216 mac_conv_init();
1217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218}
1219
1220 static void
1221set_signals()
1222{
1223#if defined(SIGWINCH)
1224 /*
1225 * WINDOW CHANGE signal is handled with sig_winch().
1226 */
1227 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1228#endif
1229
1230 /*
1231 * We want the STOP signal to work, to make mch_suspend() work.
1232 * For "rvim" the STOP signal is ignored.
1233 */
1234#ifdef SIGTSTP
1235 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1236#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001237#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 signal(SIGCONT, sigcont_handler);
1239#endif
1240
1241 /*
1242 * We want to ignore breaking of PIPEs.
1243 */
1244#ifdef SIGPIPE
1245 signal(SIGPIPE, SIG_IGN);
1246#endif
1247
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001249 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250#endif
1251
1252 /*
1253 * Ignore alarm signals (Perl's alarm() generates it).
1254 */
1255#ifdef SIGALRM
1256 signal(SIGALRM, SIG_IGN);
1257#endif
1258
1259 /*
1260 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1261 * work will be lost.
1262 */
1263#ifdef SIGPWR
1264 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1265#endif
1266
1267 /*
1268 * Arrange for other signals to gracefully shutdown Vim.
1269 */
1270 catch_signals(deathtrap, SIG_ERR);
1271
1272#if defined(FEAT_GUI) && defined(SIGHUP)
1273 /*
1274 * When the GUI is running, ignore the hangup signal.
1275 */
1276 if (gui.in_use)
1277 signal(SIGHUP, SIG_IGN);
1278#endif
1279}
1280
Bram Moolenaardf177f62005-02-22 08:39:57 +00001281#if defined(SIGINT) || defined(PROTO)
1282/*
1283 * Catch CTRL-C (only works while in Cooked mode).
1284 */
1285 static void
1286catch_int_signal()
1287{
1288 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1289}
1290#endif
1291
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 void
1293reset_signals()
1294{
1295 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001296#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297 /* SIGCONT isn't in the list, because its default action is ignore */
1298 signal(SIGCONT, SIG_DFL);
1299#endif
1300}
1301
1302 static void
1303catch_signals(func_deadly, func_other)
1304 RETSIGTYPE (*func_deadly)();
1305 RETSIGTYPE (*func_other)();
1306{
1307 int i;
1308
1309 for (i = 0; signal_info[i].sig != -1; i++)
1310 if (signal_info[i].deadly)
1311 {
1312#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1313 struct sigaction sa;
1314
1315 /* Setup to use the alternate stack for the signal function. */
1316 sa.sa_handler = func_deadly;
1317 sigemptyset(&sa.sa_mask);
1318# if defined(__linux__) && defined(_REENTRANT)
1319 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1320 * thread handling in combination with using the alternate stack:
1321 * pthread library functions try to use the stack pointer to
1322 * identify the current thread, causing a SEGV signal, which
1323 * recursively calls deathtrap() and hangs. */
1324 sa.sa_flags = 0;
1325# else
1326 sa.sa_flags = SA_ONSTACK;
1327# endif
1328 sigaction(signal_info[i].sig, &sa, NULL);
1329#else
1330# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1331 struct sigvec sv;
1332
1333 /* Setup to use the alternate stack for the signal function. */
1334 sv.sv_handler = func_deadly;
1335 sv.sv_mask = 0;
1336 sv.sv_flags = SV_ONSTACK;
1337 sigvec(signal_info[i].sig, &sv, NULL);
1338# else
1339 signal(signal_info[i].sig, func_deadly);
1340# endif
1341#endif
1342 }
1343 else if (func_other != SIG_ERR)
1344 signal(signal_info[i].sig, func_other);
1345}
1346
1347/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001348 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001349 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1350 * return TRUE
1351 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1352 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001353 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001354 * Returns TRUE when Vim should exit.
1355 */
1356 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001357vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001358 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001359{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001360 static int got_signal = 0;
1361 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001362
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001363 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001364 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001365 case SIGNAL_BLOCK: blocked = TRUE;
1366 break;
1367
1368 case SIGNAL_UNBLOCK: blocked = FALSE;
1369 if (got_signal != 0)
1370 {
1371 kill(getpid(), got_signal);
1372 got_signal = 0;
1373 }
1374 break;
1375
1376 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001377 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001378 got_signal = sig;
1379#ifdef SIGPWR
1380 if (sig != SIGPWR)
1381#endif
1382 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001383 break;
1384 }
1385 return FALSE;
1386}
1387
1388/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389 * Check_win checks whether we have an interactive stdout.
1390 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391 int
1392mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001393 int argc UNUSED;
1394 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395{
1396#ifdef OS2
1397 /*
1398 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1399 * name, mostly it's just "vim" and found in the path, which is unusable.
1400 */
1401 if (mch_isFullName(argv[0]))
1402 exe_name = vim_strsave((char_u *)argv[0]);
1403#endif
1404 if (isatty(1))
1405 return OK;
1406 return FAIL;
1407}
1408
1409/*
1410 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1411 */
1412 int
1413mch_input_isatty()
1414{
1415 if (isatty(read_cmd_fd))
1416 return TRUE;
1417 return FALSE;
1418}
1419
1420#ifdef FEAT_X11
1421
1422# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1423 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1424
1425static void xopen_message __ARGS((struct timeval *tvp));
1426
1427/*
1428 * Give a message about the elapsed time for opening the X window.
1429 */
1430 static void
1431xopen_message(tvp)
1432 struct timeval *tvp; /* must contain start time */
1433{
1434 struct timeval end_tv;
1435
1436 /* Compute elapsed time. */
1437 gettimeofday(&end_tv, NULL);
1438 smsg((char_u *)_("Opening the X display took %ld msec"),
1439 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001440 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441}
1442# endif
1443#endif
1444
1445#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1446/*
1447 * A few functions shared by X11 title and clipboard code.
1448 */
1449static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1450static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1451static int x_connect_to_server __ARGS((void));
1452static int test_x11_window __ARGS((Display *dpy));
1453
1454static int got_x_error = FALSE;
1455
1456/*
1457 * X Error handler, otherwise X just exits! (very rude) -- webb
1458 */
1459 static int
1460x_error_handler(dpy, error_event)
1461 Display *dpy;
1462 XErrorEvent *error_event;
1463{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001464 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 STRCAT(IObuff, _("\nVim: Got X error\n"));
1466
1467 /* We cannot print a message and continue, because no X calls are allowed
1468 * here (causes my system to hang). Silently continuing might be an
1469 * alternative... */
1470 preserve_exit(); /* preserve files and exit */
1471
1472 return 0; /* NOTREACHED */
1473}
1474
1475/*
1476 * Another X Error handler, just used to check for errors.
1477 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 static int
1479x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001480 Display *dpy UNUSED;
1481 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482{
1483 got_x_error = TRUE;
1484 return 0;
1485}
1486
1487#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1488# if defined(HAVE_SETJMP_H)
1489/*
1490 * An X IO Error handler, used to catch error while opening the display.
1491 */
1492static int x_IOerror_check __ARGS((Display *dpy));
1493
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 static int
1495x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001496 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497{
1498 /* This function should not return, it causes exit(). Longjump instead. */
1499 LONGJMP(lc_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001500# ifdef VMS
1501 return 0; /* avoid the compiler complains about missing return value */
1502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503}
1504# endif
1505
1506/*
1507 * An X IO Error handler, used to catch terminal errors.
1508 */
1509static int x_IOerror_handler __ARGS((Display *dpy));
1510
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 static int
1512x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001513 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514{
1515 xterm_dpy = NULL;
1516 x11_window = 0;
1517 x11_display = NULL;
1518 xterm_Shell = (Widget)0;
1519
1520 /* This function should not return, it causes exit(). Longjump instead. */
1521 LONGJMP(x_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001522# ifdef VMS
1523 return 0; /* avoid the compiler complains about missing return value */
1524# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525}
1526#endif
1527
1528/*
1529 * Return TRUE when connection to the X server is desired.
1530 */
1531 static int
1532x_connect_to_server()
1533{
1534 regmatch_T regmatch;
1535
1536#if defined(FEAT_CLIENTSERVER)
1537 if (x_force_connect)
1538 return TRUE;
1539#endif
1540 if (x_no_connect)
1541 return FALSE;
1542
1543 /* Check for a match with "exclude:" from 'clipboard'. */
1544 if (clip_exclude_prog != NULL)
1545 {
1546 regmatch.rm_ic = FALSE; /* Don't ignore case */
1547 regmatch.regprog = clip_exclude_prog;
1548 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1549 return FALSE;
1550 }
1551 return TRUE;
1552}
1553
1554/*
1555 * Test if "dpy" and x11_window are valid by getting the window title.
1556 * I don't actually want it yet, so there may be a simpler call to use, but
1557 * this will cause the error handler x_error_check() to be called if anything
1558 * is wrong, such as the window pointer being invalid (as can happen when the
1559 * user changes his DISPLAY, but not his WINDOWID) -- webb
1560 */
1561 static int
1562test_x11_window(dpy)
1563 Display *dpy;
1564{
1565 int (*old_handler)();
1566 XTextProperty text_prop;
1567
1568 old_handler = XSetErrorHandler(x_error_check);
1569 got_x_error = FALSE;
1570 if (XGetWMName(dpy, x11_window, &text_prop))
1571 XFree((void *)text_prop.value);
1572 XSync(dpy, False);
1573 (void)XSetErrorHandler(old_handler);
1574
1575 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001576 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577
1578 return (got_x_error ? FAIL : OK);
1579}
1580#endif
1581
1582#ifdef FEAT_TITLE
1583
1584#ifdef FEAT_X11
1585
1586static int get_x11_thing __ARGS((int get_title, int test_only));
1587
1588/*
1589 * try to get x11 window and display
1590 *
1591 * return FAIL for failure, OK otherwise
1592 */
1593 static int
1594get_x11_windis()
1595{
1596 char *winid;
1597 static int result = -1;
1598#define XD_NONE 0 /* x11_display not set here */
1599#define XD_HERE 1 /* x11_display opened here */
1600#define XD_GUI 2 /* x11_display used from gui.dpy */
1601#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1602 static int x11_display_from = XD_NONE;
1603 static int did_set_error_handler = FALSE;
1604
1605 if (!did_set_error_handler)
1606 {
1607 /* X just exits if it finds an error otherwise! */
1608 (void)XSetErrorHandler(x_error_handler);
1609 did_set_error_handler = TRUE;
1610 }
1611
Bram Moolenaar9372a112005-12-06 19:59:18 +00001612#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 if (gui.in_use)
1614 {
1615 /*
1616 * If the X11 display was opened here before, for the window where Vim
1617 * was started, close that one now to avoid a memory leak.
1618 */
1619 if (x11_display_from == XD_HERE && x11_display != NULL)
1620 {
1621 XCloseDisplay(x11_display);
1622 x11_display_from = XD_NONE;
1623 }
1624 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1625 {
1626 x11_display_from = XD_GUI;
1627 return OK;
1628 }
1629 x11_display = NULL;
1630 return FAIL;
1631 }
1632 else if (x11_display_from == XD_GUI)
1633 {
1634 /* GUI must have stopped somehow, clear x11_display */
1635 x11_window = 0;
1636 x11_display = NULL;
1637 x11_display_from = XD_NONE;
1638 }
1639#endif
1640
1641 /* When started with the "-X" argument, don't try connecting. */
1642 if (!x_connect_to_server())
1643 return FAIL;
1644
1645 /*
1646 * If WINDOWID not set, should try another method to find out
1647 * what the current window number is. The only code I know for
1648 * this is very complicated.
1649 * We assume that zero is invalid for WINDOWID.
1650 */
1651 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1652 x11_window = (Window)atol(winid);
1653
1654#ifdef FEAT_XCLIPBOARD
1655 if (xterm_dpy != NULL && x11_window != 0)
1656 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001657 /* We may have checked it already, but Gnome terminal can move us to
1658 * another window, so we need to check every time. */
1659 if (x11_display_from != XD_XTERM)
1660 {
1661 /*
1662 * If the X11 display was opened here before, for the window where
1663 * Vim was started, close that one now to avoid a memory leak.
1664 */
1665 if (x11_display_from == XD_HERE && x11_display != NULL)
1666 XCloseDisplay(x11_display);
1667 x11_display = xterm_dpy;
1668 x11_display_from = XD_XTERM;
1669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 if (test_x11_window(x11_display) == FAIL)
1671 {
1672 /* probably bad $WINDOWID */
1673 x11_window = 0;
1674 x11_display = NULL;
1675 x11_display_from = XD_NONE;
1676 return FAIL;
1677 }
1678 return OK;
1679 }
1680#endif
1681
1682 if (x11_window == 0 || x11_display == NULL)
1683 result = -1;
1684
1685 if (result != -1) /* Have already been here and set this */
1686 return result; /* Don't do all these X calls again */
1687
1688 if (x11_window != 0 && x11_display == NULL)
1689 {
1690#ifdef SET_SIG_ALARM
1691 RETSIGTYPE (*sig_save)();
1692#endif
1693#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1694 struct timeval start_tv;
1695
1696 if (p_verbose > 0)
1697 gettimeofday(&start_tv, NULL);
1698#endif
1699
1700#ifdef SET_SIG_ALARM
1701 /*
1702 * Opening the Display may hang if the DISPLAY setting is wrong, or
1703 * the network connection is bad. Set an alarm timer to get out.
1704 */
1705 sig_alarm_called = FALSE;
1706 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1707 (RETSIGTYPE (*)())sig_alarm);
1708 alarm(2);
1709#endif
1710 x11_display = XOpenDisplay(NULL);
1711
1712#ifdef SET_SIG_ALARM
1713 alarm(0);
1714 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1715 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001716 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717#endif
1718 if (x11_display != NULL)
1719 {
1720# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1721 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001722 {
1723 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001725 verbose_leave();
1726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727# endif
1728 if (test_x11_window(x11_display) == FAIL)
1729 {
1730 /* Maybe window id is bad */
1731 x11_window = 0;
1732 XCloseDisplay(x11_display);
1733 x11_display = NULL;
1734 }
1735 else
1736 x11_display_from = XD_HERE;
1737 }
1738 }
1739 if (x11_window == 0 || x11_display == NULL)
1740 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001741
1742# ifdef FEAT_EVAL
1743 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1744# endif
1745
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 return (result = OK);
1747}
1748
1749/*
1750 * Determine original x11 Window Title
1751 */
1752 static int
1753get_x11_title(test_only)
1754 int test_only;
1755{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001756 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757}
1758
1759/*
1760 * Determine original x11 Window icon
1761 */
1762 static int
1763get_x11_icon(test_only)
1764 int test_only;
1765{
1766 int retval = FALSE;
1767
1768 retval = get_x11_thing(FALSE, test_only);
1769
1770 /* could not get old icon, use terminal name */
1771 if (oldicon == NULL && !test_only)
1772 {
1773 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001774 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001776 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 }
1778
1779 return retval;
1780}
1781
1782 static int
1783get_x11_thing(get_title, test_only)
1784 int get_title; /* get title string */
1785 int test_only;
1786{
1787 XTextProperty text_prop;
1788 int retval = FALSE;
1789 Status status;
1790
1791 if (get_x11_windis() == OK)
1792 {
1793 /* Get window/icon name if any */
1794 if (get_title)
1795 status = XGetWMName(x11_display, x11_window, &text_prop);
1796 else
1797 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1798
1799 /*
1800 * If terminal is xterm, then x11_window may be a child window of the
1801 * outer xterm window that actually contains the window/icon name, so
1802 * keep traversing up the tree until a window with a title/icon is
1803 * found.
1804 */
1805 /* Previously this was only done for xterm and alikes. I don't see a
1806 * reason why it would fail for other terminal emulators.
1807 * if (term_is_xterm) */
1808 {
1809 Window root;
1810 Window parent;
1811 Window win = x11_window;
1812 Window *children;
1813 unsigned int num_children;
1814
1815 while (!status || text_prop.value == NULL)
1816 {
1817 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1818 &num_children))
1819 break;
1820 if (children)
1821 XFree((void *)children);
1822 if (parent == root || parent == 0)
1823 break;
1824
1825 win = parent;
1826 if (get_title)
1827 status = XGetWMName(x11_display, win, &text_prop);
1828 else
1829 status = XGetWMIconName(x11_display, win, &text_prop);
1830 }
1831 }
1832 if (status && text_prop.value != NULL)
1833 {
1834 retval = TRUE;
1835 if (!test_only)
1836 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001837#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1838 if (text_prop.encoding == XA_STRING
1839# ifdef FEAT_MBYTE
1840 && !has_mbyte
1841# endif
1842 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 {
1844#endif
1845 if (get_title)
1846 oldtitle = vim_strsave((char_u *)text_prop.value);
1847 else
1848 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001849#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 }
1851 else
1852 {
1853 char **cl;
1854 Status transform_status;
1855 int n = 0;
1856
1857 transform_status = XmbTextPropertyToTextList(x11_display,
1858 &text_prop,
1859 &cl, &n);
1860 if (transform_status >= Success && n > 0 && cl[0])
1861 {
1862 if (get_title)
1863 oldtitle = vim_strsave((char_u *) cl[0]);
1864 else
1865 oldicon = vim_strsave((char_u *) cl[0]);
1866 XFreeStringList(cl);
1867 }
1868 else
1869 {
1870 if (get_title)
1871 oldtitle = vim_strsave((char_u *)text_prop.value);
1872 else
1873 oldicon = vim_strsave((char_u *)text_prop.value);
1874 }
1875 }
1876#endif
1877 }
1878 XFree((void *)text_prop.value);
1879 }
1880 }
1881 return retval;
1882}
1883
1884/* Are Xutf8 functions available? Avoid error from old compilers. */
1885#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1886# if X_HAVE_UTF8_STRING
1887# define USE_UTF8_STRING
1888# endif
1889#endif
1890
1891/*
1892 * Set x11 Window Title
1893 *
1894 * get_x11_windis() must be called before this and have returned OK
1895 */
1896 static void
1897set_x11_title(title)
1898 char_u *title;
1899{
1900 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1901 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1902 * supported everywhere and STRING doesn't work for multi-byte titles.
1903 */
1904#ifdef USE_UTF8_STRING
1905 if (enc_utf8)
1906 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1907 NULL, NULL, 0, NULL, NULL, NULL);
1908 else
1909#endif
1910 {
1911#if XtSpecificationRelease >= 4
1912# ifdef FEAT_XFONTSET
1913 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1914 NULL, NULL, 0, NULL, NULL, NULL);
1915# else
1916 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001917 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918
1919 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001920 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 XSetWMProperties(x11_display, x11_window, &text_prop,
1922 NULL, NULL, 0, NULL, NULL, NULL);
1923# endif
1924#else
1925 XStoreName(x11_display, x11_window, (char *)title);
1926#endif
1927 }
1928 XFlush(x11_display);
1929}
1930
1931/*
1932 * Set x11 Window icon
1933 *
1934 * get_x11_windis() must be called before this and have returned OK
1935 */
1936 static void
1937set_x11_icon(icon)
1938 char_u *icon;
1939{
1940 /* See above for comments about using X*SetWMProperties(). */
1941#ifdef USE_UTF8_STRING
1942 if (enc_utf8)
1943 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1944 NULL, 0, NULL, NULL, NULL);
1945 else
1946#endif
1947 {
1948#if XtSpecificationRelease >= 4
1949# ifdef FEAT_XFONTSET
1950 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1951 NULL, 0, NULL, NULL, NULL);
1952# else
1953 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001954 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001956 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1958 NULL, 0, NULL, NULL, NULL);
1959# endif
1960#else
1961 XSetIconName(x11_display, x11_window, (char *)icon);
1962#endif
1963 }
1964 XFlush(x11_display);
1965}
1966
1967#else /* FEAT_X11 */
1968
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 static int
1970get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001971 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972{
1973 return FALSE;
1974}
1975
1976 static int
1977get_x11_icon(test_only)
1978 int test_only;
1979{
1980 if (!test_only)
1981 {
1982 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001983 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001985 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 }
1987 return FALSE;
1988}
1989
1990#endif /* FEAT_X11 */
1991
1992 int
1993mch_can_restore_title()
1994{
1995 return get_x11_title(TRUE);
1996}
1997
1998 int
1999mch_can_restore_icon()
2000{
2001 return get_x11_icon(TRUE);
2002}
2003
2004/*
2005 * Set the window title and icon.
2006 */
2007 void
2008mch_settitle(title, icon)
2009 char_u *title;
2010 char_u *icon;
2011{
2012 int type = 0;
2013 static int recursive = 0;
2014
2015 if (T_NAME == NULL) /* no terminal name (yet) */
2016 return;
2017 if (title == NULL && icon == NULL) /* nothing to do */
2018 return;
2019
2020 /* When one of the X11 functions causes a deadly signal, we get here again
2021 * recursively. Avoid hanging then (something is probably locked). */
2022 if (recursive)
2023 return;
2024 ++recursive;
2025
2026 /*
2027 * if the window ID and the display is known, we may use X11 calls
2028 */
2029#ifdef FEAT_X11
2030 if (get_x11_windis() == OK)
2031 type = 1;
2032#else
2033# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2034 if (gui.in_use)
2035 type = 1;
2036# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037#endif
2038
2039 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002040 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 * than x11 calls, because the x11 calls don't always work
2042 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 if ((type || *T_TS != NUL) && title != NULL)
2044 {
2045 if (oldtitle == NULL
2046#ifdef FEAT_GUI
2047 && !gui.in_use
2048#endif
2049 ) /* first call but not in GUI, save title */
2050 (void)get_x11_title(FALSE);
2051
2052 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2053 term_settitle(title);
2054#ifdef FEAT_X11
2055 else
2056# ifdef FEAT_GUI_GTK
2057 if (!gui.in_use) /* don't do this if GTK+ is running */
2058# endif
2059 set_x11_title(title); /* x11 */
2060#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002061#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2063 else
2064 gui_mch_settitle(title, icon);
2065#endif
2066 did_set_title = TRUE;
2067 }
2068
2069 if ((type || *T_CIS != NUL) && icon != NULL)
2070 {
2071 if (oldicon == NULL
2072#ifdef FEAT_GUI
2073 && !gui.in_use
2074#endif
2075 ) /* first call, save icon */
2076 get_x11_icon(FALSE);
2077
2078 if (*T_CIS != NUL)
2079 {
2080 out_str(T_CIS); /* set icon start */
2081 out_str_nf(icon);
2082 out_str(T_CIE); /* set icon end */
2083 out_flush();
2084 }
2085#ifdef FEAT_X11
2086 else
2087# ifdef FEAT_GUI_GTK
2088 if (!gui.in_use) /* don't do this if GTK+ is running */
2089# endif
2090 set_x11_icon(icon); /* x11 */
2091#endif
2092 did_set_icon = TRUE;
2093 }
2094 --recursive;
2095}
2096
2097/*
2098 * Restore the window/icon title.
2099 * "which" is one of:
2100 * 1 only restore title
2101 * 2 only restore icon
2102 * 3 restore title and icon
2103 */
2104 void
2105mch_restore_title(which)
2106 int which;
2107{
2108 /* only restore the title or icon when it has been set */
2109 mch_settitle(((which & 1) && did_set_title) ?
2110 (oldtitle ? oldtitle : p_titleold) : NULL,
2111 ((which & 2) && did_set_icon) ? oldicon : NULL);
2112}
2113
2114#endif /* FEAT_TITLE */
2115
2116/*
2117 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002118 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 */
2120 int
2121vim_is_xterm(name)
2122 char_u *name;
2123{
2124 if (name == NULL)
2125 return FALSE;
2126 return (STRNICMP(name, "xterm", 5) == 0
2127 || STRNICMP(name, "nxterm", 6) == 0
2128 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002129 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130 || STRNICMP(name, "rxvt", 4) == 0
2131 || STRCMP(name, "builtin_xterm") == 0);
2132}
2133
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002134#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2135/*
2136 * Return TRUE if "name" appears to be that of a terminal
2137 * known to support the xterm-style mouse protocol.
2138 * Relies on term_is_xterm having been set to its correct value.
2139 */
2140 int
2141use_xterm_like_mouse(name)
2142 char_u *name;
2143{
2144 return (name != NULL
2145 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2146}
2147#endif
2148
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2150/*
2151 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2152 * Return 1 for "xterm".
2153 * Return 2 for "xterm2".
2154 */
2155 int
2156use_xterm_mouse()
2157{
2158 if (ttym_flags == TTYM_XTERM2)
2159 return 2;
2160 if (ttym_flags == TTYM_XTERM)
2161 return 1;
2162 return 0;
2163}
2164#endif
2165
2166 int
2167vim_is_iris(name)
2168 char_u *name;
2169{
2170 if (name == NULL)
2171 return FALSE;
2172 return (STRNICMP(name, "iris-ansi", 9) == 0
2173 || STRCMP(name, "builtin_iris-ansi") == 0);
2174}
2175
2176 int
2177vim_is_vt300(name)
2178 char_u *name;
2179{
2180 if (name == NULL)
2181 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002182 /* catch VT100 - VT5xx */
2183 return ((STRNICMP(name, "vt", 2) == 0
2184 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 || STRCMP(name, "builtin_vt320") == 0);
2186}
2187
2188/*
2189 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2190 * This should include all windowed terminal emulators.
2191 */
2192 int
2193vim_is_fastterm(name)
2194 char_u *name;
2195{
2196 if (name == NULL)
2197 return FALSE;
2198 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2199 return TRUE;
2200 return ( STRNICMP(name, "hpterm", 6) == 0
2201 || STRNICMP(name, "sun-cmd", 7) == 0
2202 || STRNICMP(name, "screen", 6) == 0
2203 || STRNICMP(name, "dtterm", 6) == 0);
2204}
2205
2206/*
2207 * Insert user name in s[len].
2208 * Return OK if a name found.
2209 */
2210 int
2211mch_get_user_name(s, len)
2212 char_u *s;
2213 int len;
2214{
2215#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002216 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002217 return OK;
2218#else
2219 return mch_get_uname(getuid(), s, len);
2220#endif
2221}
2222
2223/*
2224 * Insert user name for "uid" in s[len].
2225 * Return OK if a name found.
2226 */
2227 int
2228mch_get_uname(uid, s, len)
2229 uid_t uid;
2230 char_u *s;
2231 int len;
2232{
2233#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2234 struct passwd *pw;
2235
2236 if ((pw = getpwuid(uid)) != NULL
2237 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2238 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002239 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 return OK;
2241 }
2242#endif
2243 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2244 return FAIL; /* a number is not a name */
2245}
2246
2247/*
2248 * Insert host name is s[len].
2249 */
2250
2251#ifdef HAVE_SYS_UTSNAME_H
2252 void
2253mch_get_host_name(s, len)
2254 char_u *s;
2255 int len;
2256{
2257 struct utsname vutsname;
2258
2259 if (uname(&vutsname) < 0)
2260 *s = NUL;
2261 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002262 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263}
2264#else /* HAVE_SYS_UTSNAME_H */
2265
2266# ifdef HAVE_SYS_SYSTEMINFO_H
2267# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2268# endif
2269
2270 void
2271mch_get_host_name(s, len)
2272 char_u *s;
2273 int len;
2274{
2275# ifdef VAXC
2276 vaxc$gethostname((char *)s, len);
2277# else
2278 gethostname((char *)s, len);
2279# endif
2280 s[len - 1] = NUL; /* make sure it's terminated */
2281}
2282#endif /* HAVE_SYS_UTSNAME_H */
2283
2284/*
2285 * return process ID
2286 */
2287 long
2288mch_get_pid()
2289{
2290 return (long)getpid();
2291}
2292
2293#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2294static char *strerror __ARGS((int));
2295
2296 static char *
2297strerror(err)
2298 int err;
2299{
2300 extern int sys_nerr;
2301 extern char *sys_errlist[];
2302 static char er[20];
2303
2304 if (err > 0 && err < sys_nerr)
2305 return (sys_errlist[err]);
2306 sprintf(er, "Error %d", err);
2307 return er;
2308}
2309#endif
2310
2311/*
2312 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2313 * Return OK for success, FAIL for failure.
2314 */
2315 int
2316mch_dirname(buf, len)
2317 char_u *buf;
2318 int len;
2319{
2320#if defined(USE_GETCWD)
2321 if (getcwd((char *)buf, len) == NULL)
2322 {
2323 STRCPY(buf, strerror(errno));
2324 return FAIL;
2325 }
2326 return OK;
2327#else
2328 return (getwd((char *)buf) != NULL ? OK : FAIL);
2329#endif
2330}
2331
2332#if defined(OS2) || defined(PROTO)
2333/*
2334 * Replace all slashes by backslashes.
2335 * When 'shellslash' set do it the other way around.
2336 */
2337 void
2338slash_adjust(p)
2339 char_u *p;
2340{
2341 while (*p)
2342 {
2343 if (*p == psepcN)
2344 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002345 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 }
2347}
2348#endif
2349
2350/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002351 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 *
2353 * return FAIL for failure, OK for success
2354 */
2355 int
2356mch_FullName(fname, buf, len, force)
2357 char_u *fname, *buf;
2358 int len;
2359 int force; /* also expand when already absolute path */
2360{
2361 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002362#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002364#endif
2365#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 int fd = -1;
2367 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002368#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 char_u olddir[MAXPATHL];
2370 char_u *p;
2371 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002372#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002373 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2374 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002375#endif
2376
Bram Moolenaar38323e42007-03-06 19:22:53 +00002377#ifdef VMS
2378 fname = vms_fixfilename(fname);
2379#endif
2380
Bram Moolenaara2442432007-04-26 14:26:37 +00002381#ifdef __CYGWIN__
2382 /*
2383 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2384 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002385# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2386 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2387# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002388 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002389# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002390 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002391#endif
2392
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 /* expand it if forced or not an absolute path */
2394 if (force || !mch_isFullName(fname))
2395 {
2396 /*
2397 * If the file name has a path, change to that directory for a moment,
2398 * and then do the getwd() (and get back to where we were).
2399 * This will get the correct path name with "../" things.
2400 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002401#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 only_drive = 0;
2403 if (((p = vim_strrchr(fname, '/')) != NULL)
2404 || ((p = vim_strrchr(fname, '\\')) != NULL)
2405 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002406#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002408#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002410#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 /*
2412 * Use fchdir() if possible, it's said to be faster and more
2413 * reliable. But on SunOS 4 it might not work. Check this by
2414 * doing a fchdir() right now.
2415 */
2416 if (!dont_fchdir)
2417 {
2418 fd = open(".", O_RDONLY | O_EXTRA, 0);
2419 if (fd >= 0 && fchdir(fd) < 0)
2420 {
2421 close(fd);
2422 fd = -1;
2423 dont_fchdir = TRUE; /* don't try again */
2424 }
2425 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002426#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427
2428 /* Only change directory when we are sure we can return to where
2429 * we are now. After doing "su" chdir(".") might not work. */
2430 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002431#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002433#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 (mch_dirname(olddir, MAXPATHL) == FAIL
2435 || mch_chdir((char *)olddir) != 0))
2436 {
2437 p = NULL; /* can't get current dir: don't chdir */
2438 retval = FAIL;
2439 }
2440 else
2441 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002442#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 /*
2444 * compensate for case where ':' from "D:" was the only
2445 * path separator detected in the file name; the _next_
2446 * character has to be removed, and then restored later.
2447 */
2448 if (only_drive)
2449 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002450#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 /* The directory is copied into buf[], to be able to remove
2452 * the file name without changing it (could be a string in
2453 * read-only memory) */
2454 if (p - fname >= len)
2455 retval = FAIL;
2456 else
2457 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002458 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 if (mch_chdir((char *)buf))
2460 retval = FAIL;
2461 else
2462 fname = p + 1;
2463 *buf = NUL;
2464 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002465#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 if (only_drive)
2467 {
2468 p--;
2469 if (retval != FAIL)
2470 fname--;
2471 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002472#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 }
2474 }
2475 if (mch_dirname(buf, len) == FAIL)
2476 {
2477 retval = FAIL;
2478 *buf = NUL;
2479 }
2480 if (p != NULL)
2481 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002482#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 if (fd >= 0)
2484 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002485 if (p_verbose >= 5)
2486 {
2487 verbose_enter();
2488 MSG("fchdir() to previous dir");
2489 verbose_leave();
2490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 l = fchdir(fd);
2492 close(fd);
2493 }
2494 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002495#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 l = mch_chdir((char *)olddir);
2497 if (l != 0)
2498 EMSG(_(e_prev_dir));
2499 }
2500
2501 l = STRLEN(buf);
2502 if (l >= len)
2503 retval = FAIL;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002504#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505 else
2506 {
2507 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2508 && STRCMP(fname, ".") != 0)
2509 STRCAT(buf, "/");
2510 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002511#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002513
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002515 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 return FAIL;
2517
2518 /* Do not append ".", "/dir/." is equal to "/dir". */
2519 if (STRCMP(fname, ".") != 0)
2520 STRCAT(buf, fname);
2521
2522 return OK;
2523}
2524
2525/*
2526 * Return TRUE if "fname" does not depend on the current directory.
2527 */
2528 int
2529mch_isFullName(fname)
2530 char_u *fname;
2531{
2532#ifdef __EMX__
2533 return _fnisabs(fname);
2534#else
2535# ifdef VMS
2536 return ( fname[0] == '/' || fname[0] == '.' ||
2537 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2538 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2539 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2540# else
2541 return (*fname == '/' || *fname == '~');
2542# endif
2543#endif
2544}
2545
Bram Moolenaar24552be2005-12-10 20:17:30 +00002546#if defined(USE_FNAME_CASE) || defined(PROTO)
2547/*
2548 * Set the case of the file name, if it already exists. This will cause the
2549 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002550 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002551 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002552 void
2553fname_case(name, len)
2554 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002555 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002556{
2557 struct stat st;
2558 char_u *slash, *tail;
2559 DIR *dirp;
2560 struct dirent *dp;
2561
2562 if (lstat((char *)name, &st) >= 0)
2563 {
2564 /* Open the directory where the file is located. */
2565 slash = vim_strrchr(name, '/');
2566 if (slash == NULL)
2567 {
2568 dirp = opendir(".");
2569 tail = name;
2570 }
2571 else
2572 {
2573 *slash = NUL;
2574 dirp = opendir((char *)name);
2575 *slash = '/';
2576 tail = slash + 1;
2577 }
2578
2579 if (dirp != NULL)
2580 {
2581 while ((dp = readdir(dirp)) != NULL)
2582 {
2583 /* Only accept names that differ in case and are the same byte
2584 * length. TODO: accept different length name. */
2585 if (STRICMP(tail, dp->d_name) == 0
2586 && STRLEN(tail) == STRLEN(dp->d_name))
2587 {
2588 char_u newname[MAXPATHL + 1];
2589 struct stat st2;
2590
2591 /* Verify the inode is equal. */
2592 vim_strncpy(newname, name, MAXPATHL);
2593 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2594 MAXPATHL - (tail - name));
2595 if (lstat((char *)newname, &st2) >= 0
2596 && st.st_ino == st2.st_ino
2597 && st.st_dev == st2.st_dev)
2598 {
2599 STRCPY(tail, dp->d_name);
2600 break;
2601 }
2602 }
2603 }
2604
2605 closedir(dirp);
2606 }
2607 }
2608}
2609#endif
2610
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611/*
2612 * Get file permissions for 'name'.
2613 * Returns -1 when it doesn't exist.
2614 */
2615 long
2616mch_getperm(name)
2617 char_u *name;
2618{
2619 struct stat statb;
2620
2621 /* Keep the #ifdef outside of stat(), it may be a macro. */
2622#ifdef VMS
2623 if (stat((char *)vms_fixfilename(name), &statb))
2624#else
2625 if (stat((char *)name, &statb))
2626#endif
2627 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002628#ifdef __INTERIX
2629 /* The top bit makes the value negative, which means the file doesn't
2630 * exist. Remove the bit, we don't use it. */
2631 return statb.st_mode & ~S_ADDACE;
2632#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002634#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635}
2636
2637/*
2638 * set file permission for 'name' to 'perm'
2639 *
2640 * return FAIL for failure, OK otherwise
2641 */
2642 int
2643mch_setperm(name, perm)
2644 char_u *name;
2645 long perm;
2646{
2647 return (chmod((char *)
2648#ifdef VMS
2649 vms_fixfilename(name),
2650#else
2651 name,
2652#endif
2653 (mode_t)perm) == 0 ? OK : FAIL);
2654}
2655
2656#if defined(HAVE_ACL) || defined(PROTO)
2657# ifdef HAVE_SYS_ACL_H
2658# include <sys/acl.h>
2659# endif
2660# ifdef HAVE_SYS_ACCESS_H
2661# include <sys/access.h>
2662# endif
2663
2664# ifdef HAVE_SOLARIS_ACL
2665typedef struct vim_acl_solaris_T {
2666 int acl_cnt;
2667 aclent_t *acl_entry;
2668} vim_acl_solaris_T;
2669# endif
2670
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002671#if defined(HAVE_SELINUX) || defined(PROTO)
2672/*
2673 * Copy security info from "from_file" to "to_file".
2674 */
2675 void
2676mch_copy_sec(from_file, to_file)
2677 char_u *from_file;
2678 char_u *to_file;
2679{
2680 if (from_file == NULL)
2681 return;
2682
2683 if (selinux_enabled == -1)
2684 selinux_enabled = is_selinux_enabled();
2685
2686 if (selinux_enabled > 0)
2687 {
2688 security_context_t from_context = NULL;
2689 security_context_t to_context = NULL;
2690
2691 if (getfilecon((char *)from_file, &from_context) < 0)
2692 {
2693 /* If the filesystem doesn't support extended attributes,
2694 the original had no special security context and the
2695 target cannot have one either. */
2696 if (errno == EOPNOTSUPP)
2697 return;
2698
2699 MSG_PUTS(_("\nCould not get security context for "));
2700 msg_outtrans(from_file);
2701 msg_putchar('\n');
2702 return;
2703 }
2704 if (getfilecon((char *)to_file, &to_context) < 0)
2705 {
2706 MSG_PUTS(_("\nCould not get security context for "));
2707 msg_outtrans(to_file);
2708 msg_putchar('\n');
2709 freecon (from_context);
2710 return ;
2711 }
2712 if (strcmp(from_context, to_context) != 0)
2713 {
2714 if (setfilecon((char *)to_file, from_context) < 0)
2715 {
2716 MSG_PUTS(_("\nCould not set security context for "));
2717 msg_outtrans(to_file);
2718 msg_putchar('\n');
2719 }
2720 }
2721 freecon(to_context);
2722 freecon(from_context);
2723 }
2724}
2725#endif /* HAVE_SELINUX */
2726
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727/*
2728 * Return a pointer to the ACL of file "fname" in allocated memory.
2729 * Return NULL if the ACL is not available for whatever reason.
2730 */
2731 vim_acl_T
2732mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002733 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734{
2735 vim_acl_T ret = NULL;
2736#ifdef HAVE_POSIX_ACL
2737 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2738#else
2739#ifdef HAVE_SOLARIS_ACL
2740 vim_acl_solaris_T *aclent;
2741
2742 aclent = malloc(sizeof(vim_acl_solaris_T));
2743 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2744 {
2745 free(aclent);
2746 return NULL;
2747 }
2748 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2749 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2750 {
2751 free(aclent->acl_entry);
2752 free(aclent);
2753 return NULL;
2754 }
2755 ret = (vim_acl_T)aclent;
2756#else
2757#if defined(HAVE_AIX_ACL)
2758 int aclsize;
2759 struct acl *aclent;
2760
2761 aclsize = sizeof(struct acl);
2762 aclent = malloc(aclsize);
2763 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2764 {
2765 if (errno == ENOSPC)
2766 {
2767 aclsize = aclent->acl_len;
2768 aclent = realloc(aclent, aclsize);
2769 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2770 {
2771 free(aclent);
2772 return NULL;
2773 }
2774 }
2775 else
2776 {
2777 free(aclent);
2778 return NULL;
2779 }
2780 }
2781 ret = (vim_acl_T)aclent;
2782#endif /* HAVE_AIX_ACL */
2783#endif /* HAVE_SOLARIS_ACL */
2784#endif /* HAVE_POSIX_ACL */
2785 return ret;
2786}
2787
2788/*
2789 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2790 */
2791 void
2792mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002793 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 vim_acl_T aclent;
2795{
2796 if (aclent == NULL)
2797 return;
2798#ifdef HAVE_POSIX_ACL
2799 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2800#else
2801#ifdef HAVE_SOLARIS_ACL
2802 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2803 ((vim_acl_solaris_T *)aclent)->acl_entry);
2804#else
2805#ifdef HAVE_AIX_ACL
2806 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2807#endif /* HAVE_AIX_ACL */
2808#endif /* HAVE_SOLARIS_ACL */
2809#endif /* HAVE_POSIX_ACL */
2810}
2811
2812 void
2813mch_free_acl(aclent)
2814 vim_acl_T aclent;
2815{
2816 if (aclent == NULL)
2817 return;
2818#ifdef HAVE_POSIX_ACL
2819 acl_free((acl_t)aclent);
2820#else
2821#ifdef HAVE_SOLARIS_ACL
2822 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2823 free(aclent);
2824#else
2825#ifdef HAVE_AIX_ACL
2826 free(aclent);
2827#endif /* HAVE_AIX_ACL */
2828#endif /* HAVE_SOLARIS_ACL */
2829#endif /* HAVE_POSIX_ACL */
2830}
2831#endif
2832
2833/*
2834 * Set hidden flag for "name".
2835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 void
2837mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002838 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839{
2840 /* can't hide a file */
2841}
2842
2843/*
2844 * return TRUE if "name" is a directory
2845 * return FALSE if "name" is not a directory
2846 * return FALSE for error
2847 */
2848 int
2849mch_isdir(name)
2850 char_u *name;
2851{
2852 struct stat statb;
2853
2854 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2855 return FALSE;
2856 if (stat((char *)name, &statb))
2857 return FALSE;
2858#ifdef _POSIX_SOURCE
2859 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2860#else
2861 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2862#endif
2863}
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865static int executable_file __ARGS((char_u *name));
2866
2867/*
2868 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2869 */
2870 static int
2871executable_file(name)
2872 char_u *name;
2873{
2874 struct stat st;
2875
2876 if (stat((char *)name, &st))
2877 return 0;
2878 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2879}
2880
2881/*
2882 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2883 * Return -1 if unknown.
2884 */
2885 int
2886mch_can_exe(name)
2887 char_u *name;
2888{
2889 char_u *buf;
2890 char_u *p, *e;
2891 int retval;
2892
2893 /* If it's an absolute or relative path don't need to use $PATH. */
2894 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2895 || (name[1] == '.' && name[2] == '/'))))
2896 return executable_file(name);
2897
2898 p = (char_u *)getenv("PATH");
2899 if (p == NULL || *p == NUL)
2900 return -1;
2901 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2902 if (buf == NULL)
2903 return -1;
2904
2905 /*
2906 * Walk through all entries in $PATH to check if "name" exists there and
2907 * is an executable file.
2908 */
2909 for (;;)
2910 {
2911 e = (char_u *)strchr((char *)p, ':');
2912 if (e == NULL)
2913 e = p + STRLEN(p);
2914 if (e - p <= 1) /* empty entry means current dir */
2915 STRCPY(buf, "./");
2916 else
2917 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002918 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 add_pathsep(buf);
2920 }
2921 STRCAT(buf, name);
2922 retval = executable_file(buf);
2923 if (retval == 1)
2924 break;
2925
2926 if (*e != ':')
2927 break;
2928 p = e + 1;
2929 }
2930
2931 vim_free(buf);
2932 return retval;
2933}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934
2935/*
2936 * Check what "name" is:
2937 * NODE_NORMAL: file or directory (or doesn't exist)
2938 * NODE_WRITABLE: writable device, socket, fifo, etc.
2939 * NODE_OTHER: non-writable things
2940 */
2941 int
2942mch_nodetype(name)
2943 char_u *name;
2944{
2945 struct stat st;
2946
2947 if (stat((char *)name, &st))
2948 return NODE_NORMAL;
2949 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2950 return NODE_NORMAL;
2951#ifndef OS2
2952 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2953 return NODE_OTHER;
2954#endif
2955 /* Everything else is writable? */
2956 return NODE_WRITABLE;
2957}
2958
2959 void
2960mch_early_init()
2961{
2962#ifdef HAVE_CHECK_STACK_GROWTH
2963 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 check_stack_growth((char *)&i);
2966
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002967# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 get_stack_limit();
2969# endif
2970
2971#endif
2972
2973 /*
2974 * Setup an alternative stack for signals. Helps to catch signals when
2975 * running out of stack space.
2976 * Use of sigaltstack() is preferred, it's more portable.
2977 * Ignore any errors.
2978 */
2979#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00002980 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981 init_signal_stack();
2982#endif
2983}
2984
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002985#if defined(EXITFREE) || defined(PROTO)
2986 void
2987mch_free_mem()
2988{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00002989# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2990 if (clip_star.owned)
2991 clip_lose_selection(&clip_star);
2992 if (clip_plus.owned)
2993 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002994# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00002995# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002996 if (xterm_Shell != (Widget)0)
2997 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00002998# ifndef LESSTIF_VERSION
2999 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003000 if (xterm_dpy != NULL)
3001 XtCloseDisplay(xterm_dpy);
3002 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003003 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003004 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003005# ifdef FEAT_X11
3006 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3007# endif
3008 }
3009# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003010# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003011# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003012 if (x11_display != NULL
3013# ifdef FEAT_XCLIPBOARD
3014 && x11_display != xterm_dpy
3015# endif
3016 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003017 XCloseDisplay(x11_display);
3018# endif
3019# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3020 vim_free(signal_stack);
3021 signal_stack = NULL;
3022# endif
3023# ifdef FEAT_TITLE
3024 vim_free(oldtitle);
3025 vim_free(oldicon);
3026# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003027}
3028#endif
3029
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030static void exit_scroll __ARGS((void));
3031
3032/*
3033 * Output a newline when exiting.
3034 * Make sure the newline goes to the same stream as the text.
3035 */
3036 static void
3037exit_scroll()
3038{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003039 if (silent_mode)
3040 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041 if (newline_on_exit || msg_didout)
3042 {
3043 if (msg_use_printf())
3044 {
3045 if (info_message)
3046 mch_msg("\n");
3047 else
3048 mch_errmsg("\r\n");
3049 }
3050 else
3051 out_char('\n');
3052 }
3053 else
3054 {
3055 restore_cterm_colors(); /* get original colors back */
3056 msg_clr_eos_force(); /* clear the rest of the display */
3057 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3058 }
3059}
3060
3061 void
3062mch_exit(r)
3063 int r;
3064{
3065 exiting = TRUE;
3066
3067#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3068 x11_export_final_selection();
3069#endif
3070
3071#ifdef FEAT_GUI
3072 if (!gui.in_use)
3073#endif
3074 {
3075 settmode(TMODE_COOK);
3076#ifdef FEAT_TITLE
3077 mch_restore_title(3); /* restore xterm title and icon name */
3078#endif
3079 /*
3080 * When t_ti is not empty but it doesn't cause swapping terminal
3081 * pages, need to output a newline when msg_didout is set. But when
3082 * t_ti does swap pages it should not go to the shell page. Do this
3083 * before stoptermcap().
3084 */
3085 if (swapping_screen() && !newline_on_exit)
3086 exit_scroll();
3087
3088 /* Stop termcap: May need to check for T_CRV response, which
3089 * requires RAW mode. */
3090 stoptermcap();
3091
3092 /*
3093 * A newline is only required after a message in the alternate screen.
3094 * This is set to TRUE by wait_return().
3095 */
3096 if (!swapping_screen() || newline_on_exit)
3097 exit_scroll();
3098
3099 /* Cursor may have been switched off without calling starttermcap()
3100 * when doing "vim -u vimrc" and vimrc contains ":q". */
3101 if (full_screen)
3102 cursor_on();
3103 }
3104 out_flush();
3105 ml_close_all(TRUE); /* remove all memfiles */
3106 may_core_dump();
3107#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109 gui_exit(r);
3110#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003111
Bram Moolenaar56718732006-03-15 22:53:57 +00003112#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003113 mac_conv_cleanup();
3114#endif
3115
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116#ifdef __QNX__
3117 /* A core dump won't be created if the signal handler
3118 * doesn't return, so we can't call exit() */
3119 if (deadly_signal != 0)
3120 return;
3121#endif
3122
Bram Moolenaar009b2592004-10-24 19:18:58 +00003123#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003124 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003125#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003126
3127#ifdef EXITFREE
3128 free_all_mem();
3129#endif
3130
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 exit(r);
3132}
3133
3134 static void
3135may_core_dump()
3136{
3137 if (deadly_signal != 0)
3138 {
3139 signal(deadly_signal, SIG_DFL);
3140 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3141 }
3142}
3143
3144#ifndef VMS
3145
3146 void
3147mch_settmode(tmode)
3148 int tmode;
3149{
3150 static int first = TRUE;
3151
3152 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3153#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3154 /*
3155 * for "new" tty systems
3156 */
3157# ifdef HAVE_TERMIOS_H
3158 static struct termios told;
3159 struct termios tnew;
3160# else
3161 static struct termio told;
3162 struct termio tnew;
3163# endif
3164
3165 if (first)
3166 {
3167 first = FALSE;
3168# if defined(HAVE_TERMIOS_H)
3169 tcgetattr(read_cmd_fd, &told);
3170# else
3171 ioctl(read_cmd_fd, TCGETA, &told);
3172# endif
3173 }
3174
3175 tnew = told;
3176 if (tmode == TMODE_RAW)
3177 {
3178 /*
3179 * ~ICRNL enables typing ^V^M
3180 */
3181 tnew.c_iflag &= ~ICRNL;
3182 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3183# if defined(IEXTEN) && !defined(__MINT__)
3184 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3185 /* but it breaks function keys on MINT */
3186# endif
3187 );
3188# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3189 tnew.c_oflag &= ~ONLCR;
3190# endif
3191 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3192 tnew.c_cc[VTIME] = 0; /* don't wait */
3193 }
3194 else if (tmode == TMODE_SLEEP)
3195 tnew.c_lflag &= ~(ECHO);
3196
3197# if defined(HAVE_TERMIOS_H)
3198 {
3199 int n = 10;
3200
3201 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3202 * few times. */
3203 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3204 && errno == EINTR && n > 0)
3205 --n;
3206 }
3207# else
3208 ioctl(read_cmd_fd, TCSETA, &tnew);
3209# endif
3210
3211#else
3212
3213 /*
3214 * for "old" tty systems
3215 */
3216# ifndef TIOCSETN
3217# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3218# endif
3219 static struct sgttyb ttybold;
3220 struct sgttyb ttybnew;
3221
3222 if (first)
3223 {
3224 first = FALSE;
3225 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3226 }
3227
3228 ttybnew = ttybold;
3229 if (tmode == TMODE_RAW)
3230 {
3231 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3232 ttybnew.sg_flags |= RAW;
3233 }
3234 else if (tmode == TMODE_SLEEP)
3235 ttybnew.sg_flags &= ~(ECHO);
3236 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3237#endif
3238 curr_tmode = tmode;
3239}
3240
3241/*
3242 * Try to get the code for "t_kb" from the stty setting
3243 *
3244 * Even if termcap claims a backspace key, the user's setting *should*
3245 * prevail. stty knows more about reality than termcap does, and if
3246 * somebody's usual erase key is DEL (which, for most BSD users, it will
3247 * be), they're going to get really annoyed if their erase key starts
3248 * doing forward deletes for no reason. (Eric Fischer)
3249 */
3250 void
3251get_stty()
3252{
3253 char_u buf[2];
3254 char_u *p;
3255
3256 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3257#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3258 /* for "new" tty systems */
3259# ifdef HAVE_TERMIOS_H
3260 struct termios keys;
3261# else
3262 struct termio keys;
3263# endif
3264
3265# if defined(HAVE_TERMIOS_H)
3266 if (tcgetattr(read_cmd_fd, &keys) != -1)
3267# else
3268 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3269# endif
3270 {
3271 buf[0] = keys.c_cc[VERASE];
3272 intr_char = keys.c_cc[VINTR];
3273#else
3274 /* for "old" tty systems */
3275 struct sgttyb keys;
3276
3277 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3278 {
3279 buf[0] = keys.sg_erase;
3280 intr_char = keys.sg_kill;
3281#endif
3282 buf[1] = NUL;
3283 add_termcode((char_u *)"kb", buf, FALSE);
3284
3285 /*
3286 * If <BS> and <DEL> are now the same, redefine <DEL>.
3287 */
3288 p = find_termcode((char_u *)"kD");
3289 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3290 do_fixdel(NULL);
3291 }
3292#if 0
3293 } /* to keep cindent happy */
3294#endif
3295}
3296
3297#endif /* VMS */
3298
3299#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3300/*
3301 * Set mouse clicks on or off.
3302 */
3303 void
3304mch_setmouse(on)
3305 int on;
3306{
3307 static int ison = FALSE;
3308 int xterm_mouse_vers;
3309
3310 if (on == ison) /* return quickly if nothing to do */
3311 return;
3312
3313 xterm_mouse_vers = use_xterm_mouse();
3314 if (xterm_mouse_vers > 0)
3315 {
3316 if (on) /* enable mouse events, use mouse tracking if available */
3317 out_str_nf((char_u *)
3318 (xterm_mouse_vers > 1
3319 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3320 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3321 else /* disable mouse events, could probably always send the same */
3322 out_str_nf((char_u *)
3323 (xterm_mouse_vers > 1
3324 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3325 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3326 ison = on;
3327 }
3328
3329# ifdef FEAT_MOUSE_DEC
3330 else if (ttym_flags == TTYM_DEC)
3331 {
3332 if (on) /* enable mouse events */
3333 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3334 else /* disable mouse events */
3335 out_str_nf((char_u *)"\033['z");
3336 ison = on;
3337 }
3338# endif
3339
3340# ifdef FEAT_MOUSE_GPM
3341 else
3342 {
3343 if (on)
3344 {
3345 if (gpm_open())
3346 ison = TRUE;
3347 }
3348 else
3349 {
3350 gpm_close();
3351 ison = FALSE;
3352 }
3353 }
3354# endif
3355
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003356# ifdef FEAT_SYSMOUSE
3357 else
3358 {
3359 if (on)
3360 {
3361 if (sysmouse_open() == OK)
3362 ison = TRUE;
3363 }
3364 else
3365 {
3366 sysmouse_close();
3367 ison = FALSE;
3368 }
3369 }
3370# endif
3371
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372# ifdef FEAT_MOUSE_JSB
3373 else
3374 {
3375 if (on)
3376 {
3377 /* D - Enable Mouse up/down messages
3378 * L - Enable Left Button Reporting
3379 * M - Enable Middle Button Reporting
3380 * R - Enable Right Button Reporting
3381 * K - Enable SHIFT and CTRL key Reporting
3382 * + - Enable Advanced messaging of mouse moves and up/down messages
3383 * Q - Quiet No Ack
3384 * # - Numeric value of mouse pointer required
3385 * 0 = Multiview 2000 cursor, used as standard
3386 * 1 = Windows Arrow
3387 * 2 = Windows I Beam
3388 * 3 = Windows Hour Glass
3389 * 4 = Windows Cross Hair
3390 * 5 = Windows UP Arrow
3391 */
3392#ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3393 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3394 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3395#else
3396 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3397 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3398#endif
3399 ison = TRUE;
3400 }
3401 else
3402 {
3403 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3404 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3405 ison = FALSE;
3406 }
3407 }
3408# endif
3409# ifdef FEAT_MOUSE_PTERM
3410 else
3411 {
3412 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3413 if (on)
3414 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3415 else
3416 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3417 ison = on;
3418 }
3419# endif
3420}
3421
3422/*
3423 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3424 */
3425 void
3426check_mouse_termcode()
3427{
3428# ifdef FEAT_MOUSE_XTERM
3429 if (use_xterm_mouse()
3430# ifdef FEAT_GUI
3431 && !gui.in_use
3432# endif
3433 )
3434 {
3435 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003436 ? IF_EB("\233M", CSI_STR "M")
3437 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 if (*p_mouse != NUL)
3439 {
3440 /* force mouse off and maybe on to send possibly new mouse
3441 * activation sequence to the xterm, with(out) drag tracing. */
3442 mch_setmouse(FALSE);
3443 setmouse();
3444 }
3445 }
3446 else
3447 del_mouse_termcode(KS_MOUSE);
3448# endif
3449
3450# ifdef FEAT_MOUSE_GPM
3451 if (!use_xterm_mouse()
3452# ifdef FEAT_GUI
3453 && !gui.in_use
3454# endif
3455 )
3456 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3457# endif
3458
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003459# ifdef FEAT_SYSMOUSE
3460 if (!use_xterm_mouse()
3461# ifdef FEAT_GUI
3462 && !gui.in_use
3463# endif
3464 )
3465 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3466# endif
3467
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468# ifdef FEAT_MOUSE_JSB
3469 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3470 if (!use_xterm_mouse()
3471# ifdef FEAT_GUI
3472 && !gui.in_use
3473# endif
3474 )
3475 set_mouse_termcode(KS_JSBTERM_MOUSE,
3476 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3477 else
3478 del_mouse_termcode(KS_JSBTERM_MOUSE);
3479# endif
3480
3481# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003482 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 * define it in the GUI or when using an xterm. */
3484 if (!use_xterm_mouse()
3485# ifdef FEAT_GUI
3486 && !gui.in_use
3487# endif
3488 )
3489 set_mouse_termcode(KS_NETTERM_MOUSE,
3490 (char_u *)IF_EB("\033}", ESC_STR "}"));
3491 else
3492 del_mouse_termcode(KS_NETTERM_MOUSE);
3493# endif
3494
3495# ifdef FEAT_MOUSE_DEC
3496 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3497 if (!use_xterm_mouse()
3498# ifdef FEAT_GUI
3499 && !gui.in_use
3500# endif
3501 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003502 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3503 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 else
3505 del_mouse_termcode(KS_DEC_MOUSE);
3506# endif
3507# ifdef FEAT_MOUSE_PTERM
3508 /* same as the dec mouse */
3509 if (!use_xterm_mouse()
3510# ifdef FEAT_GUI
3511 && !gui.in_use
3512# endif
3513 )
3514 set_mouse_termcode(KS_PTERM_MOUSE,
3515 (char_u *) IF_EB("\033[", ESC_STR "["));
3516 else
3517 del_mouse_termcode(KS_PTERM_MOUSE);
3518# endif
3519}
3520#endif
3521
3522/*
3523 * set screen mode, always fails.
3524 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 int
3526mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003527 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528{
3529 EMSG(_(e_screenmode));
3530 return FAIL;
3531}
3532
3533#ifndef VMS
3534
3535/*
3536 * Try to get the current window size:
3537 * 1. with an ioctl(), most accurate method
3538 * 2. from the environment variables LINES and COLUMNS
3539 * 3. from the termcap
3540 * 4. keep using the old values
3541 * Return OK when size could be determined, FAIL otherwise.
3542 */
3543 int
3544mch_get_shellsize()
3545{
3546 long rows = 0;
3547 long columns = 0;
3548 char_u *p;
3549
3550 /*
3551 * For OS/2 use _scrsize().
3552 */
3553# ifdef __EMX__
3554 {
3555 int s[2];
3556
3557 _scrsize(s);
3558 columns = s[0];
3559 rows = s[1];
3560 }
3561# endif
3562
3563 /*
3564 * 1. try using an ioctl. It is the most accurate method.
3565 *
3566 * Try using TIOCGWINSZ first, some systems that have it also define
3567 * TIOCGSIZE but don't have a struct ttysize.
3568 */
3569# ifdef TIOCGWINSZ
3570 {
3571 struct winsize ws;
3572 int fd = 1;
3573
3574 /* When stdout is not a tty, use stdin for the ioctl(). */
3575 if (!isatty(fd) && isatty(read_cmd_fd))
3576 fd = read_cmd_fd;
3577 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3578 {
3579 columns = ws.ws_col;
3580 rows = ws.ws_row;
3581 }
3582 }
3583# else /* TIOCGWINSZ */
3584# ifdef TIOCGSIZE
3585 {
3586 struct ttysize ts;
3587 int fd = 1;
3588
3589 /* When stdout is not a tty, use stdin for the ioctl(). */
3590 if (!isatty(fd) && isatty(read_cmd_fd))
3591 fd = read_cmd_fd;
3592 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3593 {
3594 columns = ts.ts_cols;
3595 rows = ts.ts_lines;
3596 }
3597 }
3598# endif /* TIOCGSIZE */
3599# endif /* TIOCGWINSZ */
3600
3601 /*
3602 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003603 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3604 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003606 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 {
3608 if ((p = (char_u *)getenv("LINES")))
3609 rows = atoi((char *)p);
3610 if ((p = (char_u *)getenv("COLUMNS")))
3611 columns = atoi((char *)p);
3612 }
3613
3614#ifdef HAVE_TGETENT
3615 /*
3616 * 3. try reading "co" and "li" entries from termcap
3617 */
3618 if (columns == 0 || rows == 0)
3619 getlinecol(&columns, &rows);
3620#endif
3621
3622 /*
3623 * 4. If everything fails, use the old values
3624 */
3625 if (columns <= 0 || rows <= 0)
3626 return FAIL;
3627
3628 Rows = rows;
3629 Columns = columns;
3630 return OK;
3631}
3632
3633/*
3634 * Try to set the window size to Rows and Columns.
3635 */
3636 void
3637mch_set_shellsize()
3638{
3639 if (*T_CWS)
3640 {
3641 /*
3642 * NOTE: if you get an error here that term_set_winsize() is
3643 * undefined, check the output of configure. It could probably not
3644 * find a ncurses, termcap or termlib library.
3645 */
3646 term_set_winsize((int)Rows, (int)Columns);
3647 out_flush();
3648 screen_start(); /* don't know where cursor is now */
3649 }
3650}
3651
3652#endif /* VMS */
3653
3654/*
3655 * Rows and/or Columns has changed.
3656 */
3657 void
3658mch_new_shellsize()
3659{
3660 /* Nothing to do. */
3661}
3662
3663 int
3664mch_call_shell(cmd, options)
3665 char_u *cmd;
3666 int options; /* SHELL_*, see vim.h */
3667{
3668#ifdef VMS
3669 char *ifn = NULL;
3670 char *ofn = NULL;
3671#endif
3672 int tmode = cur_tmode;
3673#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3674 int x;
3675# ifndef __EMX__
3676 char_u *newcmd; /* only needed for unix */
3677# else
3678 /*
3679 * Set the preferred shell in the EMXSHELL environment variable (but
3680 * only if it is different from what is already in the environment).
3681 * Emx then takes care of whether to use "/c" or "-c" in an
3682 * intelligent way. Simply pass the whole thing to emx's system() call.
3683 * Emx also starts an interactive shell if system() is passed an empty
3684 * string.
3685 */
3686 char_u *p, *old;
3687
3688 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3689 {
3690 /* should check HAVE_SETENV, but I know we don't have it. */
3691 p = alloc(10 + strlen(p_sh));
3692 if (p)
3693 {
3694 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3695 putenv((char *)p); /* don't free the pointer! */
3696 }
3697 }
3698# endif
3699
3700 out_flush();
3701
3702 if (options & SHELL_COOKED)
3703 settmode(TMODE_COOK); /* set to normal mode */
3704
Bram Moolenaar62b42182010-09-21 22:09:37 +02003705# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3706 loose_clipboard();
3707# endif
3708
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709# ifdef __EMX__
3710 if (cmd == NULL)
3711 x = system(""); /* this starts an interactive shell in emx */
3712 else
3713 x = system((char *)cmd);
3714 /* system() returns -1 when error occurs in starting shell */
3715 if (x == -1 && !emsg_silent)
3716 {
3717 MSG_PUTS(_("\nCannot execute shell "));
3718 msg_outtrans(p_sh);
3719 msg_putchar('\n');
3720 }
3721# else /* not __EMX__ */
3722 if (cmd == NULL)
3723 x = system((char *)p_sh);
3724 else
3725 {
3726# ifdef VMS
3727 if (ofn = strchr((char *)cmd, '>'))
3728 *ofn++ = '\0';
3729 if (ifn = strchr((char *)cmd, '<'))
3730 {
3731 char *p;
3732
3733 *ifn++ = '\0';
3734 p = strchr(ifn,' '); /* chop off any trailing spaces */
3735 if (p)
3736 *p = '\0';
3737 }
3738 if (ofn)
3739 x = vms_sys((char *)cmd, ofn, ifn);
3740 else
3741 x = system((char *)cmd);
3742# else
3743 newcmd = lalloc(STRLEN(p_sh)
3744 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3745 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3746 if (newcmd == NULL)
3747 x = 0;
3748 else
3749 {
3750 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3751 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3752 (char *)p_shcf,
3753 (char *)cmd);
3754 x = system((char *)newcmd);
3755 vim_free(newcmd);
3756 }
3757# endif
3758 }
3759# ifdef VMS
3760 x = vms_sys_status(x);
3761# endif
3762 if (emsg_silent)
3763 ;
3764 else if (x == 127)
3765 MSG_PUTS(_("\nCannot execute shell sh\n"));
3766# endif /* __EMX__ */
3767 else if (x && !(options & SHELL_SILENT))
3768 {
3769 MSG_PUTS(_("\nshell returned "));
3770 msg_outnum((long)x);
3771 msg_putchar('\n');
3772 }
3773
3774 if (tmode == TMODE_RAW)
3775 settmode(TMODE_RAW); /* set to raw mode */
3776# ifdef FEAT_TITLE
3777 resettitle();
3778# endif
3779 return x;
3780
3781#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3782
Bram Moolenaardf177f62005-02-22 08:39:57 +00003783# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3784 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785
3786 char_u *newcmd = NULL;
3787 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003788 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 pid_t wait_pid = 0;
3790# ifdef HAVE_UNION_WAIT
3791 union wait status;
3792# else
3793 int status = -1;
3794# endif
3795 int retval = -1;
3796 char **argv = NULL;
3797 int argc;
3798 int i;
3799 char_u *p;
3800 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003802# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 int pty_slave_fd = -1;
3804 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003805# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003806 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 int fd_fromshell[2];
3808 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003809# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003811# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 static char envbuf_Rows[20];
3813 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003815 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816
Bram Moolenaar62b42182010-09-21 22:09:37 +02003817 newcmd = vim_strsave(p_sh);
3818 if (newcmd == NULL) /* out of memory */
3819 goto error;
3820
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 out_flush();
3822 if (options & SHELL_COOKED)
3823 settmode(TMODE_COOK); /* set to normal mode */
3824
Bram Moolenaar62b42182010-09-21 22:09:37 +02003825# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3826 loose_clipboard();
3827# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003828
3829 /*
3830 * Do this loop twice:
3831 * 1: find number of arguments
3832 * 2: separate them and build argv[]
3833 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 for (i = 0; i < 2; ++i)
3835 {
3836 p = newcmd;
3837 inquote = FALSE;
3838 argc = 0;
3839 for (;;)
3840 {
3841 if (i == 1)
3842 argv[argc] = (char *)p;
3843 ++argc;
3844 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3845 {
3846 if (*p == '"')
3847 inquote = !inquote;
3848 ++p;
3849 }
3850 if (*p == NUL)
3851 break;
3852 if (i == 1)
3853 *p++ = NUL;
3854 p = skipwhite(p);
3855 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003856 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 {
3858 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3859 if (argv == NULL) /* out of memory */
3860 goto error;
3861 }
3862 }
3863 if (cmd != NULL)
3864 {
3865 if (extra_shell_arg != NULL)
3866 argv[argc++] = (char *)extra_shell_arg;
3867 argv[argc++] = (char *)p_shcf;
3868 argv[argc++] = (char *)cmd;
3869 }
3870 argv[argc] = NULL;
3871
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003873 * For the GUI, when writing the output into the buffer and when reading
3874 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3875 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003877 if ((options & (SHELL_READ|SHELL_WRITE))
3878# ifdef FEAT_GUI
3879 || (gui.in_use && show_shell_mess)
3880# endif
3881 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003883# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 /*
3885 * Try to open a master pty.
3886 * If this works, open the slave pty.
3887 * If the slave can't be opened, close the master pty.
3888 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003889 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 {
3891 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02003892 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02003894 /* Leaving out O_NOCTTY may lead to waitpid() always returning
3895 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
3896 * adding O_NOCTTY always works when defined. */
3897#ifdef O_NOCTTY
3898 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
3899#else
3900 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
3901#endif
3902 if (pty_slave_fd < 0)
3903 {
3904 close(pty_master_fd);
3905 pty_master_fd = -1;
3906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 }
3908 }
3909 /*
3910 * If not opening a pty or it didn't work, try using pipes.
3911 */
3912 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 {
3915 pipe_error = (pipe(fd_toshell) < 0);
3916 if (!pipe_error) /* pipe create OK */
3917 {
3918 pipe_error = (pipe(fd_fromshell) < 0);
3919 if (pipe_error) /* pipe create failed */
3920 {
3921 close(fd_toshell[0]);
3922 close(fd_toshell[1]);
3923 }
3924 }
3925 if (pipe_error)
3926 {
3927 MSG_PUTS(_("\nCannot create pipes\n"));
3928 out_flush();
3929 }
3930 }
3931 }
3932
3933 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 {
3935# ifdef __BEOS__
3936 beos_cleanup_read_thread();
3937# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003938
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3940 {
3941 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003942 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003944 || (gui.in_use && show_shell_mess)
3945# endif
3946 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003948# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949 if (pty_master_fd >= 0) /* close the pseudo tty */
3950 {
3951 close(pty_master_fd);
3952 close(pty_slave_fd);
3953 }
3954 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003955# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 {
3957 close(fd_toshell[0]);
3958 close(fd_toshell[1]);
3959 close(fd_fromshell[0]);
3960 close(fd_fromshell[1]);
3961 }
3962 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963 }
3964 else if (pid == 0) /* child */
3965 {
3966 reset_signals(); /* handle signals normally */
3967
3968 if (!show_shell_mess || (options & SHELL_EXPAND))
3969 {
3970 int fd;
3971
3972 /*
3973 * Don't want to show any message from the shell. Can't just
3974 * close stdout and stderr though, because some systems will
3975 * break if you try to write to them after that, so we must
3976 * use dup() to replace them with something else -- webb
3977 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3978 * waiting for input.
3979 */
3980 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3981 fclose(stdin);
3982 fclose(stdout);
3983 fclose(stderr);
3984
3985 /*
3986 * If any of these open()'s and dup()'s fail, we just continue
3987 * anyway. It's not fatal, and on most systems it will make
3988 * no difference at all. On a few it will cause the execvp()
3989 * to exit with a non-zero status even when the completion
3990 * could be done, which is nothing too serious. If the open()
3991 * or dup() failed we'd just do the same thing ourselves
3992 * anyway -- webb
3993 */
3994 if (fd >= 0)
3995 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003996 ignored = dup(fd); /* To replace stdin (fd 0) */
3997 ignored = dup(fd); /* To replace stdout (fd 1) */
3998 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999
4000 /* Don't need this now that we've duplicated it */
4001 close(fd);
4002 }
4003 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004004 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004006 || gui.in_use
4007# endif
4008 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 {
4010
Bram Moolenaardf177f62005-02-22 08:39:57 +00004011# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004012 /* Create our own process group, so that the child and all its
4013 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004014 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004015 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004016 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004017 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004018# if defined(SIGHUP)
4019 /* When doing "!xterm&" and 'shell' is bash: the shell
4020 * will exit and send SIGHUP to all processes in its
4021 * group, killing the just started process. Ignore SIGHUP
4022 * to avoid that. (suggested by Simon Schubert)
4023 */
4024 signal(SIGHUP, SIG_IGN);
4025# endif
4026 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004027# endif
4028# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004029 if (pty_slave_fd >= 0)
4030 {
4031 /* push stream discipline modules */
4032 if (options & SHELL_COOKED)
4033 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004035 /* Try to become controlling tty (probably doesn't work,
4036 * unless run by root) */
4037 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004039 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004040# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004042# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 setenv("TERM", "dumb", 1);
4044 sprintf((char *)envbuf, "%ld", Rows);
4045 setenv("ROWS", (char *)envbuf, 1);
4046 sprintf((char *)envbuf, "%ld", Rows);
4047 setenv("LINES", (char *)envbuf, 1);
4048 sprintf((char *)envbuf, "%ld", Columns);
4049 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004050# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 /*
4052 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004053 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 */
4055 putenv("TERM=dumb");
4056 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4057 putenv(envbuf_Rows);
4058 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4059 putenv(envbuf_Rows);
4060 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4061 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004062# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063
Bram Moolenaara5792f52005-11-23 21:25:05 +00004064 /*
4065 * stderr is only redirected when using the GUI, so that a
4066 * program like gpg can still access the terminal to get a
4067 * passphrase using stderr.
4068 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004069# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 if (pty_master_fd >= 0)
4071 {
4072 close(pty_master_fd); /* close master side of pty */
4073
4074 /* set up stdin/stdout/stderr for the child */
4075 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004076 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004078 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004079 if (gui.in_use)
4080 {
4081 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004082 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004083 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084
4085 close(pty_slave_fd); /* has been dupped, close it now */
4086 }
4087 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004088# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 {
4090 /* set up stdin for the child */
4091 close(fd_toshell[1]);
4092 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004093 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094 close(fd_toshell[0]);
4095
4096 /* set up stdout for the child */
4097 close(fd_fromshell[0]);
4098 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004099 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 close(fd_fromshell[1]);
4101
Bram Moolenaara5792f52005-11-23 21:25:05 +00004102# ifdef FEAT_GUI
4103 if (gui.in_use)
4104 {
4105 /* set up stderr for the child */
4106 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004107 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004108 }
4109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110 }
4111 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004112
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113 /*
4114 * There is no type cast for the argv, because the type may be
4115 * different on different machines. This may cause a warning
4116 * message with strict compilers, don't worry about it.
4117 * Call _exit() instead of exit() to avoid closing the connection
4118 * to the X server (esp. with GTK, which uses atexit()).
4119 */
4120 execvp(argv[0], argv);
4121 _exit(EXEC_FAILED); /* exec failed, return failure code */
4122 }
4123 else /* parent */
4124 {
4125 /*
4126 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004127 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 */
4129 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004130 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131
4132 /*
4133 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004134 * This is also used to pipe stdin/stdout to/from the external
4135 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004137 if ((options & (SHELL_READ|SHELL_WRITE))
4138# ifdef FEAT_GUI
4139 || (gui.in_use && show_shell_mess)
4140# endif
4141 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004143# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004145# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004147# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4149 int ta_len = 0; /* valid bytes in ta_buf[] */
4150 int len;
4151 int p_more_save;
4152 int old_State;
4153 int c;
4154 int toshell_fd;
4155 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004156 garray_T ga;
4157 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004158# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4159 struct timeval start_tv;
4160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161
Bram Moolenaardf177f62005-02-22 08:39:57 +00004162# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 if (pty_master_fd >= 0)
4164 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 fromshell_fd = pty_master_fd;
4166 toshell_fd = dup(pty_master_fd);
4167 }
4168 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004169# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170 {
4171 close(fd_toshell[0]);
4172 close(fd_fromshell[1]);
4173 toshell_fd = fd_toshell[1];
4174 fromshell_fd = fd_fromshell[0];
4175 }
4176
4177 /*
4178 * Write to the child if there are typed characters.
4179 * Read from the child if there are characters available.
4180 * Repeat the reading a few times if more characters are
4181 * available. Need to check for typed keys now and then, but
4182 * not too often (delays when no chars are available).
4183 * This loop is quit if no characters can be read from the pty
4184 * (WaitForChar detected special condition), or there are no
4185 * characters available and the child has exited.
4186 * Only check if the child has exited when there is no more
4187 * output. The child may exit before all the output has
4188 * been printed.
4189 *
4190 * Currently this busy loops!
4191 * This can probably dead-lock when the write blocks!
4192 */
4193 p_more_save = p_more;
4194 p_more = FALSE;
4195 old_State = State;
4196 State = EXTERNCMD; /* don't redraw at window resize */
4197
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004198 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004199 {
4200 /* Fork a process that will write the lines to the
4201 * external program. */
4202 if ((wpid = fork()) == -1)
4203 {
4204 MSG_PUTS(_("\nCannot fork\n"));
4205 }
4206 else if (wpid == 0)
4207 {
4208 linenr_T lnum = curbuf->b_op_start.lnum;
4209 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004210 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004211 char_u *s;
4212 size_t l;
4213
4214 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004215 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004216 for (;;)
4217 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004218 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004219 if (l == 0)
4220 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004221 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004222 /* NL -> NUL translation */
4223 len = write(toshell_fd, "", (size_t)1);
4224 else
4225 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004226 s = vim_strchr(lp + written, NL);
4227 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004228 s == NULL ? l
4229 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004230 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004231 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004232 {
4233 /* Finished a line, add a NL, unless this line
4234 * should not have one. */
4235 if (lnum != curbuf->b_op_end.lnum
4236 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004237 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004238 && (lnum !=
4239 curbuf->b_ml.ml_line_count
4240 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004241 ignored = write(toshell_fd, "\n",
4242 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004243 ++lnum;
4244 if (lnum > curbuf->b_op_end.lnum)
4245 {
4246 /* finished all the lines, close pipe */
4247 close(toshell_fd);
4248 toshell_fd = -1;
4249 break;
4250 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004251 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004252 written = 0;
4253 }
4254 else if (len > 0)
4255 written += len;
4256 }
4257 _exit(0);
4258 }
4259 else
4260 {
4261 close(toshell_fd);
4262 toshell_fd = -1;
4263 }
4264 }
4265
4266 if (options & SHELL_READ)
4267 ga_init2(&ga, 1, BUFLEN);
4268
4269 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004270# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4271 gettimeofday(&start_tv, NULL);
4272# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 for (;;)
4274 {
4275 /*
4276 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004277 * if there are any.
4278 * Don't do this if we are expanding wild cards (would eat
4279 * typeahead).
4280 * Don't do this when filtering and terminal is in cooked
4281 * mode, the shell command will handle the I/O. Avoids
4282 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004283 * Don't get characters when the child has already
4284 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004285 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004286 * while (noread_cnt > 4), avoids that ":r !ls" eats
4287 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288 */
4289 len = 0;
4290 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004291 && ((options &
4292 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4293 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004294# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004295 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004296# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004297 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004298 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004299 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004301 if (ta_len == 0)
4302 {
4303 /* Get extra characters when we don't have any.
4304 * Reset the counter and timer. */
4305 noread_cnt = 0;
4306# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4307 gettimeofday(&start_tv, NULL);
4308# endif
4309 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4310 }
4311 if (ta_len > 0 || len > 0)
4312 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 /*
4314 * For pipes:
4315 * Check for CTRL-C: send interrupt signal to child.
4316 * Check for CTRL-D: EOF, close pipe to child.
4317 */
4318 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4319 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004320# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 /*
4322 * Send SIGINT to the child's group or all
4323 * processes in our group.
4324 */
4325 if (ta_buf[ta_len] == Ctrl_C
4326 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004327 {
4328# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004329 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004330# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004333 if (wpid > 0)
4334 kill(wpid, SIGINT);
4335 }
4336# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 if (pty_master_fd < 0 && toshell_fd >= 0
4338 && ta_buf[ta_len] == Ctrl_D)
4339 {
4340 close(toshell_fd);
4341 toshell_fd = -1;
4342 }
4343 }
4344
4345 /* replace K_BS by <BS> and K_DEL by <DEL> */
4346 for (i = ta_len; i < ta_len + len; ++i)
4347 {
4348 if (ta_buf[i] == CSI && len - i > 2)
4349 {
4350 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4351 if (c == K_DEL || c == K_KDEL || c == K_BS)
4352 {
4353 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4354 (size_t)(len - i - 2));
4355 if (c == K_DEL || c == K_KDEL)
4356 ta_buf[i] = DEL;
4357 else
4358 ta_buf[i] = Ctrl_H;
4359 len -= 2;
4360 }
4361 }
4362 else if (ta_buf[i] == '\r')
4363 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004364# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004366 i += (*mb_ptr2len_len)(ta_buf + i,
4367 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004368# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 }
4370
4371 /*
4372 * For pipes: echo the typed characters.
4373 * For a pty this does not seem to work.
4374 */
4375 if (pty_master_fd < 0)
4376 {
4377 for (i = ta_len; i < ta_len + len; ++i)
4378 {
4379 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4380 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004381# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382 else if (has_mbyte)
4383 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004384 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004385
4386 msg_outtrans_len(ta_buf + i, l);
4387 i += l - 1;
4388 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004389# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004390 else
4391 msg_outtrans_len(ta_buf + i, 1);
4392 }
4393 windgoto(msg_row, msg_col);
4394 out_flush();
4395 }
4396
4397 ta_len += len;
4398
4399 /*
4400 * Write the characters to the child, unless EOF has
4401 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004402 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004403 * When writing buffer lines, drop the typed
4404 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004406 if (options & SHELL_WRITE)
4407 ta_len = 0;
4408 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 {
4410 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4411 if (len > 0)
4412 {
4413 ta_len -= len;
4414 mch_memmove(ta_buf, ta_buf + len, ta_len);
4415 }
4416 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004417 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 }
4419
Bram Moolenaardf177f62005-02-22 08:39:57 +00004420 if (got_int)
4421 {
4422 /* CTRL-C sends a signal to the child, we ignore it
4423 * ourselves */
4424# ifdef HAVE_SETSID
4425 kill(-pid, SIGINT);
4426# else
4427 kill(0, SIGINT);
4428# endif
4429 if (wpid > 0)
4430 kill(wpid, SIGINT);
4431 got_int = FALSE;
4432 }
4433
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 /*
4435 * Check if the child has any characters to be printed.
4436 * Read them and write them to our window. Repeat this as
4437 * long as there is something to do, avoid the 10ms wait
4438 * for mch_inchar(), or sending typeahead characters to
4439 * the external process.
4440 * TODO: This should handle escape sequences, compatible
4441 * to some terminal (vt52?).
4442 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004443 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4445 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004446 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004447# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004449# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004451# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452 );
4453 if (len <= 0) /* end of file or error */
4454 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004455
4456 noread_cnt = 0;
4457 if (options & SHELL_READ)
4458 {
4459 /* Do NUL -> NL translation, append NL separated
4460 * lines to the current buffer. */
4461 for (i = 0; i < len; ++i)
4462 {
4463 if (buffer[i] == NL)
4464 append_ga_line(&ga);
4465 else if (buffer[i] == NUL)
4466 ga_append(&ga, NL);
4467 else
4468 ga_append(&ga, buffer[i]);
4469 }
4470 }
4471# ifdef FEAT_MBYTE
4472 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 {
4474 int l;
4475
Bram Moolenaardf177f62005-02-22 08:39:57 +00004476 len += buffer_off;
4477 buffer[len] = NUL;
4478
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 /* Check if the last character in buffer[] is
4480 * incomplete, keep these bytes for the next
4481 * round. */
4482 for (p = buffer; p < buffer + len; p += l)
4483 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004484 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485 if (l == 0)
4486 l = 1; /* NUL byte? */
4487 else if (MB_BYTE2LEN(*p) != l)
4488 break;
4489 }
4490 if (p == buffer) /* no complete character */
4491 {
4492 /* avoid getting stuck at an illegal byte */
4493 if (len >= 12)
4494 ++p;
4495 else
4496 {
4497 buffer_off = len;
4498 continue;
4499 }
4500 }
4501 c = *p;
4502 *p = NUL;
4503 msg_puts(buffer);
4504 if (p < buffer + len)
4505 {
4506 *p = c;
4507 buffer_off = (buffer + len) - p;
4508 mch_memmove(buffer, p, buffer_off);
4509 continue;
4510 }
4511 buffer_off = 0;
4512 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004513# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515 {
4516 buffer[len] = NUL;
4517 msg_puts(buffer);
4518 }
4519
4520 windgoto(msg_row, msg_col);
4521 cursor_on();
4522 out_flush();
4523 if (got_int)
4524 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004525
4526# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4527 {
4528 struct timeval now_tv;
4529 long msec;
4530
4531 /* Avoid that we keep looping here without
4532 * checking for a CTRL-C for a long time. Don't
4533 * break out too often to avoid losing typeahead. */
4534 gettimeofday(&now_tv, NULL);
4535 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4536 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4537 if (msec > 2000)
4538 {
4539 noread_cnt = 5;
4540 break;
4541 }
4542 }
4543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 }
4545
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004546 /* If we already detected the child has finished break the
4547 * loop now. */
4548 if (wait_pid == pid)
4549 break;
4550
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 /*
4552 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004553 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004554 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004555# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004557# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4561 || (wait_pid == pid && WIFEXITED(status)))
4562 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004563 /* Don't break the loop yet, try reading more
4564 * characters from "fromshell_fd" first. When using
4565 * pipes there might still be something to read and
4566 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004569 else
4570 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 }
4572finished:
4573 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004574 if (options & SHELL_READ)
4575 {
4576 if (ga.ga_len > 0)
4577 {
4578 append_ga_line(&ga);
4579 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004580 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004581 }
4582 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004583 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004584 ga_clear(&ga);
4585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 /*
4588 * Give all typeahead that wasn't used back to ui_inchar().
4589 */
4590 if (ta_len)
4591 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 State = old_State;
4593 if (toshell_fd >= 0)
4594 close(toshell_fd);
4595 close(fromshell_fd);
4596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597
4598 /*
4599 * Wait until our child has exited.
4600 * Ignore wait() returning pids of other children and returning
4601 * because of some signal like SIGWINCH.
4602 * Don't wait if wait_pid was already set above, indicating the
4603 * child already exited.
4604 */
4605 while (wait_pid != pid)
4606 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004607# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608 /* Ugly hack: when compiled with Python threads are probably
4609 * used, in which case wait() sometimes hangs for no obvious
4610 * reason. Use waitpid() instead and loop (like the GUI). */
4611# ifdef __NeXT__
4612 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4613# else
4614 wait_pid = waitpid(pid, &status, WNOHANG);
4615# endif
4616 if (wait_pid == 0)
4617 {
4618 /* Wait for 1/100 sec before trying again. */
4619 mch_delay(10L, TRUE);
4620 continue;
4621 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004622# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004624# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004625 if (wait_pid <= 0
4626# ifdef ECHILD
4627 && errno == ECHILD
4628# endif
4629 )
4630 break;
4631 }
4632
Bram Moolenaar624891f2010-10-13 16:22:09 +02004633# ifdef FEAT_GUI
4634 /* Close slave side of pty. Only do this after the child has
4635 * exited, otherwise the child may hang when it tries to write on
4636 * the pty. */
4637 if (pty_master_fd >= 0)
4638 close(pty_slave_fd);
4639# endif
4640
Bram Moolenaardf177f62005-02-22 08:39:57 +00004641 /* Make sure the child that writes to the external program is
4642 * dead. */
4643 if (wpid > 0)
4644 kill(wpid, SIGKILL);
4645
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 /*
4647 * Set to raw mode right now, otherwise a CTRL-C after
4648 * catch_signals() will kill Vim.
4649 */
4650 if (tmode == TMODE_RAW)
4651 settmode(TMODE_RAW);
4652 did_settmode = TRUE;
4653 set_signals();
4654
4655 if (WIFEXITED(status))
4656 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004657 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004658 retval = WEXITSTATUS(status);
4659 if (retval && !emsg_silent)
4660 {
4661 if (retval == EXEC_FAILED)
4662 {
4663 MSG_PUTS(_("\nCannot execute shell "));
4664 msg_outtrans(p_sh);
4665 msg_putchar('\n');
4666 }
4667 else if (!(options & SHELL_SILENT))
4668 {
4669 MSG_PUTS(_("\nshell returned "));
4670 msg_outnum((long)retval);
4671 msg_putchar('\n');
4672 }
4673 }
4674 }
4675 else
4676 MSG_PUTS(_("\nCommand terminated\n"));
4677 }
4678 }
4679 vim_free(argv);
4680
4681error:
4682 if (!did_settmode)
4683 if (tmode == TMODE_RAW)
4684 settmode(TMODE_RAW); /* set to raw mode */
4685# ifdef FEAT_TITLE
4686 resettitle();
4687# endif
4688 vim_free(newcmd);
4689
4690 return retval;
4691
4692#endif /* USE_SYSTEM */
4693}
4694
4695/*
4696 * Check for CTRL-C typed by reading all available characters.
4697 * In cooked mode we should get SIGINT, no need to check.
4698 */
4699 void
4700mch_breakcheck()
4701{
4702 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4703 fill_input_buf(FALSE);
4704}
4705
4706/*
4707 * Wait "msec" msec until a character is available from the keyboard or from
4708 * inbuf[]. msec == -1 will block forever.
4709 * When a GUI is being used, this will never get called -- webb
4710 */
4711 static int
4712WaitForChar(msec)
4713 long msec;
4714{
4715#ifdef FEAT_MOUSE_GPM
4716 int gpm_process_wanted;
4717#endif
4718#ifdef FEAT_XCLIPBOARD
4719 int rest;
4720#endif
4721 int avail;
4722
4723 if (input_available()) /* something in inbuf[] */
4724 return 1;
4725
4726#if defined(FEAT_MOUSE_DEC)
4727 /* May need to query the mouse position. */
4728 if (WantQueryMouse)
4729 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004730 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4732 }
4733#endif
4734
4735 /*
4736 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4737 * events. This is a bit complicated, because they might both be defined.
4738 */
4739#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4740# ifdef FEAT_XCLIPBOARD
4741 rest = 0;
4742 if (do_xterm_trace())
4743 rest = msec;
4744# endif
4745 do
4746 {
4747# ifdef FEAT_XCLIPBOARD
4748 if (rest != 0)
4749 {
4750 msec = XT_TRACE_DELAY;
4751 if (rest >= 0 && rest < XT_TRACE_DELAY)
4752 msec = rest;
4753 if (rest >= 0)
4754 rest -= msec;
4755 }
4756# endif
4757# ifdef FEAT_MOUSE_GPM
4758 gpm_process_wanted = 0;
4759 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4760# else
4761 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4762# endif
4763 if (!avail)
4764 {
4765 if (input_available())
4766 return 1;
4767# ifdef FEAT_XCLIPBOARD
4768 if (rest == 0 || !do_xterm_trace())
4769# endif
4770 break;
4771 }
4772 }
4773 while (FALSE
4774# ifdef FEAT_MOUSE_GPM
4775 || (gpm_process_wanted && mch_gpm_process() == 0)
4776# endif
4777# ifdef FEAT_XCLIPBOARD
4778 || (!avail && rest != 0)
4779# endif
4780 );
4781
4782#else
4783 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4784#endif
4785 return avail;
4786}
4787
4788/*
4789 * Wait "msec" msec until a character is available from file descriptor "fd".
4790 * Time == -1 will block forever.
4791 * When a GUI is being used, this will not be used for input -- webb
4792 * Returns also, when a request from Sniff is waiting -- toni.
4793 * Or when a Linux GPM mouse event is waiting.
4794 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795#if defined(__BEOS__)
4796 int
4797#else
4798 static int
4799#endif
4800RealWaitForChar(fd, msec, check_for_gpm)
4801 int fd;
4802 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004803 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804{
4805 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004806#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004807 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004808#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004809#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 static int busy = FALSE;
4811
4812 /* May retry getting characters after an event was handled. */
4813# define MAY_LOOP
4814
4815# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4816 /* Remember at what time we started, so that we know how much longer we
4817 * should wait after being interrupted. */
4818# define USE_START_TV
4819 struct timeval start_tv;
4820
4821 if (msec > 0 && (
4822# ifdef FEAT_XCLIPBOARD
4823 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004824# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 ||
4826# endif
4827# endif
4828# ifdef USE_XSMP
4829 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004830# ifdef FEAT_MZSCHEME
4831 ||
4832# endif
4833# endif
4834# ifdef FEAT_MZSCHEME
4835 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836# endif
4837 ))
4838 gettimeofday(&start_tv, NULL);
4839# endif
4840
4841 /* Handle being called recursively. This may happen for the session
4842 * manager stuff, it may save the file, which does a breakcheck. */
4843 if (busy)
4844 return 0;
4845#endif
4846
4847#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004848 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849#endif
4850 {
4851#ifdef MAY_LOOP
4852 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004853# ifdef FEAT_MZSCHEME
4854 int mzquantum_used = FALSE;
4855# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856#endif
4857#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004858 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 int nfd;
4860# ifdef FEAT_XCLIPBOARD
4861 int xterm_idx = -1;
4862# endif
4863# ifdef FEAT_MOUSE_GPM
4864 int gpm_idx = -1;
4865# endif
4866# ifdef USE_XSMP
4867 int xsmp_idx = -1;
4868# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004869# ifdef FEAT_NETBEANS_INTG
4870 int nb_idx = -1;
4871# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004872 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004874# ifdef FEAT_MZSCHEME
4875 mzvim_check_threads();
4876 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4877 {
4878 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4879 mzquantum_used = TRUE;
4880 }
4881# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 fds[0].fd = fd;
4883 fds[0].events = POLLIN;
4884 nfd = 1;
4885
4886# ifdef FEAT_SNIFF
4887# define SNIFF_IDX 1
4888 if (want_sniff_request)
4889 {
4890 fds[SNIFF_IDX].fd = fd_from_sniff;
4891 fds[SNIFF_IDX].events = POLLIN;
4892 nfd++;
4893 }
4894# endif
4895# ifdef FEAT_XCLIPBOARD
4896 if (xterm_Shell != (Widget)0)
4897 {
4898 xterm_idx = nfd;
4899 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4900 fds[nfd].events = POLLIN;
4901 nfd++;
4902 }
4903# endif
4904# ifdef FEAT_MOUSE_GPM
4905 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4906 {
4907 gpm_idx = nfd;
4908 fds[nfd].fd = gpm_fd;
4909 fds[nfd].events = POLLIN;
4910 nfd++;
4911 }
4912# endif
4913# ifdef USE_XSMP
4914 if (xsmp_icefd != -1)
4915 {
4916 xsmp_idx = nfd;
4917 fds[nfd].fd = xsmp_icefd;
4918 fds[nfd].events = POLLIN;
4919 nfd++;
4920 }
4921# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004922#ifdef FEAT_NETBEANS_INTG
4923 if (nb_fd != -1)
4924 {
4925 nb_idx = nfd;
4926 fds[nfd].fd = nb_fd;
4927 fds[nfd].events = POLLIN;
4928 nfd++;
4929 }
4930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004932 ret = poll(fds, nfd, towait);
4933# ifdef FEAT_MZSCHEME
4934 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004935 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004936 finished = FALSE;
4937# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938
4939# ifdef FEAT_SNIFF
4940 if (ret < 0)
4941 sniff_disconnect(1);
4942 else if (want_sniff_request)
4943 {
4944 if (fds[SNIFF_IDX].revents & POLLHUP)
4945 sniff_disconnect(1);
4946 if (fds[SNIFF_IDX].revents & POLLIN)
4947 sniff_request_waiting = 1;
4948 }
4949# endif
4950# ifdef FEAT_XCLIPBOARD
4951 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4952 {
4953 xterm_update(); /* Maybe we should hand out clipboard */
4954 if (--ret == 0 && !input_available())
4955 /* Try again */
4956 finished = FALSE;
4957 }
4958# endif
4959# ifdef FEAT_MOUSE_GPM
4960 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4961 {
4962 *check_for_gpm = 1;
4963 }
4964# endif
4965# ifdef USE_XSMP
4966 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4967 {
4968 if (fds[xsmp_idx].revents & POLLIN)
4969 {
4970 busy = TRUE;
4971 xsmp_handle_requests();
4972 busy = FALSE;
4973 }
4974 else if (fds[xsmp_idx].revents & POLLHUP)
4975 {
4976 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004977 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 xsmp_close();
4979 }
4980 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004981 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 }
4983# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004984#ifdef FEAT_NETBEANS_INTG
4985 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
4986 {
4987 netbeans_read();
4988 --ret;
4989 }
4990#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991
4992
4993#else /* HAVE_SELECT */
4994
4995 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004996 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997 fd_set rfds, efds;
4998 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004999 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005001# ifdef FEAT_MZSCHEME
5002 mzvim_check_threads();
5003 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5004 {
5005 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5006 mzquantum_used = TRUE;
5007 }
5008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009# ifdef __EMX__
5010 /* don't check for incoming chars if not in raw mode, because select()
5011 * always returns TRUE then (in some version of emx.dll) */
5012 if (curr_tmode != TMODE_RAW)
5013 return 0;
5014# endif
5015
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005016 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005018 tv.tv_sec = towait / 1000;
5019 tv.tv_usec = (towait % 1000) * (1000000/1000);
5020 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005022 else
5023 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024
5025 /*
5026 * Select on ready for reading and exceptional condition (end of file).
5027 */
5028 FD_ZERO(&rfds); /* calls bzero() on a sun */
5029 FD_ZERO(&efds);
5030 FD_SET(fd, &rfds);
5031# if !defined(__QNX__) && !defined(__CYGWIN32__)
5032 /* For QNX select() always returns 1 if this is set. Why? */
5033 FD_SET(fd, &efds);
5034# endif
5035 maxfd = fd;
5036
5037# ifdef FEAT_SNIFF
5038 if (want_sniff_request)
5039 {
5040 FD_SET(fd_from_sniff, &rfds);
5041 FD_SET(fd_from_sniff, &efds);
5042 if (maxfd < fd_from_sniff)
5043 maxfd = fd_from_sniff;
5044 }
5045# endif
5046# ifdef FEAT_XCLIPBOARD
5047 if (xterm_Shell != (Widget)0)
5048 {
5049 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5050 if (maxfd < ConnectionNumber(xterm_dpy))
5051 maxfd = ConnectionNumber(xterm_dpy);
5052 }
5053# endif
5054# ifdef FEAT_MOUSE_GPM
5055 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5056 {
5057 FD_SET(gpm_fd, &rfds);
5058 FD_SET(gpm_fd, &efds);
5059 if (maxfd < gpm_fd)
5060 maxfd = gpm_fd;
5061 }
5062# endif
5063# ifdef USE_XSMP
5064 if (xsmp_icefd != -1)
5065 {
5066 FD_SET(xsmp_icefd, &rfds);
5067 FD_SET(xsmp_icefd, &efds);
5068 if (maxfd < xsmp_icefd)
5069 maxfd = xsmp_icefd;
5070 }
5071# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005072#ifdef FEAT_NETBEANS_INTG
5073 if (nb_fd != -1)
5074 {
5075 FD_SET(nb_fd, &rfds);
5076 if (maxfd < nb_fd)
5077 maxfd = nb_fd;
5078 }
5079#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080
5081# ifdef OLD_VMS
5082 /* Old VMS as v6.2 and older have broken select(). It waits more than
5083 * required. Should not be used */
5084 ret = 0;
5085# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005086 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5087# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005088# ifdef __TANDEM
5089 if (ret == -1 && errno == ENOTSUP)
5090 {
5091 FD_ZERO(&rfds);
5092 FD_ZERO(&efds);
5093 ret = 0;
5094 }
5095#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005096# ifdef FEAT_MZSCHEME
5097 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005098 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005099 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100# endif
5101
5102# ifdef FEAT_SNIFF
5103 if (ret < 0 )
5104 sniff_disconnect(1);
5105 else if (ret > 0 && want_sniff_request)
5106 {
5107 if (FD_ISSET(fd_from_sniff, &efds))
5108 sniff_disconnect(1);
5109 if (FD_ISSET(fd_from_sniff, &rfds))
5110 sniff_request_waiting = 1;
5111 }
5112# endif
5113# ifdef FEAT_XCLIPBOARD
5114 if (ret > 0 && xterm_Shell != (Widget)0
5115 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5116 {
5117 xterm_update(); /* Maybe we should hand out clipboard */
5118 /* continue looping when we only got the X event and the input
5119 * buffer is empty */
5120 if (--ret == 0 && !input_available())
5121 {
5122 /* Try again */
5123 finished = FALSE;
5124 }
5125 }
5126# endif
5127# ifdef FEAT_MOUSE_GPM
5128 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5129 {
5130 if (FD_ISSET(gpm_fd, &efds))
5131 gpm_close();
5132 else if (FD_ISSET(gpm_fd, &rfds))
5133 *check_for_gpm = 1;
5134 }
5135# endif
5136# ifdef USE_XSMP
5137 if (ret > 0 && xsmp_icefd != -1)
5138 {
5139 if (FD_ISSET(xsmp_icefd, &efds))
5140 {
5141 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005142 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 xsmp_close();
5144 if (--ret == 0)
5145 finished = FALSE; /* keep going if event was only one */
5146 }
5147 else if (FD_ISSET(xsmp_icefd, &rfds))
5148 {
5149 busy = TRUE;
5150 xsmp_handle_requests();
5151 busy = FALSE;
5152 if (--ret == 0)
5153 finished = FALSE; /* keep going if event was only one */
5154 }
5155 }
5156# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005157#ifdef FEAT_NETBEANS_INTG
5158 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5159 {
5160 netbeans_read();
5161 --ret;
5162 }
5163#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164
5165#endif /* HAVE_SELECT */
5166
5167#ifdef MAY_LOOP
5168 if (finished || msec == 0)
5169 break;
5170
5171 /* We're going to loop around again, find out for how long */
5172 if (msec > 0)
5173 {
5174# ifdef USE_START_TV
5175 struct timeval mtv;
5176
5177 /* Compute remaining wait time. */
5178 gettimeofday(&mtv, NULL);
5179 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5180 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5181# else
5182 /* Guess we got interrupted halfway. */
5183 msec = msec / 2;
5184# endif
5185 if (msec <= 0)
5186 break; /* waited long enough */
5187 }
5188#endif
5189 }
5190
5191 return (ret > 0);
5192}
5193
5194#ifndef VMS
5195
5196#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005198 * Expand a path into all matching files and/or directories. Handles "*",
5199 * "?", "[a-z]", "**", etc.
5200 * "path" has backslashes before chars that are not to be expanded.
5201 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202 */
5203 int
5204mch_expandpath(gap, path, flags)
5205 garray_T *gap;
5206 char_u *path;
5207 int flags; /* EW_* flags */
5208{
Bram Moolenaar02743632005-07-25 20:42:36 +00005209 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210}
5211#endif
5212
5213/*
5214 * mch_expand_wildcards() - this code does wild-card pattern matching using
5215 * the shell
5216 *
5217 * return OK for success, FAIL for error (you may lose some memory) and put
5218 * an error message in *file.
5219 *
5220 * num_pat is number of input patterns
5221 * pat is array of pointers to input patterns
5222 * num_file is pointer to number of matched file names
5223 * file is pointer to array of pointers to matched file names
5224 */
5225
5226#ifndef SEEK_SET
5227# define SEEK_SET 0
5228#endif
5229#ifndef SEEK_END
5230# define SEEK_END 2
5231#endif
5232
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005233#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005234
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235 int
5236mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5237 int num_pat;
5238 char_u **pat;
5239 int *num_file;
5240 char_u ***file;
5241 int flags; /* EW_* flags */
5242{
5243 int i;
5244 size_t len;
5245 char_u *p;
5246 int dir;
5247#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005248 /*
5249 * This is the OS/2 implementation.
5250 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251# define EXPL_ALLOC_INC 16
5252 char_u **expl_files;
5253 size_t files_alloced, files_free;
5254 char_u *buf;
5255 int has_wildcard;
5256
5257 *num_file = 0; /* default: no files found */
5258 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5259 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5260 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5261 if (*file == NULL)
5262 return FAIL;
5263
5264 for (; num_pat > 0; num_pat--, pat++)
5265 {
5266 expl_files = NULL;
5267 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5268 /* expand environment var or home dir */
5269 buf = expand_env_save(*pat);
5270 else
5271 buf = vim_strsave(*pat);
5272 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005273 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274 if (has_wildcard) /* yes, so expand them */
5275 expl_files = (char_u **)_fnexplode(buf);
5276
5277 /*
5278 * return value of buf if no wildcards left,
5279 * OR if no match AND EW_NOTFOUND is set.
5280 */
5281 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5282 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5283 { /* simply save the current contents of *buf */
5284 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5285 if (expl_files != NULL)
5286 {
5287 expl_files[0] = vim_strsave(buf);
5288 expl_files[1] = NULL;
5289 }
5290 }
5291 vim_free(buf);
5292
5293 /*
5294 * Count number of names resulting from expansion,
5295 * At the same time add a backslash to the end of names that happen to
5296 * be directories, and replace slashes with backslashes.
5297 */
5298 if (expl_files)
5299 {
5300 for (i = 0; (p = expl_files[i]) != NULL; i++)
5301 {
5302 dir = mch_isdir(p);
5303 /* If we don't want dirs and this is one, skip it */
5304 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5305 continue;
5306
Bram Moolenaara2031822006-03-07 22:29:51 +00005307 /* Skip files that are not executable if we check for that. */
5308 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5309 continue;
5310
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311 if (--files_free == 0)
5312 {
5313 /* need more room in table of pointers */
5314 files_alloced += EXPL_ALLOC_INC;
5315 *file = (char_u **)vim_realloc(*file,
5316 sizeof(char_u **) * files_alloced);
5317 if (*file == NULL)
5318 {
5319 EMSG(_(e_outofmem));
5320 *num_file = 0;
5321 return FAIL;
5322 }
5323 files_free = EXPL_ALLOC_INC;
5324 }
5325 slash_adjust(p);
5326 if (dir)
5327 {
5328 /* For a directory we add a '/', unless it's already
5329 * there. */
5330 len = STRLEN(p);
5331 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5332 {
5333 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005334 if (!after_pathsep((*file)[*num_file],
5335 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336 {
5337 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005338 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339 }
5340 }
5341 }
5342 else
5343 {
5344 (*file)[*num_file] = vim_strsave(p);
5345 }
5346
5347 /*
5348 * Error message already given by either alloc or vim_strsave.
5349 * Should return FAIL, but returning OK works also.
5350 */
5351 if ((*file)[*num_file] == NULL)
5352 break;
5353 (*num_file)++;
5354 }
5355 _fnexplodefree((char **)expl_files);
5356 }
5357 }
5358 return OK;
5359
5360#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005361 /*
5362 * This is the non-OS/2 implementation (really Unix).
5363 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 int j;
5365 char_u *tempname;
5366 char_u *command;
5367 FILE *fd;
5368 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005369#define STYLE_ECHO 0 /* use "echo", the default */
5370#define STYLE_GLOB 1 /* use "glob", for csh */
5371#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5372#define STYLE_PRINT 3 /* use "print -N", for zsh */
5373#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5374 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 int shell_style = STYLE_ECHO;
5376 int check_spaces;
5377 static int did_find_nul = FALSE;
5378 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005379 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005380 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381
5382 *num_file = 0; /* default: no files found */
5383 *file = NULL;
5384
5385 /*
5386 * If there are no wildcards, just copy the names to allocated memory.
5387 * Saves a lot of time, because we don't have to start a new shell.
5388 */
5389 if (!have_wildcard(num_pat, pat))
5390 return save_patterns(num_pat, pat, num_file, file);
5391
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005392# ifdef HAVE_SANDBOX
5393 /* Don't allow any shell command in the sandbox. */
5394 if (sandbox != 0 && check_secure())
5395 return FAIL;
5396# endif
5397
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398 /*
5399 * Don't allow the use of backticks in secure and restricted mode.
5400 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005401 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 for (i = 0; i < num_pat; ++i)
5403 if (vim_strchr(pat[i], '`') != NULL
5404 && (check_restricted() || check_secure()))
5405 return FAIL;
5406
5407 /*
5408 * get a name for the temp file
5409 */
5410 if ((tempname = vim_tempname('o')) == NULL)
5411 {
5412 EMSG(_(e_notmp));
5413 return FAIL;
5414 }
5415
5416 /*
5417 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005418 * file.
5419 * STYLE_BT: NL separated
5420 * If expanding `cmd` execute it directly.
5421 * STYLE_GLOB: NUL separated
5422 * If we use *csh, "glob" will work better than "echo".
5423 * STYLE_PRINT: NL or NUL separated
5424 * If we use *zsh, "print -N" will work better than "glob".
5425 * STYLE_VIMGLOB: NL separated
5426 * If we use *sh*, we define "vimglob()".
5427 * STYLE_ECHO: space separated.
5428 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005429 */
5430 if (num_pat == 1 && *pat[0] == '`'
5431 && (len = STRLEN(pat[0])) > 2
5432 && *(pat[0] + len - 1) == '`')
5433 shell_style = STYLE_BT;
5434 else if ((len = STRLEN(p_sh)) >= 3)
5435 {
5436 if (STRCMP(p_sh + len - 3, "csh") == 0)
5437 shell_style = STYLE_GLOB;
5438 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5439 shell_style = STYLE_PRINT;
5440 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005441 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5442 "sh") != NULL)
5443 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444
Bram Moolenaarc7247912008-01-13 12:54:11 +00005445 /* Compute the length of the command. We need 2 extra bytes: for the
5446 * optional '&' and for the NUL.
5447 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005449 if (shell_style == STYLE_VIMGLOB)
5450 len += STRLEN(sh_vimglob_func);
5451
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005452 for (i = 0; i < num_pat; ++i)
5453 {
5454 /* Count the length of the patterns in the same way as they are put in
5455 * "command" below. */
5456#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005457 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005458#else
5459 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005460 for (j = 0; pat[i][j] != NUL; ++j)
5461 {
5462 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5463 ++len; /* may add a backslash */
5464 ++len;
5465 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005466#endif
5467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 command = alloc(len);
5469 if (command == NULL)
5470 {
5471 /* out of memory */
5472 vim_free(tempname);
5473 return FAIL;
5474 }
5475
5476 /*
5477 * Build the shell command:
5478 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5479 * recognizes this).
5480 * - Add the shell command to print the expanded names.
5481 * - Add the temp file name.
5482 * - Add the file name patterns.
5483 */
5484 if (shell_style == STYLE_BT)
5485 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005486 /* change `command; command& ` to (command; command ) */
5487 STRCPY(command, "(");
5488 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005490 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 while (p > command && vim_iswhite(*p))
5492 --p;
5493 if (*p == '&') /* remove trailing '&' */
5494 {
5495 ampersent = TRUE;
5496 *p = ' ';
5497 }
5498 STRCAT(command, ">");
5499 }
5500 else
5501 {
5502 if (flags & EW_NOTFOUND)
5503 STRCPY(command, "set nonomatch; ");
5504 else
5505 STRCPY(command, "unset nonomatch; ");
5506 if (shell_style == STYLE_GLOB)
5507 STRCAT(command, "glob >");
5508 else if (shell_style == STYLE_PRINT)
5509 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005510 else if (shell_style == STYLE_VIMGLOB)
5511 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 else
5513 STRCAT(command, "echo >");
5514 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005515
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005517
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 if (shell_style != STYLE_BT)
5519 for (i = 0; i < num_pat; ++i)
5520 {
5521 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005522 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005523 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524#ifdef USE_SYSTEM
5525 STRCAT(command, " \"");
5526 STRCAT(command, pat[i]);
5527 STRCAT(command, "\"");
5528#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005529 int intick = FALSE;
5530
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531 p = command + STRLEN(command);
5532 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005533 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005534 {
5535 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005536 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005537 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5538 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005539 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005540 * backslash inside backticks, before a special character
5541 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005542 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005543 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5544 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005545 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005546 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005547 }
5548 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005549 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005550 /* Put a backslash before a special character, but not
5551 * when inside ``. */
5552 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005553
5554 /* Copy one character. */
5555 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 *p = NUL;
5558#endif
5559 }
5560 if (flags & EW_SILENT)
5561 show_shell_mess = FALSE;
5562 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005563 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564
5565 /*
5566 * Using zsh -G: If a pattern has no matches, it is just deleted from
5567 * the argument list, otherwise zsh gives an error message and doesn't
5568 * expand any other pattern.
5569 */
5570 if (shell_style == STYLE_PRINT)
5571 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5572
5573 /*
5574 * If we use -f then shell variables set in .cshrc won't get expanded.
5575 * vi can do it, so we will too, but it is only necessary if there is a "$"
5576 * in one of the patterns, otherwise we can still use the fast option.
5577 */
5578 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5579 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5580
5581 /*
5582 * execute the shell command
5583 */
5584 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5585
5586 /* When running in the background, give it some time to create the temp
5587 * file, but don't wait for it to finish. */
5588 if (ampersent)
5589 mch_delay(10L, TRUE);
5590
5591 extra_shell_arg = NULL; /* cleanup */
5592 show_shell_mess = TRUE;
5593 vim_free(command);
5594
Bram Moolenaarc7247912008-01-13 12:54:11 +00005595 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 {
5597 mch_remove(tempname);
5598 vim_free(tempname);
5599 /*
5600 * With interactive completion, the error message is not printed.
5601 * However with USE_SYSTEM, I don't know how to turn off error messages
5602 * from the shell, so screen may still get messed up -- webb.
5603 */
5604#ifndef USE_SYSTEM
5605 if (!(flags & EW_SILENT))
5606#endif
5607 {
5608 redraw_later_clear(); /* probably messed up screen */
5609 msg_putchar('\n'); /* clear bottom line quickly */
5610 cmdline_row = Rows - 1; /* continue on last line */
5611#ifdef USE_SYSTEM
5612 if (!(flags & EW_SILENT))
5613#endif
5614 {
5615 MSG(_(e_wildexpand));
5616 msg_start(); /* don't overwrite this message */
5617 }
5618 }
5619 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5620 * EW_NOTFOUND is given */
5621 if (shell_style == STYLE_BT)
5622 return FAIL;
5623 goto notfound;
5624 }
5625
5626 /*
5627 * read the names from the file into memory
5628 */
5629 fd = fopen((char *)tempname, READBIN);
5630 if (fd == NULL)
5631 {
5632 /* Something went wrong, perhaps a file name with a special char. */
5633 if (!(flags & EW_SILENT))
5634 {
5635 MSG(_(e_wildexpand));
5636 msg_start(); /* don't overwrite this message */
5637 }
5638 vim_free(tempname);
5639 goto notfound;
5640 }
5641 fseek(fd, 0L, SEEK_END);
5642 len = ftell(fd); /* get size of temp file */
5643 fseek(fd, 0L, SEEK_SET);
5644 buffer = alloc(len + 1);
5645 if (buffer == NULL)
5646 {
5647 /* out of memory */
5648 mch_remove(tempname);
5649 vim_free(tempname);
5650 fclose(fd);
5651 return FAIL;
5652 }
5653 i = fread((char *)buffer, 1, len, fd);
5654 fclose(fd);
5655 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005656 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 {
5658 /* unexpected read error */
5659 EMSG2(_(e_notread), tempname);
5660 vim_free(tempname);
5661 vim_free(buffer);
5662 return FAIL;
5663 }
5664 vim_free(tempname);
5665
Bram Moolenaarc7247912008-01-13 12:54:11 +00005666# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5668 p = buffer;
5669 for (i = 0; i < len; ++i)
5670 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5671 *p++ = buffer[i];
5672 len = p - buffer;
5673# endif
5674
5675
5676 /* file names are separated with Space */
5677 if (shell_style == STYLE_ECHO)
5678 {
5679 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5680 p = buffer;
5681 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5682 {
5683 while (*p != ' ' && *p != '\n')
5684 ++p;
5685 p = skipwhite(p); /* skip to next entry */
5686 }
5687 }
5688 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005689 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 {
5691 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5692 p = buffer;
5693 for (i = 0; *p != NUL; ++i) /* count number of entries */
5694 {
5695 while (*p != '\n' && *p != NUL)
5696 ++p;
5697 if (*p != NUL)
5698 ++p;
5699 p = skipwhite(p); /* skip leading white space */
5700 }
5701 }
5702 /* file names are separated with NUL */
5703 else
5704 {
5705 /*
5706 * Some versions of zsh use spaces instead of NULs to separate
5707 * results. Only do this when there is no NUL before the end of the
5708 * buffer, otherwise we would never be able to use file names with
5709 * embedded spaces when zsh does use NULs.
5710 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5711 * don't check for spaces again.
5712 */
5713 check_spaces = FALSE;
5714 if (shell_style == STYLE_PRINT && !did_find_nul)
5715 {
5716 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005717 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005718 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 did_find_nul = TRUE;
5720 else
5721 check_spaces = TRUE;
5722 }
5723
5724 /*
5725 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5726 * already is one, for STYLE_GLOB it needs to be added.
5727 */
5728 if (len && buffer[len - 1] == NUL)
5729 --len;
5730 else
5731 buffer[len] = NUL;
5732 i = 0;
5733 for (p = buffer; p < buffer + len; ++p)
5734 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5735 {
5736 ++i;
5737 *p = NUL;
5738 }
5739 if (len)
5740 ++i; /* count last entry */
5741 }
5742 if (i == 0)
5743 {
5744 /*
5745 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5746 * /bin/sh will happily expand it to nothing rather than returning an
5747 * error; and hey, it's good to check anyway -- webb.
5748 */
5749 vim_free(buffer);
5750 goto notfound;
5751 }
5752 *num_file = i;
5753 *file = (char_u **)alloc(sizeof(char_u *) * i);
5754 if (*file == NULL)
5755 {
5756 /* out of memory */
5757 vim_free(buffer);
5758 return FAIL;
5759 }
5760
5761 /*
5762 * Isolate the individual file names.
5763 */
5764 p = buffer;
5765 for (i = 0; i < *num_file; ++i)
5766 {
5767 (*file)[i] = p;
5768 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005769 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5770 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005772 while (!(shell_style == STYLE_ECHO && *p == ' ')
5773 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774 ++p;
5775 if (p == buffer + len) /* last entry */
5776 *p = NUL;
5777 else
5778 {
5779 *p++ = NUL;
5780 p = skipwhite(p); /* skip to next entry */
5781 }
5782 }
5783 else /* NUL separates */
5784 {
5785 while (*p && p < buffer + len) /* skip entry */
5786 ++p;
5787 ++p; /* skip NUL */
5788 }
5789 }
5790
5791 /*
5792 * Move the file names to allocated memory.
5793 */
5794 for (j = 0, i = 0; i < *num_file; ++i)
5795 {
5796 /* Require the files to exist. Helps when using /bin/sh */
5797 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5798 continue;
5799
5800 /* check if this entry should be included */
5801 dir = (mch_isdir((*file)[i]));
5802 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5803 continue;
5804
Bram Moolenaara2031822006-03-07 22:29:51 +00005805 /* Skip files that are not executable if we check for that. */
5806 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5807 continue;
5808
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5810 if (p)
5811 {
5812 STRCPY(p, (*file)[i]);
5813 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005814 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 (*file)[j++] = p;
5816 }
5817 }
5818 vim_free(buffer);
5819 *num_file = j;
5820
5821 if (*num_file == 0) /* rejected all entries */
5822 {
5823 vim_free(*file);
5824 *file = NULL;
5825 goto notfound;
5826 }
5827
5828 return OK;
5829
5830notfound:
5831 if (flags & EW_NOTFOUND)
5832 return save_patterns(num_pat, pat, num_file, file);
5833 return FAIL;
5834
5835#endif /* __EMX__ */
5836}
5837
5838#endif /* VMS */
5839
5840#ifndef __EMX__
5841 static int
5842save_patterns(num_pat, pat, num_file, file)
5843 int num_pat;
5844 char_u **pat;
5845 int *num_file;
5846 char_u ***file;
5847{
5848 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005849 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850
5851 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5852 if (*file == NULL)
5853 return FAIL;
5854 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005855 {
5856 s = vim_strsave(pat[i]);
5857 if (s != NULL)
5858 /* Be compatible with expand_filename(): halve the number of
5859 * backslashes. */
5860 backslash_halve(s);
5861 (*file)[i] = s;
5862 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 *num_file = num_pat;
5864 return OK;
5865}
5866#endif
5867
5868
5869/*
5870 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5871 * expand.
5872 */
5873 int
5874mch_has_exp_wildcard(p)
5875 char_u *p;
5876{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005877 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 {
5879#ifndef OS2
5880 if (*p == '\\' && p[1] != NUL)
5881 ++p;
5882 else
5883#endif
5884 if (vim_strchr((char_u *)
5885#ifdef VMS
5886 "*?%"
5887#else
5888# ifdef OS2
5889 "*?"
5890# else
5891 "*?[{'"
5892# endif
5893#endif
5894 , *p) != NULL)
5895 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 }
5897 return FALSE;
5898}
5899
5900/*
5901 * Return TRUE if the string "p" contains a wildcard.
5902 * Don't recognize '~' at the end as a wildcard.
5903 */
5904 int
5905mch_has_wildcard(p)
5906 char_u *p;
5907{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005908 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 {
5910#ifndef OS2
5911 if (*p == '\\' && p[1] != NUL)
5912 ++p;
5913 else
5914#endif
5915 if (vim_strchr((char_u *)
5916#ifdef VMS
5917 "*?%$"
5918#else
5919# ifdef OS2
5920# ifdef VIM_BACKTICK
5921 "*?$`"
5922# else
5923 "*?$"
5924# endif
5925# else
5926 "*?[{`'$"
5927# endif
5928#endif
5929 , *p) != NULL
5930 || (*p == '~' && p[1] != NUL))
5931 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 }
5933 return FALSE;
5934}
5935
5936#ifndef __EMX__
5937 static int
5938have_wildcard(num, file)
5939 int num;
5940 char_u **file;
5941{
5942 int i;
5943
5944 for (i = 0; i < num; i++)
5945 if (mch_has_wildcard(file[i]))
5946 return 1;
5947 return 0;
5948}
5949
5950 static int
5951have_dollars(num, file)
5952 int num;
5953 char_u **file;
5954{
5955 int i;
5956
5957 for (i = 0; i < num; i++)
5958 if (vim_strchr(file[i], '$') != NULL)
5959 return TRUE;
5960 return FALSE;
5961}
5962#endif /* ifndef __EMX__ */
5963
5964#ifndef HAVE_RENAME
5965/*
5966 * Scaled-down version of rename(), which is missing in Xenix.
5967 * This version can only move regular files and will fail if the
5968 * destination exists.
5969 */
5970 int
5971mch_rename(src, dest)
5972 const char *src, *dest;
5973{
5974 struct stat st;
5975
5976 if (stat(dest, &st) >= 0) /* fail if destination exists */
5977 return -1;
5978 if (link(src, dest) != 0) /* link file to new name */
5979 return -1;
5980 if (mch_remove(src) == 0) /* delete link to old name */
5981 return 0;
5982 return -1;
5983}
5984#endif /* !HAVE_RENAME */
5985
5986#ifdef FEAT_MOUSE_GPM
5987/*
5988 * Initializes connection with gpm (if it isn't already opened)
5989 * Return 1 if succeeded (or connection already opened), 0 if failed
5990 */
5991 static int
5992gpm_open()
5993{
5994 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
5995
5996 if (!gpm_flag)
5997 {
5998 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
5999 gpm_connect.defaultMask = ~GPM_HARD;
6000 /* Default handling for mouse move*/
6001 gpm_connect.minMod = 0; /* Handle any modifier keys */
6002 gpm_connect.maxMod = 0xffff;
6003 if (Gpm_Open(&gpm_connect, 0) > 0)
6004 {
6005 /* gpm library tries to handling TSTP causes
6006 * problems. Anyways, we close connection to Gpm whenever
6007 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006008 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006010# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006011 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006012# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013 return 1; /* succeed */
6014 }
6015 if (gpm_fd == -2)
6016 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6017 return 0;
6018 }
6019 return 1; /* already open */
6020}
6021
6022/*
6023 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 */
6025 static void
6026gpm_close()
6027{
6028 if (gpm_flag && gpm_fd >= 0) /* if Open */
6029 Gpm_Close();
6030}
6031
6032/* Reads gpm event and adds special keys to input buf. Returns length of
6033 * generated key sequence.
6034 * This function is made after gui_send_mouse_event
6035 */
6036 static int
6037mch_gpm_process()
6038{
6039 int button;
6040 static Gpm_Event gpm_event;
6041 char_u string[6];
6042 int_u vim_modifiers;
6043 int row,col;
6044 unsigned char buttons_mask;
6045 unsigned char gpm_modifiers;
6046 static unsigned char old_buttons = 0;
6047
6048 Gpm_GetEvent(&gpm_event);
6049
6050#ifdef FEAT_GUI
6051 /* Don't put events in the input queue now. */
6052 if (hold_gui_events)
6053 return 0;
6054#endif
6055
6056 row = gpm_event.y - 1;
6057 col = gpm_event.x - 1;
6058
6059 string[0] = ESC; /* Our termcode */
6060 string[1] = 'M';
6061 string[2] = 'G';
6062 switch (GPM_BARE_EVENTS(gpm_event.type))
6063 {
6064 case GPM_DRAG:
6065 string[3] = MOUSE_DRAG;
6066 break;
6067 case GPM_DOWN:
6068 buttons_mask = gpm_event.buttons & ~old_buttons;
6069 old_buttons = gpm_event.buttons;
6070 switch (buttons_mask)
6071 {
6072 case GPM_B_LEFT:
6073 button = MOUSE_LEFT;
6074 break;
6075 case GPM_B_MIDDLE:
6076 button = MOUSE_MIDDLE;
6077 break;
6078 case GPM_B_RIGHT:
6079 button = MOUSE_RIGHT;
6080 break;
6081 default:
6082 return 0;
6083 /*Don't know what to do. Can more than one button be
6084 * reported in one event? */
6085 }
6086 string[3] = (char_u)(button | 0x20);
6087 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6088 break;
6089 case GPM_UP:
6090 string[3] = MOUSE_RELEASE;
6091 old_buttons &= ~gpm_event.buttons;
6092 break;
6093 default:
6094 return 0;
6095 }
6096 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6097 gpm_modifiers = gpm_event.modifiers;
6098 vim_modifiers = 0x0;
6099 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6100 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6101 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6102 */
6103 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6104 vim_modifiers |= MOUSE_SHIFT;
6105
6106 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6107 vim_modifiers |= MOUSE_CTRL;
6108 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6109 vim_modifiers |= MOUSE_ALT;
6110 string[3] |= vim_modifiers;
6111 string[4] = (char_u)(col + ' ' + 1);
6112 string[5] = (char_u)(row + ' ' + 1);
6113 add_to_input_buf(string, 6);
6114 return 6;
6115}
6116#endif /* FEAT_MOUSE_GPM */
6117
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006118#ifdef FEAT_SYSMOUSE
6119/*
6120 * Initialize connection with sysmouse.
6121 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6122 * output, any sysmouse output than will be processed via sig_sysmouse().
6123 * Return OK if succeeded, FAIL if failed.
6124 */
6125 static int
6126sysmouse_open()
6127{
6128 struct mouse_info mouse;
6129
6130 mouse.operation = MOUSE_MODE;
6131 mouse.u.mode.mode = 0;
6132 mouse.u.mode.signal = SIGUSR2;
6133 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6134 {
6135 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6136 mouse.operation = MOUSE_SHOW;
6137 ioctl(1, CONS_MOUSECTL, &mouse);
6138 return OK;
6139 }
6140 return FAIL;
6141}
6142
6143/*
6144 * Stop processing SIGUSR2 signals, and also make sure that
6145 * virtual console do not send us any sysmouse related signal.
6146 */
6147 static void
6148sysmouse_close()
6149{
6150 struct mouse_info mouse;
6151
6152 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6153 mouse.operation = MOUSE_MODE;
6154 mouse.u.mode.mode = 0;
6155 mouse.u.mode.signal = 0;
6156 ioctl(1, CONS_MOUSECTL, &mouse);
6157}
6158
6159/*
6160 * Gets info from sysmouse and adds special keys to input buf.
6161 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006162 static RETSIGTYPE
6163sig_sysmouse SIGDEFARG(sigarg)
6164{
6165 struct mouse_info mouse;
6166 struct video_info video;
6167 char_u string[6];
6168 int row, col;
6169 int button;
6170 int buttons;
6171 static int oldbuttons = 0;
6172
6173#ifdef FEAT_GUI
6174 /* Don't put events in the input queue now. */
6175 if (hold_gui_events)
6176 return;
6177#endif
6178
6179 mouse.operation = MOUSE_GETINFO;
6180 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6181 && ioctl(1, FBIO_MODEINFO, &video) != -1
6182 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6183 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6184 {
6185 row = mouse.u.data.y / video.vi_cheight;
6186 col = mouse.u.data.x / video.vi_cwidth;
6187 buttons = mouse.u.data.buttons;
6188 string[0] = ESC; /* Our termcode */
6189 string[1] = 'M';
6190 string[2] = 'S';
6191 if (oldbuttons == buttons && buttons != 0)
6192 {
6193 button = MOUSE_DRAG;
6194 }
6195 else
6196 {
6197 switch (buttons)
6198 {
6199 case 0:
6200 button = MOUSE_RELEASE;
6201 break;
6202 case 1:
6203 button = MOUSE_LEFT;
6204 break;
6205 case 2:
6206 button = MOUSE_MIDDLE;
6207 break;
6208 case 4:
6209 button = MOUSE_RIGHT;
6210 break;
6211 default:
6212 return;
6213 }
6214 oldbuttons = buttons;
6215 }
6216 string[3] = (char_u)(button);
6217 string[4] = (char_u)(col + ' ' + 1);
6218 string[5] = (char_u)(row + ' ' + 1);
6219 add_to_input_buf(string, 6);
6220 }
6221 return;
6222}
6223#endif /* FEAT_SYSMOUSE */
6224
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225#if defined(FEAT_LIBCALL) || defined(PROTO)
6226typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6227typedef char_u * (*INTPROCSTR)__ARGS((int));
6228typedef int (*STRPROCINT)__ARGS((char_u *));
6229typedef int (*INTPROCINT)__ARGS((int));
6230
6231/*
6232 * Call a DLL routine which takes either a string or int param
6233 * and returns an allocated string.
6234 */
6235 int
6236mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6237 char_u *libname;
6238 char_u *funcname;
6239 char_u *argstring; /* NULL when using a argint */
6240 int argint;
6241 char_u **string_result;/* NULL when using number_result */
6242 int *number_result;
6243{
6244# if defined(USE_DLOPEN)
6245 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006246 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247# else
6248 shl_t hinstLib;
6249# endif
6250 STRPROCSTR ProcAdd;
6251 INTPROCSTR ProcAddI;
6252 char_u *retval_str = NULL;
6253 int retval_int = 0;
6254 int success = FALSE;
6255
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006256 /*
6257 * Get a handle to the DLL module.
6258 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006260 /* First clear any error, it's not cleared by the dlopen() call. */
6261 (void)dlerror();
6262
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 hinstLib = dlopen((char *)libname, RTLD_LAZY
6264# ifdef RTLD_LOCAL
6265 | RTLD_LOCAL
6266# endif
6267 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006268 if (hinstLib == NULL)
6269 {
6270 /* "dlerr" must be used before dlclose() */
6271 dlerr = (char *)dlerror();
6272 if (dlerr != NULL)
6273 EMSG2(_("dlerror = \"%s\""), dlerr);
6274 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275# else
6276 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6277# endif
6278
6279 /* If the handle is valid, try to get the function address. */
6280 if (hinstLib != NULL)
6281 {
6282# ifdef HAVE_SETJMP_H
6283 /*
6284 * Catch a crash when calling the library function. For example when
6285 * using a number where a string pointer is expected.
6286 */
6287 mch_startjmp();
6288 if (SETJMP(lc_jump_env) != 0)
6289 {
6290 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006291# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006292 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006293# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 mch_didjmp();
6295 }
6296 else
6297# endif
6298 {
6299 retval_str = NULL;
6300 retval_int = 0;
6301
6302 if (argstring != NULL)
6303 {
6304# if defined(USE_DLOPEN)
6305 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006306 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307# else
6308 if (shl_findsym(&hinstLib, (const char *)funcname,
6309 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6310 ProcAdd = NULL;
6311# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006312 if ((success = (ProcAdd != NULL
6313# if defined(USE_DLOPEN)
6314 && dlerr == NULL
6315# endif
6316 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 {
6318 if (string_result == NULL)
6319 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6320 else
6321 retval_str = (ProcAdd)(argstring);
6322 }
6323 }
6324 else
6325 {
6326# if defined(USE_DLOPEN)
6327 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006328 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329# else
6330 if (shl_findsym(&hinstLib, (const char *)funcname,
6331 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6332 ProcAddI = NULL;
6333# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006334 if ((success = (ProcAddI != NULL
6335# if defined(USE_DLOPEN)
6336 && dlerr == NULL
6337# endif
6338 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 {
6340 if (string_result == NULL)
6341 retval_int = ((INTPROCINT)ProcAddI)(argint);
6342 else
6343 retval_str = (ProcAddI)(argint);
6344 }
6345 }
6346
6347 /* Save the string before we free the library. */
6348 /* Assume that a "1" or "-1" result is an illegal pointer. */
6349 if (string_result == NULL)
6350 *number_result = retval_int;
6351 else if (retval_str != NULL
6352 && retval_str != (char_u *)1
6353 && retval_str != (char_u *)-1)
6354 *string_result = vim_strsave(retval_str);
6355 }
6356
6357# ifdef HAVE_SETJMP_H
6358 mch_endjmp();
6359# ifdef SIGHASARG
6360 if (lc_signal != 0)
6361 {
6362 int i;
6363
6364 /* try to find the name of this signal */
6365 for (i = 0; signal_info[i].sig != -1; i++)
6366 if (lc_signal == signal_info[i].sig)
6367 break;
6368 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6369 }
6370# endif
6371# endif
6372
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006374 /* "dlerr" must be used before dlclose() */
6375 if (dlerr != NULL)
6376 EMSG2(_("dlerror = \"%s\""), dlerr);
6377
6378 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 (void)dlclose(hinstLib);
6380# else
6381 (void)shl_unload(hinstLib);
6382# endif
6383 }
6384
6385 if (!success)
6386 {
6387 EMSG2(_(e_libcall), funcname);
6388 return FAIL;
6389 }
6390
6391 return OK;
6392}
6393#endif
6394
6395#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6396static int xterm_trace = -1; /* default: disabled */
6397static int xterm_button;
6398
6399/*
6400 * Setup a dummy window for X selections in a terminal.
6401 */
6402 void
6403setup_term_clip()
6404{
6405 int z = 0;
6406 char *strp = "";
6407 Widget AppShell;
6408
6409 if (!x_connect_to_server())
6410 return;
6411
6412 open_app_context();
6413 if (app_context != NULL && xterm_Shell == (Widget)0)
6414 {
6415 int (*oldhandler)();
6416#if defined(HAVE_SETJMP_H)
6417 int (*oldIOhandler)();
6418#endif
6419# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6420 struct timeval start_tv;
6421
6422 if (p_verbose > 0)
6423 gettimeofday(&start_tv, NULL);
6424# endif
6425
6426 /* Ignore X errors while opening the display */
6427 oldhandler = XSetErrorHandler(x_error_check);
6428
6429#if defined(HAVE_SETJMP_H)
6430 /* Ignore X IO errors while opening the display */
6431 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6432 mch_startjmp();
6433 if (SETJMP(lc_jump_env) != 0)
6434 {
6435 mch_didjmp();
6436 xterm_dpy = NULL;
6437 }
6438 else
6439#endif
6440 {
6441 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6442 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6443#if defined(HAVE_SETJMP_H)
6444 mch_endjmp();
6445#endif
6446 }
6447
6448#if defined(HAVE_SETJMP_H)
6449 /* Now handle X IO errors normally. */
6450 (void)XSetIOErrorHandler(oldIOhandler);
6451#endif
6452 /* Now handle X errors normally. */
6453 (void)XSetErrorHandler(oldhandler);
6454
6455 if (xterm_dpy == NULL)
6456 {
6457 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006458 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459 return;
6460 }
6461
6462 /* Catch terminating error of the X server connection. */
6463 (void)XSetIOErrorHandler(x_IOerror_handler);
6464
6465# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6466 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006467 {
6468 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006470 verbose_leave();
6471 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472# endif
6473
6474 /* Create a Shell to make converters work. */
6475 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6476 applicationShellWidgetClass, xterm_dpy,
6477 NULL);
6478 if (AppShell == (Widget)0)
6479 return;
6480 xterm_Shell = XtVaCreatePopupShell("VIM",
6481 topLevelShellWidgetClass, AppShell,
6482 XtNmappedWhenManaged, 0,
6483 XtNwidth, 1,
6484 XtNheight, 1,
6485 NULL);
6486 if (xterm_Shell == (Widget)0)
6487 return;
6488
6489 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006490 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 if (x11_display == NULL)
6492 x11_display = xterm_dpy;
6493
6494 XtRealizeWidget(xterm_Shell);
6495 XSync(xterm_dpy, False);
6496 xterm_update();
6497 }
6498 if (xterm_Shell != (Widget)0)
6499 {
6500 clip_init(TRUE);
6501 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6502 x11_window = (Window)atol(strp);
6503 /* Check if $WINDOWID is valid. */
6504 if (test_x11_window(xterm_dpy) == FAIL)
6505 x11_window = 0;
6506 if (x11_window != 0)
6507 xterm_trace = 0;
6508 }
6509}
6510
6511 void
6512start_xterm_trace(button)
6513 int button;
6514{
6515 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6516 return;
6517 xterm_trace = 1;
6518 xterm_button = button;
6519 do_xterm_trace();
6520}
6521
6522
6523 void
6524stop_xterm_trace()
6525{
6526 if (xterm_trace < 0)
6527 return;
6528 xterm_trace = 0;
6529}
6530
6531/*
6532 * Query the xterm pointer and generate mouse termcodes if necessary
6533 * return TRUE if dragging is active, else FALSE
6534 */
6535 static int
6536do_xterm_trace()
6537{
6538 Window root, child;
6539 int root_x, root_y;
6540 int win_x, win_y;
6541 int row, col;
6542 int_u mask_return;
6543 char_u buf[50];
6544 char_u *strp;
6545 long got_hints;
6546 static char_u *mouse_code;
6547 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6548 static int prev_row = 0, prev_col = 0;
6549 static XSizeHints xterm_hints;
6550
6551 if (xterm_trace <= 0)
6552 return FALSE;
6553
6554 if (xterm_trace == 1)
6555 {
6556 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006557 * have changed recently. */
6558 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6559 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 || xterm_hints.width_inc <= 1
6561 || xterm_hints.height_inc <= 1)
6562 {
6563 xterm_trace = -1; /* Not enough data -- disable tracing */
6564 return FALSE;
6565 }
6566
6567 /* Rely on the same mouse code for the duration of this */
6568 mouse_code = find_termcode(mouse_name);
6569 prev_row = mouse_row;
6570 prev_row = mouse_col;
6571 xterm_trace = 2;
6572
6573 /* Find the offset of the chars, there might be a scrollbar on the
6574 * left of the window and/or a menu on the top (eterm etc.) */
6575 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6576 &win_x, &win_y, &mask_return);
6577 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6578 - (xterm_hints.height_inc / 2);
6579 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6580 xterm_hints.y = 2;
6581 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6582 - (xterm_hints.width_inc / 2);
6583 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6584 xterm_hints.x = 2;
6585 return TRUE;
6586 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006587 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 {
6589 xterm_trace = 0;
6590 return FALSE;
6591 }
6592
6593 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6594 &win_x, &win_y, &mask_return);
6595
6596 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6597 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6598 if (row == prev_row && col == prev_col)
6599 return TRUE;
6600
6601 STRCPY(buf, mouse_code);
6602 strp = buf + STRLEN(buf);
6603 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6604 *strp++ = (char_u)(col + ' ' + 1);
6605 *strp++ = (char_u)(row + ' ' + 1);
6606 *strp = 0;
6607 add_to_input_buf(buf, STRLEN(buf));
6608
6609 prev_row = row;
6610 prev_col = col;
6611 return TRUE;
6612}
6613
6614# if defined(FEAT_GUI) || defined(PROTO)
6615/*
6616 * Destroy the display, window and app_context. Required for GTK.
6617 */
6618 void
6619clear_xterm_clip()
6620{
6621 if (xterm_Shell != (Widget)0)
6622 {
6623 XtDestroyWidget(xterm_Shell);
6624 xterm_Shell = (Widget)0;
6625 }
6626 if (xterm_dpy != NULL)
6627 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006628# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 /* Lesstif and Solaris crash here, lose some memory */
6630 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006631# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 if (x11_display == xterm_dpy)
6633 x11_display = NULL;
6634 xterm_dpy = NULL;
6635 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006636# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (app_context != (XtAppContext)NULL)
6638 {
6639 /* Lesstif and Solaris crash here, lose some memory */
6640 XtDestroyApplicationContext(app_context);
6641 app_context = (XtAppContext)NULL;
6642 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644}
6645# endif
6646
6647/*
6648 * Catch up with any queued X events. This may put keyboard input into the
6649 * input buffer, call resize call-backs, trigger timers etc. If there is
6650 * nothing in the X event queue (& no timers pending), then we return
6651 * immediately.
6652 */
6653 static void
6654xterm_update()
6655{
6656 XEvent event;
6657
6658 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6659 {
6660 XtAppNextEvent(app_context, &event);
6661#ifdef FEAT_CLIENTSERVER
6662 {
6663 XPropertyEvent *e = (XPropertyEvent *)&event;
6664
6665 if (e->type == PropertyNotify && e->window == commWindow
6666 && e->atom == commProperty && e->state == PropertyNewValue)
6667 serverEventProc(xterm_dpy, &event);
6668 }
6669#endif
6670 XtDispatchEvent(&event);
6671 }
6672}
6673
6674 int
6675clip_xterm_own_selection(cbd)
6676 VimClipboard *cbd;
6677{
6678 if (xterm_Shell != (Widget)0)
6679 return clip_x11_own_selection(xterm_Shell, cbd);
6680 return FAIL;
6681}
6682
6683 void
6684clip_xterm_lose_selection(cbd)
6685 VimClipboard *cbd;
6686{
6687 if (xterm_Shell != (Widget)0)
6688 clip_x11_lose_selection(xterm_Shell, cbd);
6689}
6690
6691 void
6692clip_xterm_request_selection(cbd)
6693 VimClipboard *cbd;
6694{
6695 if (xterm_Shell != (Widget)0)
6696 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6697}
6698
6699 void
6700clip_xterm_set_selection(cbd)
6701 VimClipboard *cbd;
6702{
6703 clip_x11_set_selection(cbd);
6704}
6705#endif
6706
6707
6708#if defined(USE_XSMP) || defined(PROTO)
6709/*
6710 * Code for X Session Management Protocol.
6711 */
6712static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6713static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6714static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6715static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6716static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6717
6718
6719# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6720static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6721
6722/*
6723 * This is our chance to ask the user if they want to save,
6724 * or abort the logout
6725 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 static void
6727xsmp_handle_interaction(smc_conn, client_data)
6728 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006729 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730{
6731 cmdmod_T save_cmdmod;
6732 int cancel_shutdown = False;
6733
6734 save_cmdmod = cmdmod;
6735 cmdmod.confirm = TRUE;
6736 if (check_changed_any(FALSE))
6737 /* Mustn't logout */
6738 cancel_shutdown = True;
6739 cmdmod = save_cmdmod;
6740 setcursor(); /* position cursor */
6741 out_flush();
6742
6743 /* Done interaction */
6744 SmcInteractDone(smc_conn, cancel_shutdown);
6745
6746 /* Finish off
6747 * Only end save-yourself here if we're not cancelling shutdown;
6748 * we'll get a cancelled callback later in which we'll end it.
6749 * Hopefully get around glitchy SMs (like GNOME-1)
6750 */
6751 if (!cancel_shutdown)
6752 {
6753 xsmp.save_yourself = False;
6754 SmcSaveYourselfDone(smc_conn, True);
6755 }
6756}
6757# endif
6758
6759/*
6760 * Callback that starts save-yourself.
6761 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 static void
6763xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6764 shutdown, interact_style, fast)
6765 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006766 SmPointer client_data UNUSED;
6767 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006769 int interact_style UNUSED;
6770 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771{
6772 /* Handle already being in saveyourself */
6773 if (xsmp.save_yourself)
6774 SmcSaveYourselfDone(smc_conn, True);
6775 xsmp.save_yourself = True;
6776 xsmp.shutdown = shutdown;
6777
6778 /* First up, preserve all files */
6779 out_flush();
6780 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6781
6782 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006783 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784
6785# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6786 /* Now see if we can ask about unsaved files */
6787 if (shutdown && !fast && gui.in_use)
6788 /* Need to interact with user, but need SM's permission */
6789 SmcInteractRequest(smc_conn, SmDialogError,
6790 xsmp_handle_interaction, client_data);
6791 else
6792# endif
6793 {
6794 /* Can stop the cycle here */
6795 SmcSaveYourselfDone(smc_conn, True);
6796 xsmp.save_yourself = False;
6797 }
6798}
6799
6800
6801/*
6802 * Callback to warn us of imminent death.
6803 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 static void
6805xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006806 SmcConn smc_conn UNUSED;
6807 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808{
6809 xsmp_close();
6810
6811 /* quit quickly leaving swapfiles for modified buffers behind */
6812 getout_preserve_modified(0);
6813}
6814
6815
6816/*
6817 * Callback to tell us that save-yourself has completed.
6818 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819 static void
6820xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006821 SmcConn smc_conn UNUSED;
6822 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823{
6824 xsmp.save_yourself = False;
6825}
6826
6827
6828/*
6829 * Callback to tell us that an instigated shutdown was cancelled
6830 * (maybe even by us)
6831 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832 static void
6833xsmp_shutdown_cancelled(smc_conn, client_data)
6834 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006835 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836{
6837 if (xsmp.save_yourself)
6838 SmcSaveYourselfDone(smc_conn, True);
6839 xsmp.save_yourself = False;
6840 xsmp.shutdown = False;
6841}
6842
6843
6844/*
6845 * Callback to tell us that a new ICE connection has been established.
6846 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847 static void
6848xsmp_ice_connection(iceConn, clientData, opening, watchData)
6849 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006850 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006852 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853{
6854 /* Intercept creation of ICE connection fd */
6855 if (opening)
6856 {
6857 xsmp_icefd = IceConnectionNumber(iceConn);
6858 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6859 }
6860}
6861
6862
6863/* Handle any ICE processing that's required; return FAIL if SM lost */
6864 int
6865xsmp_handle_requests()
6866{
6867 Bool rep;
6868
6869 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6870 == IceProcessMessagesIOError)
6871 {
6872 /* Lost ICE */
6873 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006874 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 xsmp_close();
6876 return FAIL;
6877 }
6878 else
6879 return OK;
6880}
6881
6882static int dummy;
6883
6884/* Set up X Session Management Protocol */
6885 void
6886xsmp_init(void)
6887{
6888 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 SmcCallbacks smcallbacks;
6890#if 0
6891 SmPropValue smname;
6892 SmProp smnameprop;
6893 SmProp *smprops[1];
6894#endif
6895
6896 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006897 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898
6899 xsmp.save_yourself = xsmp.shutdown = False;
6900
6901 /* Set up SM callbacks - must have all, even if they're not used */
6902 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6903 smcallbacks.save_yourself.client_data = NULL;
6904 smcallbacks.die.callback = xsmp_die;
6905 smcallbacks.die.client_data = NULL;
6906 smcallbacks.save_complete.callback = xsmp_save_complete;
6907 smcallbacks.save_complete.client_data = NULL;
6908 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6909 smcallbacks.shutdown_cancelled.client_data = NULL;
6910
6911 /* Set up a watch on ICE connection creations. The "dummy" argument is
6912 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6913 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6914 {
6915 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006916 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 return;
6918 }
6919
6920 /* Create an SM connection */
6921 xsmp.smcconn = SmcOpenConnection(
6922 NULL,
6923 NULL,
6924 SmProtoMajor,
6925 SmProtoMinor,
6926 SmcSaveYourselfProcMask | SmcDieProcMask
6927 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6928 &smcallbacks,
6929 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00006930 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 sizeof(errorstring),
6932 errorstring);
6933 if (xsmp.smcconn == NULL)
6934 {
6935 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006936
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006938 {
6939 vim_snprintf(errorreport, sizeof(errorreport),
6940 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6941 verb_msg((char_u *)errorreport);
6942 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 return;
6944 }
6945 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6946
6947#if 0
6948 /* ID ourselves */
6949 smname.value = "vim";
6950 smname.length = 3;
6951 smnameprop.name = "SmProgram";
6952 smnameprop.type = "SmARRAY8";
6953 smnameprop.num_vals = 1;
6954 smnameprop.vals = &smname;
6955
6956 smprops[0] = &smnameprop;
6957 SmcSetProperties(xsmp.smcconn, 1, smprops);
6958#endif
6959}
6960
6961
6962/* Shut down XSMP comms. */
6963 void
6964xsmp_close()
6965{
6966 if (xsmp_icefd != -1)
6967 {
6968 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00006969 if (xsmp.clientid != NULL)
6970 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00006971 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 xsmp_icefd = -1;
6973 }
6974}
6975#endif /* USE_XSMP */
6976
6977
6978#ifdef EBCDIC
6979/* Translate character to its CTRL- value */
6980char CtrlTable[] =
6981{
6982/* 00 - 5E */
6983 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6984 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6985 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6986 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6987 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6988 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6989/* ^ */ 0x1E,
6990/* - */ 0x1F,
6991/* 61 - 6C */
6992 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6993/* _ */ 0x1F,
6994/* 6E - 80 */
6995 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6996/* a */ 0x01,
6997/* b */ 0x02,
6998/* c */ 0x03,
6999/* d */ 0x37,
7000/* e */ 0x2D,
7001/* f */ 0x2E,
7002/* g */ 0x2F,
7003/* h */ 0x16,
7004/* i */ 0x05,
7005/* 8A - 90 */
7006 0, 0, 0, 0, 0, 0, 0,
7007/* j */ 0x15,
7008/* k */ 0x0B,
7009/* l */ 0x0C,
7010/* m */ 0x0D,
7011/* n */ 0x0E,
7012/* o */ 0x0F,
7013/* p */ 0x10,
7014/* q */ 0x11,
7015/* r */ 0x12,
7016/* 9A - A1 */
7017 0, 0, 0, 0, 0, 0, 0, 0,
7018/* s */ 0x13,
7019/* t */ 0x3C,
7020/* u */ 0x3D,
7021/* v */ 0x32,
7022/* w */ 0x26,
7023/* x */ 0x18,
7024/* y */ 0x19,
7025/* z */ 0x3F,
7026/* AA - AC */
7027 0, 0, 0,
7028/* [ */ 0x27,
7029/* AE - BC */
7030 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7031/* ] */ 0x1D,
7032/* BE - C0 */ 0, 0, 0,
7033/* A */ 0x01,
7034/* B */ 0x02,
7035/* C */ 0x03,
7036/* D */ 0x37,
7037/* E */ 0x2D,
7038/* F */ 0x2E,
7039/* G */ 0x2F,
7040/* H */ 0x16,
7041/* I */ 0x05,
7042/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7043/* J */ 0x15,
7044/* K */ 0x0B,
7045/* L */ 0x0C,
7046/* M */ 0x0D,
7047/* N */ 0x0E,
7048/* O */ 0x0F,
7049/* P */ 0x10,
7050/* Q */ 0x11,
7051/* R */ 0x12,
7052/* DA - DF */ 0, 0, 0, 0, 0, 0,
7053/* \ */ 0x1C,
7054/* E1 */ 0,
7055/* S */ 0x13,
7056/* T */ 0x3C,
7057/* U */ 0x3D,
7058/* V */ 0x32,
7059/* W */ 0x26,
7060/* X */ 0x18,
7061/* Y */ 0x19,
7062/* Z */ 0x3F,
7063/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7064 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7065};
7066
7067char MetaCharTable[]=
7068{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7069 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7070 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7071 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7072 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7073};
7074
7075
7076/* TODO: Use characters NOT numbers!!! */
7077char CtrlCharTable[]=
7078{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7079 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7080 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7081 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7082 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7083};
7084
7085
7086#endif