blob: 7b41a90a4f81967bb899c201dc13f28738052966 [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;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003798 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 int i;
3800 char_u *p;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003801 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003804# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805 int pty_slave_fd = -1;
3806 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003807# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003808 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 int fd_fromshell[2];
3810 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003811# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003813# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 static char envbuf_Rows[20];
3815 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003817 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818
Bram Moolenaar62b42182010-09-21 22:09:37 +02003819 newcmd = vim_strsave(p_sh);
3820 if (newcmd == NULL) /* out of memory */
3821 goto error;
3822
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 out_flush();
3824 if (options & SHELL_COOKED)
3825 settmode(TMODE_COOK); /* set to normal mode */
3826
Bram Moolenaar62b42182010-09-21 22:09:37 +02003827# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3828 loose_clipboard();
3829# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003830
3831 /*
3832 * Do this loop twice:
3833 * 1: find number of arguments
3834 * 2: separate them and build argv[]
3835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836 for (i = 0; i < 2; ++i)
3837 {
3838 p = newcmd;
3839 inquote = FALSE;
3840 argc = 0;
3841 for (;;)
3842 {
3843 if (i == 1)
3844 argv[argc] = (char *)p;
3845 ++argc;
3846 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3847 {
3848 if (*p == '"')
3849 inquote = !inquote;
3850 ++p;
3851 }
3852 if (*p == NUL)
3853 break;
3854 if (i == 1)
3855 *p++ = NUL;
3856 p = skipwhite(p);
3857 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003858 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003860 /*
3861 * Account for possible multiple args in p_shcf.
3862 */
3863 p = p_shcf;
3864 for (;;)
3865 {
3866 p = skiptowhite(p);
3867 if (*p == NUL)
3868 break;
3869 ++argc;
3870 p = skipwhite(p);
3871 }
3872
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3874 if (argv == NULL) /* out of memory */
3875 goto error;
3876 }
3877 }
3878 if (cmd != NULL)
3879 {
3880 if (extra_shell_arg != NULL)
3881 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003882
3883 /* Break 'shellcmdflag' into white separated parts. This doesn't
3884 * handle quoted strings, they are very unlikely to appear. */
3885 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
3886 if (p_shcf_copy == NULL) /* out of memory */
3887 goto error;
3888 s = p_shcf_copy;
3889 p = p_shcf;
3890 while (*p != NUL)
3891 {
3892 argv[argc++] = (char *)s;
3893 while (*p && *p != ' ' && *p != TAB)
3894 *s++ = *p++;
3895 *s++ = NUL;
3896 p = skipwhite(p);
3897 }
3898
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899 argv[argc++] = (char *)cmd;
3900 }
3901 argv[argc] = NULL;
3902
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003904 * For the GUI, when writing the output into the buffer and when reading
3905 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3906 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003908 if ((options & (SHELL_READ|SHELL_WRITE))
3909# ifdef FEAT_GUI
3910 || (gui.in_use && show_shell_mess)
3911# endif
3912 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003914# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003915 /*
3916 * Try to open a master pty.
3917 * If this works, open the slave pty.
3918 * If the slave can't be opened, close the master pty.
3919 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003920 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 {
3922 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02003923 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02003925 /* Leaving out O_NOCTTY may lead to waitpid() always returning
3926 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
3927 * adding O_NOCTTY always works when defined. */
3928#ifdef O_NOCTTY
3929 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
3930#else
3931 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
3932#endif
3933 if (pty_slave_fd < 0)
3934 {
3935 close(pty_master_fd);
3936 pty_master_fd = -1;
3937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 }
3939 }
3940 /*
3941 * If not opening a pty or it didn't work, try using pipes.
3942 */
3943 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003944# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 {
3946 pipe_error = (pipe(fd_toshell) < 0);
3947 if (!pipe_error) /* pipe create OK */
3948 {
3949 pipe_error = (pipe(fd_fromshell) < 0);
3950 if (pipe_error) /* pipe create failed */
3951 {
3952 close(fd_toshell[0]);
3953 close(fd_toshell[1]);
3954 }
3955 }
3956 if (pipe_error)
3957 {
3958 MSG_PUTS(_("\nCannot create pipes\n"));
3959 out_flush();
3960 }
3961 }
3962 }
3963
3964 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 {
3966# ifdef __BEOS__
3967 beos_cleanup_read_thread();
3968# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003969
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3971 {
3972 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003973 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003975 || (gui.in_use && show_shell_mess)
3976# endif
3977 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003979# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 if (pty_master_fd >= 0) /* close the pseudo tty */
3981 {
3982 close(pty_master_fd);
3983 close(pty_slave_fd);
3984 }
3985 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 {
3988 close(fd_toshell[0]);
3989 close(fd_toshell[1]);
3990 close(fd_fromshell[0]);
3991 close(fd_fromshell[1]);
3992 }
3993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 }
3995 else if (pid == 0) /* child */
3996 {
3997 reset_signals(); /* handle signals normally */
3998
3999 if (!show_shell_mess || (options & SHELL_EXPAND))
4000 {
4001 int fd;
4002
4003 /*
4004 * Don't want to show any message from the shell. Can't just
4005 * close stdout and stderr though, because some systems will
4006 * break if you try to write to them after that, so we must
4007 * use dup() to replace them with something else -- webb
4008 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4009 * waiting for input.
4010 */
4011 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4012 fclose(stdin);
4013 fclose(stdout);
4014 fclose(stderr);
4015
4016 /*
4017 * If any of these open()'s and dup()'s fail, we just continue
4018 * anyway. It's not fatal, and on most systems it will make
4019 * no difference at all. On a few it will cause the execvp()
4020 * to exit with a non-zero status even when the completion
4021 * could be done, which is nothing too serious. If the open()
4022 * or dup() failed we'd just do the same thing ourselves
4023 * anyway -- webb
4024 */
4025 if (fd >= 0)
4026 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004027 ignored = dup(fd); /* To replace stdin (fd 0) */
4028 ignored = dup(fd); /* To replace stdout (fd 1) */
4029 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030
4031 /* Don't need this now that we've duplicated it */
4032 close(fd);
4033 }
4034 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004035 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004037 || gui.in_use
4038# endif
4039 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 {
4041
Bram Moolenaardf177f62005-02-22 08:39:57 +00004042# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004043 /* Create our own process group, so that the child and all its
4044 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004045 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004046 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004047 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004048 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004049# if defined(SIGHUP)
4050 /* When doing "!xterm&" and 'shell' is bash: the shell
4051 * will exit and send SIGHUP to all processes in its
4052 * group, killing the just started process. Ignore SIGHUP
4053 * to avoid that. (suggested by Simon Schubert)
4054 */
4055 signal(SIGHUP, SIG_IGN);
4056# endif
4057 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004058# endif
4059# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004060 if (pty_slave_fd >= 0)
4061 {
4062 /* push stream discipline modules */
4063 if (options & SHELL_COOKED)
4064 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004066 /* Try to become controlling tty (probably doesn't work,
4067 * unless run by root) */
4068 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004070 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004071# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004073# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074 setenv("TERM", "dumb", 1);
4075 sprintf((char *)envbuf, "%ld", Rows);
4076 setenv("ROWS", (char *)envbuf, 1);
4077 sprintf((char *)envbuf, "%ld", Rows);
4078 setenv("LINES", (char *)envbuf, 1);
4079 sprintf((char *)envbuf, "%ld", Columns);
4080 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004081# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004082 /*
4083 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004084 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004085 */
4086 putenv("TERM=dumb");
4087 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4088 putenv(envbuf_Rows);
4089 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4090 putenv(envbuf_Rows);
4091 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4092 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004093# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094
Bram Moolenaara5792f52005-11-23 21:25:05 +00004095 /*
4096 * stderr is only redirected when using the GUI, so that a
4097 * program like gpg can still access the terminal to get a
4098 * passphrase using stderr.
4099 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004100# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 if (pty_master_fd >= 0)
4102 {
4103 close(pty_master_fd); /* close master side of pty */
4104
4105 /* set up stdin/stdout/stderr for the child */
4106 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004107 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004109 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004110 if (gui.in_use)
4111 {
4112 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004113 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004114 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
4116 close(pty_slave_fd); /* has been dupped, close it now */
4117 }
4118 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 {
4121 /* set up stdin for the child */
4122 close(fd_toshell[1]);
4123 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004124 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 close(fd_toshell[0]);
4126
4127 /* set up stdout for the child */
4128 close(fd_fromshell[0]);
4129 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004130 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 close(fd_fromshell[1]);
4132
Bram Moolenaara5792f52005-11-23 21:25:05 +00004133# ifdef FEAT_GUI
4134 if (gui.in_use)
4135 {
4136 /* set up stderr for the child */
4137 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004138 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004139 }
4140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 }
4142 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004143
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 /*
4145 * There is no type cast for the argv, because the type may be
4146 * different on different machines. This may cause a warning
4147 * message with strict compilers, don't worry about it.
4148 * Call _exit() instead of exit() to avoid closing the connection
4149 * to the X server (esp. with GTK, which uses atexit()).
4150 */
4151 execvp(argv[0], argv);
4152 _exit(EXEC_FAILED); /* exec failed, return failure code */
4153 }
4154 else /* parent */
4155 {
4156 /*
4157 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004158 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 */
4160 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004161 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162
4163 /*
4164 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004165 * This is also used to pipe stdin/stdout to/from the external
4166 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004168 if ((options & (SHELL_READ|SHELL_WRITE))
4169# ifdef FEAT_GUI
4170 || (gui.in_use && show_shell_mess)
4171# endif
4172 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004174# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004176# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004178# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4180 int ta_len = 0; /* valid bytes in ta_buf[] */
4181 int len;
4182 int p_more_save;
4183 int old_State;
4184 int c;
4185 int toshell_fd;
4186 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004187 garray_T ga;
4188 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004189# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4190 struct timeval start_tv;
4191# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192
Bram Moolenaardf177f62005-02-22 08:39:57 +00004193# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 if (pty_master_fd >= 0)
4195 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196 fromshell_fd = pty_master_fd;
4197 toshell_fd = dup(pty_master_fd);
4198 }
4199 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004200# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 {
4202 close(fd_toshell[0]);
4203 close(fd_fromshell[1]);
4204 toshell_fd = fd_toshell[1];
4205 fromshell_fd = fd_fromshell[0];
4206 }
4207
4208 /*
4209 * Write to the child if there are typed characters.
4210 * Read from the child if there are characters available.
4211 * Repeat the reading a few times if more characters are
4212 * available. Need to check for typed keys now and then, but
4213 * not too often (delays when no chars are available).
4214 * This loop is quit if no characters can be read from the pty
4215 * (WaitForChar detected special condition), or there are no
4216 * characters available and the child has exited.
4217 * Only check if the child has exited when there is no more
4218 * output. The child may exit before all the output has
4219 * been printed.
4220 *
4221 * Currently this busy loops!
4222 * This can probably dead-lock when the write blocks!
4223 */
4224 p_more_save = p_more;
4225 p_more = FALSE;
4226 old_State = State;
4227 State = EXTERNCMD; /* don't redraw at window resize */
4228
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004229 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004230 {
4231 /* Fork a process that will write the lines to the
4232 * external program. */
4233 if ((wpid = fork()) == -1)
4234 {
4235 MSG_PUTS(_("\nCannot fork\n"));
4236 }
4237 else if (wpid == 0)
4238 {
4239 linenr_T lnum = curbuf->b_op_start.lnum;
4240 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004241 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004242 char_u *s;
4243 size_t l;
4244
4245 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004246 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004247 for (;;)
4248 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004249 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004250 if (l == 0)
4251 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004252 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004253 /* NL -> NUL translation */
4254 len = write(toshell_fd, "", (size_t)1);
4255 else
4256 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004257 s = vim_strchr(lp + written, NL);
4258 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004259 s == NULL ? l
4260 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004261 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004262 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004263 {
4264 /* Finished a line, add a NL, unless this line
4265 * should not have one. */
4266 if (lnum != curbuf->b_op_end.lnum
4267 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004268 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004269 && (lnum !=
4270 curbuf->b_ml.ml_line_count
4271 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004272 ignored = write(toshell_fd, "\n",
4273 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004274 ++lnum;
4275 if (lnum > curbuf->b_op_end.lnum)
4276 {
4277 /* finished all the lines, close pipe */
4278 close(toshell_fd);
4279 toshell_fd = -1;
4280 break;
4281 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004282 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004283 written = 0;
4284 }
4285 else if (len > 0)
4286 written += len;
4287 }
4288 _exit(0);
4289 }
4290 else
4291 {
4292 close(toshell_fd);
4293 toshell_fd = -1;
4294 }
4295 }
4296
4297 if (options & SHELL_READ)
4298 ga_init2(&ga, 1, BUFLEN);
4299
4300 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004301# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4302 gettimeofday(&start_tv, NULL);
4303# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 for (;;)
4305 {
4306 /*
4307 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004308 * if there are any.
4309 * Don't do this if we are expanding wild cards (would eat
4310 * typeahead).
4311 * Don't do this when filtering and terminal is in cooked
4312 * mode, the shell command will handle the I/O. Avoids
4313 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004314 * Don't get characters when the child has already
4315 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004316 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004317 * while (noread_cnt > 4), avoids that ":r !ls" eats
4318 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 */
4320 len = 0;
4321 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004322 && ((options &
4323 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4324 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004325# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004326 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004327# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004328 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004329 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004330 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004332 if (ta_len == 0)
4333 {
4334 /* Get extra characters when we don't have any.
4335 * Reset the counter and timer. */
4336 noread_cnt = 0;
4337# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4338 gettimeofday(&start_tv, NULL);
4339# endif
4340 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4341 }
4342 if (ta_len > 0 || len > 0)
4343 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 /*
4345 * For pipes:
4346 * Check for CTRL-C: send interrupt signal to child.
4347 * Check for CTRL-D: EOF, close pipe to child.
4348 */
4349 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4350 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004351# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 /*
4353 * Send SIGINT to the child's group or all
4354 * processes in our group.
4355 */
4356 if (ta_buf[ta_len] == Ctrl_C
4357 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004358 {
4359# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004361# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004364 if (wpid > 0)
4365 kill(wpid, SIGINT);
4366 }
4367# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 if (pty_master_fd < 0 && toshell_fd >= 0
4369 && ta_buf[ta_len] == Ctrl_D)
4370 {
4371 close(toshell_fd);
4372 toshell_fd = -1;
4373 }
4374 }
4375
4376 /* replace K_BS by <BS> and K_DEL by <DEL> */
4377 for (i = ta_len; i < ta_len + len; ++i)
4378 {
4379 if (ta_buf[i] == CSI && len - i > 2)
4380 {
4381 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4382 if (c == K_DEL || c == K_KDEL || c == K_BS)
4383 {
4384 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4385 (size_t)(len - i - 2));
4386 if (c == K_DEL || c == K_KDEL)
4387 ta_buf[i] = DEL;
4388 else
4389 ta_buf[i] = Ctrl_H;
4390 len -= 2;
4391 }
4392 }
4393 else if (ta_buf[i] == '\r')
4394 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004395# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004397 i += (*mb_ptr2len_len)(ta_buf + i,
4398 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004399# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 }
4401
4402 /*
4403 * For pipes: echo the typed characters.
4404 * For a pty this does not seem to work.
4405 */
4406 if (pty_master_fd < 0)
4407 {
4408 for (i = ta_len; i < ta_len + len; ++i)
4409 {
4410 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4411 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004412# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413 else if (has_mbyte)
4414 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004415 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416
4417 msg_outtrans_len(ta_buf + i, l);
4418 i += l - 1;
4419 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004420# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421 else
4422 msg_outtrans_len(ta_buf + i, 1);
4423 }
4424 windgoto(msg_row, msg_col);
4425 out_flush();
4426 }
4427
4428 ta_len += len;
4429
4430 /*
4431 * Write the characters to the child, unless EOF has
4432 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004433 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004434 * When writing buffer lines, drop the typed
4435 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004437 if (options & SHELL_WRITE)
4438 ta_len = 0;
4439 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 {
4441 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4442 if (len > 0)
4443 {
4444 ta_len -= len;
4445 mch_memmove(ta_buf, ta_buf + len, ta_len);
4446 }
4447 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 }
4450
Bram Moolenaardf177f62005-02-22 08:39:57 +00004451 if (got_int)
4452 {
4453 /* CTRL-C sends a signal to the child, we ignore it
4454 * ourselves */
4455# ifdef HAVE_SETSID
4456 kill(-pid, SIGINT);
4457# else
4458 kill(0, SIGINT);
4459# endif
4460 if (wpid > 0)
4461 kill(wpid, SIGINT);
4462 got_int = FALSE;
4463 }
4464
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465 /*
4466 * Check if the child has any characters to be printed.
4467 * Read them and write them to our window. Repeat this as
4468 * long as there is something to do, avoid the 10ms wait
4469 * for mch_inchar(), or sending typeahead characters to
4470 * the external process.
4471 * TODO: This should handle escape sequences, compatible
4472 * to some terminal (vt52?).
4473 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004474 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4476 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004477 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004478# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004480# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004482# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 );
4484 if (len <= 0) /* end of file or error */
4485 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004486
4487 noread_cnt = 0;
4488 if (options & SHELL_READ)
4489 {
4490 /* Do NUL -> NL translation, append NL separated
4491 * lines to the current buffer. */
4492 for (i = 0; i < len; ++i)
4493 {
4494 if (buffer[i] == NL)
4495 append_ga_line(&ga);
4496 else if (buffer[i] == NUL)
4497 ga_append(&ga, NL);
4498 else
4499 ga_append(&ga, buffer[i]);
4500 }
4501 }
4502# ifdef FEAT_MBYTE
4503 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 {
4505 int l;
4506
Bram Moolenaardf177f62005-02-22 08:39:57 +00004507 len += buffer_off;
4508 buffer[len] = NUL;
4509
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 /* Check if the last character in buffer[] is
4511 * incomplete, keep these bytes for the next
4512 * round. */
4513 for (p = buffer; p < buffer + len; p += l)
4514 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004515 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 if (l == 0)
4517 l = 1; /* NUL byte? */
4518 else if (MB_BYTE2LEN(*p) != l)
4519 break;
4520 }
4521 if (p == buffer) /* no complete character */
4522 {
4523 /* avoid getting stuck at an illegal byte */
4524 if (len >= 12)
4525 ++p;
4526 else
4527 {
4528 buffer_off = len;
4529 continue;
4530 }
4531 }
4532 c = *p;
4533 *p = NUL;
4534 msg_puts(buffer);
4535 if (p < buffer + len)
4536 {
4537 *p = c;
4538 buffer_off = (buffer + len) - p;
4539 mch_memmove(buffer, p, buffer_off);
4540 continue;
4541 }
4542 buffer_off = 0;
4543 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004544# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 {
4547 buffer[len] = NUL;
4548 msg_puts(buffer);
4549 }
4550
4551 windgoto(msg_row, msg_col);
4552 cursor_on();
4553 out_flush();
4554 if (got_int)
4555 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004556
4557# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4558 {
4559 struct timeval now_tv;
4560 long msec;
4561
4562 /* Avoid that we keep looping here without
4563 * checking for a CTRL-C for a long time. Don't
4564 * break out too often to avoid losing typeahead. */
4565 gettimeofday(&now_tv, NULL);
4566 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4567 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4568 if (msec > 2000)
4569 {
4570 noread_cnt = 5;
4571 break;
4572 }
4573 }
4574# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575 }
4576
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004577 /* If we already detected the child has finished break the
4578 * loop now. */
4579 if (wait_pid == pid)
4580 break;
4581
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 /*
4583 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004584 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004586# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004588# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004590# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4592 || (wait_pid == pid && WIFEXITED(status)))
4593 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004594 /* Don't break the loop yet, try reading more
4595 * characters from "fromshell_fd" first. When using
4596 * pipes there might still be something to read and
4597 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004600 else
4601 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 }
4603finished:
4604 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004605 if (options & SHELL_READ)
4606 {
4607 if (ga.ga_len > 0)
4608 {
4609 append_ga_line(&ga);
4610 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004611 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004612 }
4613 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004614 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004615 ga_clear(&ga);
4616 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004617
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 /*
4619 * Give all typeahead that wasn't used back to ui_inchar().
4620 */
4621 if (ta_len)
4622 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 State = old_State;
4624 if (toshell_fd >= 0)
4625 close(toshell_fd);
4626 close(fromshell_fd);
4627 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628
4629 /*
4630 * Wait until our child has exited.
4631 * Ignore wait() returning pids of other children and returning
4632 * because of some signal like SIGWINCH.
4633 * Don't wait if wait_pid was already set above, indicating the
4634 * child already exited.
4635 */
4636 while (wait_pid != pid)
4637 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004638# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 /* Ugly hack: when compiled with Python threads are probably
4640 * used, in which case wait() sometimes hangs for no obvious
4641 * reason. Use waitpid() instead and loop (like the GUI). */
4642# ifdef __NeXT__
4643 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4644# else
4645 wait_pid = waitpid(pid, &status, WNOHANG);
4646# endif
4647 if (wait_pid == 0)
4648 {
4649 /* Wait for 1/100 sec before trying again. */
4650 mch_delay(10L, TRUE);
4651 continue;
4652 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004653# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004655# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 if (wait_pid <= 0
4657# ifdef ECHILD
4658 && errno == ECHILD
4659# endif
4660 )
4661 break;
4662 }
4663
Bram Moolenaar624891f2010-10-13 16:22:09 +02004664# ifdef FEAT_GUI
4665 /* Close slave side of pty. Only do this after the child has
4666 * exited, otherwise the child may hang when it tries to write on
4667 * the pty. */
4668 if (pty_master_fd >= 0)
4669 close(pty_slave_fd);
4670# endif
4671
Bram Moolenaardf177f62005-02-22 08:39:57 +00004672 /* Make sure the child that writes to the external program is
4673 * dead. */
4674 if (wpid > 0)
4675 kill(wpid, SIGKILL);
4676
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 /*
4678 * Set to raw mode right now, otherwise a CTRL-C after
4679 * catch_signals() will kill Vim.
4680 */
4681 if (tmode == TMODE_RAW)
4682 settmode(TMODE_RAW);
4683 did_settmode = TRUE;
4684 set_signals();
4685
4686 if (WIFEXITED(status))
4687 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004688 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 retval = WEXITSTATUS(status);
4690 if (retval && !emsg_silent)
4691 {
4692 if (retval == EXEC_FAILED)
4693 {
4694 MSG_PUTS(_("\nCannot execute shell "));
4695 msg_outtrans(p_sh);
4696 msg_putchar('\n');
4697 }
4698 else if (!(options & SHELL_SILENT))
4699 {
4700 MSG_PUTS(_("\nshell returned "));
4701 msg_outnum((long)retval);
4702 msg_putchar('\n');
4703 }
4704 }
4705 }
4706 else
4707 MSG_PUTS(_("\nCommand terminated\n"));
4708 }
4709 }
4710 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004711 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712
4713error:
4714 if (!did_settmode)
4715 if (tmode == TMODE_RAW)
4716 settmode(TMODE_RAW); /* set to raw mode */
4717# ifdef FEAT_TITLE
4718 resettitle();
4719# endif
4720 vim_free(newcmd);
4721
4722 return retval;
4723
4724#endif /* USE_SYSTEM */
4725}
4726
4727/*
4728 * Check for CTRL-C typed by reading all available characters.
4729 * In cooked mode we should get SIGINT, no need to check.
4730 */
4731 void
4732mch_breakcheck()
4733{
4734 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4735 fill_input_buf(FALSE);
4736}
4737
4738/*
4739 * Wait "msec" msec until a character is available from the keyboard or from
4740 * inbuf[]. msec == -1 will block forever.
4741 * When a GUI is being used, this will never get called -- webb
4742 */
4743 static int
4744WaitForChar(msec)
4745 long msec;
4746{
4747#ifdef FEAT_MOUSE_GPM
4748 int gpm_process_wanted;
4749#endif
4750#ifdef FEAT_XCLIPBOARD
4751 int rest;
4752#endif
4753 int avail;
4754
4755 if (input_available()) /* something in inbuf[] */
4756 return 1;
4757
4758#if defined(FEAT_MOUSE_DEC)
4759 /* May need to query the mouse position. */
4760 if (WantQueryMouse)
4761 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004762 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4764 }
4765#endif
4766
4767 /*
4768 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4769 * events. This is a bit complicated, because they might both be defined.
4770 */
4771#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4772# ifdef FEAT_XCLIPBOARD
4773 rest = 0;
4774 if (do_xterm_trace())
4775 rest = msec;
4776# endif
4777 do
4778 {
4779# ifdef FEAT_XCLIPBOARD
4780 if (rest != 0)
4781 {
4782 msec = XT_TRACE_DELAY;
4783 if (rest >= 0 && rest < XT_TRACE_DELAY)
4784 msec = rest;
4785 if (rest >= 0)
4786 rest -= msec;
4787 }
4788# endif
4789# ifdef FEAT_MOUSE_GPM
4790 gpm_process_wanted = 0;
4791 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4792# else
4793 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4794# endif
4795 if (!avail)
4796 {
4797 if (input_available())
4798 return 1;
4799# ifdef FEAT_XCLIPBOARD
4800 if (rest == 0 || !do_xterm_trace())
4801# endif
4802 break;
4803 }
4804 }
4805 while (FALSE
4806# ifdef FEAT_MOUSE_GPM
4807 || (gpm_process_wanted && mch_gpm_process() == 0)
4808# endif
4809# ifdef FEAT_XCLIPBOARD
4810 || (!avail && rest != 0)
4811# endif
4812 );
4813
4814#else
4815 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4816#endif
4817 return avail;
4818}
4819
4820/*
4821 * Wait "msec" msec until a character is available from file descriptor "fd".
4822 * Time == -1 will block forever.
4823 * When a GUI is being used, this will not be used for input -- webb
4824 * Returns also, when a request from Sniff is waiting -- toni.
4825 * Or when a Linux GPM mouse event is waiting.
4826 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827#if defined(__BEOS__)
4828 int
4829#else
4830 static int
4831#endif
4832RealWaitForChar(fd, msec, check_for_gpm)
4833 int fd;
4834 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004835 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836{
4837 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004838#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004839 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004840#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004841#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 static int busy = FALSE;
4843
4844 /* May retry getting characters after an event was handled. */
4845# define MAY_LOOP
4846
4847# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4848 /* Remember at what time we started, so that we know how much longer we
4849 * should wait after being interrupted. */
4850# define USE_START_TV
4851 struct timeval start_tv;
4852
4853 if (msec > 0 && (
4854# ifdef FEAT_XCLIPBOARD
4855 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004856# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 ||
4858# endif
4859# endif
4860# ifdef USE_XSMP
4861 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004862# ifdef FEAT_MZSCHEME
4863 ||
4864# endif
4865# endif
4866# ifdef FEAT_MZSCHEME
4867 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868# endif
4869 ))
4870 gettimeofday(&start_tv, NULL);
4871# endif
4872
4873 /* Handle being called recursively. This may happen for the session
4874 * manager stuff, it may save the file, which does a breakcheck. */
4875 if (busy)
4876 return 0;
4877#endif
4878
4879#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004880 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881#endif
4882 {
4883#ifdef MAY_LOOP
4884 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004885# ifdef FEAT_MZSCHEME
4886 int mzquantum_used = FALSE;
4887# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888#endif
4889#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004890 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 int nfd;
4892# ifdef FEAT_XCLIPBOARD
4893 int xterm_idx = -1;
4894# endif
4895# ifdef FEAT_MOUSE_GPM
4896 int gpm_idx = -1;
4897# endif
4898# ifdef USE_XSMP
4899 int xsmp_idx = -1;
4900# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004901# ifdef FEAT_NETBEANS_INTG
4902 int nb_idx = -1;
4903# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004904 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004906# ifdef FEAT_MZSCHEME
4907 mzvim_check_threads();
4908 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4909 {
4910 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4911 mzquantum_used = TRUE;
4912 }
4913# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 fds[0].fd = fd;
4915 fds[0].events = POLLIN;
4916 nfd = 1;
4917
4918# ifdef FEAT_SNIFF
4919# define SNIFF_IDX 1
4920 if (want_sniff_request)
4921 {
4922 fds[SNIFF_IDX].fd = fd_from_sniff;
4923 fds[SNIFF_IDX].events = POLLIN;
4924 nfd++;
4925 }
4926# endif
4927# ifdef FEAT_XCLIPBOARD
4928 if (xterm_Shell != (Widget)0)
4929 {
4930 xterm_idx = nfd;
4931 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4932 fds[nfd].events = POLLIN;
4933 nfd++;
4934 }
4935# endif
4936# ifdef FEAT_MOUSE_GPM
4937 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4938 {
4939 gpm_idx = nfd;
4940 fds[nfd].fd = gpm_fd;
4941 fds[nfd].events = POLLIN;
4942 nfd++;
4943 }
4944# endif
4945# ifdef USE_XSMP
4946 if (xsmp_icefd != -1)
4947 {
4948 xsmp_idx = nfd;
4949 fds[nfd].fd = xsmp_icefd;
4950 fds[nfd].events = POLLIN;
4951 nfd++;
4952 }
4953# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004954#ifdef FEAT_NETBEANS_INTG
4955 if (nb_fd != -1)
4956 {
4957 nb_idx = nfd;
4958 fds[nfd].fd = nb_fd;
4959 fds[nfd].events = POLLIN;
4960 nfd++;
4961 }
4962#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004964 ret = poll(fds, nfd, towait);
4965# ifdef FEAT_MZSCHEME
4966 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004967 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004968 finished = FALSE;
4969# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970
4971# ifdef FEAT_SNIFF
4972 if (ret < 0)
4973 sniff_disconnect(1);
4974 else if (want_sniff_request)
4975 {
4976 if (fds[SNIFF_IDX].revents & POLLHUP)
4977 sniff_disconnect(1);
4978 if (fds[SNIFF_IDX].revents & POLLIN)
4979 sniff_request_waiting = 1;
4980 }
4981# endif
4982# ifdef FEAT_XCLIPBOARD
4983 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4984 {
4985 xterm_update(); /* Maybe we should hand out clipboard */
4986 if (--ret == 0 && !input_available())
4987 /* Try again */
4988 finished = FALSE;
4989 }
4990# endif
4991# ifdef FEAT_MOUSE_GPM
4992 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4993 {
4994 *check_for_gpm = 1;
4995 }
4996# endif
4997# ifdef USE_XSMP
4998 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4999 {
5000 if (fds[xsmp_idx].revents & POLLIN)
5001 {
5002 busy = TRUE;
5003 xsmp_handle_requests();
5004 busy = FALSE;
5005 }
5006 else if (fds[xsmp_idx].revents & POLLHUP)
5007 {
5008 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005009 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005010 xsmp_close();
5011 }
5012 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005013 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 }
5015# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005016#ifdef FEAT_NETBEANS_INTG
5017 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5018 {
5019 netbeans_read();
5020 --ret;
5021 }
5022#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023
5024
5025#else /* HAVE_SELECT */
5026
5027 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005028 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 fd_set rfds, efds;
5030 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005031 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005033# ifdef FEAT_MZSCHEME
5034 mzvim_check_threads();
5035 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5036 {
5037 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5038 mzquantum_used = TRUE;
5039 }
5040# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041# ifdef __EMX__
5042 /* don't check for incoming chars if not in raw mode, because select()
5043 * always returns TRUE then (in some version of emx.dll) */
5044 if (curr_tmode != TMODE_RAW)
5045 return 0;
5046# endif
5047
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005048 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005050 tv.tv_sec = towait / 1000;
5051 tv.tv_usec = (towait % 1000) * (1000000/1000);
5052 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005054 else
5055 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056
5057 /*
5058 * Select on ready for reading and exceptional condition (end of file).
5059 */
5060 FD_ZERO(&rfds); /* calls bzero() on a sun */
5061 FD_ZERO(&efds);
5062 FD_SET(fd, &rfds);
5063# if !defined(__QNX__) && !defined(__CYGWIN32__)
5064 /* For QNX select() always returns 1 if this is set. Why? */
5065 FD_SET(fd, &efds);
5066# endif
5067 maxfd = fd;
5068
5069# ifdef FEAT_SNIFF
5070 if (want_sniff_request)
5071 {
5072 FD_SET(fd_from_sniff, &rfds);
5073 FD_SET(fd_from_sniff, &efds);
5074 if (maxfd < fd_from_sniff)
5075 maxfd = fd_from_sniff;
5076 }
5077# endif
5078# ifdef FEAT_XCLIPBOARD
5079 if (xterm_Shell != (Widget)0)
5080 {
5081 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5082 if (maxfd < ConnectionNumber(xterm_dpy))
5083 maxfd = ConnectionNumber(xterm_dpy);
5084 }
5085# endif
5086# ifdef FEAT_MOUSE_GPM
5087 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5088 {
5089 FD_SET(gpm_fd, &rfds);
5090 FD_SET(gpm_fd, &efds);
5091 if (maxfd < gpm_fd)
5092 maxfd = gpm_fd;
5093 }
5094# endif
5095# ifdef USE_XSMP
5096 if (xsmp_icefd != -1)
5097 {
5098 FD_SET(xsmp_icefd, &rfds);
5099 FD_SET(xsmp_icefd, &efds);
5100 if (maxfd < xsmp_icefd)
5101 maxfd = xsmp_icefd;
5102 }
5103# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005104#ifdef FEAT_NETBEANS_INTG
5105 if (nb_fd != -1)
5106 {
5107 FD_SET(nb_fd, &rfds);
5108 if (maxfd < nb_fd)
5109 maxfd = nb_fd;
5110 }
5111#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005112
5113# ifdef OLD_VMS
5114 /* Old VMS as v6.2 and older have broken select(). It waits more than
5115 * required. Should not be used */
5116 ret = 0;
5117# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005118 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5119# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005120# ifdef __TANDEM
5121 if (ret == -1 && errno == ENOTSUP)
5122 {
5123 FD_ZERO(&rfds);
5124 FD_ZERO(&efds);
5125 ret = 0;
5126 }
5127#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005128# ifdef FEAT_MZSCHEME
5129 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005130 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005131 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005132# endif
5133
5134# ifdef FEAT_SNIFF
5135 if (ret < 0 )
5136 sniff_disconnect(1);
5137 else if (ret > 0 && want_sniff_request)
5138 {
5139 if (FD_ISSET(fd_from_sniff, &efds))
5140 sniff_disconnect(1);
5141 if (FD_ISSET(fd_from_sniff, &rfds))
5142 sniff_request_waiting = 1;
5143 }
5144# endif
5145# ifdef FEAT_XCLIPBOARD
5146 if (ret > 0 && xterm_Shell != (Widget)0
5147 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5148 {
5149 xterm_update(); /* Maybe we should hand out clipboard */
5150 /* continue looping when we only got the X event and the input
5151 * buffer is empty */
5152 if (--ret == 0 && !input_available())
5153 {
5154 /* Try again */
5155 finished = FALSE;
5156 }
5157 }
5158# endif
5159# ifdef FEAT_MOUSE_GPM
5160 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5161 {
5162 if (FD_ISSET(gpm_fd, &efds))
5163 gpm_close();
5164 else if (FD_ISSET(gpm_fd, &rfds))
5165 *check_for_gpm = 1;
5166 }
5167# endif
5168# ifdef USE_XSMP
5169 if (ret > 0 && xsmp_icefd != -1)
5170 {
5171 if (FD_ISSET(xsmp_icefd, &efds))
5172 {
5173 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005174 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 xsmp_close();
5176 if (--ret == 0)
5177 finished = FALSE; /* keep going if event was only one */
5178 }
5179 else if (FD_ISSET(xsmp_icefd, &rfds))
5180 {
5181 busy = TRUE;
5182 xsmp_handle_requests();
5183 busy = FALSE;
5184 if (--ret == 0)
5185 finished = FALSE; /* keep going if event was only one */
5186 }
5187 }
5188# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005189#ifdef FEAT_NETBEANS_INTG
5190 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5191 {
5192 netbeans_read();
5193 --ret;
5194 }
5195#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196
5197#endif /* HAVE_SELECT */
5198
5199#ifdef MAY_LOOP
5200 if (finished || msec == 0)
5201 break;
5202
5203 /* We're going to loop around again, find out for how long */
5204 if (msec > 0)
5205 {
5206# ifdef USE_START_TV
5207 struct timeval mtv;
5208
5209 /* Compute remaining wait time. */
5210 gettimeofday(&mtv, NULL);
5211 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5212 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5213# else
5214 /* Guess we got interrupted halfway. */
5215 msec = msec / 2;
5216# endif
5217 if (msec <= 0)
5218 break; /* waited long enough */
5219 }
5220#endif
5221 }
5222
5223 return (ret > 0);
5224}
5225
5226#ifndef VMS
5227
5228#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005230 * Expand a path into all matching files and/or directories. Handles "*",
5231 * "?", "[a-z]", "**", etc.
5232 * "path" has backslashes before chars that are not to be expanded.
5233 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 */
5235 int
5236mch_expandpath(gap, path, flags)
5237 garray_T *gap;
5238 char_u *path;
5239 int flags; /* EW_* flags */
5240{
Bram Moolenaar02743632005-07-25 20:42:36 +00005241 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005242}
5243#endif
5244
5245/*
5246 * mch_expand_wildcards() - this code does wild-card pattern matching using
5247 * the shell
5248 *
5249 * return OK for success, FAIL for error (you may lose some memory) and put
5250 * an error message in *file.
5251 *
5252 * num_pat is number of input patterns
5253 * pat is array of pointers to input patterns
5254 * num_file is pointer to number of matched file names
5255 * file is pointer to array of pointers to matched file names
5256 */
5257
5258#ifndef SEEK_SET
5259# define SEEK_SET 0
5260#endif
5261#ifndef SEEK_END
5262# define SEEK_END 2
5263#endif
5264
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005265#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005266
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267 int
5268mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5269 int num_pat;
5270 char_u **pat;
5271 int *num_file;
5272 char_u ***file;
5273 int flags; /* EW_* flags */
5274{
5275 int i;
5276 size_t len;
5277 char_u *p;
5278 int dir;
5279#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005280 /*
5281 * This is the OS/2 implementation.
5282 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005283# define EXPL_ALLOC_INC 16
5284 char_u **expl_files;
5285 size_t files_alloced, files_free;
5286 char_u *buf;
5287 int has_wildcard;
5288
5289 *num_file = 0; /* default: no files found */
5290 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5291 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5292 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5293 if (*file == NULL)
5294 return FAIL;
5295
5296 for (; num_pat > 0; num_pat--, pat++)
5297 {
5298 expl_files = NULL;
5299 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5300 /* expand environment var or home dir */
5301 buf = expand_env_save(*pat);
5302 else
5303 buf = vim_strsave(*pat);
5304 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005305 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306 if (has_wildcard) /* yes, so expand them */
5307 expl_files = (char_u **)_fnexplode(buf);
5308
5309 /*
5310 * return value of buf if no wildcards left,
5311 * OR if no match AND EW_NOTFOUND is set.
5312 */
5313 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5314 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5315 { /* simply save the current contents of *buf */
5316 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5317 if (expl_files != NULL)
5318 {
5319 expl_files[0] = vim_strsave(buf);
5320 expl_files[1] = NULL;
5321 }
5322 }
5323 vim_free(buf);
5324
5325 /*
5326 * Count number of names resulting from expansion,
5327 * At the same time add a backslash to the end of names that happen to
5328 * be directories, and replace slashes with backslashes.
5329 */
5330 if (expl_files)
5331 {
5332 for (i = 0; (p = expl_files[i]) != NULL; i++)
5333 {
5334 dir = mch_isdir(p);
5335 /* If we don't want dirs and this is one, skip it */
5336 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5337 continue;
5338
Bram Moolenaara2031822006-03-07 22:29:51 +00005339 /* Skip files that are not executable if we check for that. */
5340 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5341 continue;
5342
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343 if (--files_free == 0)
5344 {
5345 /* need more room in table of pointers */
5346 files_alloced += EXPL_ALLOC_INC;
5347 *file = (char_u **)vim_realloc(*file,
5348 sizeof(char_u **) * files_alloced);
5349 if (*file == NULL)
5350 {
5351 EMSG(_(e_outofmem));
5352 *num_file = 0;
5353 return FAIL;
5354 }
5355 files_free = EXPL_ALLOC_INC;
5356 }
5357 slash_adjust(p);
5358 if (dir)
5359 {
5360 /* For a directory we add a '/', unless it's already
5361 * there. */
5362 len = STRLEN(p);
5363 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5364 {
5365 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005366 if (!after_pathsep((*file)[*num_file],
5367 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368 {
5369 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005370 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 }
5372 }
5373 }
5374 else
5375 {
5376 (*file)[*num_file] = vim_strsave(p);
5377 }
5378
5379 /*
5380 * Error message already given by either alloc or vim_strsave.
5381 * Should return FAIL, but returning OK works also.
5382 */
5383 if ((*file)[*num_file] == NULL)
5384 break;
5385 (*num_file)++;
5386 }
5387 _fnexplodefree((char **)expl_files);
5388 }
5389 }
5390 return OK;
5391
5392#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005393 /*
5394 * This is the non-OS/2 implementation (really Unix).
5395 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005396 int j;
5397 char_u *tempname;
5398 char_u *command;
5399 FILE *fd;
5400 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005401#define STYLE_ECHO 0 /* use "echo", the default */
5402#define STYLE_GLOB 1 /* use "glob", for csh */
5403#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5404#define STYLE_PRINT 3 /* use "print -N", for zsh */
5405#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5406 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407 int shell_style = STYLE_ECHO;
5408 int check_spaces;
5409 static int did_find_nul = FALSE;
5410 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005411 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005412 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413
5414 *num_file = 0; /* default: no files found */
5415 *file = NULL;
5416
5417 /*
5418 * If there are no wildcards, just copy the names to allocated memory.
5419 * Saves a lot of time, because we don't have to start a new shell.
5420 */
5421 if (!have_wildcard(num_pat, pat))
5422 return save_patterns(num_pat, pat, num_file, file);
5423
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005424# ifdef HAVE_SANDBOX
5425 /* Don't allow any shell command in the sandbox. */
5426 if (sandbox != 0 && check_secure())
5427 return FAIL;
5428# endif
5429
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430 /*
5431 * Don't allow the use of backticks in secure and restricted mode.
5432 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005433 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005434 for (i = 0; i < num_pat; ++i)
5435 if (vim_strchr(pat[i], '`') != NULL
5436 && (check_restricted() || check_secure()))
5437 return FAIL;
5438
5439 /*
5440 * get a name for the temp file
5441 */
5442 if ((tempname = vim_tempname('o')) == NULL)
5443 {
5444 EMSG(_(e_notmp));
5445 return FAIL;
5446 }
5447
5448 /*
5449 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005450 * file.
5451 * STYLE_BT: NL separated
5452 * If expanding `cmd` execute it directly.
5453 * STYLE_GLOB: NUL separated
5454 * If we use *csh, "glob" will work better than "echo".
5455 * STYLE_PRINT: NL or NUL separated
5456 * If we use *zsh, "print -N" will work better than "glob".
5457 * STYLE_VIMGLOB: NL separated
5458 * If we use *sh*, we define "vimglob()".
5459 * STYLE_ECHO: space separated.
5460 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461 */
5462 if (num_pat == 1 && *pat[0] == '`'
5463 && (len = STRLEN(pat[0])) > 2
5464 && *(pat[0] + len - 1) == '`')
5465 shell_style = STYLE_BT;
5466 else if ((len = STRLEN(p_sh)) >= 3)
5467 {
5468 if (STRCMP(p_sh + len - 3, "csh") == 0)
5469 shell_style = STYLE_GLOB;
5470 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5471 shell_style = STYLE_PRINT;
5472 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005473 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5474 "sh") != NULL)
5475 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476
Bram Moolenaarc7247912008-01-13 12:54:11 +00005477 /* Compute the length of the command. We need 2 extra bytes: for the
5478 * optional '&' and for the NUL.
5479 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005480 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005481 if (shell_style == STYLE_VIMGLOB)
5482 len += STRLEN(sh_vimglob_func);
5483
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005484 for (i = 0; i < num_pat; ++i)
5485 {
5486 /* Count the length of the patterns in the same way as they are put in
5487 * "command" below. */
5488#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005490#else
5491 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005492 for (j = 0; pat[i][j] != NUL; ++j)
5493 {
5494 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5495 ++len; /* may add a backslash */
5496 ++len;
5497 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005498#endif
5499 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 command = alloc(len);
5501 if (command == NULL)
5502 {
5503 /* out of memory */
5504 vim_free(tempname);
5505 return FAIL;
5506 }
5507
5508 /*
5509 * Build the shell command:
5510 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5511 * recognizes this).
5512 * - Add the shell command to print the expanded names.
5513 * - Add the temp file name.
5514 * - Add the file name patterns.
5515 */
5516 if (shell_style == STYLE_BT)
5517 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005518 /* change `command; command& ` to (command; command ) */
5519 STRCPY(command, "(");
5520 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005522 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 while (p > command && vim_iswhite(*p))
5524 --p;
5525 if (*p == '&') /* remove trailing '&' */
5526 {
5527 ampersent = TRUE;
5528 *p = ' ';
5529 }
5530 STRCAT(command, ">");
5531 }
5532 else
5533 {
5534 if (flags & EW_NOTFOUND)
5535 STRCPY(command, "set nonomatch; ");
5536 else
5537 STRCPY(command, "unset nonomatch; ");
5538 if (shell_style == STYLE_GLOB)
5539 STRCAT(command, "glob >");
5540 else if (shell_style == STYLE_PRINT)
5541 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005542 else if (shell_style == STYLE_VIMGLOB)
5543 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544 else
5545 STRCAT(command, "echo >");
5546 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005547
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005549
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 if (shell_style != STYLE_BT)
5551 for (i = 0; i < num_pat; ++i)
5552 {
5553 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005554 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005555 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556#ifdef USE_SYSTEM
5557 STRCAT(command, " \"");
5558 STRCAT(command, pat[i]);
5559 STRCAT(command, "\"");
5560#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005561 int intick = FALSE;
5562
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 p = command + STRLEN(command);
5564 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005565 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005566 {
5567 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005568 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005569 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5570 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005571 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005572 * backslash inside backticks, before a special character
5573 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005574 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005575 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5576 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005577 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005578 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005579 }
5580 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005581 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005582 /* Put a backslash before a special character, but not
5583 * when inside ``. */
5584 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005585
5586 /* Copy one character. */
5587 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 *p = NUL;
5590#endif
5591 }
5592 if (flags & EW_SILENT)
5593 show_shell_mess = FALSE;
5594 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005595 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596
5597 /*
5598 * Using zsh -G: If a pattern has no matches, it is just deleted from
5599 * the argument list, otherwise zsh gives an error message and doesn't
5600 * expand any other pattern.
5601 */
5602 if (shell_style == STYLE_PRINT)
5603 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5604
5605 /*
5606 * If we use -f then shell variables set in .cshrc won't get expanded.
5607 * vi can do it, so we will too, but it is only necessary if there is a "$"
5608 * in one of the patterns, otherwise we can still use the fast option.
5609 */
5610 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5611 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5612
5613 /*
5614 * execute the shell command
5615 */
5616 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5617
5618 /* When running in the background, give it some time to create the temp
5619 * file, but don't wait for it to finish. */
5620 if (ampersent)
5621 mch_delay(10L, TRUE);
5622
5623 extra_shell_arg = NULL; /* cleanup */
5624 show_shell_mess = TRUE;
5625 vim_free(command);
5626
Bram Moolenaarc7247912008-01-13 12:54:11 +00005627 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 {
5629 mch_remove(tempname);
5630 vim_free(tempname);
5631 /*
5632 * With interactive completion, the error message is not printed.
5633 * However with USE_SYSTEM, I don't know how to turn off error messages
5634 * from the shell, so screen may still get messed up -- webb.
5635 */
5636#ifndef USE_SYSTEM
5637 if (!(flags & EW_SILENT))
5638#endif
5639 {
5640 redraw_later_clear(); /* probably messed up screen */
5641 msg_putchar('\n'); /* clear bottom line quickly */
5642 cmdline_row = Rows - 1; /* continue on last line */
5643#ifdef USE_SYSTEM
5644 if (!(flags & EW_SILENT))
5645#endif
5646 {
5647 MSG(_(e_wildexpand));
5648 msg_start(); /* don't overwrite this message */
5649 }
5650 }
5651 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5652 * EW_NOTFOUND is given */
5653 if (shell_style == STYLE_BT)
5654 return FAIL;
5655 goto notfound;
5656 }
5657
5658 /*
5659 * read the names from the file into memory
5660 */
5661 fd = fopen((char *)tempname, READBIN);
5662 if (fd == NULL)
5663 {
5664 /* Something went wrong, perhaps a file name with a special char. */
5665 if (!(flags & EW_SILENT))
5666 {
5667 MSG(_(e_wildexpand));
5668 msg_start(); /* don't overwrite this message */
5669 }
5670 vim_free(tempname);
5671 goto notfound;
5672 }
5673 fseek(fd, 0L, SEEK_END);
5674 len = ftell(fd); /* get size of temp file */
5675 fseek(fd, 0L, SEEK_SET);
5676 buffer = alloc(len + 1);
5677 if (buffer == NULL)
5678 {
5679 /* out of memory */
5680 mch_remove(tempname);
5681 vim_free(tempname);
5682 fclose(fd);
5683 return FAIL;
5684 }
5685 i = fread((char *)buffer, 1, len, fd);
5686 fclose(fd);
5687 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005688 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 {
5690 /* unexpected read error */
5691 EMSG2(_(e_notread), tempname);
5692 vim_free(tempname);
5693 vim_free(buffer);
5694 return FAIL;
5695 }
5696 vim_free(tempname);
5697
Bram Moolenaarc7247912008-01-13 12:54:11 +00005698# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5700 p = buffer;
5701 for (i = 0; i < len; ++i)
5702 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5703 *p++ = buffer[i];
5704 len = p - buffer;
5705# endif
5706
5707
5708 /* file names are separated with Space */
5709 if (shell_style == STYLE_ECHO)
5710 {
5711 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5712 p = buffer;
5713 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5714 {
5715 while (*p != ' ' && *p != '\n')
5716 ++p;
5717 p = skipwhite(p); /* skip to next entry */
5718 }
5719 }
5720 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005721 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722 {
5723 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5724 p = buffer;
5725 for (i = 0; *p != NUL; ++i) /* count number of entries */
5726 {
5727 while (*p != '\n' && *p != NUL)
5728 ++p;
5729 if (*p != NUL)
5730 ++p;
5731 p = skipwhite(p); /* skip leading white space */
5732 }
5733 }
5734 /* file names are separated with NUL */
5735 else
5736 {
5737 /*
5738 * Some versions of zsh use spaces instead of NULs to separate
5739 * results. Only do this when there is no NUL before the end of the
5740 * buffer, otherwise we would never be able to use file names with
5741 * embedded spaces when zsh does use NULs.
5742 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5743 * don't check for spaces again.
5744 */
5745 check_spaces = FALSE;
5746 if (shell_style == STYLE_PRINT && !did_find_nul)
5747 {
5748 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005749 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005750 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751 did_find_nul = TRUE;
5752 else
5753 check_spaces = TRUE;
5754 }
5755
5756 /*
5757 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5758 * already is one, for STYLE_GLOB it needs to be added.
5759 */
5760 if (len && buffer[len - 1] == NUL)
5761 --len;
5762 else
5763 buffer[len] = NUL;
5764 i = 0;
5765 for (p = buffer; p < buffer + len; ++p)
5766 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5767 {
5768 ++i;
5769 *p = NUL;
5770 }
5771 if (len)
5772 ++i; /* count last entry */
5773 }
5774 if (i == 0)
5775 {
5776 /*
5777 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5778 * /bin/sh will happily expand it to nothing rather than returning an
5779 * error; and hey, it's good to check anyway -- webb.
5780 */
5781 vim_free(buffer);
5782 goto notfound;
5783 }
5784 *num_file = i;
5785 *file = (char_u **)alloc(sizeof(char_u *) * i);
5786 if (*file == NULL)
5787 {
5788 /* out of memory */
5789 vim_free(buffer);
5790 return FAIL;
5791 }
5792
5793 /*
5794 * Isolate the individual file names.
5795 */
5796 p = buffer;
5797 for (i = 0; i < *num_file; ++i)
5798 {
5799 (*file)[i] = p;
5800 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005801 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5802 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005804 while (!(shell_style == STYLE_ECHO && *p == ' ')
5805 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 ++p;
5807 if (p == buffer + len) /* last entry */
5808 *p = NUL;
5809 else
5810 {
5811 *p++ = NUL;
5812 p = skipwhite(p); /* skip to next entry */
5813 }
5814 }
5815 else /* NUL separates */
5816 {
5817 while (*p && p < buffer + len) /* skip entry */
5818 ++p;
5819 ++p; /* skip NUL */
5820 }
5821 }
5822
5823 /*
5824 * Move the file names to allocated memory.
5825 */
5826 for (j = 0, i = 0; i < *num_file; ++i)
5827 {
5828 /* Require the files to exist. Helps when using /bin/sh */
5829 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5830 continue;
5831
5832 /* check if this entry should be included */
5833 dir = (mch_isdir((*file)[i]));
5834 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5835 continue;
5836
Bram Moolenaara2031822006-03-07 22:29:51 +00005837 /* Skip files that are not executable if we check for that. */
5838 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5839 continue;
5840
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5842 if (p)
5843 {
5844 STRCPY(p, (*file)[i]);
5845 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005846 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 (*file)[j++] = p;
5848 }
5849 }
5850 vim_free(buffer);
5851 *num_file = j;
5852
5853 if (*num_file == 0) /* rejected all entries */
5854 {
5855 vim_free(*file);
5856 *file = NULL;
5857 goto notfound;
5858 }
5859
5860 return OK;
5861
5862notfound:
5863 if (flags & EW_NOTFOUND)
5864 return save_patterns(num_pat, pat, num_file, file);
5865 return FAIL;
5866
5867#endif /* __EMX__ */
5868}
5869
5870#endif /* VMS */
5871
5872#ifndef __EMX__
5873 static int
5874save_patterns(num_pat, pat, num_file, file)
5875 int num_pat;
5876 char_u **pat;
5877 int *num_file;
5878 char_u ***file;
5879{
5880 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005881 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882
5883 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5884 if (*file == NULL)
5885 return FAIL;
5886 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005887 {
5888 s = vim_strsave(pat[i]);
5889 if (s != NULL)
5890 /* Be compatible with expand_filename(): halve the number of
5891 * backslashes. */
5892 backslash_halve(s);
5893 (*file)[i] = s;
5894 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895 *num_file = num_pat;
5896 return OK;
5897}
5898#endif
5899
5900
5901/*
5902 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5903 * expand.
5904 */
5905 int
5906mch_has_exp_wildcard(p)
5907 char_u *p;
5908{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005909 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 {
5911#ifndef OS2
5912 if (*p == '\\' && p[1] != NUL)
5913 ++p;
5914 else
5915#endif
5916 if (vim_strchr((char_u *)
5917#ifdef VMS
5918 "*?%"
5919#else
5920# ifdef OS2
5921 "*?"
5922# else
5923 "*?[{'"
5924# endif
5925#endif
5926 , *p) != NULL)
5927 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 }
5929 return FALSE;
5930}
5931
5932/*
5933 * Return TRUE if the string "p" contains a wildcard.
5934 * Don't recognize '~' at the end as a wildcard.
5935 */
5936 int
5937mch_has_wildcard(p)
5938 char_u *p;
5939{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005940 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 {
5942#ifndef OS2
5943 if (*p == '\\' && p[1] != NUL)
5944 ++p;
5945 else
5946#endif
5947 if (vim_strchr((char_u *)
5948#ifdef VMS
5949 "*?%$"
5950#else
5951# ifdef OS2
5952# ifdef VIM_BACKTICK
5953 "*?$`"
5954# else
5955 "*?$"
5956# endif
5957# else
5958 "*?[{`'$"
5959# endif
5960#endif
5961 , *p) != NULL
5962 || (*p == '~' && p[1] != NUL))
5963 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964 }
5965 return FALSE;
5966}
5967
5968#ifndef __EMX__
5969 static int
5970have_wildcard(num, file)
5971 int num;
5972 char_u **file;
5973{
5974 int i;
5975
5976 for (i = 0; i < num; i++)
5977 if (mch_has_wildcard(file[i]))
5978 return 1;
5979 return 0;
5980}
5981
5982 static int
5983have_dollars(num, file)
5984 int num;
5985 char_u **file;
5986{
5987 int i;
5988
5989 for (i = 0; i < num; i++)
5990 if (vim_strchr(file[i], '$') != NULL)
5991 return TRUE;
5992 return FALSE;
5993}
5994#endif /* ifndef __EMX__ */
5995
5996#ifndef HAVE_RENAME
5997/*
5998 * Scaled-down version of rename(), which is missing in Xenix.
5999 * This version can only move regular files and will fail if the
6000 * destination exists.
6001 */
6002 int
6003mch_rename(src, dest)
6004 const char *src, *dest;
6005{
6006 struct stat st;
6007
6008 if (stat(dest, &st) >= 0) /* fail if destination exists */
6009 return -1;
6010 if (link(src, dest) != 0) /* link file to new name */
6011 return -1;
6012 if (mch_remove(src) == 0) /* delete link to old name */
6013 return 0;
6014 return -1;
6015}
6016#endif /* !HAVE_RENAME */
6017
6018#ifdef FEAT_MOUSE_GPM
6019/*
6020 * Initializes connection with gpm (if it isn't already opened)
6021 * Return 1 if succeeded (or connection already opened), 0 if failed
6022 */
6023 static int
6024gpm_open()
6025{
6026 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6027
6028 if (!gpm_flag)
6029 {
6030 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6031 gpm_connect.defaultMask = ~GPM_HARD;
6032 /* Default handling for mouse move*/
6033 gpm_connect.minMod = 0; /* Handle any modifier keys */
6034 gpm_connect.maxMod = 0xffff;
6035 if (Gpm_Open(&gpm_connect, 0) > 0)
6036 {
6037 /* gpm library tries to handling TSTP causes
6038 * problems. Anyways, we close connection to Gpm whenever
6039 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006040 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006042# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006044# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045 return 1; /* succeed */
6046 }
6047 if (gpm_fd == -2)
6048 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6049 return 0;
6050 }
6051 return 1; /* already open */
6052}
6053
6054/*
6055 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006056 */
6057 static void
6058gpm_close()
6059{
6060 if (gpm_flag && gpm_fd >= 0) /* if Open */
6061 Gpm_Close();
6062}
6063
6064/* Reads gpm event and adds special keys to input buf. Returns length of
6065 * generated key sequence.
6066 * This function is made after gui_send_mouse_event
6067 */
6068 static int
6069mch_gpm_process()
6070{
6071 int button;
6072 static Gpm_Event gpm_event;
6073 char_u string[6];
6074 int_u vim_modifiers;
6075 int row,col;
6076 unsigned char buttons_mask;
6077 unsigned char gpm_modifiers;
6078 static unsigned char old_buttons = 0;
6079
6080 Gpm_GetEvent(&gpm_event);
6081
6082#ifdef FEAT_GUI
6083 /* Don't put events in the input queue now. */
6084 if (hold_gui_events)
6085 return 0;
6086#endif
6087
6088 row = gpm_event.y - 1;
6089 col = gpm_event.x - 1;
6090
6091 string[0] = ESC; /* Our termcode */
6092 string[1] = 'M';
6093 string[2] = 'G';
6094 switch (GPM_BARE_EVENTS(gpm_event.type))
6095 {
6096 case GPM_DRAG:
6097 string[3] = MOUSE_DRAG;
6098 break;
6099 case GPM_DOWN:
6100 buttons_mask = gpm_event.buttons & ~old_buttons;
6101 old_buttons = gpm_event.buttons;
6102 switch (buttons_mask)
6103 {
6104 case GPM_B_LEFT:
6105 button = MOUSE_LEFT;
6106 break;
6107 case GPM_B_MIDDLE:
6108 button = MOUSE_MIDDLE;
6109 break;
6110 case GPM_B_RIGHT:
6111 button = MOUSE_RIGHT;
6112 break;
6113 default:
6114 return 0;
6115 /*Don't know what to do. Can more than one button be
6116 * reported in one event? */
6117 }
6118 string[3] = (char_u)(button | 0x20);
6119 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6120 break;
6121 case GPM_UP:
6122 string[3] = MOUSE_RELEASE;
6123 old_buttons &= ~gpm_event.buttons;
6124 break;
6125 default:
6126 return 0;
6127 }
6128 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6129 gpm_modifiers = gpm_event.modifiers;
6130 vim_modifiers = 0x0;
6131 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6132 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6133 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6134 */
6135 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6136 vim_modifiers |= MOUSE_SHIFT;
6137
6138 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6139 vim_modifiers |= MOUSE_CTRL;
6140 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6141 vim_modifiers |= MOUSE_ALT;
6142 string[3] |= vim_modifiers;
6143 string[4] = (char_u)(col + ' ' + 1);
6144 string[5] = (char_u)(row + ' ' + 1);
6145 add_to_input_buf(string, 6);
6146 return 6;
6147}
6148#endif /* FEAT_MOUSE_GPM */
6149
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006150#ifdef FEAT_SYSMOUSE
6151/*
6152 * Initialize connection with sysmouse.
6153 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6154 * output, any sysmouse output than will be processed via sig_sysmouse().
6155 * Return OK if succeeded, FAIL if failed.
6156 */
6157 static int
6158sysmouse_open()
6159{
6160 struct mouse_info mouse;
6161
6162 mouse.operation = MOUSE_MODE;
6163 mouse.u.mode.mode = 0;
6164 mouse.u.mode.signal = SIGUSR2;
6165 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6166 {
6167 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6168 mouse.operation = MOUSE_SHOW;
6169 ioctl(1, CONS_MOUSECTL, &mouse);
6170 return OK;
6171 }
6172 return FAIL;
6173}
6174
6175/*
6176 * Stop processing SIGUSR2 signals, and also make sure that
6177 * virtual console do not send us any sysmouse related signal.
6178 */
6179 static void
6180sysmouse_close()
6181{
6182 struct mouse_info mouse;
6183
6184 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6185 mouse.operation = MOUSE_MODE;
6186 mouse.u.mode.mode = 0;
6187 mouse.u.mode.signal = 0;
6188 ioctl(1, CONS_MOUSECTL, &mouse);
6189}
6190
6191/*
6192 * Gets info from sysmouse and adds special keys to input buf.
6193 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006194 static RETSIGTYPE
6195sig_sysmouse SIGDEFARG(sigarg)
6196{
6197 struct mouse_info mouse;
6198 struct video_info video;
6199 char_u string[6];
6200 int row, col;
6201 int button;
6202 int buttons;
6203 static int oldbuttons = 0;
6204
6205#ifdef FEAT_GUI
6206 /* Don't put events in the input queue now. */
6207 if (hold_gui_events)
6208 return;
6209#endif
6210
6211 mouse.operation = MOUSE_GETINFO;
6212 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6213 && ioctl(1, FBIO_MODEINFO, &video) != -1
6214 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6215 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6216 {
6217 row = mouse.u.data.y / video.vi_cheight;
6218 col = mouse.u.data.x / video.vi_cwidth;
6219 buttons = mouse.u.data.buttons;
6220 string[0] = ESC; /* Our termcode */
6221 string[1] = 'M';
6222 string[2] = 'S';
6223 if (oldbuttons == buttons && buttons != 0)
6224 {
6225 button = MOUSE_DRAG;
6226 }
6227 else
6228 {
6229 switch (buttons)
6230 {
6231 case 0:
6232 button = MOUSE_RELEASE;
6233 break;
6234 case 1:
6235 button = MOUSE_LEFT;
6236 break;
6237 case 2:
6238 button = MOUSE_MIDDLE;
6239 break;
6240 case 4:
6241 button = MOUSE_RIGHT;
6242 break;
6243 default:
6244 return;
6245 }
6246 oldbuttons = buttons;
6247 }
6248 string[3] = (char_u)(button);
6249 string[4] = (char_u)(col + ' ' + 1);
6250 string[5] = (char_u)(row + ' ' + 1);
6251 add_to_input_buf(string, 6);
6252 }
6253 return;
6254}
6255#endif /* FEAT_SYSMOUSE */
6256
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257#if defined(FEAT_LIBCALL) || defined(PROTO)
6258typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6259typedef char_u * (*INTPROCSTR)__ARGS((int));
6260typedef int (*STRPROCINT)__ARGS((char_u *));
6261typedef int (*INTPROCINT)__ARGS((int));
6262
6263/*
6264 * Call a DLL routine which takes either a string or int param
6265 * and returns an allocated string.
6266 */
6267 int
6268mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6269 char_u *libname;
6270 char_u *funcname;
6271 char_u *argstring; /* NULL when using a argint */
6272 int argint;
6273 char_u **string_result;/* NULL when using number_result */
6274 int *number_result;
6275{
6276# if defined(USE_DLOPEN)
6277 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006278 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279# else
6280 shl_t hinstLib;
6281# endif
6282 STRPROCSTR ProcAdd;
6283 INTPROCSTR ProcAddI;
6284 char_u *retval_str = NULL;
6285 int retval_int = 0;
6286 int success = FALSE;
6287
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006288 /*
6289 * Get a handle to the DLL module.
6290 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006292 /* First clear any error, it's not cleared by the dlopen() call. */
6293 (void)dlerror();
6294
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 hinstLib = dlopen((char *)libname, RTLD_LAZY
6296# ifdef RTLD_LOCAL
6297 | RTLD_LOCAL
6298# endif
6299 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006300 if (hinstLib == NULL)
6301 {
6302 /* "dlerr" must be used before dlclose() */
6303 dlerr = (char *)dlerror();
6304 if (dlerr != NULL)
6305 EMSG2(_("dlerror = \"%s\""), dlerr);
6306 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307# else
6308 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6309# endif
6310
6311 /* If the handle is valid, try to get the function address. */
6312 if (hinstLib != NULL)
6313 {
6314# ifdef HAVE_SETJMP_H
6315 /*
6316 * Catch a crash when calling the library function. For example when
6317 * using a number where a string pointer is expected.
6318 */
6319 mch_startjmp();
6320 if (SETJMP(lc_jump_env) != 0)
6321 {
6322 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006323# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006324 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006325# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 mch_didjmp();
6327 }
6328 else
6329# endif
6330 {
6331 retval_str = NULL;
6332 retval_int = 0;
6333
6334 if (argstring != NULL)
6335 {
6336# if defined(USE_DLOPEN)
6337 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006338 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339# else
6340 if (shl_findsym(&hinstLib, (const char *)funcname,
6341 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6342 ProcAdd = NULL;
6343# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006344 if ((success = (ProcAdd != NULL
6345# if defined(USE_DLOPEN)
6346 && dlerr == NULL
6347# endif
6348 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 {
6350 if (string_result == NULL)
6351 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6352 else
6353 retval_str = (ProcAdd)(argstring);
6354 }
6355 }
6356 else
6357 {
6358# if defined(USE_DLOPEN)
6359 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006360 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361# else
6362 if (shl_findsym(&hinstLib, (const char *)funcname,
6363 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6364 ProcAddI = NULL;
6365# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006366 if ((success = (ProcAddI != NULL
6367# if defined(USE_DLOPEN)
6368 && dlerr == NULL
6369# endif
6370 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 {
6372 if (string_result == NULL)
6373 retval_int = ((INTPROCINT)ProcAddI)(argint);
6374 else
6375 retval_str = (ProcAddI)(argint);
6376 }
6377 }
6378
6379 /* Save the string before we free the library. */
6380 /* Assume that a "1" or "-1" result is an illegal pointer. */
6381 if (string_result == NULL)
6382 *number_result = retval_int;
6383 else if (retval_str != NULL
6384 && retval_str != (char_u *)1
6385 && retval_str != (char_u *)-1)
6386 *string_result = vim_strsave(retval_str);
6387 }
6388
6389# ifdef HAVE_SETJMP_H
6390 mch_endjmp();
6391# ifdef SIGHASARG
6392 if (lc_signal != 0)
6393 {
6394 int i;
6395
6396 /* try to find the name of this signal */
6397 for (i = 0; signal_info[i].sig != -1; i++)
6398 if (lc_signal == signal_info[i].sig)
6399 break;
6400 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6401 }
6402# endif
6403# endif
6404
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006406 /* "dlerr" must be used before dlclose() */
6407 if (dlerr != NULL)
6408 EMSG2(_("dlerror = \"%s\""), dlerr);
6409
6410 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 (void)dlclose(hinstLib);
6412# else
6413 (void)shl_unload(hinstLib);
6414# endif
6415 }
6416
6417 if (!success)
6418 {
6419 EMSG2(_(e_libcall), funcname);
6420 return FAIL;
6421 }
6422
6423 return OK;
6424}
6425#endif
6426
6427#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6428static int xterm_trace = -1; /* default: disabled */
6429static int xterm_button;
6430
6431/*
6432 * Setup a dummy window for X selections in a terminal.
6433 */
6434 void
6435setup_term_clip()
6436{
6437 int z = 0;
6438 char *strp = "";
6439 Widget AppShell;
6440
6441 if (!x_connect_to_server())
6442 return;
6443
6444 open_app_context();
6445 if (app_context != NULL && xterm_Shell == (Widget)0)
6446 {
6447 int (*oldhandler)();
6448#if defined(HAVE_SETJMP_H)
6449 int (*oldIOhandler)();
6450#endif
6451# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6452 struct timeval start_tv;
6453
6454 if (p_verbose > 0)
6455 gettimeofday(&start_tv, NULL);
6456# endif
6457
6458 /* Ignore X errors while opening the display */
6459 oldhandler = XSetErrorHandler(x_error_check);
6460
6461#if defined(HAVE_SETJMP_H)
6462 /* Ignore X IO errors while opening the display */
6463 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6464 mch_startjmp();
6465 if (SETJMP(lc_jump_env) != 0)
6466 {
6467 mch_didjmp();
6468 xterm_dpy = NULL;
6469 }
6470 else
6471#endif
6472 {
6473 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6474 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6475#if defined(HAVE_SETJMP_H)
6476 mch_endjmp();
6477#endif
6478 }
6479
6480#if defined(HAVE_SETJMP_H)
6481 /* Now handle X IO errors normally. */
6482 (void)XSetIOErrorHandler(oldIOhandler);
6483#endif
6484 /* Now handle X errors normally. */
6485 (void)XSetErrorHandler(oldhandler);
6486
6487 if (xterm_dpy == NULL)
6488 {
6489 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006490 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 return;
6492 }
6493
6494 /* Catch terminating error of the X server connection. */
6495 (void)XSetIOErrorHandler(x_IOerror_handler);
6496
6497# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6498 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006499 {
6500 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006502 verbose_leave();
6503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504# endif
6505
6506 /* Create a Shell to make converters work. */
6507 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6508 applicationShellWidgetClass, xterm_dpy,
6509 NULL);
6510 if (AppShell == (Widget)0)
6511 return;
6512 xterm_Shell = XtVaCreatePopupShell("VIM",
6513 topLevelShellWidgetClass, AppShell,
6514 XtNmappedWhenManaged, 0,
6515 XtNwidth, 1,
6516 XtNheight, 1,
6517 NULL);
6518 if (xterm_Shell == (Widget)0)
6519 return;
6520
6521 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006522 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 if (x11_display == NULL)
6524 x11_display = xterm_dpy;
6525
6526 XtRealizeWidget(xterm_Shell);
6527 XSync(xterm_dpy, False);
6528 xterm_update();
6529 }
6530 if (xterm_Shell != (Widget)0)
6531 {
6532 clip_init(TRUE);
6533 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6534 x11_window = (Window)atol(strp);
6535 /* Check if $WINDOWID is valid. */
6536 if (test_x11_window(xterm_dpy) == FAIL)
6537 x11_window = 0;
6538 if (x11_window != 0)
6539 xterm_trace = 0;
6540 }
6541}
6542
6543 void
6544start_xterm_trace(button)
6545 int button;
6546{
6547 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6548 return;
6549 xterm_trace = 1;
6550 xterm_button = button;
6551 do_xterm_trace();
6552}
6553
6554
6555 void
6556stop_xterm_trace()
6557{
6558 if (xterm_trace < 0)
6559 return;
6560 xterm_trace = 0;
6561}
6562
6563/*
6564 * Query the xterm pointer and generate mouse termcodes if necessary
6565 * return TRUE if dragging is active, else FALSE
6566 */
6567 static int
6568do_xterm_trace()
6569{
6570 Window root, child;
6571 int root_x, root_y;
6572 int win_x, win_y;
6573 int row, col;
6574 int_u mask_return;
6575 char_u buf[50];
6576 char_u *strp;
6577 long got_hints;
6578 static char_u *mouse_code;
6579 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6580 static int prev_row = 0, prev_col = 0;
6581 static XSizeHints xterm_hints;
6582
6583 if (xterm_trace <= 0)
6584 return FALSE;
6585
6586 if (xterm_trace == 1)
6587 {
6588 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006589 * have changed recently. */
6590 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6591 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006592 || xterm_hints.width_inc <= 1
6593 || xterm_hints.height_inc <= 1)
6594 {
6595 xterm_trace = -1; /* Not enough data -- disable tracing */
6596 return FALSE;
6597 }
6598
6599 /* Rely on the same mouse code for the duration of this */
6600 mouse_code = find_termcode(mouse_name);
6601 prev_row = mouse_row;
6602 prev_row = mouse_col;
6603 xterm_trace = 2;
6604
6605 /* Find the offset of the chars, there might be a scrollbar on the
6606 * left of the window and/or a menu on the top (eterm etc.) */
6607 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6608 &win_x, &win_y, &mask_return);
6609 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6610 - (xterm_hints.height_inc / 2);
6611 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6612 xterm_hints.y = 2;
6613 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6614 - (xterm_hints.width_inc / 2);
6615 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6616 xterm_hints.x = 2;
6617 return TRUE;
6618 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006619 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 {
6621 xterm_trace = 0;
6622 return FALSE;
6623 }
6624
6625 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6626 &win_x, &win_y, &mask_return);
6627
6628 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6629 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6630 if (row == prev_row && col == prev_col)
6631 return TRUE;
6632
6633 STRCPY(buf, mouse_code);
6634 strp = buf + STRLEN(buf);
6635 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6636 *strp++ = (char_u)(col + ' ' + 1);
6637 *strp++ = (char_u)(row + ' ' + 1);
6638 *strp = 0;
6639 add_to_input_buf(buf, STRLEN(buf));
6640
6641 prev_row = row;
6642 prev_col = col;
6643 return TRUE;
6644}
6645
6646# if defined(FEAT_GUI) || defined(PROTO)
6647/*
6648 * Destroy the display, window and app_context. Required for GTK.
6649 */
6650 void
6651clear_xterm_clip()
6652{
6653 if (xterm_Shell != (Widget)0)
6654 {
6655 XtDestroyWidget(xterm_Shell);
6656 xterm_Shell = (Widget)0;
6657 }
6658 if (xterm_dpy != NULL)
6659 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006660# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 /* Lesstif and Solaris crash here, lose some memory */
6662 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 if (x11_display == xterm_dpy)
6665 x11_display = NULL;
6666 xterm_dpy = NULL;
6667 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006668# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 if (app_context != (XtAppContext)NULL)
6670 {
6671 /* Lesstif and Solaris crash here, lose some memory */
6672 XtDestroyApplicationContext(app_context);
6673 app_context = (XtAppContext)NULL;
6674 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006675# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676}
6677# endif
6678
6679/*
6680 * Catch up with any queued X events. This may put keyboard input into the
6681 * input buffer, call resize call-backs, trigger timers etc. If there is
6682 * nothing in the X event queue (& no timers pending), then we return
6683 * immediately.
6684 */
6685 static void
6686xterm_update()
6687{
6688 XEvent event;
6689
6690 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6691 {
6692 XtAppNextEvent(app_context, &event);
6693#ifdef FEAT_CLIENTSERVER
6694 {
6695 XPropertyEvent *e = (XPropertyEvent *)&event;
6696
6697 if (e->type == PropertyNotify && e->window == commWindow
6698 && e->atom == commProperty && e->state == PropertyNewValue)
6699 serverEventProc(xterm_dpy, &event);
6700 }
6701#endif
6702 XtDispatchEvent(&event);
6703 }
6704}
6705
6706 int
6707clip_xterm_own_selection(cbd)
6708 VimClipboard *cbd;
6709{
6710 if (xterm_Shell != (Widget)0)
6711 return clip_x11_own_selection(xterm_Shell, cbd);
6712 return FAIL;
6713}
6714
6715 void
6716clip_xterm_lose_selection(cbd)
6717 VimClipboard *cbd;
6718{
6719 if (xterm_Shell != (Widget)0)
6720 clip_x11_lose_selection(xterm_Shell, cbd);
6721}
6722
6723 void
6724clip_xterm_request_selection(cbd)
6725 VimClipboard *cbd;
6726{
6727 if (xterm_Shell != (Widget)0)
6728 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6729}
6730
6731 void
6732clip_xterm_set_selection(cbd)
6733 VimClipboard *cbd;
6734{
6735 clip_x11_set_selection(cbd);
6736}
6737#endif
6738
6739
6740#if defined(USE_XSMP) || defined(PROTO)
6741/*
6742 * Code for X Session Management Protocol.
6743 */
6744static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6745static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6746static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6747static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6748static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6749
6750
6751# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6752static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6753
6754/*
6755 * This is our chance to ask the user if they want to save,
6756 * or abort the logout
6757 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 static void
6759xsmp_handle_interaction(smc_conn, client_data)
6760 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006761 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762{
6763 cmdmod_T save_cmdmod;
6764 int cancel_shutdown = False;
6765
6766 save_cmdmod = cmdmod;
6767 cmdmod.confirm = TRUE;
6768 if (check_changed_any(FALSE))
6769 /* Mustn't logout */
6770 cancel_shutdown = True;
6771 cmdmod = save_cmdmod;
6772 setcursor(); /* position cursor */
6773 out_flush();
6774
6775 /* Done interaction */
6776 SmcInteractDone(smc_conn, cancel_shutdown);
6777
6778 /* Finish off
6779 * Only end save-yourself here if we're not cancelling shutdown;
6780 * we'll get a cancelled callback later in which we'll end it.
6781 * Hopefully get around glitchy SMs (like GNOME-1)
6782 */
6783 if (!cancel_shutdown)
6784 {
6785 xsmp.save_yourself = False;
6786 SmcSaveYourselfDone(smc_conn, True);
6787 }
6788}
6789# endif
6790
6791/*
6792 * Callback that starts save-yourself.
6793 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 static void
6795xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6796 shutdown, interact_style, fast)
6797 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006798 SmPointer client_data UNUSED;
6799 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006801 int interact_style UNUSED;
6802 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803{
6804 /* Handle already being in saveyourself */
6805 if (xsmp.save_yourself)
6806 SmcSaveYourselfDone(smc_conn, True);
6807 xsmp.save_yourself = True;
6808 xsmp.shutdown = shutdown;
6809
6810 /* First up, preserve all files */
6811 out_flush();
6812 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6813
6814 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006815 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816
6817# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6818 /* Now see if we can ask about unsaved files */
6819 if (shutdown && !fast && gui.in_use)
6820 /* Need to interact with user, but need SM's permission */
6821 SmcInteractRequest(smc_conn, SmDialogError,
6822 xsmp_handle_interaction, client_data);
6823 else
6824# endif
6825 {
6826 /* Can stop the cycle here */
6827 SmcSaveYourselfDone(smc_conn, True);
6828 xsmp.save_yourself = False;
6829 }
6830}
6831
6832
6833/*
6834 * Callback to warn us of imminent death.
6835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 static void
6837xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006838 SmcConn smc_conn UNUSED;
6839 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840{
6841 xsmp_close();
6842
6843 /* quit quickly leaving swapfiles for modified buffers behind */
6844 getout_preserve_modified(0);
6845}
6846
6847
6848/*
6849 * Callback to tell us that save-yourself has completed.
6850 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 static void
6852xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006853 SmcConn smc_conn UNUSED;
6854 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855{
6856 xsmp.save_yourself = False;
6857}
6858
6859
6860/*
6861 * Callback to tell us that an instigated shutdown was cancelled
6862 * (maybe even by us)
6863 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 static void
6865xsmp_shutdown_cancelled(smc_conn, client_data)
6866 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006867 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868{
6869 if (xsmp.save_yourself)
6870 SmcSaveYourselfDone(smc_conn, True);
6871 xsmp.save_yourself = False;
6872 xsmp.shutdown = False;
6873}
6874
6875
6876/*
6877 * Callback to tell us that a new ICE connection has been established.
6878 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 static void
6880xsmp_ice_connection(iceConn, clientData, opening, watchData)
6881 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006882 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006884 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885{
6886 /* Intercept creation of ICE connection fd */
6887 if (opening)
6888 {
6889 xsmp_icefd = IceConnectionNumber(iceConn);
6890 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6891 }
6892}
6893
6894
6895/* Handle any ICE processing that's required; return FAIL if SM lost */
6896 int
6897xsmp_handle_requests()
6898{
6899 Bool rep;
6900
6901 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6902 == IceProcessMessagesIOError)
6903 {
6904 /* Lost ICE */
6905 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006906 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 xsmp_close();
6908 return FAIL;
6909 }
6910 else
6911 return OK;
6912}
6913
6914static int dummy;
6915
6916/* Set up X Session Management Protocol */
6917 void
6918xsmp_init(void)
6919{
6920 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 SmcCallbacks smcallbacks;
6922#if 0
6923 SmPropValue smname;
6924 SmProp smnameprop;
6925 SmProp *smprops[1];
6926#endif
6927
6928 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006929 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930
6931 xsmp.save_yourself = xsmp.shutdown = False;
6932
6933 /* Set up SM callbacks - must have all, even if they're not used */
6934 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6935 smcallbacks.save_yourself.client_data = NULL;
6936 smcallbacks.die.callback = xsmp_die;
6937 smcallbacks.die.client_data = NULL;
6938 smcallbacks.save_complete.callback = xsmp_save_complete;
6939 smcallbacks.save_complete.client_data = NULL;
6940 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6941 smcallbacks.shutdown_cancelled.client_data = NULL;
6942
6943 /* Set up a watch on ICE connection creations. The "dummy" argument is
6944 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6945 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6946 {
6947 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006948 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 return;
6950 }
6951
6952 /* Create an SM connection */
6953 xsmp.smcconn = SmcOpenConnection(
6954 NULL,
6955 NULL,
6956 SmProtoMajor,
6957 SmProtoMinor,
6958 SmcSaveYourselfProcMask | SmcDieProcMask
6959 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6960 &smcallbacks,
6961 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00006962 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006963 sizeof(errorstring),
6964 errorstring);
6965 if (xsmp.smcconn == NULL)
6966 {
6967 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006968
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006970 {
6971 vim_snprintf(errorreport, sizeof(errorreport),
6972 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6973 verb_msg((char_u *)errorreport);
6974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 return;
6976 }
6977 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6978
6979#if 0
6980 /* ID ourselves */
6981 smname.value = "vim";
6982 smname.length = 3;
6983 smnameprop.name = "SmProgram";
6984 smnameprop.type = "SmARRAY8";
6985 smnameprop.num_vals = 1;
6986 smnameprop.vals = &smname;
6987
6988 smprops[0] = &smnameprop;
6989 SmcSetProperties(xsmp.smcconn, 1, smprops);
6990#endif
6991}
6992
6993
6994/* Shut down XSMP comms. */
6995 void
6996xsmp_close()
6997{
6998 if (xsmp_icefd != -1)
6999 {
7000 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007001 if (xsmp.clientid != NULL)
7002 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007003 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 xsmp_icefd = -1;
7005 }
7006}
7007#endif /* USE_XSMP */
7008
7009
7010#ifdef EBCDIC
7011/* Translate character to its CTRL- value */
7012char CtrlTable[] =
7013{
7014/* 00 - 5E */
7015 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7016 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7017 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7018 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7019 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7020 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7021/* ^ */ 0x1E,
7022/* - */ 0x1F,
7023/* 61 - 6C */
7024 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7025/* _ */ 0x1F,
7026/* 6E - 80 */
7027 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7028/* a */ 0x01,
7029/* b */ 0x02,
7030/* c */ 0x03,
7031/* d */ 0x37,
7032/* e */ 0x2D,
7033/* f */ 0x2E,
7034/* g */ 0x2F,
7035/* h */ 0x16,
7036/* i */ 0x05,
7037/* 8A - 90 */
7038 0, 0, 0, 0, 0, 0, 0,
7039/* j */ 0x15,
7040/* k */ 0x0B,
7041/* l */ 0x0C,
7042/* m */ 0x0D,
7043/* n */ 0x0E,
7044/* o */ 0x0F,
7045/* p */ 0x10,
7046/* q */ 0x11,
7047/* r */ 0x12,
7048/* 9A - A1 */
7049 0, 0, 0, 0, 0, 0, 0, 0,
7050/* s */ 0x13,
7051/* t */ 0x3C,
7052/* u */ 0x3D,
7053/* v */ 0x32,
7054/* w */ 0x26,
7055/* x */ 0x18,
7056/* y */ 0x19,
7057/* z */ 0x3F,
7058/* AA - AC */
7059 0, 0, 0,
7060/* [ */ 0x27,
7061/* AE - BC */
7062 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7063/* ] */ 0x1D,
7064/* BE - C0 */ 0, 0, 0,
7065/* A */ 0x01,
7066/* B */ 0x02,
7067/* C */ 0x03,
7068/* D */ 0x37,
7069/* E */ 0x2D,
7070/* F */ 0x2E,
7071/* G */ 0x2F,
7072/* H */ 0x16,
7073/* I */ 0x05,
7074/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7075/* J */ 0x15,
7076/* K */ 0x0B,
7077/* L */ 0x0C,
7078/* M */ 0x0D,
7079/* N */ 0x0E,
7080/* O */ 0x0F,
7081/* P */ 0x10,
7082/* Q */ 0x11,
7083/* R */ 0x12,
7084/* DA - DF */ 0, 0, 0, 0, 0, 0,
7085/* \ */ 0x1C,
7086/* E1 */ 0,
7087/* S */ 0x13,
7088/* T */ 0x3C,
7089/* U */ 0x3D,
7090/* V */ 0x32,
7091/* W */ 0x26,
7092/* X */ 0x18,
7093/* Y */ 0x19,
7094/* Z */ 0x3F,
7095/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7096 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7097};
7098
7099char MetaCharTable[]=
7100{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7101 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7102 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7103 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7104 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7105};
7106
7107
7108/* TODO: Use characters NOT numbers!!! */
7109char CtrlCharTable[]=
7110{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7111 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7112 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7113 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7114 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7115};
7116
7117
7118#endif