blob: ba86dbf8507b1757388a31875198aa3e00d329b5 [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
286#ifdef SIGVTALRM
287 {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 *
1110 * volatile because it is used in 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
Bram Moolenaardf177f62005-02-22 08:39:57 +00003663#ifndef USE_SYSTEM
3664static void append_ga_line __ARGS((garray_T *gap));
3665
3666/*
3667 * Append the text in "gap" below the cursor line and clear "gap".
3668 */
3669 static void
3670append_ga_line(gap)
3671 garray_T *gap;
3672{
3673 /* Remove trailing CR. */
3674 if (gap->ga_len > 0
3675 && !curbuf->b_p_bin
3676 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
3677 --gap->ga_len;
3678 ga_append(gap, NUL);
3679 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
3680 gap->ga_len = 0;
3681}
3682#endif
3683
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 int
3685mch_call_shell(cmd, options)
3686 char_u *cmd;
3687 int options; /* SHELL_*, see vim.h */
3688{
3689#ifdef VMS
3690 char *ifn = NULL;
3691 char *ofn = NULL;
3692#endif
3693 int tmode = cur_tmode;
3694#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3695 int x;
3696# ifndef __EMX__
3697 char_u *newcmd; /* only needed for unix */
3698# else
3699 /*
3700 * Set the preferred shell in the EMXSHELL environment variable (but
3701 * only if it is different from what is already in the environment).
3702 * Emx then takes care of whether to use "/c" or "-c" in an
3703 * intelligent way. Simply pass the whole thing to emx's system() call.
3704 * Emx also starts an interactive shell if system() is passed an empty
3705 * string.
3706 */
3707 char_u *p, *old;
3708
3709 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3710 {
3711 /* should check HAVE_SETENV, but I know we don't have it. */
3712 p = alloc(10 + strlen(p_sh));
3713 if (p)
3714 {
3715 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3716 putenv((char *)p); /* don't free the pointer! */
3717 }
3718 }
3719# endif
3720
3721 out_flush();
3722
3723 if (options & SHELL_COOKED)
3724 settmode(TMODE_COOK); /* set to normal mode */
3725
Bram Moolenaar62b42182010-09-21 22:09:37 +02003726# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3727 loose_clipboard();
3728# endif
3729
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730# ifdef __EMX__
3731 if (cmd == NULL)
3732 x = system(""); /* this starts an interactive shell in emx */
3733 else
3734 x = system((char *)cmd);
3735 /* system() returns -1 when error occurs in starting shell */
3736 if (x == -1 && !emsg_silent)
3737 {
3738 MSG_PUTS(_("\nCannot execute shell "));
3739 msg_outtrans(p_sh);
3740 msg_putchar('\n');
3741 }
3742# else /* not __EMX__ */
3743 if (cmd == NULL)
3744 x = system((char *)p_sh);
3745 else
3746 {
3747# ifdef VMS
3748 if (ofn = strchr((char *)cmd, '>'))
3749 *ofn++ = '\0';
3750 if (ifn = strchr((char *)cmd, '<'))
3751 {
3752 char *p;
3753
3754 *ifn++ = '\0';
3755 p = strchr(ifn,' '); /* chop off any trailing spaces */
3756 if (p)
3757 *p = '\0';
3758 }
3759 if (ofn)
3760 x = vms_sys((char *)cmd, ofn, ifn);
3761 else
3762 x = system((char *)cmd);
3763# else
3764 newcmd = lalloc(STRLEN(p_sh)
3765 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3766 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3767 if (newcmd == NULL)
3768 x = 0;
3769 else
3770 {
3771 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3772 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3773 (char *)p_shcf,
3774 (char *)cmd);
3775 x = system((char *)newcmd);
3776 vim_free(newcmd);
3777 }
3778# endif
3779 }
3780# ifdef VMS
3781 x = vms_sys_status(x);
3782# endif
3783 if (emsg_silent)
3784 ;
3785 else if (x == 127)
3786 MSG_PUTS(_("\nCannot execute shell sh\n"));
3787# endif /* __EMX__ */
3788 else if (x && !(options & SHELL_SILENT))
3789 {
3790 MSG_PUTS(_("\nshell returned "));
3791 msg_outnum((long)x);
3792 msg_putchar('\n');
3793 }
3794
3795 if (tmode == TMODE_RAW)
3796 settmode(TMODE_RAW); /* set to raw mode */
3797# ifdef FEAT_TITLE
3798 resettitle();
3799# endif
3800 return x;
3801
3802#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3803
Bram Moolenaardf177f62005-02-22 08:39:57 +00003804# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3805 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806
3807 char_u *newcmd = NULL;
3808 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003809 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 pid_t wait_pid = 0;
3811# ifdef HAVE_UNION_WAIT
3812 union wait status;
3813# else
3814 int status = -1;
3815# endif
3816 int retval = -1;
3817 char **argv = NULL;
3818 int argc;
3819 int i;
3820 char_u *p;
3821 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003823# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 int pty_slave_fd = -1;
3825 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003826# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003827 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 int fd_fromshell[2];
3829 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003830# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003832# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833 static char envbuf_Rows[20];
3834 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003836 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837
Bram Moolenaar62b42182010-09-21 22:09:37 +02003838 newcmd = vim_strsave(p_sh);
3839 if (newcmd == NULL) /* out of memory */
3840 goto error;
3841
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 out_flush();
3843 if (options & SHELL_COOKED)
3844 settmode(TMODE_COOK); /* set to normal mode */
3845
Bram Moolenaar62b42182010-09-21 22:09:37 +02003846# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3847 loose_clipboard();
3848# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003849
3850 /*
3851 * Do this loop twice:
3852 * 1: find number of arguments
3853 * 2: separate them and build argv[]
3854 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 for (i = 0; i < 2; ++i)
3856 {
3857 p = newcmd;
3858 inquote = FALSE;
3859 argc = 0;
3860 for (;;)
3861 {
3862 if (i == 1)
3863 argv[argc] = (char *)p;
3864 ++argc;
3865 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3866 {
3867 if (*p == '"')
3868 inquote = !inquote;
3869 ++p;
3870 }
3871 if (*p == NUL)
3872 break;
3873 if (i == 1)
3874 *p++ = NUL;
3875 p = skipwhite(p);
3876 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003877 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 {
3879 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3880 if (argv == NULL) /* out of memory */
3881 goto error;
3882 }
3883 }
3884 if (cmd != NULL)
3885 {
3886 if (extra_shell_arg != NULL)
3887 argv[argc++] = (char *)extra_shell_arg;
3888 argv[argc++] = (char *)p_shcf;
3889 argv[argc++] = (char *)cmd;
3890 }
3891 argv[argc] = NULL;
3892
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003894 * For the GUI, when writing the output into the buffer and when reading
3895 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3896 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003898 if ((options & (SHELL_READ|SHELL_WRITE))
3899# ifdef FEAT_GUI
3900 || (gui.in_use && show_shell_mess)
3901# endif
3902 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003904# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 /*
3906 * Try to open a master pty.
3907 * If this works, open the slave pty.
3908 * If the slave can't be opened, close the master pty.
3909 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003910 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 {
3912 pty_master_fd = OpenPTY(&tty_name); /* open pty */
3913 if (pty_master_fd >= 0 && ((pty_slave_fd =
3914 open(tty_name, O_RDWR | O_EXTRA, 0)) < 0))
3915 {
3916 close(pty_master_fd);
3917 pty_master_fd = -1;
3918 }
3919 }
3920 /*
3921 * If not opening a pty or it didn't work, try using pipes.
3922 */
3923 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003924# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 {
3926 pipe_error = (pipe(fd_toshell) < 0);
3927 if (!pipe_error) /* pipe create OK */
3928 {
3929 pipe_error = (pipe(fd_fromshell) < 0);
3930 if (pipe_error) /* pipe create failed */
3931 {
3932 close(fd_toshell[0]);
3933 close(fd_toshell[1]);
3934 }
3935 }
3936 if (pipe_error)
3937 {
3938 MSG_PUTS(_("\nCannot create pipes\n"));
3939 out_flush();
3940 }
3941 }
3942 }
3943
3944 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 {
3946# ifdef __BEOS__
3947 beos_cleanup_read_thread();
3948# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003949
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3951 {
3952 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003953 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003955 || (gui.in_use && show_shell_mess)
3956# endif
3957 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003959# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 if (pty_master_fd >= 0) /* close the pseudo tty */
3961 {
3962 close(pty_master_fd);
3963 close(pty_slave_fd);
3964 }
3965 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003966# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967 {
3968 close(fd_toshell[0]);
3969 close(fd_toshell[1]);
3970 close(fd_fromshell[0]);
3971 close(fd_fromshell[1]);
3972 }
3973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 }
3975 else if (pid == 0) /* child */
3976 {
3977 reset_signals(); /* handle signals normally */
3978
3979 if (!show_shell_mess || (options & SHELL_EXPAND))
3980 {
3981 int fd;
3982
3983 /*
3984 * Don't want to show any message from the shell. Can't just
3985 * close stdout and stderr though, because some systems will
3986 * break if you try to write to them after that, so we must
3987 * use dup() to replace them with something else -- webb
3988 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3989 * waiting for input.
3990 */
3991 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3992 fclose(stdin);
3993 fclose(stdout);
3994 fclose(stderr);
3995
3996 /*
3997 * If any of these open()'s and dup()'s fail, we just continue
3998 * anyway. It's not fatal, and on most systems it will make
3999 * no difference at all. On a few it will cause the execvp()
4000 * to exit with a non-zero status even when the completion
4001 * could be done, which is nothing too serious. If the open()
4002 * or dup() failed we'd just do the same thing ourselves
4003 * anyway -- webb
4004 */
4005 if (fd >= 0)
4006 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004007 ignored = dup(fd); /* To replace stdin (fd 0) */
4008 ignored = dup(fd); /* To replace stdout (fd 1) */
4009 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010
4011 /* Don't need this now that we've duplicated it */
4012 close(fd);
4013 }
4014 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004015 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004017 || gui.in_use
4018# endif
4019 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 {
4021
Bram Moolenaardf177f62005-02-22 08:39:57 +00004022# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004023 /* Create our own process group, so that the child and all its
4024 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004025 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004026 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004027 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004028 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004029# if defined(SIGHUP)
4030 /* When doing "!xterm&" and 'shell' is bash: the shell
4031 * will exit and send SIGHUP to all processes in its
4032 * group, killing the just started process. Ignore SIGHUP
4033 * to avoid that. (suggested by Simon Schubert)
4034 */
4035 signal(SIGHUP, SIG_IGN);
4036# endif
4037 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004038# endif
4039# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004040 if (pty_slave_fd >= 0)
4041 {
4042 /* push stream discipline modules */
4043 if (options & SHELL_COOKED)
4044 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004046 /* Try to become controlling tty (probably doesn't work,
4047 * unless run by root) */
4048 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004050 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004051# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004053# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 setenv("TERM", "dumb", 1);
4055 sprintf((char *)envbuf, "%ld", Rows);
4056 setenv("ROWS", (char *)envbuf, 1);
4057 sprintf((char *)envbuf, "%ld", Rows);
4058 setenv("LINES", (char *)envbuf, 1);
4059 sprintf((char *)envbuf, "%ld", Columns);
4060 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004061# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 /*
4063 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004064 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065 */
4066 putenv("TERM=dumb");
4067 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4068 putenv(envbuf_Rows);
4069 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4070 putenv(envbuf_Rows);
4071 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4072 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004073# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074
Bram Moolenaara5792f52005-11-23 21:25:05 +00004075 /*
4076 * stderr is only redirected when using the GUI, so that a
4077 * program like gpg can still access the terminal to get a
4078 * passphrase using stderr.
4079 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004080# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 if (pty_master_fd >= 0)
4082 {
4083 close(pty_master_fd); /* close master side of pty */
4084
4085 /* set up stdin/stdout/stderr for the child */
4086 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004087 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004089 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004090 if (gui.in_use)
4091 {
4092 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004093 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095
4096 close(pty_slave_fd); /* has been dupped, close it now */
4097 }
4098 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004099# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 {
4101 /* set up stdin for the child */
4102 close(fd_toshell[1]);
4103 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004104 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 close(fd_toshell[0]);
4106
4107 /* set up stdout for the child */
4108 close(fd_fromshell[0]);
4109 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004110 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 close(fd_fromshell[1]);
4112
Bram Moolenaara5792f52005-11-23 21:25:05 +00004113# ifdef FEAT_GUI
4114 if (gui.in_use)
4115 {
4116 /* set up stderr for the child */
4117 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004118 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004119 }
4120# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004123
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 /*
4125 * There is no type cast for the argv, because the type may be
4126 * different on different machines. This may cause a warning
4127 * message with strict compilers, don't worry about it.
4128 * Call _exit() instead of exit() to avoid closing the connection
4129 * to the X server (esp. with GTK, which uses atexit()).
4130 */
4131 execvp(argv[0], argv);
4132 _exit(EXEC_FAILED); /* exec failed, return failure code */
4133 }
4134 else /* parent */
4135 {
4136 /*
4137 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004138 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 */
4140 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004141 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142
4143 /*
4144 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004145 * This is also used to pipe stdin/stdout to/from the external
4146 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004148 if ((options & (SHELL_READ|SHELL_WRITE))
4149# ifdef FEAT_GUI
4150 || (gui.in_use && show_shell_mess)
4151# endif
4152 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004154# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004156# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004158# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4160 int ta_len = 0; /* valid bytes in ta_buf[] */
4161 int len;
4162 int p_more_save;
4163 int old_State;
4164 int c;
4165 int toshell_fd;
4166 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004167 garray_T ga;
4168 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004169# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4170 struct timeval start_tv;
4171# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172
Bram Moolenaardf177f62005-02-22 08:39:57 +00004173# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 if (pty_master_fd >= 0)
4175 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 fromshell_fd = pty_master_fd;
4177 toshell_fd = dup(pty_master_fd);
4178 }
4179 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004180# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 {
4182 close(fd_toshell[0]);
4183 close(fd_fromshell[1]);
4184 toshell_fd = fd_toshell[1];
4185 fromshell_fd = fd_fromshell[0];
4186 }
4187
4188 /*
4189 * Write to the child if there are typed characters.
4190 * Read from the child if there are characters available.
4191 * Repeat the reading a few times if more characters are
4192 * available. Need to check for typed keys now and then, but
4193 * not too often (delays when no chars are available).
4194 * This loop is quit if no characters can be read from the pty
4195 * (WaitForChar detected special condition), or there are no
4196 * characters available and the child has exited.
4197 * Only check if the child has exited when there is no more
4198 * output. The child may exit before all the output has
4199 * been printed.
4200 *
4201 * Currently this busy loops!
4202 * This can probably dead-lock when the write blocks!
4203 */
4204 p_more_save = p_more;
4205 p_more = FALSE;
4206 old_State = State;
4207 State = EXTERNCMD; /* don't redraw at window resize */
4208
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004209 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004210 {
4211 /* Fork a process that will write the lines to the
4212 * external program. */
4213 if ((wpid = fork()) == -1)
4214 {
4215 MSG_PUTS(_("\nCannot fork\n"));
4216 }
4217 else if (wpid == 0)
4218 {
4219 linenr_T lnum = curbuf->b_op_start.lnum;
4220 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004221 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004222 char_u *s;
4223 size_t l;
4224
4225 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004226 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004227 for (;;)
4228 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004229 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004230 if (l == 0)
4231 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004232 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004233 /* NL -> NUL translation */
4234 len = write(toshell_fd, "", (size_t)1);
4235 else
4236 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004237 s = vim_strchr(lp + written, NL);
4238 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004239 s == NULL ? l
4240 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004241 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004242 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004243 {
4244 /* Finished a line, add a NL, unless this line
4245 * should not have one. */
4246 if (lnum != curbuf->b_op_end.lnum
4247 || !curbuf->b_p_bin
4248 || (lnum != write_no_eol_lnum
4249 && (lnum !=
4250 curbuf->b_ml.ml_line_count
4251 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004252 ignored = write(toshell_fd, "\n",
4253 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004254 ++lnum;
4255 if (lnum > curbuf->b_op_end.lnum)
4256 {
4257 /* finished all the lines, close pipe */
4258 close(toshell_fd);
4259 toshell_fd = -1;
4260 break;
4261 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004262 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004263 written = 0;
4264 }
4265 else if (len > 0)
4266 written += len;
4267 }
4268 _exit(0);
4269 }
4270 else
4271 {
4272 close(toshell_fd);
4273 toshell_fd = -1;
4274 }
4275 }
4276
4277 if (options & SHELL_READ)
4278 ga_init2(&ga, 1, BUFLEN);
4279
4280 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004281# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4282 gettimeofday(&start_tv, NULL);
4283# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 for (;;)
4285 {
4286 /*
4287 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004288 * if there are any.
4289 * Don't do this if we are expanding wild cards (would eat
4290 * typeahead).
4291 * Don't do this when filtering and terminal is in cooked
4292 * mode, the shell command will handle the I/O. Avoids
4293 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004294 * Don't get characters when the child has already
4295 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004296 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004297 * while (noread_cnt > 4), avoids that ":r !ls" eats
4298 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 */
4300 len = 0;
4301 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004302 && ((options &
4303 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4304 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004305# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004306 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004307# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004308 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004309 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004310 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004312 if (ta_len == 0)
4313 {
4314 /* Get extra characters when we don't have any.
4315 * Reset the counter and timer. */
4316 noread_cnt = 0;
4317# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4318 gettimeofday(&start_tv, NULL);
4319# endif
4320 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4321 }
4322 if (ta_len > 0 || len > 0)
4323 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 /*
4325 * For pipes:
4326 * Check for CTRL-C: send interrupt signal to child.
4327 * Check for CTRL-D: EOF, close pipe to child.
4328 */
4329 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4330 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004331# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332 /*
4333 * Send SIGINT to the child's group or all
4334 * processes in our group.
4335 */
4336 if (ta_buf[ta_len] == Ctrl_C
4337 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004338 {
4339# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004341# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004344 if (wpid > 0)
4345 kill(wpid, SIGINT);
4346 }
4347# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 if (pty_master_fd < 0 && toshell_fd >= 0
4349 && ta_buf[ta_len] == Ctrl_D)
4350 {
4351 close(toshell_fd);
4352 toshell_fd = -1;
4353 }
4354 }
4355
4356 /* replace K_BS by <BS> and K_DEL by <DEL> */
4357 for (i = ta_len; i < ta_len + len; ++i)
4358 {
4359 if (ta_buf[i] == CSI && len - i > 2)
4360 {
4361 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4362 if (c == K_DEL || c == K_KDEL || c == K_BS)
4363 {
4364 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4365 (size_t)(len - i - 2));
4366 if (c == K_DEL || c == K_KDEL)
4367 ta_buf[i] = DEL;
4368 else
4369 ta_buf[i] = Ctrl_H;
4370 len -= 2;
4371 }
4372 }
4373 else if (ta_buf[i] == '\r')
4374 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004375# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004377 i += (*mb_ptr2len_len)(ta_buf + i,
4378 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004379# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380 }
4381
4382 /*
4383 * For pipes: echo the typed characters.
4384 * For a pty this does not seem to work.
4385 */
4386 if (pty_master_fd < 0)
4387 {
4388 for (i = ta_len; i < ta_len + len; ++i)
4389 {
4390 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4391 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004392# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 else if (has_mbyte)
4394 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004395 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396
4397 msg_outtrans_len(ta_buf + i, l);
4398 i += l - 1;
4399 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004400# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 else
4402 msg_outtrans_len(ta_buf + i, 1);
4403 }
4404 windgoto(msg_row, msg_col);
4405 out_flush();
4406 }
4407
4408 ta_len += len;
4409
4410 /*
4411 * Write the characters to the child, unless EOF has
4412 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004413 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004414 * When writing buffer lines, drop the typed
4415 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004417 if (options & SHELL_WRITE)
4418 ta_len = 0;
4419 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420 {
4421 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4422 if (len > 0)
4423 {
4424 ta_len -= len;
4425 mch_memmove(ta_buf, ta_buf + len, ta_len);
4426 }
4427 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004429 }
4430
Bram Moolenaardf177f62005-02-22 08:39:57 +00004431 if (got_int)
4432 {
4433 /* CTRL-C sends a signal to the child, we ignore it
4434 * ourselves */
4435# ifdef HAVE_SETSID
4436 kill(-pid, SIGINT);
4437# else
4438 kill(0, SIGINT);
4439# endif
4440 if (wpid > 0)
4441 kill(wpid, SIGINT);
4442 got_int = FALSE;
4443 }
4444
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 /*
4446 * Check if the child has any characters to be printed.
4447 * Read them and write them to our window. Repeat this as
4448 * long as there is something to do, avoid the 10ms wait
4449 * for mch_inchar(), or sending typeahead characters to
4450 * the external process.
4451 * TODO: This should handle escape sequences, compatible
4452 * to some terminal (vt52?).
4453 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004454 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4456 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004457 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004458# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004459 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004460# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004462# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 );
4464 if (len <= 0) /* end of file or error */
4465 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004466
4467 noread_cnt = 0;
4468 if (options & SHELL_READ)
4469 {
4470 /* Do NUL -> NL translation, append NL separated
4471 * lines to the current buffer. */
4472 for (i = 0; i < len; ++i)
4473 {
4474 if (buffer[i] == NL)
4475 append_ga_line(&ga);
4476 else if (buffer[i] == NUL)
4477 ga_append(&ga, NL);
4478 else
4479 ga_append(&ga, buffer[i]);
4480 }
4481 }
4482# ifdef FEAT_MBYTE
4483 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 {
4485 int l;
4486
Bram Moolenaardf177f62005-02-22 08:39:57 +00004487 len += buffer_off;
4488 buffer[len] = NUL;
4489
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 /* Check if the last character in buffer[] is
4491 * incomplete, keep these bytes for the next
4492 * round. */
4493 for (p = buffer; p < buffer + len; p += l)
4494 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004495 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 if (l == 0)
4497 l = 1; /* NUL byte? */
4498 else if (MB_BYTE2LEN(*p) != l)
4499 break;
4500 }
4501 if (p == buffer) /* no complete character */
4502 {
4503 /* avoid getting stuck at an illegal byte */
4504 if (len >= 12)
4505 ++p;
4506 else
4507 {
4508 buffer_off = len;
4509 continue;
4510 }
4511 }
4512 c = *p;
4513 *p = NUL;
4514 msg_puts(buffer);
4515 if (p < buffer + len)
4516 {
4517 *p = c;
4518 buffer_off = (buffer + len) - p;
4519 mch_memmove(buffer, p, buffer_off);
4520 continue;
4521 }
4522 buffer_off = 0;
4523 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004524# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 {
4527 buffer[len] = NUL;
4528 msg_puts(buffer);
4529 }
4530
4531 windgoto(msg_row, msg_col);
4532 cursor_on();
4533 out_flush();
4534 if (got_int)
4535 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004536
4537# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4538 {
4539 struct timeval now_tv;
4540 long msec;
4541
4542 /* Avoid that we keep looping here without
4543 * checking for a CTRL-C for a long time. Don't
4544 * break out too often to avoid losing typeahead. */
4545 gettimeofday(&now_tv, NULL);
4546 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4547 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4548 if (msec > 2000)
4549 {
4550 noread_cnt = 5;
4551 break;
4552 }
4553 }
4554# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 }
4556
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004557 /* If we already detected the child has finished break the
4558 * loop now. */
4559 if (wait_pid == pid)
4560 break;
4561
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 /*
4563 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004564 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004566# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004568# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004570# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4572 || (wait_pid == pid && WIFEXITED(status)))
4573 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004574 /* Don't break the loop yet, try reading more
4575 * characters from "fromshell_fd" first. When using
4576 * pipes there might still be something to read and
4577 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004580 else
4581 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 }
4583finished:
4584 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004585 if (options & SHELL_READ)
4586 {
4587 if (ga.ga_len > 0)
4588 {
4589 append_ga_line(&ga);
4590 /* remember that the NL was missing */
4591 write_no_eol_lnum = curwin->w_cursor.lnum;
4592 }
4593 else
4594 write_no_eol_lnum = 0;
4595 ga_clear(&ga);
4596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 /*
4599 * Give all typeahead that wasn't used back to ui_inchar().
4600 */
4601 if (ta_len)
4602 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603 State = old_State;
4604 if (toshell_fd >= 0)
4605 close(toshell_fd);
4606 close(fromshell_fd);
4607 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608
4609 /*
4610 * Wait until our child has exited.
4611 * Ignore wait() returning pids of other children and returning
4612 * because of some signal like SIGWINCH.
4613 * Don't wait if wait_pid was already set above, indicating the
4614 * child already exited.
4615 */
4616 while (wait_pid != pid)
4617 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004618# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 /* Ugly hack: when compiled with Python threads are probably
4620 * used, in which case wait() sometimes hangs for no obvious
4621 * reason. Use waitpid() instead and loop (like the GUI). */
4622# ifdef __NeXT__
4623 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4624# else
4625 wait_pid = waitpid(pid, &status, WNOHANG);
4626# endif
4627 if (wait_pid == 0)
4628 {
4629 /* Wait for 1/100 sec before trying again. */
4630 mch_delay(10L, TRUE);
4631 continue;
4632 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004633# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004635# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636 if (wait_pid <= 0
4637# ifdef ECHILD
4638 && errno == ECHILD
4639# endif
4640 )
4641 break;
4642 }
4643
Bram Moolenaar624891f2010-10-13 16:22:09 +02004644# ifdef FEAT_GUI
4645 /* Close slave side of pty. Only do this after the child has
4646 * exited, otherwise the child may hang when it tries to write on
4647 * the pty. */
4648 if (pty_master_fd >= 0)
4649 close(pty_slave_fd);
4650# endif
4651
Bram Moolenaardf177f62005-02-22 08:39:57 +00004652 /* Make sure the child that writes to the external program is
4653 * dead. */
4654 if (wpid > 0)
4655 kill(wpid, SIGKILL);
4656
Bram Moolenaar071d4272004-06-13 20:20:40 +00004657 /*
4658 * Set to raw mode right now, otherwise a CTRL-C after
4659 * catch_signals() will kill Vim.
4660 */
4661 if (tmode == TMODE_RAW)
4662 settmode(TMODE_RAW);
4663 did_settmode = TRUE;
4664 set_signals();
4665
4666 if (WIFEXITED(status))
4667 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004668 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669 retval = WEXITSTATUS(status);
4670 if (retval && !emsg_silent)
4671 {
4672 if (retval == EXEC_FAILED)
4673 {
4674 MSG_PUTS(_("\nCannot execute shell "));
4675 msg_outtrans(p_sh);
4676 msg_putchar('\n');
4677 }
4678 else if (!(options & SHELL_SILENT))
4679 {
4680 MSG_PUTS(_("\nshell returned "));
4681 msg_outnum((long)retval);
4682 msg_putchar('\n');
4683 }
4684 }
4685 }
4686 else
4687 MSG_PUTS(_("\nCommand terminated\n"));
4688 }
4689 }
4690 vim_free(argv);
4691
4692error:
4693 if (!did_settmode)
4694 if (tmode == TMODE_RAW)
4695 settmode(TMODE_RAW); /* set to raw mode */
4696# ifdef FEAT_TITLE
4697 resettitle();
4698# endif
4699 vim_free(newcmd);
4700
4701 return retval;
4702
4703#endif /* USE_SYSTEM */
4704}
4705
4706/*
4707 * Check for CTRL-C typed by reading all available characters.
4708 * In cooked mode we should get SIGINT, no need to check.
4709 */
4710 void
4711mch_breakcheck()
4712{
4713 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4714 fill_input_buf(FALSE);
4715}
4716
4717/*
4718 * Wait "msec" msec until a character is available from the keyboard or from
4719 * inbuf[]. msec == -1 will block forever.
4720 * When a GUI is being used, this will never get called -- webb
4721 */
4722 static int
4723WaitForChar(msec)
4724 long msec;
4725{
4726#ifdef FEAT_MOUSE_GPM
4727 int gpm_process_wanted;
4728#endif
4729#ifdef FEAT_XCLIPBOARD
4730 int rest;
4731#endif
4732 int avail;
4733
4734 if (input_available()) /* something in inbuf[] */
4735 return 1;
4736
4737#if defined(FEAT_MOUSE_DEC)
4738 /* May need to query the mouse position. */
4739 if (WantQueryMouse)
4740 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004741 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4743 }
4744#endif
4745
4746 /*
4747 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4748 * events. This is a bit complicated, because they might both be defined.
4749 */
4750#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4751# ifdef FEAT_XCLIPBOARD
4752 rest = 0;
4753 if (do_xterm_trace())
4754 rest = msec;
4755# endif
4756 do
4757 {
4758# ifdef FEAT_XCLIPBOARD
4759 if (rest != 0)
4760 {
4761 msec = XT_TRACE_DELAY;
4762 if (rest >= 0 && rest < XT_TRACE_DELAY)
4763 msec = rest;
4764 if (rest >= 0)
4765 rest -= msec;
4766 }
4767# endif
4768# ifdef FEAT_MOUSE_GPM
4769 gpm_process_wanted = 0;
4770 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4771# else
4772 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4773# endif
4774 if (!avail)
4775 {
4776 if (input_available())
4777 return 1;
4778# ifdef FEAT_XCLIPBOARD
4779 if (rest == 0 || !do_xterm_trace())
4780# endif
4781 break;
4782 }
4783 }
4784 while (FALSE
4785# ifdef FEAT_MOUSE_GPM
4786 || (gpm_process_wanted && mch_gpm_process() == 0)
4787# endif
4788# ifdef FEAT_XCLIPBOARD
4789 || (!avail && rest != 0)
4790# endif
4791 );
4792
4793#else
4794 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4795#endif
4796 return avail;
4797}
4798
4799/*
4800 * Wait "msec" msec until a character is available from file descriptor "fd".
4801 * Time == -1 will block forever.
4802 * When a GUI is being used, this will not be used for input -- webb
4803 * Returns also, when a request from Sniff is waiting -- toni.
4804 * Or when a Linux GPM mouse event is waiting.
4805 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806#if defined(__BEOS__)
4807 int
4808#else
4809 static int
4810#endif
4811RealWaitForChar(fd, msec, check_for_gpm)
4812 int fd;
4813 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004814 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815{
4816 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004817#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004818 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004819#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004820#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 static int busy = FALSE;
4822
4823 /* May retry getting characters after an event was handled. */
4824# define MAY_LOOP
4825
4826# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4827 /* Remember at what time we started, so that we know how much longer we
4828 * should wait after being interrupted. */
4829# define USE_START_TV
4830 struct timeval start_tv;
4831
4832 if (msec > 0 && (
4833# ifdef FEAT_XCLIPBOARD
4834 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004835# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 ||
4837# endif
4838# endif
4839# ifdef USE_XSMP
4840 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004841# ifdef FEAT_MZSCHEME
4842 ||
4843# endif
4844# endif
4845# ifdef FEAT_MZSCHEME
4846 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847# endif
4848 ))
4849 gettimeofday(&start_tv, NULL);
4850# endif
4851
4852 /* Handle being called recursively. This may happen for the session
4853 * manager stuff, it may save the file, which does a breakcheck. */
4854 if (busy)
4855 return 0;
4856#endif
4857
4858#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004859 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860#endif
4861 {
4862#ifdef MAY_LOOP
4863 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004864# ifdef FEAT_MZSCHEME
4865 int mzquantum_used = FALSE;
4866# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867#endif
4868#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004869 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 int nfd;
4871# ifdef FEAT_XCLIPBOARD
4872 int xterm_idx = -1;
4873# endif
4874# ifdef FEAT_MOUSE_GPM
4875 int gpm_idx = -1;
4876# endif
4877# ifdef USE_XSMP
4878 int xsmp_idx = -1;
4879# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004880# ifdef FEAT_NETBEANS_INTG
4881 int nb_idx = -1;
4882# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004883 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004885# ifdef FEAT_MZSCHEME
4886 mzvim_check_threads();
4887 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4888 {
4889 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4890 mzquantum_used = TRUE;
4891 }
4892# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 fds[0].fd = fd;
4894 fds[0].events = POLLIN;
4895 nfd = 1;
4896
4897# ifdef FEAT_SNIFF
4898# define SNIFF_IDX 1
4899 if (want_sniff_request)
4900 {
4901 fds[SNIFF_IDX].fd = fd_from_sniff;
4902 fds[SNIFF_IDX].events = POLLIN;
4903 nfd++;
4904 }
4905# endif
4906# ifdef FEAT_XCLIPBOARD
4907 if (xterm_Shell != (Widget)0)
4908 {
4909 xterm_idx = nfd;
4910 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4911 fds[nfd].events = POLLIN;
4912 nfd++;
4913 }
4914# endif
4915# ifdef FEAT_MOUSE_GPM
4916 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4917 {
4918 gpm_idx = nfd;
4919 fds[nfd].fd = gpm_fd;
4920 fds[nfd].events = POLLIN;
4921 nfd++;
4922 }
4923# endif
4924# ifdef USE_XSMP
4925 if (xsmp_icefd != -1)
4926 {
4927 xsmp_idx = nfd;
4928 fds[nfd].fd = xsmp_icefd;
4929 fds[nfd].events = POLLIN;
4930 nfd++;
4931 }
4932# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004933#ifdef FEAT_NETBEANS_INTG
4934 if (nb_fd != -1)
4935 {
4936 nb_idx = nfd;
4937 fds[nfd].fd = nb_fd;
4938 fds[nfd].events = POLLIN;
4939 nfd++;
4940 }
4941#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004943 ret = poll(fds, nfd, towait);
4944# ifdef FEAT_MZSCHEME
4945 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004946 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004947 finished = FALSE;
4948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949
4950# ifdef FEAT_SNIFF
4951 if (ret < 0)
4952 sniff_disconnect(1);
4953 else if (want_sniff_request)
4954 {
4955 if (fds[SNIFF_IDX].revents & POLLHUP)
4956 sniff_disconnect(1);
4957 if (fds[SNIFF_IDX].revents & POLLIN)
4958 sniff_request_waiting = 1;
4959 }
4960# endif
4961# ifdef FEAT_XCLIPBOARD
4962 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4963 {
4964 xterm_update(); /* Maybe we should hand out clipboard */
4965 if (--ret == 0 && !input_available())
4966 /* Try again */
4967 finished = FALSE;
4968 }
4969# endif
4970# ifdef FEAT_MOUSE_GPM
4971 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4972 {
4973 *check_for_gpm = 1;
4974 }
4975# endif
4976# ifdef USE_XSMP
4977 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4978 {
4979 if (fds[xsmp_idx].revents & POLLIN)
4980 {
4981 busy = TRUE;
4982 xsmp_handle_requests();
4983 busy = FALSE;
4984 }
4985 else if (fds[xsmp_idx].revents & POLLHUP)
4986 {
4987 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004988 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 xsmp_close();
4990 }
4991 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004992 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 }
4994# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004995#ifdef FEAT_NETBEANS_INTG
4996 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
4997 {
4998 netbeans_read();
4999 --ret;
5000 }
5001#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002
5003
5004#else /* HAVE_SELECT */
5005
5006 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005007 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 fd_set rfds, efds;
5009 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005010 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005012# ifdef FEAT_MZSCHEME
5013 mzvim_check_threads();
5014 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5015 {
5016 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5017 mzquantum_used = TRUE;
5018 }
5019# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020# ifdef __EMX__
5021 /* don't check for incoming chars if not in raw mode, because select()
5022 * always returns TRUE then (in some version of emx.dll) */
5023 if (curr_tmode != TMODE_RAW)
5024 return 0;
5025# endif
5026
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005027 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005029 tv.tv_sec = towait / 1000;
5030 tv.tv_usec = (towait % 1000) * (1000000/1000);
5031 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005033 else
5034 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035
5036 /*
5037 * Select on ready for reading and exceptional condition (end of file).
5038 */
5039 FD_ZERO(&rfds); /* calls bzero() on a sun */
5040 FD_ZERO(&efds);
5041 FD_SET(fd, &rfds);
5042# if !defined(__QNX__) && !defined(__CYGWIN32__)
5043 /* For QNX select() always returns 1 if this is set. Why? */
5044 FD_SET(fd, &efds);
5045# endif
5046 maxfd = fd;
5047
5048# ifdef FEAT_SNIFF
5049 if (want_sniff_request)
5050 {
5051 FD_SET(fd_from_sniff, &rfds);
5052 FD_SET(fd_from_sniff, &efds);
5053 if (maxfd < fd_from_sniff)
5054 maxfd = fd_from_sniff;
5055 }
5056# endif
5057# ifdef FEAT_XCLIPBOARD
5058 if (xterm_Shell != (Widget)0)
5059 {
5060 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5061 if (maxfd < ConnectionNumber(xterm_dpy))
5062 maxfd = ConnectionNumber(xterm_dpy);
5063 }
5064# endif
5065# ifdef FEAT_MOUSE_GPM
5066 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5067 {
5068 FD_SET(gpm_fd, &rfds);
5069 FD_SET(gpm_fd, &efds);
5070 if (maxfd < gpm_fd)
5071 maxfd = gpm_fd;
5072 }
5073# endif
5074# ifdef USE_XSMP
5075 if (xsmp_icefd != -1)
5076 {
5077 FD_SET(xsmp_icefd, &rfds);
5078 FD_SET(xsmp_icefd, &efds);
5079 if (maxfd < xsmp_icefd)
5080 maxfd = xsmp_icefd;
5081 }
5082# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005083#ifdef FEAT_NETBEANS_INTG
5084 if (nb_fd != -1)
5085 {
5086 FD_SET(nb_fd, &rfds);
5087 if (maxfd < nb_fd)
5088 maxfd = nb_fd;
5089 }
5090#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091
5092# ifdef OLD_VMS
5093 /* Old VMS as v6.2 and older have broken select(). It waits more than
5094 * required. Should not be used */
5095 ret = 0;
5096# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005097 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5098# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005099# ifdef __TANDEM
5100 if (ret == -1 && errno == ENOTSUP)
5101 {
5102 FD_ZERO(&rfds);
5103 FD_ZERO(&efds);
5104 ret = 0;
5105 }
5106#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005107# ifdef FEAT_MZSCHEME
5108 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005109 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005110 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111# endif
5112
5113# ifdef FEAT_SNIFF
5114 if (ret < 0 )
5115 sniff_disconnect(1);
5116 else if (ret > 0 && want_sniff_request)
5117 {
5118 if (FD_ISSET(fd_from_sniff, &efds))
5119 sniff_disconnect(1);
5120 if (FD_ISSET(fd_from_sniff, &rfds))
5121 sniff_request_waiting = 1;
5122 }
5123# endif
5124# ifdef FEAT_XCLIPBOARD
5125 if (ret > 0 && xterm_Shell != (Widget)0
5126 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5127 {
5128 xterm_update(); /* Maybe we should hand out clipboard */
5129 /* continue looping when we only got the X event and the input
5130 * buffer is empty */
5131 if (--ret == 0 && !input_available())
5132 {
5133 /* Try again */
5134 finished = FALSE;
5135 }
5136 }
5137# endif
5138# ifdef FEAT_MOUSE_GPM
5139 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5140 {
5141 if (FD_ISSET(gpm_fd, &efds))
5142 gpm_close();
5143 else if (FD_ISSET(gpm_fd, &rfds))
5144 *check_for_gpm = 1;
5145 }
5146# endif
5147# ifdef USE_XSMP
5148 if (ret > 0 && xsmp_icefd != -1)
5149 {
5150 if (FD_ISSET(xsmp_icefd, &efds))
5151 {
5152 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005153 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154 xsmp_close();
5155 if (--ret == 0)
5156 finished = FALSE; /* keep going if event was only one */
5157 }
5158 else if (FD_ISSET(xsmp_icefd, &rfds))
5159 {
5160 busy = TRUE;
5161 xsmp_handle_requests();
5162 busy = FALSE;
5163 if (--ret == 0)
5164 finished = FALSE; /* keep going if event was only one */
5165 }
5166 }
5167# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005168#ifdef FEAT_NETBEANS_INTG
5169 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5170 {
5171 netbeans_read();
5172 --ret;
5173 }
5174#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175
5176#endif /* HAVE_SELECT */
5177
5178#ifdef MAY_LOOP
5179 if (finished || msec == 0)
5180 break;
5181
5182 /* We're going to loop around again, find out for how long */
5183 if (msec > 0)
5184 {
5185# ifdef USE_START_TV
5186 struct timeval mtv;
5187
5188 /* Compute remaining wait time. */
5189 gettimeofday(&mtv, NULL);
5190 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5191 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5192# else
5193 /* Guess we got interrupted halfway. */
5194 msec = msec / 2;
5195# endif
5196 if (msec <= 0)
5197 break; /* waited long enough */
5198 }
5199#endif
5200 }
5201
5202 return (ret > 0);
5203}
5204
5205#ifndef VMS
5206
5207#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005209 * Expand a path into all matching files and/or directories. Handles "*",
5210 * "?", "[a-z]", "**", etc.
5211 * "path" has backslashes before chars that are not to be expanded.
5212 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 */
5214 int
5215mch_expandpath(gap, path, flags)
5216 garray_T *gap;
5217 char_u *path;
5218 int flags; /* EW_* flags */
5219{
Bram Moolenaar02743632005-07-25 20:42:36 +00005220 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221}
5222#endif
5223
5224/*
5225 * mch_expand_wildcards() - this code does wild-card pattern matching using
5226 * the shell
5227 *
5228 * return OK for success, FAIL for error (you may lose some memory) and put
5229 * an error message in *file.
5230 *
5231 * num_pat is number of input patterns
5232 * pat is array of pointers to input patterns
5233 * num_file is pointer to number of matched file names
5234 * file is pointer to array of pointers to matched file names
5235 */
5236
5237#ifndef SEEK_SET
5238# define SEEK_SET 0
5239#endif
5240#ifndef SEEK_END
5241# define SEEK_END 2
5242#endif
5243
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005244#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005245
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 int
5247mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5248 int num_pat;
5249 char_u **pat;
5250 int *num_file;
5251 char_u ***file;
5252 int flags; /* EW_* flags */
5253{
5254 int i;
5255 size_t len;
5256 char_u *p;
5257 int dir;
5258#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005259 /*
5260 * This is the OS/2 implementation.
5261 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262# define EXPL_ALLOC_INC 16
5263 char_u **expl_files;
5264 size_t files_alloced, files_free;
5265 char_u *buf;
5266 int has_wildcard;
5267
5268 *num_file = 0; /* default: no files found */
5269 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5270 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5271 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5272 if (*file == NULL)
5273 return FAIL;
5274
5275 for (; num_pat > 0; num_pat--, pat++)
5276 {
5277 expl_files = NULL;
5278 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5279 /* expand environment var or home dir */
5280 buf = expand_env_save(*pat);
5281 else
5282 buf = vim_strsave(*pat);
5283 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005284 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285 if (has_wildcard) /* yes, so expand them */
5286 expl_files = (char_u **)_fnexplode(buf);
5287
5288 /*
5289 * return value of buf if no wildcards left,
5290 * OR if no match AND EW_NOTFOUND is set.
5291 */
5292 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5293 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5294 { /* simply save the current contents of *buf */
5295 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5296 if (expl_files != NULL)
5297 {
5298 expl_files[0] = vim_strsave(buf);
5299 expl_files[1] = NULL;
5300 }
5301 }
5302 vim_free(buf);
5303
5304 /*
5305 * Count number of names resulting from expansion,
5306 * At the same time add a backslash to the end of names that happen to
5307 * be directories, and replace slashes with backslashes.
5308 */
5309 if (expl_files)
5310 {
5311 for (i = 0; (p = expl_files[i]) != NULL; i++)
5312 {
5313 dir = mch_isdir(p);
5314 /* If we don't want dirs and this is one, skip it */
5315 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5316 continue;
5317
Bram Moolenaara2031822006-03-07 22:29:51 +00005318 /* Skip files that are not executable if we check for that. */
5319 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5320 continue;
5321
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 if (--files_free == 0)
5323 {
5324 /* need more room in table of pointers */
5325 files_alloced += EXPL_ALLOC_INC;
5326 *file = (char_u **)vim_realloc(*file,
5327 sizeof(char_u **) * files_alloced);
5328 if (*file == NULL)
5329 {
5330 EMSG(_(e_outofmem));
5331 *num_file = 0;
5332 return FAIL;
5333 }
5334 files_free = EXPL_ALLOC_INC;
5335 }
5336 slash_adjust(p);
5337 if (dir)
5338 {
5339 /* For a directory we add a '/', unless it's already
5340 * there. */
5341 len = STRLEN(p);
5342 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5343 {
5344 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005345 if (!after_pathsep((*file)[*num_file],
5346 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347 {
5348 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005349 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350 }
5351 }
5352 }
5353 else
5354 {
5355 (*file)[*num_file] = vim_strsave(p);
5356 }
5357
5358 /*
5359 * Error message already given by either alloc or vim_strsave.
5360 * Should return FAIL, but returning OK works also.
5361 */
5362 if ((*file)[*num_file] == NULL)
5363 break;
5364 (*num_file)++;
5365 }
5366 _fnexplodefree((char **)expl_files);
5367 }
5368 }
5369 return OK;
5370
5371#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005372 /*
5373 * This is the non-OS/2 implementation (really Unix).
5374 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 int j;
5376 char_u *tempname;
5377 char_u *command;
5378 FILE *fd;
5379 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005380#define STYLE_ECHO 0 /* use "echo", the default */
5381#define STYLE_GLOB 1 /* use "glob", for csh */
5382#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5383#define STYLE_PRINT 3 /* use "print -N", for zsh */
5384#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5385 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 int shell_style = STYLE_ECHO;
5387 int check_spaces;
5388 static int did_find_nul = FALSE;
5389 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005390 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005391 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392
5393 *num_file = 0; /* default: no files found */
5394 *file = NULL;
5395
5396 /*
5397 * If there are no wildcards, just copy the names to allocated memory.
5398 * Saves a lot of time, because we don't have to start a new shell.
5399 */
5400 if (!have_wildcard(num_pat, pat))
5401 return save_patterns(num_pat, pat, num_file, file);
5402
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005403# ifdef HAVE_SANDBOX
5404 /* Don't allow any shell command in the sandbox. */
5405 if (sandbox != 0 && check_secure())
5406 return FAIL;
5407# endif
5408
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409 /*
5410 * Don't allow the use of backticks in secure and restricted mode.
5411 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005412 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413 for (i = 0; i < num_pat; ++i)
5414 if (vim_strchr(pat[i], '`') != NULL
5415 && (check_restricted() || check_secure()))
5416 return FAIL;
5417
5418 /*
5419 * get a name for the temp file
5420 */
5421 if ((tempname = vim_tempname('o')) == NULL)
5422 {
5423 EMSG(_(e_notmp));
5424 return FAIL;
5425 }
5426
5427 /*
5428 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005429 * file.
5430 * STYLE_BT: NL separated
5431 * If expanding `cmd` execute it directly.
5432 * STYLE_GLOB: NUL separated
5433 * If we use *csh, "glob" will work better than "echo".
5434 * STYLE_PRINT: NL or NUL separated
5435 * If we use *zsh, "print -N" will work better than "glob".
5436 * STYLE_VIMGLOB: NL separated
5437 * If we use *sh*, we define "vimglob()".
5438 * STYLE_ECHO: space separated.
5439 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440 */
5441 if (num_pat == 1 && *pat[0] == '`'
5442 && (len = STRLEN(pat[0])) > 2
5443 && *(pat[0] + len - 1) == '`')
5444 shell_style = STYLE_BT;
5445 else if ((len = STRLEN(p_sh)) >= 3)
5446 {
5447 if (STRCMP(p_sh + len - 3, "csh") == 0)
5448 shell_style = STYLE_GLOB;
5449 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5450 shell_style = STYLE_PRINT;
5451 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005452 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5453 "sh") != NULL)
5454 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455
Bram Moolenaarc7247912008-01-13 12:54:11 +00005456 /* Compute the length of the command. We need 2 extra bytes: for the
5457 * optional '&' and for the NUL.
5458 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005460 if (shell_style == STYLE_VIMGLOB)
5461 len += STRLEN(sh_vimglob_func);
5462
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005463 for (i = 0; i < num_pat; ++i)
5464 {
5465 /* Count the length of the patterns in the same way as they are put in
5466 * "command" below. */
5467#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005469#else
5470 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005471 for (j = 0; pat[i][j] != NUL; ++j)
5472 {
5473 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5474 ++len; /* may add a backslash */
5475 ++len;
5476 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005477#endif
5478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479 command = alloc(len);
5480 if (command == NULL)
5481 {
5482 /* out of memory */
5483 vim_free(tempname);
5484 return FAIL;
5485 }
5486
5487 /*
5488 * Build the shell command:
5489 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5490 * recognizes this).
5491 * - Add the shell command to print the expanded names.
5492 * - Add the temp file name.
5493 * - Add the file name patterns.
5494 */
5495 if (shell_style == STYLE_BT)
5496 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005497 /* change `command; command& ` to (command; command ) */
5498 STRCPY(command, "(");
5499 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005501 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 while (p > command && vim_iswhite(*p))
5503 --p;
5504 if (*p == '&') /* remove trailing '&' */
5505 {
5506 ampersent = TRUE;
5507 *p = ' ';
5508 }
5509 STRCAT(command, ">");
5510 }
5511 else
5512 {
5513 if (flags & EW_NOTFOUND)
5514 STRCPY(command, "set nonomatch; ");
5515 else
5516 STRCPY(command, "unset nonomatch; ");
5517 if (shell_style == STYLE_GLOB)
5518 STRCAT(command, "glob >");
5519 else if (shell_style == STYLE_PRINT)
5520 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005521 else if (shell_style == STYLE_VIMGLOB)
5522 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 else
5524 STRCAT(command, "echo >");
5525 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005526
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005528
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 if (shell_style != STYLE_BT)
5530 for (i = 0; i < num_pat; ++i)
5531 {
5532 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005533 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005534 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535#ifdef USE_SYSTEM
5536 STRCAT(command, " \"");
5537 STRCAT(command, pat[i]);
5538 STRCAT(command, "\"");
5539#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005540 int intick = FALSE;
5541
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 p = command + STRLEN(command);
5543 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005544 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005545 {
5546 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005547 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005548 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5549 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005550 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005551 * backslash inside backticks, before a special character
5552 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005553 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005554 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5555 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005556 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005557 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005558 }
5559 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005560 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005561 /* Put a backslash before a special character, but not
5562 * when inside ``. */
5563 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005564
5565 /* Copy one character. */
5566 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005567 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568 *p = NUL;
5569#endif
5570 }
5571 if (flags & EW_SILENT)
5572 show_shell_mess = FALSE;
5573 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005574 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575
5576 /*
5577 * Using zsh -G: If a pattern has no matches, it is just deleted from
5578 * the argument list, otherwise zsh gives an error message and doesn't
5579 * expand any other pattern.
5580 */
5581 if (shell_style == STYLE_PRINT)
5582 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5583
5584 /*
5585 * If we use -f then shell variables set in .cshrc won't get expanded.
5586 * vi can do it, so we will too, but it is only necessary if there is a "$"
5587 * in one of the patterns, otherwise we can still use the fast option.
5588 */
5589 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5590 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5591
5592 /*
5593 * execute the shell command
5594 */
5595 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5596
5597 /* When running in the background, give it some time to create the temp
5598 * file, but don't wait for it to finish. */
5599 if (ampersent)
5600 mch_delay(10L, TRUE);
5601
5602 extra_shell_arg = NULL; /* cleanup */
5603 show_shell_mess = TRUE;
5604 vim_free(command);
5605
Bram Moolenaarc7247912008-01-13 12:54:11 +00005606 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 {
5608 mch_remove(tempname);
5609 vim_free(tempname);
5610 /*
5611 * With interactive completion, the error message is not printed.
5612 * However with USE_SYSTEM, I don't know how to turn off error messages
5613 * from the shell, so screen may still get messed up -- webb.
5614 */
5615#ifndef USE_SYSTEM
5616 if (!(flags & EW_SILENT))
5617#endif
5618 {
5619 redraw_later_clear(); /* probably messed up screen */
5620 msg_putchar('\n'); /* clear bottom line quickly */
5621 cmdline_row = Rows - 1; /* continue on last line */
5622#ifdef USE_SYSTEM
5623 if (!(flags & EW_SILENT))
5624#endif
5625 {
5626 MSG(_(e_wildexpand));
5627 msg_start(); /* don't overwrite this message */
5628 }
5629 }
5630 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5631 * EW_NOTFOUND is given */
5632 if (shell_style == STYLE_BT)
5633 return FAIL;
5634 goto notfound;
5635 }
5636
5637 /*
5638 * read the names from the file into memory
5639 */
5640 fd = fopen((char *)tempname, READBIN);
5641 if (fd == NULL)
5642 {
5643 /* Something went wrong, perhaps a file name with a special char. */
5644 if (!(flags & EW_SILENT))
5645 {
5646 MSG(_(e_wildexpand));
5647 msg_start(); /* don't overwrite this message */
5648 }
5649 vim_free(tempname);
5650 goto notfound;
5651 }
5652 fseek(fd, 0L, SEEK_END);
5653 len = ftell(fd); /* get size of temp file */
5654 fseek(fd, 0L, SEEK_SET);
5655 buffer = alloc(len + 1);
5656 if (buffer == NULL)
5657 {
5658 /* out of memory */
5659 mch_remove(tempname);
5660 vim_free(tempname);
5661 fclose(fd);
5662 return FAIL;
5663 }
5664 i = fread((char *)buffer, 1, len, fd);
5665 fclose(fd);
5666 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005667 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 {
5669 /* unexpected read error */
5670 EMSG2(_(e_notread), tempname);
5671 vim_free(tempname);
5672 vim_free(buffer);
5673 return FAIL;
5674 }
5675 vim_free(tempname);
5676
Bram Moolenaarc7247912008-01-13 12:54:11 +00005677# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5679 p = buffer;
5680 for (i = 0; i < len; ++i)
5681 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5682 *p++ = buffer[i];
5683 len = p - buffer;
5684# endif
5685
5686
5687 /* file names are separated with Space */
5688 if (shell_style == STYLE_ECHO)
5689 {
5690 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5691 p = buffer;
5692 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5693 {
5694 while (*p != ' ' && *p != '\n')
5695 ++p;
5696 p = skipwhite(p); /* skip to next entry */
5697 }
5698 }
5699 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005700 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 {
5702 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5703 p = buffer;
5704 for (i = 0; *p != NUL; ++i) /* count number of entries */
5705 {
5706 while (*p != '\n' && *p != NUL)
5707 ++p;
5708 if (*p != NUL)
5709 ++p;
5710 p = skipwhite(p); /* skip leading white space */
5711 }
5712 }
5713 /* file names are separated with NUL */
5714 else
5715 {
5716 /*
5717 * Some versions of zsh use spaces instead of NULs to separate
5718 * results. Only do this when there is no NUL before the end of the
5719 * buffer, otherwise we would never be able to use file names with
5720 * embedded spaces when zsh does use NULs.
5721 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5722 * don't check for spaces again.
5723 */
5724 check_spaces = FALSE;
5725 if (shell_style == STYLE_PRINT && !did_find_nul)
5726 {
5727 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaar78a15312009-05-15 19:33:18 +00005728 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 did_find_nul = TRUE;
5730 else
5731 check_spaces = TRUE;
5732 }
5733
5734 /*
5735 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5736 * already is one, for STYLE_GLOB it needs to be added.
5737 */
5738 if (len && buffer[len - 1] == NUL)
5739 --len;
5740 else
5741 buffer[len] = NUL;
5742 i = 0;
5743 for (p = buffer; p < buffer + len; ++p)
5744 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5745 {
5746 ++i;
5747 *p = NUL;
5748 }
5749 if (len)
5750 ++i; /* count last entry */
5751 }
5752 if (i == 0)
5753 {
5754 /*
5755 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5756 * /bin/sh will happily expand it to nothing rather than returning an
5757 * error; and hey, it's good to check anyway -- webb.
5758 */
5759 vim_free(buffer);
5760 goto notfound;
5761 }
5762 *num_file = i;
5763 *file = (char_u **)alloc(sizeof(char_u *) * i);
5764 if (*file == NULL)
5765 {
5766 /* out of memory */
5767 vim_free(buffer);
5768 return FAIL;
5769 }
5770
5771 /*
5772 * Isolate the individual file names.
5773 */
5774 p = buffer;
5775 for (i = 0; i < *num_file; ++i)
5776 {
5777 (*file)[i] = p;
5778 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005779 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5780 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005782 while (!(shell_style == STYLE_ECHO && *p == ' ')
5783 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 ++p;
5785 if (p == buffer + len) /* last entry */
5786 *p = NUL;
5787 else
5788 {
5789 *p++ = NUL;
5790 p = skipwhite(p); /* skip to next entry */
5791 }
5792 }
5793 else /* NUL separates */
5794 {
5795 while (*p && p < buffer + len) /* skip entry */
5796 ++p;
5797 ++p; /* skip NUL */
5798 }
5799 }
5800
5801 /*
5802 * Move the file names to allocated memory.
5803 */
5804 for (j = 0, i = 0; i < *num_file; ++i)
5805 {
5806 /* Require the files to exist. Helps when using /bin/sh */
5807 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5808 continue;
5809
5810 /* check if this entry should be included */
5811 dir = (mch_isdir((*file)[i]));
5812 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5813 continue;
5814
Bram Moolenaara2031822006-03-07 22:29:51 +00005815 /* Skip files that are not executable if we check for that. */
5816 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5817 continue;
5818
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5820 if (p)
5821 {
5822 STRCPY(p, (*file)[i]);
5823 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005824 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 (*file)[j++] = p;
5826 }
5827 }
5828 vim_free(buffer);
5829 *num_file = j;
5830
5831 if (*num_file == 0) /* rejected all entries */
5832 {
5833 vim_free(*file);
5834 *file = NULL;
5835 goto notfound;
5836 }
5837
5838 return OK;
5839
5840notfound:
5841 if (flags & EW_NOTFOUND)
5842 return save_patterns(num_pat, pat, num_file, file);
5843 return FAIL;
5844
5845#endif /* __EMX__ */
5846}
5847
5848#endif /* VMS */
5849
5850#ifndef __EMX__
5851 static int
5852save_patterns(num_pat, pat, num_file, file)
5853 int num_pat;
5854 char_u **pat;
5855 int *num_file;
5856 char_u ***file;
5857{
5858 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005859 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860
5861 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5862 if (*file == NULL)
5863 return FAIL;
5864 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005865 {
5866 s = vim_strsave(pat[i]);
5867 if (s != NULL)
5868 /* Be compatible with expand_filename(): halve the number of
5869 * backslashes. */
5870 backslash_halve(s);
5871 (*file)[i] = s;
5872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 *num_file = num_pat;
5874 return OK;
5875}
5876#endif
5877
5878
5879/*
5880 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5881 * expand.
5882 */
5883 int
5884mch_has_exp_wildcard(p)
5885 char_u *p;
5886{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005887 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888 {
5889#ifndef OS2
5890 if (*p == '\\' && p[1] != NUL)
5891 ++p;
5892 else
5893#endif
5894 if (vim_strchr((char_u *)
5895#ifdef VMS
5896 "*?%"
5897#else
5898# ifdef OS2
5899 "*?"
5900# else
5901 "*?[{'"
5902# endif
5903#endif
5904 , *p) != NULL)
5905 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 }
5907 return FALSE;
5908}
5909
5910/*
5911 * Return TRUE if the string "p" contains a wildcard.
5912 * Don't recognize '~' at the end as a wildcard.
5913 */
5914 int
5915mch_has_wildcard(p)
5916 char_u *p;
5917{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005918 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919 {
5920#ifndef OS2
5921 if (*p == '\\' && p[1] != NUL)
5922 ++p;
5923 else
5924#endif
5925 if (vim_strchr((char_u *)
5926#ifdef VMS
5927 "*?%$"
5928#else
5929# ifdef OS2
5930# ifdef VIM_BACKTICK
5931 "*?$`"
5932# else
5933 "*?$"
5934# endif
5935# else
5936 "*?[{`'$"
5937# endif
5938#endif
5939 , *p) != NULL
5940 || (*p == '~' && p[1] != NUL))
5941 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 }
5943 return FALSE;
5944}
5945
5946#ifndef __EMX__
5947 static int
5948have_wildcard(num, file)
5949 int num;
5950 char_u **file;
5951{
5952 int i;
5953
5954 for (i = 0; i < num; i++)
5955 if (mch_has_wildcard(file[i]))
5956 return 1;
5957 return 0;
5958}
5959
5960 static int
5961have_dollars(num, file)
5962 int num;
5963 char_u **file;
5964{
5965 int i;
5966
5967 for (i = 0; i < num; i++)
5968 if (vim_strchr(file[i], '$') != NULL)
5969 return TRUE;
5970 return FALSE;
5971}
5972#endif /* ifndef __EMX__ */
5973
5974#ifndef HAVE_RENAME
5975/*
5976 * Scaled-down version of rename(), which is missing in Xenix.
5977 * This version can only move regular files and will fail if the
5978 * destination exists.
5979 */
5980 int
5981mch_rename(src, dest)
5982 const char *src, *dest;
5983{
5984 struct stat st;
5985
5986 if (stat(dest, &st) >= 0) /* fail if destination exists */
5987 return -1;
5988 if (link(src, dest) != 0) /* link file to new name */
5989 return -1;
5990 if (mch_remove(src) == 0) /* delete link to old name */
5991 return 0;
5992 return -1;
5993}
5994#endif /* !HAVE_RENAME */
5995
5996#ifdef FEAT_MOUSE_GPM
5997/*
5998 * Initializes connection with gpm (if it isn't already opened)
5999 * Return 1 if succeeded (or connection already opened), 0 if failed
6000 */
6001 static int
6002gpm_open()
6003{
6004 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6005
6006 if (!gpm_flag)
6007 {
6008 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6009 gpm_connect.defaultMask = ~GPM_HARD;
6010 /* Default handling for mouse move*/
6011 gpm_connect.minMod = 0; /* Handle any modifier keys */
6012 gpm_connect.maxMod = 0xffff;
6013 if (Gpm_Open(&gpm_connect, 0) > 0)
6014 {
6015 /* gpm library tries to handling TSTP causes
6016 * problems. Anyways, we close connection to Gpm whenever
6017 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006018 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006020# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006022# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023 return 1; /* succeed */
6024 }
6025 if (gpm_fd == -2)
6026 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6027 return 0;
6028 }
6029 return 1; /* already open */
6030}
6031
6032/*
6033 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 */
6035 static void
6036gpm_close()
6037{
6038 if (gpm_flag && gpm_fd >= 0) /* if Open */
6039 Gpm_Close();
6040}
6041
6042/* Reads gpm event and adds special keys to input buf. Returns length of
6043 * generated key sequence.
6044 * This function is made after gui_send_mouse_event
6045 */
6046 static int
6047mch_gpm_process()
6048{
6049 int button;
6050 static Gpm_Event gpm_event;
6051 char_u string[6];
6052 int_u vim_modifiers;
6053 int row,col;
6054 unsigned char buttons_mask;
6055 unsigned char gpm_modifiers;
6056 static unsigned char old_buttons = 0;
6057
6058 Gpm_GetEvent(&gpm_event);
6059
6060#ifdef FEAT_GUI
6061 /* Don't put events in the input queue now. */
6062 if (hold_gui_events)
6063 return 0;
6064#endif
6065
6066 row = gpm_event.y - 1;
6067 col = gpm_event.x - 1;
6068
6069 string[0] = ESC; /* Our termcode */
6070 string[1] = 'M';
6071 string[2] = 'G';
6072 switch (GPM_BARE_EVENTS(gpm_event.type))
6073 {
6074 case GPM_DRAG:
6075 string[3] = MOUSE_DRAG;
6076 break;
6077 case GPM_DOWN:
6078 buttons_mask = gpm_event.buttons & ~old_buttons;
6079 old_buttons = gpm_event.buttons;
6080 switch (buttons_mask)
6081 {
6082 case GPM_B_LEFT:
6083 button = MOUSE_LEFT;
6084 break;
6085 case GPM_B_MIDDLE:
6086 button = MOUSE_MIDDLE;
6087 break;
6088 case GPM_B_RIGHT:
6089 button = MOUSE_RIGHT;
6090 break;
6091 default:
6092 return 0;
6093 /*Don't know what to do. Can more than one button be
6094 * reported in one event? */
6095 }
6096 string[3] = (char_u)(button | 0x20);
6097 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6098 break;
6099 case GPM_UP:
6100 string[3] = MOUSE_RELEASE;
6101 old_buttons &= ~gpm_event.buttons;
6102 break;
6103 default:
6104 return 0;
6105 }
6106 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6107 gpm_modifiers = gpm_event.modifiers;
6108 vim_modifiers = 0x0;
6109 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6110 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6111 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6112 */
6113 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6114 vim_modifiers |= MOUSE_SHIFT;
6115
6116 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6117 vim_modifiers |= MOUSE_CTRL;
6118 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6119 vim_modifiers |= MOUSE_ALT;
6120 string[3] |= vim_modifiers;
6121 string[4] = (char_u)(col + ' ' + 1);
6122 string[5] = (char_u)(row + ' ' + 1);
6123 add_to_input_buf(string, 6);
6124 return 6;
6125}
6126#endif /* FEAT_MOUSE_GPM */
6127
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006128#ifdef FEAT_SYSMOUSE
6129/*
6130 * Initialize connection with sysmouse.
6131 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6132 * output, any sysmouse output than will be processed via sig_sysmouse().
6133 * Return OK if succeeded, FAIL if failed.
6134 */
6135 static int
6136sysmouse_open()
6137{
6138 struct mouse_info mouse;
6139
6140 mouse.operation = MOUSE_MODE;
6141 mouse.u.mode.mode = 0;
6142 mouse.u.mode.signal = SIGUSR2;
6143 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6144 {
6145 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6146 mouse.operation = MOUSE_SHOW;
6147 ioctl(1, CONS_MOUSECTL, &mouse);
6148 return OK;
6149 }
6150 return FAIL;
6151}
6152
6153/*
6154 * Stop processing SIGUSR2 signals, and also make sure that
6155 * virtual console do not send us any sysmouse related signal.
6156 */
6157 static void
6158sysmouse_close()
6159{
6160 struct mouse_info mouse;
6161
6162 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6163 mouse.operation = MOUSE_MODE;
6164 mouse.u.mode.mode = 0;
6165 mouse.u.mode.signal = 0;
6166 ioctl(1, CONS_MOUSECTL, &mouse);
6167}
6168
6169/*
6170 * Gets info from sysmouse and adds special keys to input buf.
6171 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006172 static RETSIGTYPE
6173sig_sysmouse SIGDEFARG(sigarg)
6174{
6175 struct mouse_info mouse;
6176 struct video_info video;
6177 char_u string[6];
6178 int row, col;
6179 int button;
6180 int buttons;
6181 static int oldbuttons = 0;
6182
6183#ifdef FEAT_GUI
6184 /* Don't put events in the input queue now. */
6185 if (hold_gui_events)
6186 return;
6187#endif
6188
6189 mouse.operation = MOUSE_GETINFO;
6190 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6191 && ioctl(1, FBIO_MODEINFO, &video) != -1
6192 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6193 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6194 {
6195 row = mouse.u.data.y / video.vi_cheight;
6196 col = mouse.u.data.x / video.vi_cwidth;
6197 buttons = mouse.u.data.buttons;
6198 string[0] = ESC; /* Our termcode */
6199 string[1] = 'M';
6200 string[2] = 'S';
6201 if (oldbuttons == buttons && buttons != 0)
6202 {
6203 button = MOUSE_DRAG;
6204 }
6205 else
6206 {
6207 switch (buttons)
6208 {
6209 case 0:
6210 button = MOUSE_RELEASE;
6211 break;
6212 case 1:
6213 button = MOUSE_LEFT;
6214 break;
6215 case 2:
6216 button = MOUSE_MIDDLE;
6217 break;
6218 case 4:
6219 button = MOUSE_RIGHT;
6220 break;
6221 default:
6222 return;
6223 }
6224 oldbuttons = buttons;
6225 }
6226 string[3] = (char_u)(button);
6227 string[4] = (char_u)(col + ' ' + 1);
6228 string[5] = (char_u)(row + ' ' + 1);
6229 add_to_input_buf(string, 6);
6230 }
6231 return;
6232}
6233#endif /* FEAT_SYSMOUSE */
6234
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235#if defined(FEAT_LIBCALL) || defined(PROTO)
6236typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6237typedef char_u * (*INTPROCSTR)__ARGS((int));
6238typedef int (*STRPROCINT)__ARGS((char_u *));
6239typedef int (*INTPROCINT)__ARGS((int));
6240
6241/*
6242 * Call a DLL routine which takes either a string or int param
6243 * and returns an allocated string.
6244 */
6245 int
6246mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6247 char_u *libname;
6248 char_u *funcname;
6249 char_u *argstring; /* NULL when using a argint */
6250 int argint;
6251 char_u **string_result;/* NULL when using number_result */
6252 int *number_result;
6253{
6254# if defined(USE_DLOPEN)
6255 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006256 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257# else
6258 shl_t hinstLib;
6259# endif
6260 STRPROCSTR ProcAdd;
6261 INTPROCSTR ProcAddI;
6262 char_u *retval_str = NULL;
6263 int retval_int = 0;
6264 int success = FALSE;
6265
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006266 /*
6267 * Get a handle to the DLL module.
6268 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006270 /* First clear any error, it's not cleared by the dlopen() call. */
6271 (void)dlerror();
6272
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 hinstLib = dlopen((char *)libname, RTLD_LAZY
6274# ifdef RTLD_LOCAL
6275 | RTLD_LOCAL
6276# endif
6277 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006278 if (hinstLib == NULL)
6279 {
6280 /* "dlerr" must be used before dlclose() */
6281 dlerr = (char *)dlerror();
6282 if (dlerr != NULL)
6283 EMSG2(_("dlerror = \"%s\""), dlerr);
6284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285# else
6286 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6287# endif
6288
6289 /* If the handle is valid, try to get the function address. */
6290 if (hinstLib != NULL)
6291 {
6292# ifdef HAVE_SETJMP_H
6293 /*
6294 * Catch a crash when calling the library function. For example when
6295 * using a number where a string pointer is expected.
6296 */
6297 mch_startjmp();
6298 if (SETJMP(lc_jump_env) != 0)
6299 {
6300 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006301# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006302 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006303# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 mch_didjmp();
6305 }
6306 else
6307# endif
6308 {
6309 retval_str = NULL;
6310 retval_int = 0;
6311
6312 if (argstring != NULL)
6313 {
6314# if defined(USE_DLOPEN)
6315 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006316 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317# else
6318 if (shl_findsym(&hinstLib, (const char *)funcname,
6319 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6320 ProcAdd = NULL;
6321# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006322 if ((success = (ProcAdd != NULL
6323# if defined(USE_DLOPEN)
6324 && dlerr == NULL
6325# endif
6326 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 {
6328 if (string_result == NULL)
6329 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6330 else
6331 retval_str = (ProcAdd)(argstring);
6332 }
6333 }
6334 else
6335 {
6336# if defined(USE_DLOPEN)
6337 ProcAddI = (INTPROCSTR)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 *)&ProcAddI) < 0)
6342 ProcAddI = NULL;
6343# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006344 if ((success = (ProcAddI != 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 = ((INTPROCINT)ProcAddI)(argint);
6352 else
6353 retval_str = (ProcAddI)(argint);
6354 }
6355 }
6356
6357 /* Save the string before we free the library. */
6358 /* Assume that a "1" or "-1" result is an illegal pointer. */
6359 if (string_result == NULL)
6360 *number_result = retval_int;
6361 else if (retval_str != NULL
6362 && retval_str != (char_u *)1
6363 && retval_str != (char_u *)-1)
6364 *string_result = vim_strsave(retval_str);
6365 }
6366
6367# ifdef HAVE_SETJMP_H
6368 mch_endjmp();
6369# ifdef SIGHASARG
6370 if (lc_signal != 0)
6371 {
6372 int i;
6373
6374 /* try to find the name of this signal */
6375 for (i = 0; signal_info[i].sig != -1; i++)
6376 if (lc_signal == signal_info[i].sig)
6377 break;
6378 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6379 }
6380# endif
6381# endif
6382
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006384 /* "dlerr" must be used before dlclose() */
6385 if (dlerr != NULL)
6386 EMSG2(_("dlerror = \"%s\""), dlerr);
6387
6388 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 (void)dlclose(hinstLib);
6390# else
6391 (void)shl_unload(hinstLib);
6392# endif
6393 }
6394
6395 if (!success)
6396 {
6397 EMSG2(_(e_libcall), funcname);
6398 return FAIL;
6399 }
6400
6401 return OK;
6402}
6403#endif
6404
6405#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6406static int xterm_trace = -1; /* default: disabled */
6407static int xterm_button;
6408
6409/*
6410 * Setup a dummy window for X selections in a terminal.
6411 */
6412 void
6413setup_term_clip()
6414{
6415 int z = 0;
6416 char *strp = "";
6417 Widget AppShell;
6418
6419 if (!x_connect_to_server())
6420 return;
6421
6422 open_app_context();
6423 if (app_context != NULL && xterm_Shell == (Widget)0)
6424 {
6425 int (*oldhandler)();
6426#if defined(HAVE_SETJMP_H)
6427 int (*oldIOhandler)();
6428#endif
6429# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6430 struct timeval start_tv;
6431
6432 if (p_verbose > 0)
6433 gettimeofday(&start_tv, NULL);
6434# endif
6435
6436 /* Ignore X errors while opening the display */
6437 oldhandler = XSetErrorHandler(x_error_check);
6438
6439#if defined(HAVE_SETJMP_H)
6440 /* Ignore X IO errors while opening the display */
6441 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6442 mch_startjmp();
6443 if (SETJMP(lc_jump_env) != 0)
6444 {
6445 mch_didjmp();
6446 xterm_dpy = NULL;
6447 }
6448 else
6449#endif
6450 {
6451 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6452 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6453#if defined(HAVE_SETJMP_H)
6454 mch_endjmp();
6455#endif
6456 }
6457
6458#if defined(HAVE_SETJMP_H)
6459 /* Now handle X IO errors normally. */
6460 (void)XSetIOErrorHandler(oldIOhandler);
6461#endif
6462 /* Now handle X errors normally. */
6463 (void)XSetErrorHandler(oldhandler);
6464
6465 if (xterm_dpy == NULL)
6466 {
6467 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006468 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 return;
6470 }
6471
6472 /* Catch terminating error of the X server connection. */
6473 (void)XSetIOErrorHandler(x_IOerror_handler);
6474
6475# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6476 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006477 {
6478 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006480 verbose_leave();
6481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482# endif
6483
6484 /* Create a Shell to make converters work. */
6485 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6486 applicationShellWidgetClass, xterm_dpy,
6487 NULL);
6488 if (AppShell == (Widget)0)
6489 return;
6490 xterm_Shell = XtVaCreatePopupShell("VIM",
6491 topLevelShellWidgetClass, AppShell,
6492 XtNmappedWhenManaged, 0,
6493 XtNwidth, 1,
6494 XtNheight, 1,
6495 NULL);
6496 if (xterm_Shell == (Widget)0)
6497 return;
6498
6499 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006500 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 if (x11_display == NULL)
6502 x11_display = xterm_dpy;
6503
6504 XtRealizeWidget(xterm_Shell);
6505 XSync(xterm_dpy, False);
6506 xterm_update();
6507 }
6508 if (xterm_Shell != (Widget)0)
6509 {
6510 clip_init(TRUE);
6511 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6512 x11_window = (Window)atol(strp);
6513 /* Check if $WINDOWID is valid. */
6514 if (test_x11_window(xterm_dpy) == FAIL)
6515 x11_window = 0;
6516 if (x11_window != 0)
6517 xterm_trace = 0;
6518 }
6519}
6520
6521 void
6522start_xterm_trace(button)
6523 int button;
6524{
6525 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6526 return;
6527 xterm_trace = 1;
6528 xterm_button = button;
6529 do_xterm_trace();
6530}
6531
6532
6533 void
6534stop_xterm_trace()
6535{
6536 if (xterm_trace < 0)
6537 return;
6538 xterm_trace = 0;
6539}
6540
6541/*
6542 * Query the xterm pointer and generate mouse termcodes if necessary
6543 * return TRUE if dragging is active, else FALSE
6544 */
6545 static int
6546do_xterm_trace()
6547{
6548 Window root, child;
6549 int root_x, root_y;
6550 int win_x, win_y;
6551 int row, col;
6552 int_u mask_return;
6553 char_u buf[50];
6554 char_u *strp;
6555 long got_hints;
6556 static char_u *mouse_code;
6557 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6558 static int prev_row = 0, prev_col = 0;
6559 static XSizeHints xterm_hints;
6560
6561 if (xterm_trace <= 0)
6562 return FALSE;
6563
6564 if (xterm_trace == 1)
6565 {
6566 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006567 * have changed recently. */
6568 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6569 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 || xterm_hints.width_inc <= 1
6571 || xterm_hints.height_inc <= 1)
6572 {
6573 xterm_trace = -1; /* Not enough data -- disable tracing */
6574 return FALSE;
6575 }
6576
6577 /* Rely on the same mouse code for the duration of this */
6578 mouse_code = find_termcode(mouse_name);
6579 prev_row = mouse_row;
6580 prev_row = mouse_col;
6581 xterm_trace = 2;
6582
6583 /* Find the offset of the chars, there might be a scrollbar on the
6584 * left of the window and/or a menu on the top (eterm etc.) */
6585 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6586 &win_x, &win_y, &mask_return);
6587 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6588 - (xterm_hints.height_inc / 2);
6589 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6590 xterm_hints.y = 2;
6591 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6592 - (xterm_hints.width_inc / 2);
6593 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6594 xterm_hints.x = 2;
6595 return TRUE;
6596 }
6597 if (mouse_code == NULL)
6598 {
6599 xterm_trace = 0;
6600 return FALSE;
6601 }
6602
6603 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6604 &win_x, &win_y, &mask_return);
6605
6606 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6607 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6608 if (row == prev_row && col == prev_col)
6609 return TRUE;
6610
6611 STRCPY(buf, mouse_code);
6612 strp = buf + STRLEN(buf);
6613 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6614 *strp++ = (char_u)(col + ' ' + 1);
6615 *strp++ = (char_u)(row + ' ' + 1);
6616 *strp = 0;
6617 add_to_input_buf(buf, STRLEN(buf));
6618
6619 prev_row = row;
6620 prev_col = col;
6621 return TRUE;
6622}
6623
6624# if defined(FEAT_GUI) || defined(PROTO)
6625/*
6626 * Destroy the display, window and app_context. Required for GTK.
6627 */
6628 void
6629clear_xterm_clip()
6630{
6631 if (xterm_Shell != (Widget)0)
6632 {
6633 XtDestroyWidget(xterm_Shell);
6634 xterm_Shell = (Widget)0;
6635 }
6636 if (xterm_dpy != NULL)
6637 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006638# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 /* Lesstif and Solaris crash here, lose some memory */
6640 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006641# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 if (x11_display == xterm_dpy)
6643 x11_display = NULL;
6644 xterm_dpy = NULL;
6645 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006646# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 if (app_context != (XtAppContext)NULL)
6648 {
6649 /* Lesstif and Solaris crash here, lose some memory */
6650 XtDestroyApplicationContext(app_context);
6651 app_context = (XtAppContext)NULL;
6652 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006653# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654}
6655# endif
6656
6657/*
6658 * Catch up with any queued X events. This may put keyboard input into the
6659 * input buffer, call resize call-backs, trigger timers etc. If there is
6660 * nothing in the X event queue (& no timers pending), then we return
6661 * immediately.
6662 */
6663 static void
6664xterm_update()
6665{
6666 XEvent event;
6667
6668 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6669 {
6670 XtAppNextEvent(app_context, &event);
6671#ifdef FEAT_CLIENTSERVER
6672 {
6673 XPropertyEvent *e = (XPropertyEvent *)&event;
6674
6675 if (e->type == PropertyNotify && e->window == commWindow
6676 && e->atom == commProperty && e->state == PropertyNewValue)
6677 serverEventProc(xterm_dpy, &event);
6678 }
6679#endif
6680 XtDispatchEvent(&event);
6681 }
6682}
6683
6684 int
6685clip_xterm_own_selection(cbd)
6686 VimClipboard *cbd;
6687{
6688 if (xterm_Shell != (Widget)0)
6689 return clip_x11_own_selection(xterm_Shell, cbd);
6690 return FAIL;
6691}
6692
6693 void
6694clip_xterm_lose_selection(cbd)
6695 VimClipboard *cbd;
6696{
6697 if (xterm_Shell != (Widget)0)
6698 clip_x11_lose_selection(xterm_Shell, cbd);
6699}
6700
6701 void
6702clip_xterm_request_selection(cbd)
6703 VimClipboard *cbd;
6704{
6705 if (xterm_Shell != (Widget)0)
6706 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6707}
6708
6709 void
6710clip_xterm_set_selection(cbd)
6711 VimClipboard *cbd;
6712{
6713 clip_x11_set_selection(cbd);
6714}
6715#endif
6716
6717
6718#if defined(USE_XSMP) || defined(PROTO)
6719/*
6720 * Code for X Session Management Protocol.
6721 */
6722static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6723static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6724static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6725static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6726static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6727
6728
6729# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6730static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6731
6732/*
6733 * This is our chance to ask the user if they want to save,
6734 * or abort the logout
6735 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736 static void
6737xsmp_handle_interaction(smc_conn, client_data)
6738 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006739 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740{
6741 cmdmod_T save_cmdmod;
6742 int cancel_shutdown = False;
6743
6744 save_cmdmod = cmdmod;
6745 cmdmod.confirm = TRUE;
6746 if (check_changed_any(FALSE))
6747 /* Mustn't logout */
6748 cancel_shutdown = True;
6749 cmdmod = save_cmdmod;
6750 setcursor(); /* position cursor */
6751 out_flush();
6752
6753 /* Done interaction */
6754 SmcInteractDone(smc_conn, cancel_shutdown);
6755
6756 /* Finish off
6757 * Only end save-yourself here if we're not cancelling shutdown;
6758 * we'll get a cancelled callback later in which we'll end it.
6759 * Hopefully get around glitchy SMs (like GNOME-1)
6760 */
6761 if (!cancel_shutdown)
6762 {
6763 xsmp.save_yourself = False;
6764 SmcSaveYourselfDone(smc_conn, True);
6765 }
6766}
6767# endif
6768
6769/*
6770 * Callback that starts save-yourself.
6771 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 static void
6773xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6774 shutdown, interact_style, fast)
6775 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006776 SmPointer client_data UNUSED;
6777 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006779 int interact_style UNUSED;
6780 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781{
6782 /* Handle already being in saveyourself */
6783 if (xsmp.save_yourself)
6784 SmcSaveYourselfDone(smc_conn, True);
6785 xsmp.save_yourself = True;
6786 xsmp.shutdown = shutdown;
6787
6788 /* First up, preserve all files */
6789 out_flush();
6790 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6791
6792 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006793 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794
6795# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6796 /* Now see if we can ask about unsaved files */
6797 if (shutdown && !fast && gui.in_use)
6798 /* Need to interact with user, but need SM's permission */
6799 SmcInteractRequest(smc_conn, SmDialogError,
6800 xsmp_handle_interaction, client_data);
6801 else
6802# endif
6803 {
6804 /* Can stop the cycle here */
6805 SmcSaveYourselfDone(smc_conn, True);
6806 xsmp.save_yourself = False;
6807 }
6808}
6809
6810
6811/*
6812 * Callback to warn us of imminent death.
6813 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 static void
6815xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006816 SmcConn smc_conn UNUSED;
6817 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818{
6819 xsmp_close();
6820
6821 /* quit quickly leaving swapfiles for modified buffers behind */
6822 getout_preserve_modified(0);
6823}
6824
6825
6826/*
6827 * Callback to tell us that save-yourself has completed.
6828 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 static void
6830xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006831 SmcConn smc_conn UNUSED;
6832 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833{
6834 xsmp.save_yourself = False;
6835}
6836
6837
6838/*
6839 * Callback to tell us that an instigated shutdown was cancelled
6840 * (maybe even by us)
6841 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 static void
6843xsmp_shutdown_cancelled(smc_conn, client_data)
6844 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006845 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846{
6847 if (xsmp.save_yourself)
6848 SmcSaveYourselfDone(smc_conn, True);
6849 xsmp.save_yourself = False;
6850 xsmp.shutdown = False;
6851}
6852
6853
6854/*
6855 * Callback to tell us that a new ICE connection has been established.
6856 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 static void
6858xsmp_ice_connection(iceConn, clientData, opening, watchData)
6859 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006860 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006862 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863{
6864 /* Intercept creation of ICE connection fd */
6865 if (opening)
6866 {
6867 xsmp_icefd = IceConnectionNumber(iceConn);
6868 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6869 }
6870}
6871
6872
6873/* Handle any ICE processing that's required; return FAIL if SM lost */
6874 int
6875xsmp_handle_requests()
6876{
6877 Bool rep;
6878
6879 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6880 == IceProcessMessagesIOError)
6881 {
6882 /* Lost ICE */
6883 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006884 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 xsmp_close();
6886 return FAIL;
6887 }
6888 else
6889 return OK;
6890}
6891
6892static int dummy;
6893
6894/* Set up X Session Management Protocol */
6895 void
6896xsmp_init(void)
6897{
6898 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 SmcCallbacks smcallbacks;
6900#if 0
6901 SmPropValue smname;
6902 SmProp smnameprop;
6903 SmProp *smprops[1];
6904#endif
6905
6906 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006907 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
6909 xsmp.save_yourself = xsmp.shutdown = False;
6910
6911 /* Set up SM callbacks - must have all, even if they're not used */
6912 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6913 smcallbacks.save_yourself.client_data = NULL;
6914 smcallbacks.die.callback = xsmp_die;
6915 smcallbacks.die.client_data = NULL;
6916 smcallbacks.save_complete.callback = xsmp_save_complete;
6917 smcallbacks.save_complete.client_data = NULL;
6918 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6919 smcallbacks.shutdown_cancelled.client_data = NULL;
6920
6921 /* Set up a watch on ICE connection creations. The "dummy" argument is
6922 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6923 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6924 {
6925 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006926 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 return;
6928 }
6929
6930 /* Create an SM connection */
6931 xsmp.smcconn = SmcOpenConnection(
6932 NULL,
6933 NULL,
6934 SmProtoMajor,
6935 SmProtoMinor,
6936 SmcSaveYourselfProcMask | SmcDieProcMask
6937 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6938 &smcallbacks,
6939 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00006940 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 sizeof(errorstring),
6942 errorstring);
6943 if (xsmp.smcconn == NULL)
6944 {
6945 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006946
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006948 {
6949 vim_snprintf(errorreport, sizeof(errorreport),
6950 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6951 verb_msg((char_u *)errorreport);
6952 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006953 return;
6954 }
6955 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6956
6957#if 0
6958 /* ID ourselves */
6959 smname.value = "vim";
6960 smname.length = 3;
6961 smnameprop.name = "SmProgram";
6962 smnameprop.type = "SmARRAY8";
6963 smnameprop.num_vals = 1;
6964 smnameprop.vals = &smname;
6965
6966 smprops[0] = &smnameprop;
6967 SmcSetProperties(xsmp.smcconn, 1, smprops);
6968#endif
6969}
6970
6971
6972/* Shut down XSMP comms. */
6973 void
6974xsmp_close()
6975{
6976 if (xsmp_icefd != -1)
6977 {
6978 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00006979 if (xsmp.clientid != NULL)
6980 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00006981 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 xsmp_icefd = -1;
6983 }
6984}
6985#endif /* USE_XSMP */
6986
6987
6988#ifdef EBCDIC
6989/* Translate character to its CTRL- value */
6990char CtrlTable[] =
6991{
6992/* 00 - 5E */
6993 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6994 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6995 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6996 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6997 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6998 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6999/* ^ */ 0x1E,
7000/* - */ 0x1F,
7001/* 61 - 6C */
7002 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7003/* _ */ 0x1F,
7004/* 6E - 80 */
7005 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7006/* a */ 0x01,
7007/* b */ 0x02,
7008/* c */ 0x03,
7009/* d */ 0x37,
7010/* e */ 0x2D,
7011/* f */ 0x2E,
7012/* g */ 0x2F,
7013/* h */ 0x16,
7014/* i */ 0x05,
7015/* 8A - 90 */
7016 0, 0, 0, 0, 0, 0, 0,
7017/* j */ 0x15,
7018/* k */ 0x0B,
7019/* l */ 0x0C,
7020/* m */ 0x0D,
7021/* n */ 0x0E,
7022/* o */ 0x0F,
7023/* p */ 0x10,
7024/* q */ 0x11,
7025/* r */ 0x12,
7026/* 9A - A1 */
7027 0, 0, 0, 0, 0, 0, 0, 0,
7028/* s */ 0x13,
7029/* t */ 0x3C,
7030/* u */ 0x3D,
7031/* v */ 0x32,
7032/* w */ 0x26,
7033/* x */ 0x18,
7034/* y */ 0x19,
7035/* z */ 0x3F,
7036/* AA - AC */
7037 0, 0, 0,
7038/* [ */ 0x27,
7039/* AE - BC */
7040 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7041/* ] */ 0x1D,
7042/* BE - C0 */ 0, 0, 0,
7043/* A */ 0x01,
7044/* B */ 0x02,
7045/* C */ 0x03,
7046/* D */ 0x37,
7047/* E */ 0x2D,
7048/* F */ 0x2E,
7049/* G */ 0x2F,
7050/* H */ 0x16,
7051/* I */ 0x05,
7052/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7053/* J */ 0x15,
7054/* K */ 0x0B,
7055/* L */ 0x0C,
7056/* M */ 0x0D,
7057/* N */ 0x0E,
7058/* O */ 0x0F,
7059/* P */ 0x10,
7060/* Q */ 0x11,
7061/* R */ 0x12,
7062/* DA - DF */ 0, 0, 0, 0, 0, 0,
7063/* \ */ 0x1C,
7064/* E1 */ 0,
7065/* S */ 0x13,
7066/* T */ 0x3C,
7067/* U */ 0x3D,
7068/* V */ 0x32,
7069/* W */ 0x26,
7070/* X */ 0x18,
7071/* Y */ 0x19,
7072/* Z */ 0x3F,
7073/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7074 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7075};
7076
7077char MetaCharTable[]=
7078{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7079 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7080 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7081 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7082 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7083};
7084
7085
7086/* TODO: Use characters NOT numbers!!! */
7087char CtrlCharTable[]=
7088{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7089 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7090 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7091 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7092 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7093};
7094
7095
7096#endif