blob: 98ff1ea662a8125419f7d0419e7206b0fd1c98a1 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
6 *
7 * Do ":help uganda" in Vim to read copying and usage conditions.
8 * Do ":help credits" in Vim to see a list of people who contributed.
9 * See README.txt for an overview of the Vim source code.
10 */
11
12/*
13 * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
14 * Also for OS/2, using the excellent EMX package!!!
15 * Also for BeOS and Atari MiNT.
16 *
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
19 */
20
21/*
22 * Some systems have a prototype for select() that has (int *) instead of
23 * (fd_set *), which is wrong. This define removes that prototype. We define
24 * our own prototype below.
25 * Don't use it for the Mac, it causes a warning for precompiled headers.
26 * TODO: use a configure check for precompiled headers?
27 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000028#if !defined(__APPLE__) && !defined(__TANDEM)
Bram Moolenaar071d4272004-06-13 20:20:40 +000029# define select select_declared_wrong
30#endif
31
32#include "vim.h"
33
Bram Moolenaar325b7a22004-07-05 15:58:32 +000034#ifdef FEAT_MZSCHEME
35# include "if_mzsch.h"
36#endif
37
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#include "os_unixx.h" /* unix includes for os_unix.c only */
39
40#ifdef USE_XSMP
41# include <X11/SM/SMlib.h>
42#endif
43
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000044#ifdef HAVE_SELINUX
45# include <selinux/selinux.h>
46static int selinux_enabled = -1;
47#endif
48
Bram Moolenaar071d4272004-06-13 20:20:40 +000049/*
50 * Use this prototype for select, some include files have a wrong prototype
51 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000052#ifndef __TANDEM
53# undef select
54# ifdef __BEOS__
55# define select beos_select
56# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
Bram Moolenaara2442432007-04-26 14:26:37 +000059#ifdef __CYGWIN__
60# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000061# include <cygwin/version.h>
62# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
63 * for cygwin_conv_path() */
Bram Moolenaara2442432007-04-26 14:26:37 +000064# endif
65#endif
66
Bram Moolenaar071d4272004-06-13 20:20:40 +000067#if defined(HAVE_SELECT)
68extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
69#endif
70
71#ifdef FEAT_MOUSE_GPM
72# include <gpm.h>
73/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
74 * I just copied relevant defines here. A cleaner solution would be to put gpm
75 * code into separate file and include there linux/keyboard.h
76 */
77/* #include <linux/keyboard.h> */
78# define KG_SHIFT 0
79# define KG_CTRL 2
80# define KG_ALT 3
81# define KG_ALTGR 1
82# define KG_SHIFTL 4
83# define KG_SHIFTR 5
84# define KG_CTRLL 6
85# define KG_CTRLR 7
86# define KG_CAPSSHIFT 8
87
88static void gpm_close __ARGS((void));
89static int gpm_open __ARGS((void));
90static int mch_gpm_process __ARGS((void));
91#endif
92
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000093#ifdef FEAT_SYSMOUSE
94# include <sys/consio.h>
95# include <sys/fbio.h>
96
97static int sysmouse_open __ARGS((void));
98static void sysmouse_close __ARGS((void));
99static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG);
100#endif
101
Bram Moolenaar071d4272004-06-13 20:20:40 +0000102/*
103 * end of autoconf section. To be extended...
104 */
105
106/* Are the following #ifdefs still required? And why? Is that for X11? */
107
108#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
109# ifdef SIGWINCH
110# undef SIGWINCH
111# endif
112# ifdef TIOCGWINSZ
113# undef TIOCGWINSZ
114# endif
115#endif
116
117#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
118# define SIGWINCH SIGWINDOW
119#endif
120
121#ifdef FEAT_X11
122# include <X11/Xlib.h>
123# include <X11/Xutil.h>
124# include <X11/Xatom.h>
125# ifdef FEAT_XCLIPBOARD
126# include <X11/Intrinsic.h>
127# include <X11/Shell.h>
128# include <X11/StringDefs.h>
129static Widget xterm_Shell = (Widget)0;
130static void xterm_update __ARGS((void));
131# endif
132
133# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
134Window x11_window = 0;
135# endif
136Display *x11_display = NULL;
137
138# ifdef FEAT_TITLE
139static int get_x11_windis __ARGS((void));
140static void set_x11_title __ARGS((char_u *));
141static void set_x11_icon __ARGS((char_u *));
142# endif
143#endif
144
145#ifdef FEAT_TITLE
146static int get_x11_title __ARGS((int));
147static int get_x11_icon __ARGS((int));
148
149static char_u *oldtitle = NULL;
150static int did_set_title = FALSE;
151static char_u *oldicon = NULL;
152static int did_set_icon = FALSE;
153#endif
154
155static void may_core_dump __ARGS((void));
156
Bram Moolenaar205b8862011-09-07 15:04:31 +0200157#ifdef HAVE_UNION_WAIT
158typedef union wait waitstatus;
159#else
160typedef int waitstatus;
161#endif
Bram Moolenaar9f118812011-09-08 23:24:14 +0200162static pid_t wait4pid __ARGS((pid_t, waitstatus *));
Bram Moolenaar205b8862011-09-07 15:04:31 +0200163
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164static int WaitForChar __ARGS((long));
165#if defined(__BEOS__)
166int RealWaitForChar __ARGS((int, long, int *));
167#else
168static int RealWaitForChar __ARGS((int, long, int *));
169#endif
170
171#ifdef FEAT_XCLIPBOARD
172static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000173# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174#endif
175
176static void handle_resize __ARGS((void));
177
178#if defined(SIGWINCH)
179static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
180#endif
181#if defined(SIGINT)
182static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
183#endif
184#if defined(SIGPWR)
185static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
186#endif
187#if defined(SIGALRM) && defined(FEAT_X11) \
188 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
189# define SET_SIG_ALARM
190static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000191/* volatile because it is used in signal handler sig_alarm(). */
192static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193#endif
194static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
195
Bram Moolenaardf177f62005-02-22 08:39:57 +0000196static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197static void set_signals __ARGS((void));
198static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
199#ifndef __EMX__
200static int have_wildcard __ARGS((int, char_u **));
201static int have_dollars __ARGS((int, char_u **));
202#endif
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef __EMX__
205static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
206#endif
207
208#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000209# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210#endif
211
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000212/* volatile because it is used in signal handler sig_winch(). */
213static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214#ifndef __EMX__
215static char_u *extra_shell_arg = NULL;
216static int show_shell_mess = TRUE;
217#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000218/* volatile because it is used in signal handler deathtrap(). */
219static volatile int deadly_signal = 0; /* The signal we caught */
220/* volatile because it is used in signal handler deathtrap(). */
221static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222
223static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
224
225#ifdef USE_XSMP
226typedef struct
227{
228 SmcConn smcconn; /* The SM connection ID */
229 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200230 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231 Bool save_yourself; /* If we're in the middle of a save_yourself */
232 Bool shutdown; /* If we're in shutdown mode */
233} xsmp_config_T;
234
235static xsmp_config_T xsmp;
236#endif
237
238#ifdef SYS_SIGLIST_DECLARED
239/*
240 * I have seen
241 * extern char *_sys_siglist[NSIG];
242 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
243 * that describe the signals. That is nearly what we want here. But
244 * autoconf does only check for sys_siglist (without the underscore), I
245 * do not want to change everything today.... jw.
246 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
247 */
248#endif
249
250static struct signalinfo
251{
252 int sig; /* Signal number, eg. SIGSEGV etc */
253 char *name; /* Signal name (not char_u!). */
254 char deadly; /* Catch as a deadly signal? */
255} signal_info[] =
256{
257#ifdef SIGHUP
258 {SIGHUP, "HUP", TRUE},
259#endif
260#ifdef SIGQUIT
261 {SIGQUIT, "QUIT", TRUE},
262#endif
263#ifdef SIGILL
264 {SIGILL, "ILL", TRUE},
265#endif
266#ifdef SIGTRAP
267 {SIGTRAP, "TRAP", TRUE},
268#endif
269#ifdef SIGABRT
270 {SIGABRT, "ABRT", TRUE},
271#endif
272#ifdef SIGEMT
273 {SIGEMT, "EMT", TRUE},
274#endif
275#ifdef SIGFPE
276 {SIGFPE, "FPE", TRUE},
277#endif
278#ifdef SIGBUS
279 {SIGBUS, "BUS", TRUE},
280#endif
281#ifdef SIGSEGV
282 {SIGSEGV, "SEGV", TRUE},
283#endif
284#ifdef SIGSYS
285 {SIGSYS, "SYS", TRUE},
286#endif
287#ifdef SIGALRM
288 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
289#endif
290#ifdef SIGTERM
291 {SIGTERM, "TERM", TRUE},
292#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100293#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 {SIGVTALRM, "VTALRM", TRUE},
295#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000296#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
297 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
298 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299 {SIGPROF, "PROF", TRUE},
300#endif
301#ifdef SIGXCPU
302 {SIGXCPU, "XCPU", TRUE},
303#endif
304#ifdef SIGXFSZ
305 {SIGXFSZ, "XFSZ", TRUE},
306#endif
307#ifdef SIGUSR1
308 {SIGUSR1, "USR1", TRUE},
309#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000310#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
311 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312 {SIGUSR2, "USR2", TRUE},
313#endif
314#ifdef SIGINT
315 {SIGINT, "INT", FALSE},
316#endif
317#ifdef SIGWINCH
318 {SIGWINCH, "WINCH", FALSE},
319#endif
320#ifdef SIGTSTP
321 {SIGTSTP, "TSTP", FALSE},
322#endif
323#ifdef SIGPIPE
324 {SIGPIPE, "PIPE", FALSE},
325#endif
326 {-1, "Unknown!", FALSE}
327};
328
Bram Moolenaar25724922009-07-14 15:38:41 +0000329 int
330mch_chdir(path)
331 char *path;
332{
333 if (p_verbose >= 5)
334 {
335 verbose_enter();
336 smsg((char_u *)"chdir(%s)", path);
337 verbose_leave();
338 }
339# ifdef VMS
340 return chdir(vms_fixfilename(path));
341# else
342 return chdir(path);
343# endif
344}
345
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000346/*
347 * Write s[len] to the screen.
348 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 void
350mch_write(s, len)
351 char_u *s;
352 int len;
353{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000354 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355 if (p_wd) /* Unix is too fast, slow down a bit more */
356 RealWaitForChar(read_cmd_fd, p_wd, NULL);
357}
358
359/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000360 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361 * Get a characters from the keyboard.
362 * Return the number of characters that are available.
363 * If wtime == 0 do not wait for characters.
364 * If wtime == n wait a short time for characters.
365 * If wtime == -1 wait forever for characters.
366 */
367 int
368mch_inchar(buf, maxlen, wtime, tb_change_cnt)
369 char_u *buf;
370 int maxlen;
371 long wtime; /* don't use "time", MIPS cannot handle it */
372 int tb_change_cnt;
373{
374 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000375
Bram Moolenaar67c53842010-05-22 18:28:27 +0200376#ifdef FEAT_NETBEANS_INTG
377 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200378 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200379#endif
380
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 /* Check if window changed size while we were busy, perhaps the ":set
382 * columns=99" command was used. */
383 while (do_resize)
384 handle_resize();
385
386 if (wtime >= 0)
387 {
388 while (WaitForChar(wtime) == 0) /* no character available */
389 {
390 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000391 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200393#ifdef FEAT_NETBEANS_INTG
394 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200395 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 }
398 }
399 else /* wtime == -1 */
400 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 /*
402 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000403 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 * Also done when interrupted by SIGWINCH.
405 */
406 if (WaitForChar(p_ut) == 0)
407 {
408#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000409 if (trigger_cursorhold() && maxlen >= 3
410 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000412 buf[0] = K_SPECIAL;
413 buf[1] = KS_EXTRA;
414 buf[2] = (int)KE_CURSORHOLD;
415 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000418 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 }
420 }
421
422 for (;;) /* repeat until we got a character */
423 {
424 while (do_resize) /* window changed size */
425 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200426
427#ifdef FEAT_NETBEANS_INTG
428 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200429 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200430#endif
Bram Moolenaar48bae372010-07-29 23:12:15 +0200431#ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200433 * We want to be interrupted by the winch signal
434 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200436 if (WaitForChar(-1L) == 0)
437 {
438 if (do_resize) /* interrupted by SIGWINCH signal */
439 handle_resize();
440 return 0;
441 }
Bram Moolenaar48bae372010-07-29 23:12:15 +0200442#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443
444 /* If input was put directly in typeahead buffer bail out here. */
445 if (typebuf_changed(tb_change_cnt))
446 return 0;
447
448 /*
449 * For some terminals we only get one character at a time.
450 * We want the get all available characters, so we could keep on
451 * trying until none is available
452 * For some other terminals this is quite slow, that's why we don't do
453 * it.
454 */
455 len = read_from_input_buf(buf, (long)maxlen);
456 if (len > 0)
457 {
458#ifdef OS2
459 int i;
460
461 for (i = 0; i < len; i++)
462 if (buf[i] == 0)
463 buf[i] = K_NUL;
464#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 return len;
466 }
467 }
468}
469
470 static void
471handle_resize()
472{
473 do_resize = FALSE;
474 shell_resized();
475}
476
477/*
478 * return non-zero if a character is available
479 */
480 int
481mch_char_avail()
482{
483 return WaitForChar(0L);
484}
485
486#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
487# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000488# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000489# endif
490# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
491# include <sys/sysctl.h>
492# endif
493# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
494# include <sys/sysinfo.h>
495# endif
496
497/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000498 * Return total amount of memory available in Kbyte.
499 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501 long_u
502mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000503 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504{
505# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000506 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507# else
508 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000509 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510
511# ifdef HAVE_SYSCTL
512 int mib[2], physmem;
513 size_t len;
514
515 /* BSD way of getting the amount of RAM available. */
516 mib[0] = CTL_HW;
517 mib[1] = HW_USERMEM;
518 len = sizeof(physmem);
519 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
520 mem = (long_u)physmem;
521# endif
522
523# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
524 if (mem == 0)
525 {
526 struct sysinfo sinfo;
527
528 /* Linux way of getting amount of RAM available */
529 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000530 {
531# ifdef HAVE_SYSINFO_MEM_UNIT
532 /* avoid overflow as much as possible */
533 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
534 {
535 sinfo.mem_unit = sinfo.mem_unit >> 1;
536 --shiftright;
537 }
538 mem = sinfo.totalram * sinfo.mem_unit;
539# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000541# endif
542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543 }
544# endif
545
546# ifdef HAVE_SYSCONF
547 if (mem == 0)
548 {
549 long pagesize, pagecount;
550
551 /* Solaris way of getting amount of RAM available */
552 pagesize = sysconf(_SC_PAGESIZE);
553 pagecount = sysconf(_SC_PHYS_PAGES);
554 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000555 {
556 /* avoid overflow as much as possible */
557 while (shiftright > 0 && (pagesize & 1) == 0)
558 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000559 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000560 --shiftright;
561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000563 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564 }
565# endif
566
567 /* Return the minimum of the physical memory and the user limit, because
568 * using more than the user limit may cause Vim to be terminated. */
569# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
570 {
571 struct rlimit rlp;
572
573 if (getrlimit(RLIMIT_DATA, &rlp) == 0
574 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
575# ifdef RLIM_INFINITY
576 && rlp.rlim_cur != RLIM_INFINITY
577# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000578 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000580 {
581 mem = (long_u)rlp.rlim_cur;
582 shiftright = 10;
583 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 }
585# endif
586
587 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000588 return mem >> shiftright;
589 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590# endif
591}
592#endif
593
594 void
595mch_delay(msec, ignoreinput)
596 long msec;
597 int ignoreinput;
598{
599 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000600#ifdef FEAT_MZSCHEME
601 long total = msec; /* remember original value */
602#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 if (ignoreinput)
605 {
606 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000607 * here. But we don't want QUIT to kill us (CTRL-\ used in a
608 * shell may produce SIGQUIT). */
609 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 old_tmode = curr_tmode;
611 if (curr_tmode == TMODE_RAW)
612 settmode(TMODE_SLEEP);
613
614 /*
615 * Everybody sleeps in a different way...
616 * Prefer nanosleep(), some versions of usleep() can only sleep up to
617 * one second.
618 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000619#ifdef FEAT_MZSCHEME
620 do
621 {
622 /* if total is large enough, wait by portions in p_mzq */
623 if (total > p_mzq)
624 msec = p_mzq;
625 else
626 msec = total;
627 total -= msec;
628#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#ifdef HAVE_NANOSLEEP
630 {
631 struct timespec ts;
632
633 ts.tv_sec = msec / 1000;
634 ts.tv_nsec = (msec % 1000) * 1000000;
635 (void)nanosleep(&ts, NULL);
636 }
637#else
638# ifdef HAVE_USLEEP
639 while (msec >= 1000)
640 {
641 usleep((unsigned int)(999 * 1000));
642 msec -= 999;
643 }
644 usleep((unsigned int)(msec * 1000));
645# else
646# ifndef HAVE_SELECT
647 poll(NULL, 0, (int)msec);
648# else
649# ifdef __EMX__
650 _sleep2(msec);
651# else
652 {
653 struct timeval tv;
654
655 tv.tv_sec = msec / 1000;
656 tv.tv_usec = (msec % 1000) * 1000;
657 /*
658 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
659 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
660 */
661 select(0, NULL, NULL, NULL, &tv);
662 }
663# endif /* __EMX__ */
664# endif /* HAVE_SELECT */
665# endif /* HAVE_NANOSLEEP */
666#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000667#ifdef FEAT_MZSCHEME
668 }
669 while (total > 0);
670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671
672 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000673 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674 }
675 else
676 WaitForChar(msec);
677}
678
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000679#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
681# define HAVE_CHECK_STACK_GROWTH
682/*
683 * Support for checking for an almost-out-of-stack-space situation.
684 */
685
686/*
687 * Return a pointer to an item on the stack. Used to find out if the stack
688 * grows up or down.
689 */
690static void check_stack_growth __ARGS((char *p));
691static int stack_grows_downwards;
692
693/*
694 * Find out if the stack grows upwards or downwards.
695 * "p" points to a variable on the stack of the caller.
696 */
697 static void
698check_stack_growth(p)
699 char *p;
700{
701 int i;
702
703 stack_grows_downwards = (p > (char *)&i);
704}
705#endif
706
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000707#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708static char *stack_limit = NULL;
709
710#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
711# include <pthread.h>
712# include <pthread_np.h>
713#endif
714
715/*
716 * Find out until how var the stack can grow without getting into trouble.
717 * Called when starting up and when switching to the signal stack in
718 * deathtrap().
719 */
720 static void
721get_stack_limit()
722{
723 struct rlimit rlp;
724 int i;
725 long lim;
726
727 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
728 * limit doesn't fit in a long (rlim_cur might be "long long"). */
729 if (getrlimit(RLIMIT_STACK, &rlp) == 0
730 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
731# ifdef RLIM_INFINITY
732 && rlp.rlim_cur != RLIM_INFINITY
733# endif
734 )
735 {
736 lim = (long)rlp.rlim_cur;
737#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
738 {
739 pthread_attr_t attr;
740 size_t size;
741
742 /* On FreeBSD the initial thread always has a fixed stack size, no
743 * matter what the limits are set to. Normally it's 1 Mbyte. */
744 pthread_attr_init(&attr);
745 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
746 {
747 pthread_attr_getstacksize(&attr, &size);
748 if (lim > (long)size)
749 lim = (long)size;
750 }
751 pthread_attr_destroy(&attr);
752 }
753#endif
754 if (stack_grows_downwards)
755 {
756 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
757 if (stack_limit >= (char *)&i)
758 /* overflow, set to 1/16 of current stack position */
759 stack_limit = (char *)((long)&i / 16L);
760 }
761 else
762 {
763 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
764 if (stack_limit <= (char *)&i)
765 stack_limit = NULL; /* overflow */
766 }
767 }
768}
769
770/*
771 * Return FAIL when running out of stack space.
772 * "p" must point to any variable local to the caller that's on the stack.
773 */
774 int
775mch_stackcheck(p)
776 char *p;
777{
778 if (stack_limit != NULL)
779 {
780 if (stack_grows_downwards)
781 {
782 if (p < stack_limit)
783 return FAIL;
784 }
785 else if (p > stack_limit)
786 return FAIL;
787 }
788 return OK;
789}
790#endif
791
792#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
793/*
794 * Support for using the signal stack.
795 * This helps when we run out of stack space, which causes a SIGSEGV. The
796 * signal handler then must run on another stack, since the normal stack is
797 * completely full.
798 */
799
800#ifndef SIGSTKSZ
801# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
802#endif
803
804# ifdef HAVE_SIGALTSTACK
805static stack_t sigstk; /* for sigaltstack() */
806# else
807static struct sigstack sigstk; /* for sigstack() */
808# endif
809
810static void init_signal_stack __ARGS((void));
811static char *signal_stack;
812
813 static void
814init_signal_stack()
815{
816 if (signal_stack != NULL)
817 {
818# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000819# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
820 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
822 * "struct sigaltstack" needs to be declared. */
823 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
824# endif
825
826# ifdef HAVE_SS_BASE
827 sigstk.ss_base = signal_stack;
828# else
829 sigstk.ss_sp = signal_stack;
830# endif
831 sigstk.ss_size = SIGSTKSZ;
832 sigstk.ss_flags = 0;
833 (void)sigaltstack(&sigstk, NULL);
834# else
835 sigstk.ss_sp = signal_stack;
836 if (stack_grows_downwards)
837 sigstk.ss_sp += SIGSTKSZ - 1;
838 sigstk.ss_onstack = 0;
839 (void)sigstack(&sigstk, NULL);
840# endif
841 }
842}
843#endif
844
845/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000846 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 * will barf when the second argument to signal() is ``wrong''.
848 * Let me try it with a few tricky defines from my own osdef.h (jw).
849 */
850#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851 static RETSIGTYPE
852sig_winch SIGDEFARG(sigarg)
853{
854 /* this is not required on all systems, but it doesn't hurt anybody */
855 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
856 do_resize = TRUE;
857 SIGRETURN;
858}
859#endif
860
861#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 static RETSIGTYPE
863catch_sigint SIGDEFARG(sigarg)
864{
865 /* this is not required on all systems, but it doesn't hurt anybody */
866 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
867 got_int = TRUE;
868 SIGRETURN;
869}
870#endif
871
872#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 static RETSIGTYPE
874catch_sigpwr SIGDEFARG(sigarg)
875{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000876 /* this is not required on all systems, but it doesn't hurt anybody */
877 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878 /*
879 * I'm not sure we get the SIGPWR signal when the system is really going
880 * down or when the batteries are almost empty. Just preserve the swap
881 * files and don't exit, that can't do any harm.
882 */
883 ml_sync_all(FALSE, FALSE);
884 SIGRETURN;
885}
886#endif
887
888#ifdef SET_SIG_ALARM
889/*
890 * signal function for alarm().
891 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 static RETSIGTYPE
893sig_alarm SIGDEFARG(sigarg)
894{
895 /* doesn't do anything, just to break a system call */
896 sig_alarm_called = TRUE;
897 SIGRETURN;
898}
899#endif
900
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000901#if (defined(HAVE_SETJMP_H) \
902 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
903 || defined(FEAT_LIBCALL))) \
904 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905/*
906 * A simplistic version of setjmp() that only allows one level of using.
907 * Don't call twice before calling mch_endjmp()!.
908 * Usage:
909 * mch_startjmp();
910 * if (SETJMP(lc_jump_env) != 0)
911 * {
912 * mch_didjmp();
913 * EMSG("crash!");
914 * }
915 * else
916 * {
917 * do_the_work;
918 * mch_endjmp();
919 * }
920 * Note: Can't move SETJMP() here, because a function calling setjmp() must
921 * not return before the saved environment is used.
922 * Returns OK for normal return, FAIL when the protected code caused a
923 * problem and LONGJMP() was used.
924 */
925 void
926mch_startjmp()
927{
928#ifdef SIGHASARG
929 lc_signal = 0;
930#endif
931 lc_active = TRUE;
932}
933
934 void
935mch_endjmp()
936{
937 lc_active = FALSE;
938}
939
940 void
941mch_didjmp()
942{
943# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
944 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
945 * otherwise catching the signal only works once. */
946 init_signal_stack();
947# endif
948}
949#endif
950
951/*
952 * This function handles deadly signals.
953 * It tries to preserve any swap file and exit properly.
954 * (partly from Elvis).
955 */
956 static RETSIGTYPE
957deathtrap SIGDEFARG(sigarg)
958{
959 static int entered = 0; /* count the number of times we got here.
960 Note: when memory has been corrupted
961 this may get an arbitrary value! */
962#ifdef SIGHASARG
963 int i;
964#endif
965
966#if defined(HAVE_SETJMP_H)
967 /*
968 * Catch a crash in protected code.
969 * Restores the environment saved in lc_jump_env, which looks like
970 * SETJMP() returns 1.
971 */
972 if (lc_active)
973 {
974# if defined(SIGHASARG)
975 lc_signal = sigarg;
976# endif
977 lc_active = FALSE; /* don't jump again */
978 LONGJMP(lc_jump_env, 1);
979 /* NOTREACHED */
980 }
981#endif
982
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000983#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000984# ifdef SIGQUIT
985 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
986 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
987 * pressing CTRL-\, but we don't want Vim to exit then. */
988 if (in_mch_delay && sigarg == SIGQUIT)
989 SIGRETURN;
990# endif
991
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000992 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
993 * here. This avoids that a non-reentrant function is interrupted, e.g.,
994 * free(). Calling free() again may then cause a crash. */
995 if (entered == 0
996 && (0
997# ifdef SIGHUP
998 || sigarg == SIGHUP
999# endif
1000# ifdef SIGQUIT
1001 || sigarg == SIGQUIT
1002# endif
1003# ifdef SIGTERM
1004 || sigarg == SIGTERM
1005# endif
1006# ifdef SIGPWR
1007 || sigarg == SIGPWR
1008# endif
1009# ifdef SIGUSR1
1010 || sigarg == SIGUSR1
1011# endif
1012# ifdef SIGUSR2
1013 || sigarg == SIGUSR2
1014# endif
1015 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001016 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001017 SIGRETURN;
1018#endif
1019
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 /* Remember how often we have been called. */
1021 ++entered;
1022
1023#ifdef FEAT_EVAL
1024 /* Set the v:dying variable. */
1025 set_vim_var_nr(VV_DYING, (long)entered);
1026#endif
1027
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001028#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 /* Since we are now using the signal stack, need to reset the stack
1030 * limit. Otherwise using a regexp will fail. */
1031 get_stack_limit();
1032#endif
1033
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001034#if 0
1035 /* This is for opening gdb the moment Vim crashes.
1036 * You need to manually adjust the file name and Vim executable name.
1037 * Suggested by SungHyun Nam. */
1038 {
1039# define VI_GDB_FILE "/tmp/vimgdb"
1040# define VIM_NAME "/usr/bin/vim"
1041 FILE *fp = fopen(VI_GDB_FILE, "w");
1042 if (fp)
1043 {
1044 fprintf(fp,
1045 "file %s\n"
1046 "attach %d\n"
1047 "set height 1000\n"
1048 "bt full\n"
1049 , VIM_NAME, getpid());
1050 fclose(fp);
1051 system("xterm -e gdb -x "VI_GDB_FILE);
1052 unlink(VI_GDB_FILE);
1053 }
1054 }
1055#endif
1056
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057#ifdef SIGHASARG
1058 /* try to find the name of this signal */
1059 for (i = 0; signal_info[i].sig != -1; i++)
1060 if (sigarg == signal_info[i].sig)
1061 break;
1062 deadly_signal = sigarg;
1063#endif
1064
1065 full_screen = FALSE; /* don't write message to the GUI, it might be
1066 * part of the problem... */
1067 /*
1068 * If something goes wrong after entering here, we may get here again.
1069 * When this happens, give a message and try to exit nicely (resetting the
1070 * terminal mode, etc.)
1071 * When this happens twice, just exit, don't even try to give a message,
1072 * stack may be corrupt or something weird.
1073 * When this still happens again (or memory was corrupted in such a way
1074 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1075 */
1076 if (entered >= 3)
1077 {
1078 reset_signals(); /* don't catch any signals anymore */
1079 may_core_dump();
1080 if (entered >= 4)
1081 _exit(8);
1082 exit(7);
1083 }
1084 if (entered == 2)
1085 {
1086 OUT_STR(_("Vim: Double signal, exiting\n"));
1087 out_flush();
1088 getout(1);
1089 }
1090
1091#ifdef SIGHASARG
1092 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
1093 signal_info[i].name);
1094#else
1095 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
1096#endif
1097 preserve_exit(); /* preserve files and exit */
1098
Bram Moolenaar009b2592004-10-24 19:18:58 +00001099#ifdef NBDEBUG
1100 reset_signals();
1101 may_core_dump();
1102 abort();
1103#endif
1104
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 SIGRETURN;
1106}
1107
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001108#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109/*
1110 * On Solaris with multi-threading, suspending might not work immediately.
1111 * Catch the SIGCONT signal, which will be used as an indication whether the
1112 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001113 *
1114 * On Linux, signal is not always handled immediately either.
1115 * See https://bugs.launchpad.net/bugs/291373
1116 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001117 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001119static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1121
1122/*
1123 * signal handler for SIGCONT
1124 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 static RETSIGTYPE
1126sigcont_handler SIGDEFARG(sigarg)
1127{
1128 sigcont_received = TRUE;
1129 SIGRETURN;
1130}
1131#endif
1132
Bram Moolenaar62b42182010-09-21 22:09:37 +02001133# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1134static void loose_clipboard __ARGS((void));
1135
1136/*
1137 * Called when Vim is going to sleep or execute a shell command.
1138 * We can't respond to requests for the X selections. Lose them, otherwise
1139 * other applications will hang. But first copy the text to cut buffer 0.
1140 */
1141 static void
1142loose_clipboard()
1143{
1144 if (clip_star.owned || clip_plus.owned)
1145 {
1146 x11_export_final_selection();
1147 if (clip_star.owned)
1148 clip_lose_selection(&clip_star);
1149 if (clip_plus.owned)
1150 clip_lose_selection(&clip_plus);
1151 if (x11_display != NULL)
1152 XFlush(x11_display);
1153 }
1154}
1155#endif
1156
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157/*
1158 * If the machine has job control, use it to suspend the program,
1159 * otherwise fake it by starting a new shell.
1160 */
1161 void
1162mch_suspend()
1163{
1164 /* BeOS does have SIGTSTP, but it doesn't work. */
1165#if defined(SIGTSTP) && !defined(__BEOS__)
1166 out_flush(); /* needed to make cursor visible on some systems */
1167 settmode(TMODE_COOK);
1168 out_flush(); /* needed to disable mouse on some systems */
1169
1170# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001171 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172# endif
1173
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001174# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 sigcont_received = FALSE;
1176# endif
1177 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001178# if defined(_REENTRANT) && defined(SIGCONT)
1179 /*
1180 * Wait for the SIGCONT signal to be handled. It generally happens
1181 * immediately, but somehow not all the time. Do not call pause()
1182 * because there would be race condition which would hang Vim if
1183 * signal happened in between the test of sigcont_received and the
1184 * call to pause(). If signal is not yet received, call sleep(0)
1185 * to just yield CPU. Signal should then be received. If somehow
1186 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1187 * further if signal is not received after 1+2+3+4 ms (not expected
1188 * to happen).
1189 */
1190 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001191 long wait_time;
1192 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001193 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001194 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001195 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196# endif
1197
1198# ifdef FEAT_TITLE
1199 /*
1200 * Set oldtitle to NULL, so the current title is obtained again.
1201 */
1202 vim_free(oldtitle);
1203 oldtitle = NULL;
1204# endif
1205 settmode(TMODE_RAW);
1206 need_check_timestamps = TRUE;
1207 did_check_timestamps = FALSE;
1208#else
1209 suspend_shell();
1210#endif
1211}
1212
1213 void
1214mch_init()
1215{
1216 Columns = 80;
1217 Rows = 24;
1218
1219 out_flush();
1220 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001221
Bram Moolenaar56718732006-03-15 22:53:57 +00001222#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001223 mac_conv_init();
1224#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001225}
1226
1227 static void
1228set_signals()
1229{
1230#if defined(SIGWINCH)
1231 /*
1232 * WINDOW CHANGE signal is handled with sig_winch().
1233 */
1234 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1235#endif
1236
1237 /*
1238 * We want the STOP signal to work, to make mch_suspend() work.
1239 * For "rvim" the STOP signal is ignored.
1240 */
1241#ifdef SIGTSTP
1242 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1243#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001244#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 signal(SIGCONT, sigcont_handler);
1246#endif
1247
1248 /*
1249 * We want to ignore breaking of PIPEs.
1250 */
1251#ifdef SIGPIPE
1252 signal(SIGPIPE, SIG_IGN);
1253#endif
1254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001256 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257#endif
1258
1259 /*
1260 * Ignore alarm signals (Perl's alarm() generates it).
1261 */
1262#ifdef SIGALRM
1263 signal(SIGALRM, SIG_IGN);
1264#endif
1265
1266 /*
1267 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1268 * work will be lost.
1269 */
1270#ifdef SIGPWR
1271 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1272#endif
1273
1274 /*
1275 * Arrange for other signals to gracefully shutdown Vim.
1276 */
1277 catch_signals(deathtrap, SIG_ERR);
1278
1279#if defined(FEAT_GUI) && defined(SIGHUP)
1280 /*
1281 * When the GUI is running, ignore the hangup signal.
1282 */
1283 if (gui.in_use)
1284 signal(SIGHUP, SIG_IGN);
1285#endif
1286}
1287
Bram Moolenaardf177f62005-02-22 08:39:57 +00001288#if defined(SIGINT) || defined(PROTO)
1289/*
1290 * Catch CTRL-C (only works while in Cooked mode).
1291 */
1292 static void
1293catch_int_signal()
1294{
1295 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1296}
1297#endif
1298
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 void
1300reset_signals()
1301{
1302 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001303#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 /* SIGCONT isn't in the list, because its default action is ignore */
1305 signal(SIGCONT, SIG_DFL);
1306#endif
1307}
1308
1309 static void
1310catch_signals(func_deadly, func_other)
1311 RETSIGTYPE (*func_deadly)();
1312 RETSIGTYPE (*func_other)();
1313{
1314 int i;
1315
1316 for (i = 0; signal_info[i].sig != -1; i++)
1317 if (signal_info[i].deadly)
1318 {
1319#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1320 struct sigaction sa;
1321
1322 /* Setup to use the alternate stack for the signal function. */
1323 sa.sa_handler = func_deadly;
1324 sigemptyset(&sa.sa_mask);
1325# if defined(__linux__) && defined(_REENTRANT)
1326 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1327 * thread handling in combination with using the alternate stack:
1328 * pthread library functions try to use the stack pointer to
1329 * identify the current thread, causing a SEGV signal, which
1330 * recursively calls deathtrap() and hangs. */
1331 sa.sa_flags = 0;
1332# else
1333 sa.sa_flags = SA_ONSTACK;
1334# endif
1335 sigaction(signal_info[i].sig, &sa, NULL);
1336#else
1337# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1338 struct sigvec sv;
1339
1340 /* Setup to use the alternate stack for the signal function. */
1341 sv.sv_handler = func_deadly;
1342 sv.sv_mask = 0;
1343 sv.sv_flags = SV_ONSTACK;
1344 sigvec(signal_info[i].sig, &sv, NULL);
1345# else
1346 signal(signal_info[i].sig, func_deadly);
1347# endif
1348#endif
1349 }
1350 else if (func_other != SIG_ERR)
1351 signal(signal_info[i].sig, func_other);
1352}
1353
1354/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001355 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001356 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1357 * return TRUE
1358 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1359 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001360 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001361 * Returns TRUE when Vim should exit.
1362 */
1363 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001364vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001365 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001366{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001367 static int got_signal = 0;
1368 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001369
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001370 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001371 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001372 case SIGNAL_BLOCK: blocked = TRUE;
1373 break;
1374
1375 case SIGNAL_UNBLOCK: blocked = FALSE;
1376 if (got_signal != 0)
1377 {
1378 kill(getpid(), got_signal);
1379 got_signal = 0;
1380 }
1381 break;
1382
1383 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001384 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001385 got_signal = sig;
1386#ifdef SIGPWR
1387 if (sig != SIGPWR)
1388#endif
1389 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001390 break;
1391 }
1392 return FALSE;
1393}
1394
1395/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396 * Check_win checks whether we have an interactive stdout.
1397 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 int
1399mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001400 int argc UNUSED;
1401 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402{
1403#ifdef OS2
1404 /*
1405 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1406 * name, mostly it's just "vim" and found in the path, which is unusable.
1407 */
1408 if (mch_isFullName(argv[0]))
1409 exe_name = vim_strsave((char_u *)argv[0]);
1410#endif
1411 if (isatty(1))
1412 return OK;
1413 return FAIL;
1414}
1415
1416/*
1417 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1418 */
1419 int
1420mch_input_isatty()
1421{
1422 if (isatty(read_cmd_fd))
1423 return TRUE;
1424 return FALSE;
1425}
1426
1427#ifdef FEAT_X11
1428
1429# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1430 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1431
1432static void xopen_message __ARGS((struct timeval *tvp));
1433
1434/*
1435 * Give a message about the elapsed time for opening the X window.
1436 */
1437 static void
1438xopen_message(tvp)
1439 struct timeval *tvp; /* must contain start time */
1440{
1441 struct timeval end_tv;
1442
1443 /* Compute elapsed time. */
1444 gettimeofday(&end_tv, NULL);
1445 smsg((char_u *)_("Opening the X display took %ld msec"),
1446 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001447 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448}
1449# endif
1450#endif
1451
1452#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1453/*
1454 * A few functions shared by X11 title and clipboard code.
1455 */
1456static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1457static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1458static int x_connect_to_server __ARGS((void));
1459static int test_x11_window __ARGS((Display *dpy));
1460
1461static int got_x_error = FALSE;
1462
1463/*
1464 * X Error handler, otherwise X just exits! (very rude) -- webb
1465 */
1466 static int
1467x_error_handler(dpy, error_event)
1468 Display *dpy;
1469 XErrorEvent *error_event;
1470{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001471 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 STRCAT(IObuff, _("\nVim: Got X error\n"));
1473
1474 /* We cannot print a message and continue, because no X calls are allowed
1475 * here (causes my system to hang). Silently continuing might be an
1476 * alternative... */
1477 preserve_exit(); /* preserve files and exit */
1478
1479 return 0; /* NOTREACHED */
1480}
1481
1482/*
1483 * Another X Error handler, just used to check for errors.
1484 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485 static int
1486x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001487 Display *dpy UNUSED;
1488 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489{
1490 got_x_error = TRUE;
1491 return 0;
1492}
1493
1494#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1495# if defined(HAVE_SETJMP_H)
1496/*
1497 * An X IO Error handler, used to catch error while opening the display.
1498 */
1499static int x_IOerror_check __ARGS((Display *dpy));
1500
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 static int
1502x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001503 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504{
1505 /* This function should not return, it causes exit(). Longjump instead. */
1506 LONGJMP(lc_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001507# ifdef VMS
1508 return 0; /* avoid the compiler complains about missing return value */
1509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510}
1511# endif
1512
1513/*
1514 * An X IO Error handler, used to catch terminal errors.
1515 */
1516static int x_IOerror_handler __ARGS((Display *dpy));
1517
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 static int
1519x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001520 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521{
1522 xterm_dpy = NULL;
1523 x11_window = 0;
1524 x11_display = NULL;
1525 xterm_Shell = (Widget)0;
1526
1527 /* This function should not return, it causes exit(). Longjump instead. */
1528 LONGJMP(x_jump_env, 1);
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001529# ifdef VMS
1530 return 0; /* avoid the compiler complains about missing return value */
1531# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532}
1533#endif
1534
1535/*
1536 * Return TRUE when connection to the X server is desired.
1537 */
1538 static int
1539x_connect_to_server()
1540{
1541 regmatch_T regmatch;
1542
1543#if defined(FEAT_CLIENTSERVER)
1544 if (x_force_connect)
1545 return TRUE;
1546#endif
1547 if (x_no_connect)
1548 return FALSE;
1549
1550 /* Check for a match with "exclude:" from 'clipboard'. */
1551 if (clip_exclude_prog != NULL)
1552 {
1553 regmatch.rm_ic = FALSE; /* Don't ignore case */
1554 regmatch.regprog = clip_exclude_prog;
1555 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1556 return FALSE;
1557 }
1558 return TRUE;
1559}
1560
1561/*
1562 * Test if "dpy" and x11_window are valid by getting the window title.
1563 * I don't actually want it yet, so there may be a simpler call to use, but
1564 * this will cause the error handler x_error_check() to be called if anything
1565 * is wrong, such as the window pointer being invalid (as can happen when the
1566 * user changes his DISPLAY, but not his WINDOWID) -- webb
1567 */
1568 static int
1569test_x11_window(dpy)
1570 Display *dpy;
1571{
1572 int (*old_handler)();
1573 XTextProperty text_prop;
1574
1575 old_handler = XSetErrorHandler(x_error_check);
1576 got_x_error = FALSE;
1577 if (XGetWMName(dpy, x11_window, &text_prop))
1578 XFree((void *)text_prop.value);
1579 XSync(dpy, False);
1580 (void)XSetErrorHandler(old_handler);
1581
1582 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001583 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584
1585 return (got_x_error ? FAIL : OK);
1586}
1587#endif
1588
1589#ifdef FEAT_TITLE
1590
1591#ifdef FEAT_X11
1592
1593static int get_x11_thing __ARGS((int get_title, int test_only));
1594
1595/*
1596 * try to get x11 window and display
1597 *
1598 * return FAIL for failure, OK otherwise
1599 */
1600 static int
1601get_x11_windis()
1602{
1603 char *winid;
1604 static int result = -1;
1605#define XD_NONE 0 /* x11_display not set here */
1606#define XD_HERE 1 /* x11_display opened here */
1607#define XD_GUI 2 /* x11_display used from gui.dpy */
1608#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1609 static int x11_display_from = XD_NONE;
1610 static int did_set_error_handler = FALSE;
1611
1612 if (!did_set_error_handler)
1613 {
1614 /* X just exits if it finds an error otherwise! */
1615 (void)XSetErrorHandler(x_error_handler);
1616 did_set_error_handler = TRUE;
1617 }
1618
Bram Moolenaar9372a112005-12-06 19:59:18 +00001619#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 if (gui.in_use)
1621 {
1622 /*
1623 * If the X11 display was opened here before, for the window where Vim
1624 * was started, close that one now to avoid a memory leak.
1625 */
1626 if (x11_display_from == XD_HERE && x11_display != NULL)
1627 {
1628 XCloseDisplay(x11_display);
1629 x11_display_from = XD_NONE;
1630 }
1631 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1632 {
1633 x11_display_from = XD_GUI;
1634 return OK;
1635 }
1636 x11_display = NULL;
1637 return FAIL;
1638 }
1639 else if (x11_display_from == XD_GUI)
1640 {
1641 /* GUI must have stopped somehow, clear x11_display */
1642 x11_window = 0;
1643 x11_display = NULL;
1644 x11_display_from = XD_NONE;
1645 }
1646#endif
1647
1648 /* When started with the "-X" argument, don't try connecting. */
1649 if (!x_connect_to_server())
1650 return FAIL;
1651
1652 /*
1653 * If WINDOWID not set, should try another method to find out
1654 * what the current window number is. The only code I know for
1655 * this is very complicated.
1656 * We assume that zero is invalid for WINDOWID.
1657 */
1658 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1659 x11_window = (Window)atol(winid);
1660
1661#ifdef FEAT_XCLIPBOARD
1662 if (xterm_dpy != NULL && x11_window != 0)
1663 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001664 /* We may have checked it already, but Gnome terminal can move us to
1665 * another window, so we need to check every time. */
1666 if (x11_display_from != XD_XTERM)
1667 {
1668 /*
1669 * If the X11 display was opened here before, for the window where
1670 * Vim was started, close that one now to avoid a memory leak.
1671 */
1672 if (x11_display_from == XD_HERE && x11_display != NULL)
1673 XCloseDisplay(x11_display);
1674 x11_display = xterm_dpy;
1675 x11_display_from = XD_XTERM;
1676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 if (test_x11_window(x11_display) == FAIL)
1678 {
1679 /* probably bad $WINDOWID */
1680 x11_window = 0;
1681 x11_display = NULL;
1682 x11_display_from = XD_NONE;
1683 return FAIL;
1684 }
1685 return OK;
1686 }
1687#endif
1688
1689 if (x11_window == 0 || x11_display == NULL)
1690 result = -1;
1691
1692 if (result != -1) /* Have already been here and set this */
1693 return result; /* Don't do all these X calls again */
1694
1695 if (x11_window != 0 && x11_display == NULL)
1696 {
1697#ifdef SET_SIG_ALARM
1698 RETSIGTYPE (*sig_save)();
1699#endif
1700#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1701 struct timeval start_tv;
1702
1703 if (p_verbose > 0)
1704 gettimeofday(&start_tv, NULL);
1705#endif
1706
1707#ifdef SET_SIG_ALARM
1708 /*
1709 * Opening the Display may hang if the DISPLAY setting is wrong, or
1710 * the network connection is bad. Set an alarm timer to get out.
1711 */
1712 sig_alarm_called = FALSE;
1713 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1714 (RETSIGTYPE (*)())sig_alarm);
1715 alarm(2);
1716#endif
1717 x11_display = XOpenDisplay(NULL);
1718
1719#ifdef SET_SIG_ALARM
1720 alarm(0);
1721 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1722 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001723 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724#endif
1725 if (x11_display != NULL)
1726 {
1727# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1728 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001729 {
1730 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001732 verbose_leave();
1733 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734# endif
1735 if (test_x11_window(x11_display) == FAIL)
1736 {
1737 /* Maybe window id is bad */
1738 x11_window = 0;
1739 XCloseDisplay(x11_display);
1740 x11_display = NULL;
1741 }
1742 else
1743 x11_display_from = XD_HERE;
1744 }
1745 }
1746 if (x11_window == 0 || x11_display == NULL)
1747 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001748
1749# ifdef FEAT_EVAL
1750 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1751# endif
1752
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 return (result = OK);
1754}
1755
1756/*
1757 * Determine original x11 Window Title
1758 */
1759 static int
1760get_x11_title(test_only)
1761 int test_only;
1762{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001763 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764}
1765
1766/*
1767 * Determine original x11 Window icon
1768 */
1769 static int
1770get_x11_icon(test_only)
1771 int test_only;
1772{
1773 int retval = FALSE;
1774
1775 retval = get_x11_thing(FALSE, test_only);
1776
1777 /* could not get old icon, use terminal name */
1778 if (oldicon == NULL && !test_only)
1779 {
1780 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001781 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001783 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 }
1785
1786 return retval;
1787}
1788
1789 static int
1790get_x11_thing(get_title, test_only)
1791 int get_title; /* get title string */
1792 int test_only;
1793{
1794 XTextProperty text_prop;
1795 int retval = FALSE;
1796 Status status;
1797
1798 if (get_x11_windis() == OK)
1799 {
1800 /* Get window/icon name if any */
1801 if (get_title)
1802 status = XGetWMName(x11_display, x11_window, &text_prop);
1803 else
1804 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1805
1806 /*
1807 * If terminal is xterm, then x11_window may be a child window of the
1808 * outer xterm window that actually contains the window/icon name, so
1809 * keep traversing up the tree until a window with a title/icon is
1810 * found.
1811 */
1812 /* Previously this was only done for xterm and alikes. I don't see a
1813 * reason why it would fail for other terminal emulators.
1814 * if (term_is_xterm) */
1815 {
1816 Window root;
1817 Window parent;
1818 Window win = x11_window;
1819 Window *children;
1820 unsigned int num_children;
1821
1822 while (!status || text_prop.value == NULL)
1823 {
1824 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1825 &num_children))
1826 break;
1827 if (children)
1828 XFree((void *)children);
1829 if (parent == root || parent == 0)
1830 break;
1831
1832 win = parent;
1833 if (get_title)
1834 status = XGetWMName(x11_display, win, &text_prop);
1835 else
1836 status = XGetWMIconName(x11_display, win, &text_prop);
1837 }
1838 }
1839 if (status && text_prop.value != NULL)
1840 {
1841 retval = TRUE;
1842 if (!test_only)
1843 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001844#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1845 if (text_prop.encoding == XA_STRING
1846# ifdef FEAT_MBYTE
1847 && !has_mbyte
1848# endif
1849 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 {
1851#endif
1852 if (get_title)
1853 oldtitle = vim_strsave((char_u *)text_prop.value);
1854 else
1855 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001856#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 }
1858 else
1859 {
1860 char **cl;
1861 Status transform_status;
1862 int n = 0;
1863
1864 transform_status = XmbTextPropertyToTextList(x11_display,
1865 &text_prop,
1866 &cl, &n);
1867 if (transform_status >= Success && n > 0 && cl[0])
1868 {
1869 if (get_title)
1870 oldtitle = vim_strsave((char_u *) cl[0]);
1871 else
1872 oldicon = vim_strsave((char_u *) cl[0]);
1873 XFreeStringList(cl);
1874 }
1875 else
1876 {
1877 if (get_title)
1878 oldtitle = vim_strsave((char_u *)text_prop.value);
1879 else
1880 oldicon = vim_strsave((char_u *)text_prop.value);
1881 }
1882 }
1883#endif
1884 }
1885 XFree((void *)text_prop.value);
1886 }
1887 }
1888 return retval;
1889}
1890
1891/* Are Xutf8 functions available? Avoid error from old compilers. */
1892#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1893# if X_HAVE_UTF8_STRING
1894# define USE_UTF8_STRING
1895# endif
1896#endif
1897
1898/*
1899 * Set x11 Window Title
1900 *
1901 * get_x11_windis() must be called before this and have returned OK
1902 */
1903 static void
1904set_x11_title(title)
1905 char_u *title;
1906{
1907 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1908 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1909 * supported everywhere and STRING doesn't work for multi-byte titles.
1910 */
1911#ifdef USE_UTF8_STRING
1912 if (enc_utf8)
1913 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1914 NULL, NULL, 0, NULL, NULL, NULL);
1915 else
1916#endif
1917 {
1918#if XtSpecificationRelease >= 4
1919# ifdef FEAT_XFONTSET
1920 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1921 NULL, NULL, 0, NULL, NULL, NULL);
1922# else
1923 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001924 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925
1926 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001927 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 XSetWMProperties(x11_display, x11_window, &text_prop,
1929 NULL, NULL, 0, NULL, NULL, NULL);
1930# endif
1931#else
1932 XStoreName(x11_display, x11_window, (char *)title);
1933#endif
1934 }
1935 XFlush(x11_display);
1936}
1937
1938/*
1939 * Set x11 Window icon
1940 *
1941 * get_x11_windis() must be called before this and have returned OK
1942 */
1943 static void
1944set_x11_icon(icon)
1945 char_u *icon;
1946{
1947 /* See above for comments about using X*SetWMProperties(). */
1948#ifdef USE_UTF8_STRING
1949 if (enc_utf8)
1950 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1951 NULL, 0, NULL, NULL, NULL);
1952 else
1953#endif
1954 {
1955#if XtSpecificationRelease >= 4
1956# ifdef FEAT_XFONTSET
1957 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1958 NULL, 0, NULL, NULL, NULL);
1959# else
1960 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001961 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001963 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1965 NULL, 0, NULL, NULL, NULL);
1966# endif
1967#else
1968 XSetIconName(x11_display, x11_window, (char *)icon);
1969#endif
1970 }
1971 XFlush(x11_display);
1972}
1973
1974#else /* FEAT_X11 */
1975
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 static int
1977get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001978 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979{
1980 return FALSE;
1981}
1982
1983 static int
1984get_x11_icon(test_only)
1985 int test_only;
1986{
1987 if (!test_only)
1988 {
1989 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001990 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001992 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 }
1994 return FALSE;
1995}
1996
1997#endif /* FEAT_X11 */
1998
1999 int
2000mch_can_restore_title()
2001{
2002 return get_x11_title(TRUE);
2003}
2004
2005 int
2006mch_can_restore_icon()
2007{
2008 return get_x11_icon(TRUE);
2009}
2010
2011/*
2012 * Set the window title and icon.
2013 */
2014 void
2015mch_settitle(title, icon)
2016 char_u *title;
2017 char_u *icon;
2018{
2019 int type = 0;
2020 static int recursive = 0;
2021
2022 if (T_NAME == NULL) /* no terminal name (yet) */
2023 return;
2024 if (title == NULL && icon == NULL) /* nothing to do */
2025 return;
2026
2027 /* When one of the X11 functions causes a deadly signal, we get here again
2028 * recursively. Avoid hanging then (something is probably locked). */
2029 if (recursive)
2030 return;
2031 ++recursive;
2032
2033 /*
2034 * if the window ID and the display is known, we may use X11 calls
2035 */
2036#ifdef FEAT_X11
2037 if (get_x11_windis() == OK)
2038 type = 1;
2039#else
2040# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2041 if (gui.in_use)
2042 type = 1;
2043# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044#endif
2045
2046 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002047 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 * than x11 calls, because the x11 calls don't always work
2049 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 if ((type || *T_TS != NUL) && title != NULL)
2051 {
2052 if (oldtitle == NULL
2053#ifdef FEAT_GUI
2054 && !gui.in_use
2055#endif
2056 ) /* first call but not in GUI, save title */
2057 (void)get_x11_title(FALSE);
2058
2059 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2060 term_settitle(title);
2061#ifdef FEAT_X11
2062 else
2063# ifdef FEAT_GUI_GTK
2064 if (!gui.in_use) /* don't do this if GTK+ is running */
2065# endif
2066 set_x11_title(title); /* x11 */
2067#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002068#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2070 else
2071 gui_mch_settitle(title, icon);
2072#endif
2073 did_set_title = TRUE;
2074 }
2075
2076 if ((type || *T_CIS != NUL) && icon != NULL)
2077 {
2078 if (oldicon == NULL
2079#ifdef FEAT_GUI
2080 && !gui.in_use
2081#endif
2082 ) /* first call, save icon */
2083 get_x11_icon(FALSE);
2084
2085 if (*T_CIS != NUL)
2086 {
2087 out_str(T_CIS); /* set icon start */
2088 out_str_nf(icon);
2089 out_str(T_CIE); /* set icon end */
2090 out_flush();
2091 }
2092#ifdef FEAT_X11
2093 else
2094# ifdef FEAT_GUI_GTK
2095 if (!gui.in_use) /* don't do this if GTK+ is running */
2096# endif
2097 set_x11_icon(icon); /* x11 */
2098#endif
2099 did_set_icon = TRUE;
2100 }
2101 --recursive;
2102}
2103
2104/*
2105 * Restore the window/icon title.
2106 * "which" is one of:
2107 * 1 only restore title
2108 * 2 only restore icon
2109 * 3 restore title and icon
2110 */
2111 void
2112mch_restore_title(which)
2113 int which;
2114{
2115 /* only restore the title or icon when it has been set */
2116 mch_settitle(((which & 1) && did_set_title) ?
2117 (oldtitle ? oldtitle : p_titleold) : NULL,
2118 ((which & 2) && did_set_icon) ? oldicon : NULL);
2119}
2120
2121#endif /* FEAT_TITLE */
2122
2123/*
2124 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002125 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 */
2127 int
2128vim_is_xterm(name)
2129 char_u *name;
2130{
2131 if (name == NULL)
2132 return FALSE;
2133 return (STRNICMP(name, "xterm", 5) == 0
2134 || STRNICMP(name, "nxterm", 6) == 0
2135 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002136 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 || STRNICMP(name, "rxvt", 4) == 0
2138 || STRCMP(name, "builtin_xterm") == 0);
2139}
2140
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002141#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2142/*
2143 * Return TRUE if "name" appears to be that of a terminal
2144 * known to support the xterm-style mouse protocol.
2145 * Relies on term_is_xterm having been set to its correct value.
2146 */
2147 int
2148use_xterm_like_mouse(name)
2149 char_u *name;
2150{
2151 return (name != NULL
2152 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2153}
2154#endif
2155
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2157/*
2158 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2159 * Return 1 for "xterm".
2160 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002161 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002162 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163 */
2164 int
2165use_xterm_mouse()
2166{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002167 if (ttym_flags == TTYM_SGR)
2168 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002169 if (ttym_flags == TTYM_URXVT)
2170 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 if (ttym_flags == TTYM_XTERM2)
2172 return 2;
2173 if (ttym_flags == TTYM_XTERM)
2174 return 1;
2175 return 0;
2176}
2177#endif
2178
2179 int
2180vim_is_iris(name)
2181 char_u *name;
2182{
2183 if (name == NULL)
2184 return FALSE;
2185 return (STRNICMP(name, "iris-ansi", 9) == 0
2186 || STRCMP(name, "builtin_iris-ansi") == 0);
2187}
2188
2189 int
2190vim_is_vt300(name)
2191 char_u *name;
2192{
2193 if (name == NULL)
2194 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002195 /* catch VT100 - VT5xx */
2196 return ((STRNICMP(name, "vt", 2) == 0
2197 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 || STRCMP(name, "builtin_vt320") == 0);
2199}
2200
2201/*
2202 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2203 * This should include all windowed terminal emulators.
2204 */
2205 int
2206vim_is_fastterm(name)
2207 char_u *name;
2208{
2209 if (name == NULL)
2210 return FALSE;
2211 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2212 return TRUE;
2213 return ( STRNICMP(name, "hpterm", 6) == 0
2214 || STRNICMP(name, "sun-cmd", 7) == 0
2215 || STRNICMP(name, "screen", 6) == 0
2216 || STRNICMP(name, "dtterm", 6) == 0);
2217}
2218
2219/*
2220 * Insert user name in s[len].
2221 * Return OK if a name found.
2222 */
2223 int
2224mch_get_user_name(s, len)
2225 char_u *s;
2226 int len;
2227{
2228#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002229 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 return OK;
2231#else
2232 return mch_get_uname(getuid(), s, len);
2233#endif
2234}
2235
2236/*
2237 * Insert user name for "uid" in s[len].
2238 * Return OK if a name found.
2239 */
2240 int
2241mch_get_uname(uid, s, len)
2242 uid_t uid;
2243 char_u *s;
2244 int len;
2245{
2246#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2247 struct passwd *pw;
2248
2249 if ((pw = getpwuid(uid)) != NULL
2250 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2251 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002252 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 return OK;
2254 }
2255#endif
2256 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2257 return FAIL; /* a number is not a name */
2258}
2259
2260/*
2261 * Insert host name is s[len].
2262 */
2263
2264#ifdef HAVE_SYS_UTSNAME_H
2265 void
2266mch_get_host_name(s, len)
2267 char_u *s;
2268 int len;
2269{
2270 struct utsname vutsname;
2271
2272 if (uname(&vutsname) < 0)
2273 *s = NUL;
2274 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002275 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276}
2277#else /* HAVE_SYS_UTSNAME_H */
2278
2279# ifdef HAVE_SYS_SYSTEMINFO_H
2280# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2281# endif
2282
2283 void
2284mch_get_host_name(s, len)
2285 char_u *s;
2286 int len;
2287{
2288# ifdef VAXC
2289 vaxc$gethostname((char *)s, len);
2290# else
2291 gethostname((char *)s, len);
2292# endif
2293 s[len - 1] = NUL; /* make sure it's terminated */
2294}
2295#endif /* HAVE_SYS_UTSNAME_H */
2296
2297/*
2298 * return process ID
2299 */
2300 long
2301mch_get_pid()
2302{
2303 return (long)getpid();
2304}
2305
2306#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2307static char *strerror __ARGS((int));
2308
2309 static char *
2310strerror(err)
2311 int err;
2312{
2313 extern int sys_nerr;
2314 extern char *sys_errlist[];
2315 static char er[20];
2316
2317 if (err > 0 && err < sys_nerr)
2318 return (sys_errlist[err]);
2319 sprintf(er, "Error %d", err);
2320 return er;
2321}
2322#endif
2323
2324/*
2325 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2326 * Return OK for success, FAIL for failure.
2327 */
2328 int
2329mch_dirname(buf, len)
2330 char_u *buf;
2331 int len;
2332{
2333#if defined(USE_GETCWD)
2334 if (getcwd((char *)buf, len) == NULL)
2335 {
2336 STRCPY(buf, strerror(errno));
2337 return FAIL;
2338 }
2339 return OK;
2340#else
2341 return (getwd((char *)buf) != NULL ? OK : FAIL);
2342#endif
2343}
2344
2345#if defined(OS2) || defined(PROTO)
2346/*
2347 * Replace all slashes by backslashes.
2348 * When 'shellslash' set do it the other way around.
2349 */
2350 void
2351slash_adjust(p)
2352 char_u *p;
2353{
2354 while (*p)
2355 {
2356 if (*p == psepcN)
2357 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002358 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 }
2360}
2361#endif
2362
2363/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002364 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 *
2366 * return FAIL for failure, OK for success
2367 */
2368 int
2369mch_FullName(fname, buf, len, force)
2370 char_u *fname, *buf;
2371 int len;
2372 int force; /* also expand when already absolute path */
2373{
2374 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002375#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002377#endif
2378#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 int fd = -1;
2380 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002381#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 char_u olddir[MAXPATHL];
2383 char_u *p;
2384 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002385#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002386 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2387 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002388#endif
2389
Bram Moolenaar38323e42007-03-06 19:22:53 +00002390#ifdef VMS
2391 fname = vms_fixfilename(fname);
2392#endif
2393
Bram Moolenaara2442432007-04-26 14:26:37 +00002394#ifdef __CYGWIN__
2395 /*
2396 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2397 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002398# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2399 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2400# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002401 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002402# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002403 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002404#endif
2405
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 /* expand it if forced or not an absolute path */
2407 if (force || !mch_isFullName(fname))
2408 {
2409 /*
2410 * If the file name has a path, change to that directory for a moment,
2411 * and then do the getwd() (and get back to where we were).
2412 * This will get the correct path name with "../" things.
2413 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002414#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 only_drive = 0;
2416 if (((p = vim_strrchr(fname, '/')) != NULL)
2417 || ((p = vim_strrchr(fname, '\\')) != NULL)
2418 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002419#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002421#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002423#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 /*
2425 * Use fchdir() if possible, it's said to be faster and more
2426 * reliable. But on SunOS 4 it might not work. Check this by
2427 * doing a fchdir() right now.
2428 */
2429 if (!dont_fchdir)
2430 {
2431 fd = open(".", O_RDONLY | O_EXTRA, 0);
2432 if (fd >= 0 && fchdir(fd) < 0)
2433 {
2434 close(fd);
2435 fd = -1;
2436 dont_fchdir = TRUE; /* don't try again */
2437 }
2438 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002439#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440
2441 /* Only change directory when we are sure we can return to where
2442 * we are now. After doing "su" chdir(".") might not work. */
2443 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002444#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002446#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 (mch_dirname(olddir, MAXPATHL) == FAIL
2448 || mch_chdir((char *)olddir) != 0))
2449 {
2450 p = NULL; /* can't get current dir: don't chdir */
2451 retval = FAIL;
2452 }
2453 else
2454 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002455#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 /*
2457 * compensate for case where ':' from "D:" was the only
2458 * path separator detected in the file name; the _next_
2459 * character has to be removed, and then restored later.
2460 */
2461 if (only_drive)
2462 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 /* The directory is copied into buf[], to be able to remove
2465 * the file name without changing it (could be a string in
2466 * read-only memory) */
2467 if (p - fname >= len)
2468 retval = FAIL;
2469 else
2470 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002471 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 if (mch_chdir((char *)buf))
2473 retval = FAIL;
2474 else
2475 fname = p + 1;
2476 *buf = NUL;
2477 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002478#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 if (only_drive)
2480 {
2481 p--;
2482 if (retval != FAIL)
2483 fname--;
2484 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 }
2487 }
2488 if (mch_dirname(buf, len) == FAIL)
2489 {
2490 retval = FAIL;
2491 *buf = NUL;
2492 }
2493 if (p != NULL)
2494 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002495#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 if (fd >= 0)
2497 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002498 if (p_verbose >= 5)
2499 {
2500 verbose_enter();
2501 MSG("fchdir() to previous dir");
2502 verbose_leave();
2503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 l = fchdir(fd);
2505 close(fd);
2506 }
2507 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002508#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 l = mch_chdir((char *)olddir);
2510 if (l != 0)
2511 EMSG(_(e_prev_dir));
2512 }
2513
2514 l = STRLEN(buf);
2515 if (l >= len)
2516 retval = FAIL;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002517#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 else
2519 {
2520 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2521 && STRCMP(fname, ".") != 0)
2522 STRCAT(buf, "/");
2523 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002524#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002526
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002528 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 return FAIL;
2530
2531 /* Do not append ".", "/dir/." is equal to "/dir". */
2532 if (STRCMP(fname, ".") != 0)
2533 STRCAT(buf, fname);
2534
2535 return OK;
2536}
2537
2538/*
2539 * Return TRUE if "fname" does not depend on the current directory.
2540 */
2541 int
2542mch_isFullName(fname)
2543 char_u *fname;
2544{
2545#ifdef __EMX__
2546 return _fnisabs(fname);
2547#else
2548# ifdef VMS
2549 return ( fname[0] == '/' || fname[0] == '.' ||
2550 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2551 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2552 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2553# else
2554 return (*fname == '/' || *fname == '~');
2555# endif
2556#endif
2557}
2558
Bram Moolenaar24552be2005-12-10 20:17:30 +00002559#if defined(USE_FNAME_CASE) || defined(PROTO)
2560/*
2561 * Set the case of the file name, if it already exists. This will cause the
2562 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002563 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002564 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002565 void
2566fname_case(name, len)
2567 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002568 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002569{
2570 struct stat st;
2571 char_u *slash, *tail;
2572 DIR *dirp;
2573 struct dirent *dp;
2574
2575 if (lstat((char *)name, &st) >= 0)
2576 {
2577 /* Open the directory where the file is located. */
2578 slash = vim_strrchr(name, '/');
2579 if (slash == NULL)
2580 {
2581 dirp = opendir(".");
2582 tail = name;
2583 }
2584 else
2585 {
2586 *slash = NUL;
2587 dirp = opendir((char *)name);
2588 *slash = '/';
2589 tail = slash + 1;
2590 }
2591
2592 if (dirp != NULL)
2593 {
2594 while ((dp = readdir(dirp)) != NULL)
2595 {
2596 /* Only accept names that differ in case and are the same byte
2597 * length. TODO: accept different length name. */
2598 if (STRICMP(tail, dp->d_name) == 0
2599 && STRLEN(tail) == STRLEN(dp->d_name))
2600 {
2601 char_u newname[MAXPATHL + 1];
2602 struct stat st2;
2603
2604 /* Verify the inode is equal. */
2605 vim_strncpy(newname, name, MAXPATHL);
2606 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2607 MAXPATHL - (tail - name));
2608 if (lstat((char *)newname, &st2) >= 0
2609 && st.st_ino == st2.st_ino
2610 && st.st_dev == st2.st_dev)
2611 {
2612 STRCPY(tail, dp->d_name);
2613 break;
2614 }
2615 }
2616 }
2617
2618 closedir(dirp);
2619 }
2620 }
2621}
2622#endif
2623
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624/*
2625 * Get file permissions for 'name'.
2626 * Returns -1 when it doesn't exist.
2627 */
2628 long
2629mch_getperm(name)
2630 char_u *name;
2631{
2632 struct stat statb;
2633
2634 /* Keep the #ifdef outside of stat(), it may be a macro. */
2635#ifdef VMS
2636 if (stat((char *)vms_fixfilename(name), &statb))
2637#else
2638 if (stat((char *)name, &statb))
2639#endif
2640 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002641#ifdef __INTERIX
2642 /* The top bit makes the value negative, which means the file doesn't
2643 * exist. Remove the bit, we don't use it. */
2644 return statb.st_mode & ~S_ADDACE;
2645#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002647#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648}
2649
2650/*
2651 * set file permission for 'name' to 'perm'
2652 *
2653 * return FAIL for failure, OK otherwise
2654 */
2655 int
2656mch_setperm(name, perm)
2657 char_u *name;
2658 long perm;
2659{
2660 return (chmod((char *)
2661#ifdef VMS
2662 vms_fixfilename(name),
2663#else
2664 name,
2665#endif
2666 (mode_t)perm) == 0 ? OK : FAIL);
2667}
2668
2669#if defined(HAVE_ACL) || defined(PROTO)
2670# ifdef HAVE_SYS_ACL_H
2671# include <sys/acl.h>
2672# endif
2673# ifdef HAVE_SYS_ACCESS_H
2674# include <sys/access.h>
2675# endif
2676
2677# ifdef HAVE_SOLARIS_ACL
2678typedef struct vim_acl_solaris_T {
2679 int acl_cnt;
2680 aclent_t *acl_entry;
2681} vim_acl_solaris_T;
2682# endif
2683
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002684#if defined(HAVE_SELINUX) || defined(PROTO)
2685/*
2686 * Copy security info from "from_file" to "to_file".
2687 */
2688 void
2689mch_copy_sec(from_file, to_file)
2690 char_u *from_file;
2691 char_u *to_file;
2692{
2693 if (from_file == NULL)
2694 return;
2695
2696 if (selinux_enabled == -1)
2697 selinux_enabled = is_selinux_enabled();
2698
2699 if (selinux_enabled > 0)
2700 {
2701 security_context_t from_context = NULL;
2702 security_context_t to_context = NULL;
2703
2704 if (getfilecon((char *)from_file, &from_context) < 0)
2705 {
2706 /* If the filesystem doesn't support extended attributes,
2707 the original had no special security context and the
2708 target cannot have one either. */
2709 if (errno == EOPNOTSUPP)
2710 return;
2711
2712 MSG_PUTS(_("\nCould not get security context for "));
2713 msg_outtrans(from_file);
2714 msg_putchar('\n');
2715 return;
2716 }
2717 if (getfilecon((char *)to_file, &to_context) < 0)
2718 {
2719 MSG_PUTS(_("\nCould not get security context for "));
2720 msg_outtrans(to_file);
2721 msg_putchar('\n');
2722 freecon (from_context);
2723 return ;
2724 }
2725 if (strcmp(from_context, to_context) != 0)
2726 {
2727 if (setfilecon((char *)to_file, from_context) < 0)
2728 {
2729 MSG_PUTS(_("\nCould not set security context for "));
2730 msg_outtrans(to_file);
2731 msg_putchar('\n');
2732 }
2733 }
2734 freecon(to_context);
2735 freecon(from_context);
2736 }
2737}
2738#endif /* HAVE_SELINUX */
2739
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740/*
2741 * Return a pointer to the ACL of file "fname" in allocated memory.
2742 * Return NULL if the ACL is not available for whatever reason.
2743 */
2744 vim_acl_T
2745mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002746 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747{
2748 vim_acl_T ret = NULL;
2749#ifdef HAVE_POSIX_ACL
2750 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2751#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002752#ifdef HAVE_SOLARIS_ZFS_ACL
2753 acl_t *aclent;
2754
2755 if (acl_get((char *)fname, 0, &aclent) < 0)
2756 return NULL;
2757 ret = (vim_acl_T)aclent;
2758#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759#ifdef HAVE_SOLARIS_ACL
2760 vim_acl_solaris_T *aclent;
2761
2762 aclent = malloc(sizeof(vim_acl_solaris_T));
2763 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2764 {
2765 free(aclent);
2766 return NULL;
2767 }
2768 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2769 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2770 {
2771 free(aclent->acl_entry);
2772 free(aclent);
2773 return NULL;
2774 }
2775 ret = (vim_acl_T)aclent;
2776#else
2777#if defined(HAVE_AIX_ACL)
2778 int aclsize;
2779 struct acl *aclent;
2780
2781 aclsize = sizeof(struct acl);
2782 aclent = malloc(aclsize);
2783 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2784 {
2785 if (errno == ENOSPC)
2786 {
2787 aclsize = aclent->acl_len;
2788 aclent = realloc(aclent, aclsize);
2789 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2790 {
2791 free(aclent);
2792 return NULL;
2793 }
2794 }
2795 else
2796 {
2797 free(aclent);
2798 return NULL;
2799 }
2800 }
2801 ret = (vim_acl_T)aclent;
2802#endif /* HAVE_AIX_ACL */
2803#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002804#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805#endif /* HAVE_POSIX_ACL */
2806 return ret;
2807}
2808
2809/*
2810 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2811 */
2812 void
2813mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002814 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 vim_acl_T aclent;
2816{
2817 if (aclent == NULL)
2818 return;
2819#ifdef HAVE_POSIX_ACL
2820 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2821#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002822#ifdef HAVE_SOLARIS_ZFS_ACL
2823 acl_set((char *)fname, (acl_t *)aclent);
2824#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825#ifdef HAVE_SOLARIS_ACL
2826 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2827 ((vim_acl_solaris_T *)aclent)->acl_entry);
2828#else
2829#ifdef HAVE_AIX_ACL
2830 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2831#endif /* HAVE_AIX_ACL */
2832#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002833#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834#endif /* HAVE_POSIX_ACL */
2835}
2836
2837 void
2838mch_free_acl(aclent)
2839 vim_acl_T aclent;
2840{
2841 if (aclent == NULL)
2842 return;
2843#ifdef HAVE_POSIX_ACL
2844 acl_free((acl_t)aclent);
2845#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002846#ifdef HAVE_SOLARIS_ZFS_ACL
2847 acl_free((acl_t *)aclent);
2848#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849#ifdef HAVE_SOLARIS_ACL
2850 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2851 free(aclent);
2852#else
2853#ifdef HAVE_AIX_ACL
2854 free(aclent);
2855#endif /* HAVE_AIX_ACL */
2856#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002857#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858#endif /* HAVE_POSIX_ACL */
2859}
2860#endif
2861
2862/*
2863 * Set hidden flag for "name".
2864 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 void
2866mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002867 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868{
2869 /* can't hide a file */
2870}
2871
2872/*
2873 * return TRUE if "name" is a directory
2874 * return FALSE if "name" is not a directory
2875 * return FALSE for error
2876 */
2877 int
2878mch_isdir(name)
2879 char_u *name;
2880{
2881 struct stat statb;
2882
2883 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2884 return FALSE;
2885 if (stat((char *)name, &statb))
2886 return FALSE;
2887#ifdef _POSIX_SOURCE
2888 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2889#else
2890 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2891#endif
2892}
2893
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894static int executable_file __ARGS((char_u *name));
2895
2896/*
2897 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2898 */
2899 static int
2900executable_file(name)
2901 char_u *name;
2902{
2903 struct stat st;
2904
2905 if (stat((char *)name, &st))
2906 return 0;
2907 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2908}
2909
2910/*
2911 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2912 * Return -1 if unknown.
2913 */
2914 int
2915mch_can_exe(name)
2916 char_u *name;
2917{
2918 char_u *buf;
2919 char_u *p, *e;
2920 int retval;
2921
2922 /* If it's an absolute or relative path don't need to use $PATH. */
2923 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2924 || (name[1] == '.' && name[2] == '/'))))
2925 return executable_file(name);
2926
2927 p = (char_u *)getenv("PATH");
2928 if (p == NULL || *p == NUL)
2929 return -1;
2930 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2931 if (buf == NULL)
2932 return -1;
2933
2934 /*
2935 * Walk through all entries in $PATH to check if "name" exists there and
2936 * is an executable file.
2937 */
2938 for (;;)
2939 {
2940 e = (char_u *)strchr((char *)p, ':');
2941 if (e == NULL)
2942 e = p + STRLEN(p);
2943 if (e - p <= 1) /* empty entry means current dir */
2944 STRCPY(buf, "./");
2945 else
2946 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002947 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 add_pathsep(buf);
2949 }
2950 STRCAT(buf, name);
2951 retval = executable_file(buf);
2952 if (retval == 1)
2953 break;
2954
2955 if (*e != ':')
2956 break;
2957 p = e + 1;
2958 }
2959
2960 vim_free(buf);
2961 return retval;
2962}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963
2964/*
2965 * Check what "name" is:
2966 * NODE_NORMAL: file or directory (or doesn't exist)
2967 * NODE_WRITABLE: writable device, socket, fifo, etc.
2968 * NODE_OTHER: non-writable things
2969 */
2970 int
2971mch_nodetype(name)
2972 char_u *name;
2973{
2974 struct stat st;
2975
2976 if (stat((char *)name, &st))
2977 return NODE_NORMAL;
2978 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2979 return NODE_NORMAL;
2980#ifndef OS2
2981 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2982 return NODE_OTHER;
2983#endif
2984 /* Everything else is writable? */
2985 return NODE_WRITABLE;
2986}
2987
2988 void
2989mch_early_init()
2990{
2991#ifdef HAVE_CHECK_STACK_GROWTH
2992 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 check_stack_growth((char *)&i);
2995
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002996# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997 get_stack_limit();
2998# endif
2999
3000#endif
3001
3002 /*
3003 * Setup an alternative stack for signals. Helps to catch signals when
3004 * running out of stack space.
3005 * Use of sigaltstack() is preferred, it's more portable.
3006 * Ignore any errors.
3007 */
3008#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003009 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 init_signal_stack();
3011#endif
3012}
3013
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003014#if defined(EXITFREE) || defined(PROTO)
3015 void
3016mch_free_mem()
3017{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003018# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3019 if (clip_star.owned)
3020 clip_lose_selection(&clip_star);
3021 if (clip_plus.owned)
3022 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003023# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003024# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003025 if (xterm_Shell != (Widget)0)
3026 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003027# ifndef LESSTIF_VERSION
3028 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003029 if (xterm_dpy != NULL)
3030 XtCloseDisplay(xterm_dpy);
3031 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003032 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003033 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003034# ifdef FEAT_X11
3035 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3036# endif
3037 }
3038# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003039# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003040# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003041 if (x11_display != NULL
3042# ifdef FEAT_XCLIPBOARD
3043 && x11_display != xterm_dpy
3044# endif
3045 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003046 XCloseDisplay(x11_display);
3047# endif
3048# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3049 vim_free(signal_stack);
3050 signal_stack = NULL;
3051# endif
3052# ifdef FEAT_TITLE
3053 vim_free(oldtitle);
3054 vim_free(oldicon);
3055# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003056}
3057#endif
3058
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059static void exit_scroll __ARGS((void));
3060
3061/*
3062 * Output a newline when exiting.
3063 * Make sure the newline goes to the same stream as the text.
3064 */
3065 static void
3066exit_scroll()
3067{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003068 if (silent_mode)
3069 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070 if (newline_on_exit || msg_didout)
3071 {
3072 if (msg_use_printf())
3073 {
3074 if (info_message)
3075 mch_msg("\n");
3076 else
3077 mch_errmsg("\r\n");
3078 }
3079 else
3080 out_char('\n');
3081 }
3082 else
3083 {
3084 restore_cterm_colors(); /* get original colors back */
3085 msg_clr_eos_force(); /* clear the rest of the display */
3086 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3087 }
3088}
3089
3090 void
3091mch_exit(r)
3092 int r;
3093{
3094 exiting = TRUE;
3095
3096#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3097 x11_export_final_selection();
3098#endif
3099
3100#ifdef FEAT_GUI
3101 if (!gui.in_use)
3102#endif
3103 {
3104 settmode(TMODE_COOK);
3105#ifdef FEAT_TITLE
3106 mch_restore_title(3); /* restore xterm title and icon name */
3107#endif
3108 /*
3109 * When t_ti is not empty but it doesn't cause swapping terminal
3110 * pages, need to output a newline when msg_didout is set. But when
3111 * t_ti does swap pages it should not go to the shell page. Do this
3112 * before stoptermcap().
3113 */
3114 if (swapping_screen() && !newline_on_exit)
3115 exit_scroll();
3116
3117 /* Stop termcap: May need to check for T_CRV response, which
3118 * requires RAW mode. */
3119 stoptermcap();
3120
3121 /*
3122 * A newline is only required after a message in the alternate screen.
3123 * This is set to TRUE by wait_return().
3124 */
3125 if (!swapping_screen() || newline_on_exit)
3126 exit_scroll();
3127
3128 /* Cursor may have been switched off without calling starttermcap()
3129 * when doing "vim -u vimrc" and vimrc contains ":q". */
3130 if (full_screen)
3131 cursor_on();
3132 }
3133 out_flush();
3134 ml_close_all(TRUE); /* remove all memfiles */
3135 may_core_dump();
3136#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 gui_exit(r);
3139#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003140
Bram Moolenaar56718732006-03-15 22:53:57 +00003141#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003142 mac_conv_cleanup();
3143#endif
3144
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145#ifdef __QNX__
3146 /* A core dump won't be created if the signal handler
3147 * doesn't return, so we can't call exit() */
3148 if (deadly_signal != 0)
3149 return;
3150#endif
3151
Bram Moolenaar009b2592004-10-24 19:18:58 +00003152#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003153 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003154#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003155
3156#ifdef EXITFREE
3157 free_all_mem();
3158#endif
3159
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 exit(r);
3161}
3162
3163 static void
3164may_core_dump()
3165{
3166 if (deadly_signal != 0)
3167 {
3168 signal(deadly_signal, SIG_DFL);
3169 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3170 }
3171}
3172
3173#ifndef VMS
3174
3175 void
3176mch_settmode(tmode)
3177 int tmode;
3178{
3179 static int first = TRUE;
3180
3181 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3182#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3183 /*
3184 * for "new" tty systems
3185 */
3186# ifdef HAVE_TERMIOS_H
3187 static struct termios told;
3188 struct termios tnew;
3189# else
3190 static struct termio told;
3191 struct termio tnew;
3192# endif
3193
3194 if (first)
3195 {
3196 first = FALSE;
3197# if defined(HAVE_TERMIOS_H)
3198 tcgetattr(read_cmd_fd, &told);
3199# else
3200 ioctl(read_cmd_fd, TCGETA, &told);
3201# endif
3202 }
3203
3204 tnew = told;
3205 if (tmode == TMODE_RAW)
3206 {
3207 /*
3208 * ~ICRNL enables typing ^V^M
3209 */
3210 tnew.c_iflag &= ~ICRNL;
3211 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3212# if defined(IEXTEN) && !defined(__MINT__)
3213 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3214 /* but it breaks function keys on MINT */
3215# endif
3216 );
3217# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3218 tnew.c_oflag &= ~ONLCR;
3219# endif
3220 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3221 tnew.c_cc[VTIME] = 0; /* don't wait */
3222 }
3223 else if (tmode == TMODE_SLEEP)
3224 tnew.c_lflag &= ~(ECHO);
3225
3226# if defined(HAVE_TERMIOS_H)
3227 {
3228 int n = 10;
3229
3230 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3231 * few times. */
3232 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3233 && errno == EINTR && n > 0)
3234 --n;
3235 }
3236# else
3237 ioctl(read_cmd_fd, TCSETA, &tnew);
3238# endif
3239
3240#else
3241
3242 /*
3243 * for "old" tty systems
3244 */
3245# ifndef TIOCSETN
3246# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3247# endif
3248 static struct sgttyb ttybold;
3249 struct sgttyb ttybnew;
3250
3251 if (first)
3252 {
3253 first = FALSE;
3254 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3255 }
3256
3257 ttybnew = ttybold;
3258 if (tmode == TMODE_RAW)
3259 {
3260 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3261 ttybnew.sg_flags |= RAW;
3262 }
3263 else if (tmode == TMODE_SLEEP)
3264 ttybnew.sg_flags &= ~(ECHO);
3265 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3266#endif
3267 curr_tmode = tmode;
3268}
3269
3270/*
3271 * Try to get the code for "t_kb" from the stty setting
3272 *
3273 * Even if termcap claims a backspace key, the user's setting *should*
3274 * prevail. stty knows more about reality than termcap does, and if
3275 * somebody's usual erase key is DEL (which, for most BSD users, it will
3276 * be), they're going to get really annoyed if their erase key starts
3277 * doing forward deletes for no reason. (Eric Fischer)
3278 */
3279 void
3280get_stty()
3281{
3282 char_u buf[2];
3283 char_u *p;
3284
3285 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3286#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3287 /* for "new" tty systems */
3288# ifdef HAVE_TERMIOS_H
3289 struct termios keys;
3290# else
3291 struct termio keys;
3292# endif
3293
3294# if defined(HAVE_TERMIOS_H)
3295 if (tcgetattr(read_cmd_fd, &keys) != -1)
3296# else
3297 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3298# endif
3299 {
3300 buf[0] = keys.c_cc[VERASE];
3301 intr_char = keys.c_cc[VINTR];
3302#else
3303 /* for "old" tty systems */
3304 struct sgttyb keys;
3305
3306 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3307 {
3308 buf[0] = keys.sg_erase;
3309 intr_char = keys.sg_kill;
3310#endif
3311 buf[1] = NUL;
3312 add_termcode((char_u *)"kb", buf, FALSE);
3313
3314 /*
3315 * If <BS> and <DEL> are now the same, redefine <DEL>.
3316 */
3317 p = find_termcode((char_u *)"kD");
3318 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3319 do_fixdel(NULL);
3320 }
3321#if 0
3322 } /* to keep cindent happy */
3323#endif
3324}
3325
3326#endif /* VMS */
3327
3328#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3329/*
3330 * Set mouse clicks on or off.
3331 */
3332 void
3333mch_setmouse(on)
3334 int on;
3335{
3336 static int ison = FALSE;
3337 int xterm_mouse_vers;
3338
3339 if (on == ison) /* return quickly if nothing to do */
3340 return;
3341
3342 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003343
3344# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003345 if (ttym_flags == TTYM_URXVT)
3346 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003347 out_str_nf((char_u *)
3348 (on
3349 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3350 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3351 ison = on;
3352 }
3353# endif
3354
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003355# ifdef FEAT_MOUSE_SGR
3356 if (ttym_flags == TTYM_SGR)
3357 {
3358 out_str_nf((char_u *)
3359 (on
3360 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3361 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3362 ison = on;
3363 }
3364# endif
3365
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 if (xterm_mouse_vers > 0)
3367 {
3368 if (on) /* enable mouse events, use mouse tracking if available */
3369 out_str_nf((char_u *)
3370 (xterm_mouse_vers > 1
3371 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3372 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3373 else /* disable mouse events, could probably always send the same */
3374 out_str_nf((char_u *)
3375 (xterm_mouse_vers > 1
3376 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3377 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3378 ison = on;
3379 }
3380
3381# ifdef FEAT_MOUSE_DEC
3382 else if (ttym_flags == TTYM_DEC)
3383 {
3384 if (on) /* enable mouse events */
3385 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3386 else /* disable mouse events */
3387 out_str_nf((char_u *)"\033['z");
3388 ison = on;
3389 }
3390# endif
3391
3392# ifdef FEAT_MOUSE_GPM
3393 else
3394 {
3395 if (on)
3396 {
3397 if (gpm_open())
3398 ison = TRUE;
3399 }
3400 else
3401 {
3402 gpm_close();
3403 ison = FALSE;
3404 }
3405 }
3406# endif
3407
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003408# ifdef FEAT_SYSMOUSE
3409 else
3410 {
3411 if (on)
3412 {
3413 if (sysmouse_open() == OK)
3414 ison = TRUE;
3415 }
3416 else
3417 {
3418 sysmouse_close();
3419 ison = FALSE;
3420 }
3421 }
3422# endif
3423
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424# ifdef FEAT_MOUSE_JSB
3425 else
3426 {
3427 if (on)
3428 {
3429 /* D - Enable Mouse up/down messages
3430 * L - Enable Left Button Reporting
3431 * M - Enable Middle Button Reporting
3432 * R - Enable Right Button Reporting
3433 * K - Enable SHIFT and CTRL key Reporting
3434 * + - Enable Advanced messaging of mouse moves and up/down messages
3435 * Q - Quiet No Ack
3436 * # - Numeric value of mouse pointer required
3437 * 0 = Multiview 2000 cursor, used as standard
3438 * 1 = Windows Arrow
3439 * 2 = Windows I Beam
3440 * 3 = Windows Hour Glass
3441 * 4 = Windows Cross Hair
3442 * 5 = Windows UP Arrow
3443 */
3444#ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3445 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3446 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3447#else
3448 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3449 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3450#endif
3451 ison = TRUE;
3452 }
3453 else
3454 {
3455 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3456 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3457 ison = FALSE;
3458 }
3459 }
3460# endif
3461# ifdef FEAT_MOUSE_PTERM
3462 else
3463 {
3464 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3465 if (on)
3466 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3467 else
3468 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3469 ison = on;
3470 }
3471# endif
3472}
3473
3474/*
3475 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3476 */
3477 void
3478check_mouse_termcode()
3479{
3480# ifdef FEAT_MOUSE_XTERM
3481 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003482# ifdef FEAT_MOUSE_URXVT
3483 && use_xterm_mouse() != 3
3484# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485# ifdef FEAT_GUI
3486 && !gui.in_use
3487# endif
3488 )
3489 {
3490 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003491 ? IF_EB("\233M", CSI_STR "M")
3492 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 if (*p_mouse != NUL)
3494 {
3495 /* force mouse off and maybe on to send possibly new mouse
3496 * activation sequence to the xterm, with(out) drag tracing. */
3497 mch_setmouse(FALSE);
3498 setmouse();
3499 }
3500 }
3501 else
3502 del_mouse_termcode(KS_MOUSE);
3503# endif
3504
3505# ifdef FEAT_MOUSE_GPM
3506 if (!use_xterm_mouse()
3507# ifdef FEAT_GUI
3508 && !gui.in_use
3509# endif
3510 )
3511 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3512# endif
3513
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003514# ifdef FEAT_SYSMOUSE
3515 if (!use_xterm_mouse()
3516# ifdef FEAT_GUI
3517 && !gui.in_use
3518# endif
3519 )
3520 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3521# endif
3522
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523# ifdef FEAT_MOUSE_JSB
3524 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3525 if (!use_xterm_mouse()
3526# ifdef FEAT_GUI
3527 && !gui.in_use
3528# endif
3529 )
3530 set_mouse_termcode(KS_JSBTERM_MOUSE,
3531 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3532 else
3533 del_mouse_termcode(KS_JSBTERM_MOUSE);
3534# endif
3535
3536# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003537 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 * define it in the GUI or when using an xterm. */
3539 if (!use_xterm_mouse()
3540# ifdef FEAT_GUI
3541 && !gui.in_use
3542# endif
3543 )
3544 set_mouse_termcode(KS_NETTERM_MOUSE,
3545 (char_u *)IF_EB("\033}", ESC_STR "}"));
3546 else
3547 del_mouse_termcode(KS_NETTERM_MOUSE);
3548# endif
3549
3550# ifdef FEAT_MOUSE_DEC
3551 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3552 if (!use_xterm_mouse()
3553# ifdef FEAT_GUI
3554 && !gui.in_use
3555# endif
3556 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003557 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3558 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 else
3560 del_mouse_termcode(KS_DEC_MOUSE);
3561# endif
3562# ifdef FEAT_MOUSE_PTERM
3563 /* same as the dec mouse */
3564 if (!use_xterm_mouse()
3565# ifdef FEAT_GUI
3566 && !gui.in_use
3567# endif
3568 )
3569 set_mouse_termcode(KS_PTERM_MOUSE,
3570 (char_u *) IF_EB("\033[", ESC_STR "["));
3571 else
3572 del_mouse_termcode(KS_PTERM_MOUSE);
3573# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003574# ifdef FEAT_MOUSE_URXVT
3575 /* same as the dec mouse */
3576 if (use_xterm_mouse() == 3
3577# ifdef FEAT_GUI
3578 && !gui.in_use
3579# endif
3580 )
3581 {
3582 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3583 ? IF_EB("\233", CSI_STR)
3584 : IF_EB("\033[", ESC_STR "[")));
3585
3586 if (*p_mouse != NUL)
3587 {
3588 mch_setmouse(FALSE);
3589 setmouse();
3590 }
3591 }
3592 else
3593 del_mouse_termcode(KS_URXVT_MOUSE);
3594# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003595# ifdef FEAT_MOUSE_SGR
3596 /* same as the dec mouse */
3597 if (use_xterm_mouse() == 4
3598# ifdef FEAT_GUI
3599 && !gui.in_use
3600# endif
3601 )
3602 {
3603 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3604 ? IF_EB("\233<", CSI_STR "<")
3605 : IF_EB("\033[<", ESC_STR "[<")));
3606
3607 if (*p_mouse != NUL)
3608 {
3609 mch_setmouse(FALSE);
3610 setmouse();
3611 }
3612 }
3613 else
3614 del_mouse_termcode(KS_SGR_MOUSE);
3615# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616}
3617#endif
3618
3619/*
3620 * set screen mode, always fails.
3621 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003622 int
3623mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003624 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625{
3626 EMSG(_(e_screenmode));
3627 return FAIL;
3628}
3629
3630#ifndef VMS
3631
3632/*
3633 * Try to get the current window size:
3634 * 1. with an ioctl(), most accurate method
3635 * 2. from the environment variables LINES and COLUMNS
3636 * 3. from the termcap
3637 * 4. keep using the old values
3638 * Return OK when size could be determined, FAIL otherwise.
3639 */
3640 int
3641mch_get_shellsize()
3642{
3643 long rows = 0;
3644 long columns = 0;
3645 char_u *p;
3646
3647 /*
3648 * For OS/2 use _scrsize().
3649 */
3650# ifdef __EMX__
3651 {
3652 int s[2];
3653
3654 _scrsize(s);
3655 columns = s[0];
3656 rows = s[1];
3657 }
3658# endif
3659
3660 /*
3661 * 1. try using an ioctl. It is the most accurate method.
3662 *
3663 * Try using TIOCGWINSZ first, some systems that have it also define
3664 * TIOCGSIZE but don't have a struct ttysize.
3665 */
3666# ifdef TIOCGWINSZ
3667 {
3668 struct winsize ws;
3669 int fd = 1;
3670
3671 /* When stdout is not a tty, use stdin for the ioctl(). */
3672 if (!isatty(fd) && isatty(read_cmd_fd))
3673 fd = read_cmd_fd;
3674 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3675 {
3676 columns = ws.ws_col;
3677 rows = ws.ws_row;
3678 }
3679 }
3680# else /* TIOCGWINSZ */
3681# ifdef TIOCGSIZE
3682 {
3683 struct ttysize ts;
3684 int fd = 1;
3685
3686 /* When stdout is not a tty, use stdin for the ioctl(). */
3687 if (!isatty(fd) && isatty(read_cmd_fd))
3688 fd = read_cmd_fd;
3689 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3690 {
3691 columns = ts.ts_cols;
3692 rows = ts.ts_lines;
3693 }
3694 }
3695# endif /* TIOCGSIZE */
3696# endif /* TIOCGWINSZ */
3697
3698 /*
3699 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003700 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3701 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003703 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 {
3705 if ((p = (char_u *)getenv("LINES")))
3706 rows = atoi((char *)p);
3707 if ((p = (char_u *)getenv("COLUMNS")))
3708 columns = atoi((char *)p);
3709 }
3710
3711#ifdef HAVE_TGETENT
3712 /*
3713 * 3. try reading "co" and "li" entries from termcap
3714 */
3715 if (columns == 0 || rows == 0)
3716 getlinecol(&columns, &rows);
3717#endif
3718
3719 /*
3720 * 4. If everything fails, use the old values
3721 */
3722 if (columns <= 0 || rows <= 0)
3723 return FAIL;
3724
3725 Rows = rows;
3726 Columns = columns;
3727 return OK;
3728}
3729
3730/*
3731 * Try to set the window size to Rows and Columns.
3732 */
3733 void
3734mch_set_shellsize()
3735{
3736 if (*T_CWS)
3737 {
3738 /*
3739 * NOTE: if you get an error here that term_set_winsize() is
3740 * undefined, check the output of configure. It could probably not
3741 * find a ncurses, termcap or termlib library.
3742 */
3743 term_set_winsize((int)Rows, (int)Columns);
3744 out_flush();
3745 screen_start(); /* don't know where cursor is now */
3746 }
3747}
3748
3749#endif /* VMS */
3750
3751/*
3752 * Rows and/or Columns has changed.
3753 */
3754 void
3755mch_new_shellsize()
3756{
3757 /* Nothing to do. */
3758}
3759
Bram Moolenaar205b8862011-09-07 15:04:31 +02003760/*
3761 * Wait for process "child" to end.
3762 * Return "child" if it exited properly, <= 0 on error.
3763 */
3764 static pid_t
3765wait4pid(child, status)
3766 pid_t child;
3767 waitstatus *status;
3768{
3769 pid_t wait_pid = 0;
3770
3771 while (wait_pid != child)
3772 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003773 /* When compiled with Python threads are probably used, in which case
3774 * wait() sometimes hangs for no obvious reason. Use waitpid()
3775 * instead and loop (like the GUI). Also needed for other interfaces,
3776 * they might call system(). */
3777# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003778 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003779# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003780 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003781# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003782 if (wait_pid == 0)
3783 {
3784 /* Wait for 1/100 sec before trying again. */
3785 mch_delay(10L, TRUE);
3786 continue;
3787 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003788 if (wait_pid <= 0
3789# ifdef ECHILD
3790 && errno == ECHILD
3791# endif
3792 )
3793 break;
3794 }
3795 return wait_pid;
3796}
3797
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 int
3799mch_call_shell(cmd, options)
3800 char_u *cmd;
3801 int options; /* SHELL_*, see vim.h */
3802{
3803#ifdef VMS
3804 char *ifn = NULL;
3805 char *ofn = NULL;
3806#endif
3807 int tmode = cur_tmode;
3808#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3809 int x;
3810# ifndef __EMX__
3811 char_u *newcmd; /* only needed for unix */
3812# else
3813 /*
3814 * Set the preferred shell in the EMXSHELL environment variable (but
3815 * only if it is different from what is already in the environment).
3816 * Emx then takes care of whether to use "/c" or "-c" in an
3817 * intelligent way. Simply pass the whole thing to emx's system() call.
3818 * Emx also starts an interactive shell if system() is passed an empty
3819 * string.
3820 */
3821 char_u *p, *old;
3822
3823 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3824 {
3825 /* should check HAVE_SETENV, but I know we don't have it. */
3826 p = alloc(10 + strlen(p_sh));
3827 if (p)
3828 {
3829 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3830 putenv((char *)p); /* don't free the pointer! */
3831 }
3832 }
3833# endif
3834
3835 out_flush();
3836
3837 if (options & SHELL_COOKED)
3838 settmode(TMODE_COOK); /* set to normal mode */
3839
Bram Moolenaar62b42182010-09-21 22:09:37 +02003840# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3841 loose_clipboard();
3842# endif
3843
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844# ifdef __EMX__
3845 if (cmd == NULL)
3846 x = system(""); /* this starts an interactive shell in emx */
3847 else
3848 x = system((char *)cmd);
3849 /* system() returns -1 when error occurs in starting shell */
3850 if (x == -1 && !emsg_silent)
3851 {
3852 MSG_PUTS(_("\nCannot execute shell "));
3853 msg_outtrans(p_sh);
3854 msg_putchar('\n');
3855 }
3856# else /* not __EMX__ */
3857 if (cmd == NULL)
3858 x = system((char *)p_sh);
3859 else
3860 {
3861# ifdef VMS
3862 if (ofn = strchr((char *)cmd, '>'))
3863 *ofn++ = '\0';
3864 if (ifn = strchr((char *)cmd, '<'))
3865 {
3866 char *p;
3867
3868 *ifn++ = '\0';
3869 p = strchr(ifn,' '); /* chop off any trailing spaces */
3870 if (p)
3871 *p = '\0';
3872 }
3873 if (ofn)
3874 x = vms_sys((char *)cmd, ofn, ifn);
3875 else
3876 x = system((char *)cmd);
3877# else
3878 newcmd = lalloc(STRLEN(p_sh)
3879 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3880 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3881 if (newcmd == NULL)
3882 x = 0;
3883 else
3884 {
3885 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3886 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3887 (char *)p_shcf,
3888 (char *)cmd);
3889 x = system((char *)newcmd);
3890 vim_free(newcmd);
3891 }
3892# endif
3893 }
3894# ifdef VMS
3895 x = vms_sys_status(x);
3896# endif
3897 if (emsg_silent)
3898 ;
3899 else if (x == 127)
3900 MSG_PUTS(_("\nCannot execute shell sh\n"));
3901# endif /* __EMX__ */
3902 else if (x && !(options & SHELL_SILENT))
3903 {
3904 MSG_PUTS(_("\nshell returned "));
3905 msg_outnum((long)x);
3906 msg_putchar('\n');
3907 }
3908
3909 if (tmode == TMODE_RAW)
3910 settmode(TMODE_RAW); /* set to raw mode */
3911# ifdef FEAT_TITLE
3912 resettitle();
3913# endif
3914 return x;
3915
3916#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3917
Bram Moolenaardf177f62005-02-22 08:39:57 +00003918# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3919 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920
3921 char_u *newcmd = NULL;
3922 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003923 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 pid_t wait_pid = 0;
3925# ifdef HAVE_UNION_WAIT
3926 union wait status;
3927# else
3928 int status = -1;
3929# endif
3930 int retval = -1;
3931 char **argv = NULL;
3932 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003933 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 int i;
3935 char_u *p;
3936 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003938# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 int pty_slave_fd = -1;
3940 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003941# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003942 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 int fd_fromshell[2];
3944 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003945# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003947# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 static char envbuf_Rows[20];
3949 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003951 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952
Bram Moolenaar62b42182010-09-21 22:09:37 +02003953 newcmd = vim_strsave(p_sh);
3954 if (newcmd == NULL) /* out of memory */
3955 goto error;
3956
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 out_flush();
3958 if (options & SHELL_COOKED)
3959 settmode(TMODE_COOK); /* set to normal mode */
3960
Bram Moolenaar62b42182010-09-21 22:09:37 +02003961# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3962 loose_clipboard();
3963# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00003964
3965 /*
3966 * Do this loop twice:
3967 * 1: find number of arguments
3968 * 2: separate them and build argv[]
3969 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970 for (i = 0; i < 2; ++i)
3971 {
3972 p = newcmd;
3973 inquote = FALSE;
3974 argc = 0;
3975 for (;;)
3976 {
3977 if (i == 1)
3978 argv[argc] = (char *)p;
3979 ++argc;
3980 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3981 {
3982 if (*p == '"')
3983 inquote = !inquote;
3984 ++p;
3985 }
3986 if (*p == NUL)
3987 break;
3988 if (i == 1)
3989 *p++ = NUL;
3990 p = skipwhite(p);
3991 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003992 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02003994 /*
3995 * Account for possible multiple args in p_shcf.
3996 */
3997 p = p_shcf;
3998 for (;;)
3999 {
4000 p = skiptowhite(p);
4001 if (*p == NUL)
4002 break;
4003 ++argc;
4004 p = skipwhite(p);
4005 }
4006
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4008 if (argv == NULL) /* out of memory */
4009 goto error;
4010 }
4011 }
4012 if (cmd != NULL)
4013 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004014 char_u *s;
4015
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016 if (extra_shell_arg != NULL)
4017 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004018
4019 /* Break 'shellcmdflag' into white separated parts. This doesn't
4020 * handle quoted strings, they are very unlikely to appear. */
4021 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4022 if (p_shcf_copy == NULL) /* out of memory */
4023 goto error;
4024 s = p_shcf_copy;
4025 p = p_shcf;
4026 while (*p != NUL)
4027 {
4028 argv[argc++] = (char *)s;
4029 while (*p && *p != ' ' && *p != TAB)
4030 *s++ = *p++;
4031 *s++ = NUL;
4032 p = skipwhite(p);
4033 }
4034
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 argv[argc++] = (char *)cmd;
4036 }
4037 argv[argc] = NULL;
4038
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004040 * For the GUI, when writing the output into the buffer and when reading
4041 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4042 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004044 if ((options & (SHELL_READ|SHELL_WRITE))
4045# ifdef FEAT_GUI
4046 || (gui.in_use && show_shell_mess)
4047# endif
4048 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004050# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 /*
4052 * Try to open a master pty.
4053 * If this works, open the slave pty.
4054 * If the slave can't be opened, close the master pty.
4055 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004056 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 {
4058 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004059 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004060 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004061 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4062 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4063 * adding O_NOCTTY always works when defined. */
4064#ifdef O_NOCTTY
4065 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4066#else
4067 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4068#endif
4069 if (pty_slave_fd < 0)
4070 {
4071 close(pty_master_fd);
4072 pty_master_fd = -1;
4073 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074 }
4075 }
4076 /*
4077 * If not opening a pty or it didn't work, try using pipes.
4078 */
4079 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004080# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 {
4082 pipe_error = (pipe(fd_toshell) < 0);
4083 if (!pipe_error) /* pipe create OK */
4084 {
4085 pipe_error = (pipe(fd_fromshell) < 0);
4086 if (pipe_error) /* pipe create failed */
4087 {
4088 close(fd_toshell[0]);
4089 close(fd_toshell[1]);
4090 }
4091 }
4092 if (pipe_error)
4093 {
4094 MSG_PUTS(_("\nCannot create pipes\n"));
4095 out_flush();
4096 }
4097 }
4098 }
4099
4100 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 {
4102# ifdef __BEOS__
4103 beos_cleanup_read_thread();
4104# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004105
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4107 {
4108 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004109 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004111 || (gui.in_use && show_shell_mess)
4112# endif
4113 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004115# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 if (pty_master_fd >= 0) /* close the pseudo tty */
4117 {
4118 close(pty_master_fd);
4119 close(pty_slave_fd);
4120 }
4121 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004122# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 {
4124 close(fd_toshell[0]);
4125 close(fd_toshell[1]);
4126 close(fd_fromshell[0]);
4127 close(fd_fromshell[1]);
4128 }
4129 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 }
4131 else if (pid == 0) /* child */
4132 {
4133 reset_signals(); /* handle signals normally */
4134
4135 if (!show_shell_mess || (options & SHELL_EXPAND))
4136 {
4137 int fd;
4138
4139 /*
4140 * Don't want to show any message from the shell. Can't just
4141 * close stdout and stderr though, because some systems will
4142 * break if you try to write to them after that, so we must
4143 * use dup() to replace them with something else -- webb
4144 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4145 * waiting for input.
4146 */
4147 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4148 fclose(stdin);
4149 fclose(stdout);
4150 fclose(stderr);
4151
4152 /*
4153 * If any of these open()'s and dup()'s fail, we just continue
4154 * anyway. It's not fatal, and on most systems it will make
4155 * no difference at all. On a few it will cause the execvp()
4156 * to exit with a non-zero status even when the completion
4157 * could be done, which is nothing too serious. If the open()
4158 * or dup() failed we'd just do the same thing ourselves
4159 * anyway -- webb
4160 */
4161 if (fd >= 0)
4162 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004163 ignored = dup(fd); /* To replace stdin (fd 0) */
4164 ignored = dup(fd); /* To replace stdout (fd 1) */
4165 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166
4167 /* Don't need this now that we've duplicated it */
4168 close(fd);
4169 }
4170 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004171 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004173 || gui.in_use
4174# endif
4175 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 {
4177
Bram Moolenaardf177f62005-02-22 08:39:57 +00004178# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004179 /* Create our own process group, so that the child and all its
4180 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004181 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004182 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004183 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004184 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004185# if defined(SIGHUP)
4186 /* When doing "!xterm&" and 'shell' is bash: the shell
4187 * will exit and send SIGHUP to all processes in its
4188 * group, killing the just started process. Ignore SIGHUP
4189 * to avoid that. (suggested by Simon Schubert)
4190 */
4191 signal(SIGHUP, SIG_IGN);
4192# endif
4193 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004194# endif
4195# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004196 if (pty_slave_fd >= 0)
4197 {
4198 /* push stream discipline modules */
4199 if (options & SHELL_COOKED)
4200 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004202 /* Try to become controlling tty (probably doesn't work,
4203 * unless run by root) */
4204 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004206 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004207# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004209# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 setenv("TERM", "dumb", 1);
4211 sprintf((char *)envbuf, "%ld", Rows);
4212 setenv("ROWS", (char *)envbuf, 1);
4213 sprintf((char *)envbuf, "%ld", Rows);
4214 setenv("LINES", (char *)envbuf, 1);
4215 sprintf((char *)envbuf, "%ld", Columns);
4216 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004217# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218 /*
4219 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004220 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 */
4222 putenv("TERM=dumb");
4223 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4224 putenv(envbuf_Rows);
4225 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4226 putenv(envbuf_Rows);
4227 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4228 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004229# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230
Bram Moolenaara5792f52005-11-23 21:25:05 +00004231 /*
4232 * stderr is only redirected when using the GUI, so that a
4233 * program like gpg can still access the terminal to get a
4234 * passphrase using stderr.
4235 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004236# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 if (pty_master_fd >= 0)
4238 {
4239 close(pty_master_fd); /* close master side of pty */
4240
4241 /* set up stdin/stdout/stderr for the child */
4242 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004243 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004245 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004246 if (gui.in_use)
4247 {
4248 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004249 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251
4252 close(pty_slave_fd); /* has been dupped, close it now */
4253 }
4254 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004255# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256 {
4257 /* set up stdin for the child */
4258 close(fd_toshell[1]);
4259 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004260 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 close(fd_toshell[0]);
4262
4263 /* set up stdout for the child */
4264 close(fd_fromshell[0]);
4265 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004266 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267 close(fd_fromshell[1]);
4268
Bram Moolenaara5792f52005-11-23 21:25:05 +00004269# ifdef FEAT_GUI
4270 if (gui.in_use)
4271 {
4272 /* set up stderr for the child */
4273 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004274 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004275 }
4276# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 }
4278 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004279
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 /*
4281 * There is no type cast for the argv, because the type may be
4282 * different on different machines. This may cause a warning
4283 * message with strict compilers, don't worry about it.
4284 * Call _exit() instead of exit() to avoid closing the connection
4285 * to the X server (esp. with GTK, which uses atexit()).
4286 */
4287 execvp(argv[0], argv);
4288 _exit(EXEC_FAILED); /* exec failed, return failure code */
4289 }
4290 else /* parent */
4291 {
4292 /*
4293 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004294 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 */
4296 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004297 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298
4299 /*
4300 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004301 * This is also used to pipe stdin/stdout to/from the external
4302 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004304 if ((options & (SHELL_READ|SHELL_WRITE))
4305# ifdef FEAT_GUI
4306 || (gui.in_use && show_shell_mess)
4307# endif
4308 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004310# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004311 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004312# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004314# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4316 int ta_len = 0; /* valid bytes in ta_buf[] */
4317 int len;
4318 int p_more_save;
4319 int old_State;
4320 int c;
4321 int toshell_fd;
4322 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004323 garray_T ga;
4324 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004325# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4326 struct timeval start_tv;
4327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328
Bram Moolenaardf177f62005-02-22 08:39:57 +00004329# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004330 if (pty_master_fd >= 0)
4331 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332 fromshell_fd = pty_master_fd;
4333 toshell_fd = dup(pty_master_fd);
4334 }
4335 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004336# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 {
4338 close(fd_toshell[0]);
4339 close(fd_fromshell[1]);
4340 toshell_fd = fd_toshell[1];
4341 fromshell_fd = fd_fromshell[0];
4342 }
4343
4344 /*
4345 * Write to the child if there are typed characters.
4346 * Read from the child if there are characters available.
4347 * Repeat the reading a few times if more characters are
4348 * available. Need to check for typed keys now and then, but
4349 * not too often (delays when no chars are available).
4350 * This loop is quit if no characters can be read from the pty
4351 * (WaitForChar detected special condition), or there are no
4352 * characters available and the child has exited.
4353 * Only check if the child has exited when there is no more
4354 * output. The child may exit before all the output has
4355 * been printed.
4356 *
4357 * Currently this busy loops!
4358 * This can probably dead-lock when the write blocks!
4359 */
4360 p_more_save = p_more;
4361 p_more = FALSE;
4362 old_State = State;
4363 State = EXTERNCMD; /* don't redraw at window resize */
4364
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004365 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004366 {
4367 /* Fork a process that will write the lines to the
4368 * external program. */
4369 if ((wpid = fork()) == -1)
4370 {
4371 MSG_PUTS(_("\nCannot fork\n"));
4372 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004373 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004374 {
4375 linenr_T lnum = curbuf->b_op_start.lnum;
4376 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004377 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004378 size_t l;
4379
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004380 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004381 for (;;)
4382 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004383 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004384 if (l == 0)
4385 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004386 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004387 /* NL -> NUL translation */
4388 len = write(toshell_fd, "", (size_t)1);
4389 else
4390 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004391 char_u *s = vim_strchr(lp + written, NL);
4392
Bram Moolenaar89d40322006-08-29 15:30:07 +00004393 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004394 s == NULL ? l
4395 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004396 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004397 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004398 {
4399 /* Finished a line, add a NL, unless this line
4400 * should not have one. */
4401 if (lnum != curbuf->b_op_end.lnum
4402 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004403 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004404 && (lnum !=
4405 curbuf->b_ml.ml_line_count
4406 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004407 ignored = write(toshell_fd, "\n",
4408 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004409 ++lnum;
4410 if (lnum > curbuf->b_op_end.lnum)
4411 {
4412 /* finished all the lines, close pipe */
4413 close(toshell_fd);
4414 toshell_fd = -1;
4415 break;
4416 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004417 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004418 written = 0;
4419 }
4420 else if (len > 0)
4421 written += len;
4422 }
4423 _exit(0);
4424 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004425 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004426 {
4427 close(toshell_fd);
4428 toshell_fd = -1;
4429 }
4430 }
4431
4432 if (options & SHELL_READ)
4433 ga_init2(&ga, 1, BUFLEN);
4434
4435 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004436# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4437 gettimeofday(&start_tv, NULL);
4438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 for (;;)
4440 {
4441 /*
4442 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004443 * if there are any.
4444 * Don't do this if we are expanding wild cards (would eat
4445 * typeahead).
4446 * Don't do this when filtering and terminal is in cooked
4447 * mode, the shell command will handle the I/O. Avoids
4448 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004449 * Don't get characters when the child has already
4450 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004451 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004452 * while (noread_cnt > 4), avoids that ":r !ls" eats
4453 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 */
4455 len = 0;
4456 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004457 && ((options &
4458 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4459 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004460# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004461 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004462# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004463 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004464 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004465 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004467 if (ta_len == 0)
4468 {
4469 /* Get extra characters when we don't have any.
4470 * Reset the counter and timer. */
4471 noread_cnt = 0;
4472# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4473 gettimeofday(&start_tv, NULL);
4474# endif
4475 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4476 }
4477 if (ta_len > 0 || len > 0)
4478 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 /*
4480 * For pipes:
4481 * Check for CTRL-C: send interrupt signal to child.
4482 * Check for CTRL-D: EOF, close pipe to child.
4483 */
4484 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4485 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004486# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 /*
4488 * Send SIGINT to the child's group or all
4489 * processes in our group.
4490 */
4491 if (ta_buf[ta_len] == Ctrl_C
4492 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004493 {
4494# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004496# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004499 if (wpid > 0)
4500 kill(wpid, SIGINT);
4501 }
4502# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 if (pty_master_fd < 0 && toshell_fd >= 0
4504 && ta_buf[ta_len] == Ctrl_D)
4505 {
4506 close(toshell_fd);
4507 toshell_fd = -1;
4508 }
4509 }
4510
4511 /* replace K_BS by <BS> and K_DEL by <DEL> */
4512 for (i = ta_len; i < ta_len + len; ++i)
4513 {
4514 if (ta_buf[i] == CSI && len - i > 2)
4515 {
4516 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4517 if (c == K_DEL || c == K_KDEL || c == K_BS)
4518 {
4519 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4520 (size_t)(len - i - 2));
4521 if (c == K_DEL || c == K_KDEL)
4522 ta_buf[i] = DEL;
4523 else
4524 ta_buf[i] = Ctrl_H;
4525 len -= 2;
4526 }
4527 }
4528 else if (ta_buf[i] == '\r')
4529 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004530# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004532 i += (*mb_ptr2len_len)(ta_buf + i,
4533 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 }
4536
4537 /*
4538 * For pipes: echo the typed characters.
4539 * For a pty this does not seem to work.
4540 */
4541 if (pty_master_fd < 0)
4542 {
4543 for (i = ta_len; i < ta_len + len; ++i)
4544 {
4545 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4546 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004547# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 else if (has_mbyte)
4549 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004550 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551
4552 msg_outtrans_len(ta_buf + i, l);
4553 i += l - 1;
4554 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004555# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 else
4557 msg_outtrans_len(ta_buf + i, 1);
4558 }
4559 windgoto(msg_row, msg_col);
4560 out_flush();
4561 }
4562
4563 ta_len += len;
4564
4565 /*
4566 * Write the characters to the child, unless EOF has
4567 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004568 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004569 * When writing buffer lines, drop the typed
4570 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004572 if (options & SHELL_WRITE)
4573 ta_len = 0;
4574 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575 {
4576 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4577 if (len > 0)
4578 {
4579 ta_len -= len;
4580 mch_memmove(ta_buf, ta_buf + len, ta_len);
4581 }
4582 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004583 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 }
4585
Bram Moolenaardf177f62005-02-22 08:39:57 +00004586 if (got_int)
4587 {
4588 /* CTRL-C sends a signal to the child, we ignore it
4589 * ourselves */
4590# ifdef HAVE_SETSID
4591 kill(-pid, SIGINT);
4592# else
4593 kill(0, SIGINT);
4594# endif
4595 if (wpid > 0)
4596 kill(wpid, SIGINT);
4597 got_int = FALSE;
4598 }
4599
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600 /*
4601 * Check if the child has any characters to be printed.
4602 * Read them and write them to our window. Repeat this as
4603 * long as there is something to do, avoid the 10ms wait
4604 * for mch_inchar(), or sending typeahead characters to
4605 * the external process.
4606 * TODO: This should handle escape sequences, compatible
4607 * to some terminal (vt52?).
4608 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004609 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4611 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004612 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004613# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004615# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004617# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 );
4619 if (len <= 0) /* end of file or error */
4620 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004621
4622 noread_cnt = 0;
4623 if (options & SHELL_READ)
4624 {
4625 /* Do NUL -> NL translation, append NL separated
4626 * lines to the current buffer. */
4627 for (i = 0; i < len; ++i)
4628 {
4629 if (buffer[i] == NL)
4630 append_ga_line(&ga);
4631 else if (buffer[i] == NUL)
4632 ga_append(&ga, NL);
4633 else
4634 ga_append(&ga, buffer[i]);
4635 }
4636 }
4637# ifdef FEAT_MBYTE
4638 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 {
4640 int l;
4641
Bram Moolenaardf177f62005-02-22 08:39:57 +00004642 len += buffer_off;
4643 buffer[len] = NUL;
4644
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 /* Check if the last character in buffer[] is
4646 * incomplete, keep these bytes for the next
4647 * round. */
4648 for (p = buffer; p < buffer + len; p += l)
4649 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004650 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651 if (l == 0)
4652 l = 1; /* NUL byte? */
4653 else if (MB_BYTE2LEN(*p) != l)
4654 break;
4655 }
4656 if (p == buffer) /* no complete character */
4657 {
4658 /* avoid getting stuck at an illegal byte */
4659 if (len >= 12)
4660 ++p;
4661 else
4662 {
4663 buffer_off = len;
4664 continue;
4665 }
4666 }
4667 c = *p;
4668 *p = NUL;
4669 msg_puts(buffer);
4670 if (p < buffer + len)
4671 {
4672 *p = c;
4673 buffer_off = (buffer + len) - p;
4674 mch_memmove(buffer, p, buffer_off);
4675 continue;
4676 }
4677 buffer_off = 0;
4678 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004679# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004680 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 {
4682 buffer[len] = NUL;
4683 msg_puts(buffer);
4684 }
4685
4686 windgoto(msg_row, msg_col);
4687 cursor_on();
4688 out_flush();
4689 if (got_int)
4690 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004691
4692# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4693 {
4694 struct timeval now_tv;
4695 long msec;
4696
4697 /* Avoid that we keep looping here without
4698 * checking for a CTRL-C for a long time. Don't
4699 * break out too often to avoid losing typeahead. */
4700 gettimeofday(&now_tv, NULL);
4701 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4702 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4703 if (msec > 2000)
4704 {
4705 noread_cnt = 5;
4706 break;
4707 }
4708 }
4709# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 }
4711
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004712 /* If we already detected the child has finished break the
4713 * loop now. */
4714 if (wait_pid == pid)
4715 break;
4716
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 /*
4718 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004719 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004721# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004722 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004723# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4727 || (wait_pid == pid && WIFEXITED(status)))
4728 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004729 /* Don't break the loop yet, try reading more
4730 * characters from "fromshell_fd" first. When using
4731 * pipes there might still be something to read and
4732 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004735 else
4736 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 }
4738finished:
4739 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004740 if (options & SHELL_READ)
4741 {
4742 if (ga.ga_len > 0)
4743 {
4744 append_ga_line(&ga);
4745 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004746 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004747 }
4748 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004749 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004750 ga_clear(&ga);
4751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004752
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 /*
4754 * Give all typeahead that wasn't used back to ui_inchar().
4755 */
4756 if (ta_len)
4757 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 State = old_State;
4759 if (toshell_fd >= 0)
4760 close(toshell_fd);
4761 close(fromshell_fd);
4762 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763
4764 /*
4765 * Wait until our child has exited.
4766 * Ignore wait() returning pids of other children and returning
4767 * because of some signal like SIGWINCH.
4768 * Don't wait if wait_pid was already set above, indicating the
4769 * child already exited.
4770 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02004771 if (wait_pid != pid)
4772 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773
Bram Moolenaar624891f2010-10-13 16:22:09 +02004774# ifdef FEAT_GUI
4775 /* Close slave side of pty. Only do this after the child has
4776 * exited, otherwise the child may hang when it tries to write on
4777 * the pty. */
4778 if (pty_master_fd >= 0)
4779 close(pty_slave_fd);
4780# endif
4781
Bram Moolenaardf177f62005-02-22 08:39:57 +00004782 /* Make sure the child that writes to the external program is
4783 * dead. */
4784 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004785 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004786 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02004787 wait4pid(wpid, NULL);
4788 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004789
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 /*
4791 * Set to raw mode right now, otherwise a CTRL-C after
4792 * catch_signals() will kill Vim.
4793 */
4794 if (tmode == TMODE_RAW)
4795 settmode(TMODE_RAW);
4796 did_settmode = TRUE;
4797 set_signals();
4798
4799 if (WIFEXITED(status))
4800 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004801 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 retval = WEXITSTATUS(status);
4803 if (retval && !emsg_silent)
4804 {
4805 if (retval == EXEC_FAILED)
4806 {
4807 MSG_PUTS(_("\nCannot execute shell "));
4808 msg_outtrans(p_sh);
4809 msg_putchar('\n');
4810 }
4811 else if (!(options & SHELL_SILENT))
4812 {
4813 MSG_PUTS(_("\nshell returned "));
4814 msg_outnum((long)retval);
4815 msg_putchar('\n');
4816 }
4817 }
4818 }
4819 else
4820 MSG_PUTS(_("\nCommand terminated\n"));
4821 }
4822 }
4823 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004824 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825
4826error:
4827 if (!did_settmode)
4828 if (tmode == TMODE_RAW)
4829 settmode(TMODE_RAW); /* set to raw mode */
4830# ifdef FEAT_TITLE
4831 resettitle();
4832# endif
4833 vim_free(newcmd);
4834
4835 return retval;
4836
4837#endif /* USE_SYSTEM */
4838}
4839
4840/*
4841 * Check for CTRL-C typed by reading all available characters.
4842 * In cooked mode we should get SIGINT, no need to check.
4843 */
4844 void
4845mch_breakcheck()
4846{
4847 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4848 fill_input_buf(FALSE);
4849}
4850
4851/*
4852 * Wait "msec" msec until a character is available from the keyboard or from
4853 * inbuf[]. msec == -1 will block forever.
4854 * When a GUI is being used, this will never get called -- webb
4855 */
4856 static int
4857WaitForChar(msec)
4858 long msec;
4859{
4860#ifdef FEAT_MOUSE_GPM
4861 int gpm_process_wanted;
4862#endif
4863#ifdef FEAT_XCLIPBOARD
4864 int rest;
4865#endif
4866 int avail;
4867
4868 if (input_available()) /* something in inbuf[] */
4869 return 1;
4870
4871#if defined(FEAT_MOUSE_DEC)
4872 /* May need to query the mouse position. */
4873 if (WantQueryMouse)
4874 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004875 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4877 }
4878#endif
4879
4880 /*
4881 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4882 * events. This is a bit complicated, because they might both be defined.
4883 */
4884#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4885# ifdef FEAT_XCLIPBOARD
4886 rest = 0;
4887 if (do_xterm_trace())
4888 rest = msec;
4889# endif
4890 do
4891 {
4892# ifdef FEAT_XCLIPBOARD
4893 if (rest != 0)
4894 {
4895 msec = XT_TRACE_DELAY;
4896 if (rest >= 0 && rest < XT_TRACE_DELAY)
4897 msec = rest;
4898 if (rest >= 0)
4899 rest -= msec;
4900 }
4901# endif
4902# ifdef FEAT_MOUSE_GPM
4903 gpm_process_wanted = 0;
4904 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4905# else
4906 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4907# endif
4908 if (!avail)
4909 {
4910 if (input_available())
4911 return 1;
4912# ifdef FEAT_XCLIPBOARD
4913 if (rest == 0 || !do_xterm_trace())
4914# endif
4915 break;
4916 }
4917 }
4918 while (FALSE
4919# ifdef FEAT_MOUSE_GPM
4920 || (gpm_process_wanted && mch_gpm_process() == 0)
4921# endif
4922# ifdef FEAT_XCLIPBOARD
4923 || (!avail && rest != 0)
4924# endif
4925 );
4926
4927#else
4928 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4929#endif
4930 return avail;
4931}
4932
4933/*
4934 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02004935 * "msec" == 0 will check for characters once.
4936 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 * When a GUI is being used, this will not be used for input -- webb
4938 * Returns also, when a request from Sniff is waiting -- toni.
4939 * Or when a Linux GPM mouse event is waiting.
4940 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004941#if defined(__BEOS__)
4942 int
4943#else
4944 static int
4945#endif
4946RealWaitForChar(fd, msec, check_for_gpm)
4947 int fd;
4948 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004949 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950{
4951 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004952#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004953 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004954#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004955#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 static int busy = FALSE;
4957
4958 /* May retry getting characters after an event was handled. */
4959# define MAY_LOOP
4960
4961# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4962 /* Remember at what time we started, so that we know how much longer we
4963 * should wait after being interrupted. */
4964# define USE_START_TV
4965 struct timeval start_tv;
4966
4967 if (msec > 0 && (
4968# ifdef FEAT_XCLIPBOARD
4969 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004970# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 ||
4972# endif
4973# endif
4974# ifdef USE_XSMP
4975 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004976# ifdef FEAT_MZSCHEME
4977 ||
4978# endif
4979# endif
4980# ifdef FEAT_MZSCHEME
4981 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982# endif
4983 ))
4984 gettimeofday(&start_tv, NULL);
4985# endif
4986
4987 /* Handle being called recursively. This may happen for the session
4988 * manager stuff, it may save the file, which does a breakcheck. */
4989 if (busy)
4990 return 0;
4991#endif
4992
4993#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004994 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995#endif
4996 {
4997#ifdef MAY_LOOP
4998 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004999# ifdef FEAT_MZSCHEME
5000 int mzquantum_used = FALSE;
5001# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002#endif
5003#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005004 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005 int nfd;
5006# ifdef FEAT_XCLIPBOARD
5007 int xterm_idx = -1;
5008# endif
5009# ifdef FEAT_MOUSE_GPM
5010 int gpm_idx = -1;
5011# endif
5012# ifdef USE_XSMP
5013 int xsmp_idx = -1;
5014# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005015# ifdef FEAT_NETBEANS_INTG
5016 int nb_idx = -1;
5017# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005018 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005020# ifdef FEAT_MZSCHEME
5021 mzvim_check_threads();
5022 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5023 {
5024 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5025 mzquantum_used = TRUE;
5026 }
5027# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 fds[0].fd = fd;
5029 fds[0].events = POLLIN;
5030 nfd = 1;
5031
5032# ifdef FEAT_SNIFF
5033# define SNIFF_IDX 1
5034 if (want_sniff_request)
5035 {
5036 fds[SNIFF_IDX].fd = fd_from_sniff;
5037 fds[SNIFF_IDX].events = POLLIN;
5038 nfd++;
5039 }
5040# endif
5041# ifdef FEAT_XCLIPBOARD
5042 if (xterm_Shell != (Widget)0)
5043 {
5044 xterm_idx = nfd;
5045 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5046 fds[nfd].events = POLLIN;
5047 nfd++;
5048 }
5049# endif
5050# ifdef FEAT_MOUSE_GPM
5051 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5052 {
5053 gpm_idx = nfd;
5054 fds[nfd].fd = gpm_fd;
5055 fds[nfd].events = POLLIN;
5056 nfd++;
5057 }
5058# endif
5059# ifdef USE_XSMP
5060 if (xsmp_icefd != -1)
5061 {
5062 xsmp_idx = nfd;
5063 fds[nfd].fd = xsmp_icefd;
5064 fds[nfd].events = POLLIN;
5065 nfd++;
5066 }
5067# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005068#ifdef FEAT_NETBEANS_INTG
5069 if (nb_fd != -1)
5070 {
5071 nb_idx = nfd;
5072 fds[nfd].fd = nb_fd;
5073 fds[nfd].events = POLLIN;
5074 nfd++;
5075 }
5076#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005078 ret = poll(fds, nfd, towait);
5079# ifdef FEAT_MZSCHEME
5080 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005081 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005082 finished = FALSE;
5083# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084
5085# ifdef FEAT_SNIFF
5086 if (ret < 0)
5087 sniff_disconnect(1);
5088 else if (want_sniff_request)
5089 {
5090 if (fds[SNIFF_IDX].revents & POLLHUP)
5091 sniff_disconnect(1);
5092 if (fds[SNIFF_IDX].revents & POLLIN)
5093 sniff_request_waiting = 1;
5094 }
5095# endif
5096# ifdef FEAT_XCLIPBOARD
5097 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5098 {
5099 xterm_update(); /* Maybe we should hand out clipboard */
5100 if (--ret == 0 && !input_available())
5101 /* Try again */
5102 finished = FALSE;
5103 }
5104# endif
5105# ifdef FEAT_MOUSE_GPM
5106 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5107 {
5108 *check_for_gpm = 1;
5109 }
5110# endif
5111# ifdef USE_XSMP
5112 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5113 {
5114 if (fds[xsmp_idx].revents & POLLIN)
5115 {
5116 busy = TRUE;
5117 xsmp_handle_requests();
5118 busy = FALSE;
5119 }
5120 else if (fds[xsmp_idx].revents & POLLHUP)
5121 {
5122 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005123 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124 xsmp_close();
5125 }
5126 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005127 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128 }
5129# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005130#ifdef FEAT_NETBEANS_INTG
5131 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5132 {
5133 netbeans_read();
5134 --ret;
5135 }
5136#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137
5138
5139#else /* HAVE_SELECT */
5140
5141 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005142 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 fd_set rfds, efds;
5144 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005145 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005147# ifdef FEAT_MZSCHEME
5148 mzvim_check_threads();
5149 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5150 {
5151 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5152 mzquantum_used = TRUE;
5153 }
5154# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155# ifdef __EMX__
5156 /* don't check for incoming chars if not in raw mode, because select()
5157 * always returns TRUE then (in some version of emx.dll) */
5158 if (curr_tmode != TMODE_RAW)
5159 return 0;
5160# endif
5161
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005162 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005164 tv.tv_sec = towait / 1000;
5165 tv.tv_usec = (towait % 1000) * (1000000/1000);
5166 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005167 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005168 else
5169 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170
5171 /*
5172 * Select on ready for reading and exceptional condition (end of file).
5173 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005174select_eintr:
5175 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 FD_ZERO(&efds);
5177 FD_SET(fd, &rfds);
5178# if !defined(__QNX__) && !defined(__CYGWIN32__)
5179 /* For QNX select() always returns 1 if this is set. Why? */
5180 FD_SET(fd, &efds);
5181# endif
5182 maxfd = fd;
5183
5184# ifdef FEAT_SNIFF
5185 if (want_sniff_request)
5186 {
5187 FD_SET(fd_from_sniff, &rfds);
5188 FD_SET(fd_from_sniff, &efds);
5189 if (maxfd < fd_from_sniff)
5190 maxfd = fd_from_sniff;
5191 }
5192# endif
5193# ifdef FEAT_XCLIPBOARD
5194 if (xterm_Shell != (Widget)0)
5195 {
5196 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5197 if (maxfd < ConnectionNumber(xterm_dpy))
5198 maxfd = ConnectionNumber(xterm_dpy);
5199 }
5200# endif
5201# ifdef FEAT_MOUSE_GPM
5202 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5203 {
5204 FD_SET(gpm_fd, &rfds);
5205 FD_SET(gpm_fd, &efds);
5206 if (maxfd < gpm_fd)
5207 maxfd = gpm_fd;
5208 }
5209# endif
5210# ifdef USE_XSMP
5211 if (xsmp_icefd != -1)
5212 {
5213 FD_SET(xsmp_icefd, &rfds);
5214 FD_SET(xsmp_icefd, &efds);
5215 if (maxfd < xsmp_icefd)
5216 maxfd = xsmp_icefd;
5217 }
5218# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005219#ifdef FEAT_NETBEANS_INTG
5220 if (nb_fd != -1)
5221 {
5222 FD_SET(nb_fd, &rfds);
5223 if (maxfd < nb_fd)
5224 maxfd = nb_fd;
5225 }
5226#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227
5228# ifdef OLD_VMS
5229 /* Old VMS as v6.2 and older have broken select(). It waits more than
5230 * required. Should not be used */
5231 ret = 0;
5232# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005233 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5234# endif
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005235# ifdef EINTR
5236 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005237 {
5238 /* Check whether window has been resized, EINTR may be caused by
5239 * SIGWINCH. */
5240 if (do_resize)
5241 handle_resize();
5242
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005243 /* Interrupted by a signal, need to try again. We ignore msec
5244 * here, because we do want to check even after a timeout if
5245 * characters are available. Needed for reading output of an
5246 * external command after the process has finished. */
5247 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005248 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005249# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005250# ifdef __TANDEM
5251 if (ret == -1 && errno == ENOTSUP)
5252 {
5253 FD_ZERO(&rfds);
5254 FD_ZERO(&efds);
5255 ret = 0;
5256 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005257# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005258# ifdef FEAT_MZSCHEME
5259 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005260 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005261 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262# endif
5263
5264# ifdef FEAT_SNIFF
5265 if (ret < 0 )
5266 sniff_disconnect(1);
5267 else if (ret > 0 && want_sniff_request)
5268 {
5269 if (FD_ISSET(fd_from_sniff, &efds))
5270 sniff_disconnect(1);
5271 if (FD_ISSET(fd_from_sniff, &rfds))
5272 sniff_request_waiting = 1;
5273 }
5274# endif
5275# ifdef FEAT_XCLIPBOARD
5276 if (ret > 0 && xterm_Shell != (Widget)0
5277 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5278 {
5279 xterm_update(); /* Maybe we should hand out clipboard */
5280 /* continue looping when we only got the X event and the input
5281 * buffer is empty */
5282 if (--ret == 0 && !input_available())
5283 {
5284 /* Try again */
5285 finished = FALSE;
5286 }
5287 }
5288# endif
5289# ifdef FEAT_MOUSE_GPM
5290 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5291 {
5292 if (FD_ISSET(gpm_fd, &efds))
5293 gpm_close();
5294 else if (FD_ISSET(gpm_fd, &rfds))
5295 *check_for_gpm = 1;
5296 }
5297# endif
5298# ifdef USE_XSMP
5299 if (ret > 0 && xsmp_icefd != -1)
5300 {
5301 if (FD_ISSET(xsmp_icefd, &efds))
5302 {
5303 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005304 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305 xsmp_close();
5306 if (--ret == 0)
5307 finished = FALSE; /* keep going if event was only one */
5308 }
5309 else if (FD_ISSET(xsmp_icefd, &rfds))
5310 {
5311 busy = TRUE;
5312 xsmp_handle_requests();
5313 busy = FALSE;
5314 if (--ret == 0)
5315 finished = FALSE; /* keep going if event was only one */
5316 }
5317 }
5318# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005319#ifdef FEAT_NETBEANS_INTG
5320 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5321 {
5322 netbeans_read();
5323 --ret;
5324 }
5325#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326
5327#endif /* HAVE_SELECT */
5328
5329#ifdef MAY_LOOP
5330 if (finished || msec == 0)
5331 break;
5332
5333 /* We're going to loop around again, find out for how long */
5334 if (msec > 0)
5335 {
5336# ifdef USE_START_TV
5337 struct timeval mtv;
5338
5339 /* Compute remaining wait time. */
5340 gettimeofday(&mtv, NULL);
5341 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5342 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5343# else
5344 /* Guess we got interrupted halfway. */
5345 msec = msec / 2;
5346# endif
5347 if (msec <= 0)
5348 break; /* waited long enough */
5349 }
5350#endif
5351 }
5352
5353 return (ret > 0);
5354}
5355
5356#ifndef VMS
5357
5358#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005360 * Expand a path into all matching files and/or directories. Handles "*",
5361 * "?", "[a-z]", "**", etc.
5362 * "path" has backslashes before chars that are not to be expanded.
5363 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 */
5365 int
5366mch_expandpath(gap, path, flags)
5367 garray_T *gap;
5368 char_u *path;
5369 int flags; /* EW_* flags */
5370{
Bram Moolenaar02743632005-07-25 20:42:36 +00005371 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372}
5373#endif
5374
5375/*
5376 * mch_expand_wildcards() - this code does wild-card pattern matching using
5377 * the shell
5378 *
5379 * return OK for success, FAIL for error (you may lose some memory) and put
5380 * an error message in *file.
5381 *
5382 * num_pat is number of input patterns
5383 * pat is array of pointers to input patterns
5384 * num_file is pointer to number of matched file names
5385 * file is pointer to array of pointers to matched file names
5386 */
5387
5388#ifndef SEEK_SET
5389# define SEEK_SET 0
5390#endif
5391#ifndef SEEK_END
5392# define SEEK_END 2
5393#endif
5394
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005395#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005396
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397 int
5398mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5399 int num_pat;
5400 char_u **pat;
5401 int *num_file;
5402 char_u ***file;
5403 int flags; /* EW_* flags */
5404{
5405 int i;
5406 size_t len;
5407 char_u *p;
5408 int dir;
5409#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005410 /*
5411 * This is the OS/2 implementation.
5412 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413# define EXPL_ALLOC_INC 16
5414 char_u **expl_files;
5415 size_t files_alloced, files_free;
5416 char_u *buf;
5417 int has_wildcard;
5418
5419 *num_file = 0; /* default: no files found */
5420 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5421 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5422 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5423 if (*file == NULL)
5424 return FAIL;
5425
5426 for (; num_pat > 0; num_pat--, pat++)
5427 {
5428 expl_files = NULL;
5429 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5430 /* expand environment var or home dir */
5431 buf = expand_env_save(*pat);
5432 else
5433 buf = vim_strsave(*pat);
5434 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005435 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005436 if (has_wildcard) /* yes, so expand them */
5437 expl_files = (char_u **)_fnexplode(buf);
5438
5439 /*
5440 * return value of buf if no wildcards left,
5441 * OR if no match AND EW_NOTFOUND is set.
5442 */
5443 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5444 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5445 { /* simply save the current contents of *buf */
5446 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5447 if (expl_files != NULL)
5448 {
5449 expl_files[0] = vim_strsave(buf);
5450 expl_files[1] = NULL;
5451 }
5452 }
5453 vim_free(buf);
5454
5455 /*
5456 * Count number of names resulting from expansion,
5457 * At the same time add a backslash to the end of names that happen to
5458 * be directories, and replace slashes with backslashes.
5459 */
5460 if (expl_files)
5461 {
5462 for (i = 0; (p = expl_files[i]) != NULL; i++)
5463 {
5464 dir = mch_isdir(p);
5465 /* If we don't want dirs and this is one, skip it */
5466 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5467 continue;
5468
Bram Moolenaara2031822006-03-07 22:29:51 +00005469 /* Skip files that are not executable if we check for that. */
5470 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5471 continue;
5472
Bram Moolenaar071d4272004-06-13 20:20:40 +00005473 if (--files_free == 0)
5474 {
5475 /* need more room in table of pointers */
5476 files_alloced += EXPL_ALLOC_INC;
5477 *file = (char_u **)vim_realloc(*file,
5478 sizeof(char_u **) * files_alloced);
5479 if (*file == NULL)
5480 {
5481 EMSG(_(e_outofmem));
5482 *num_file = 0;
5483 return FAIL;
5484 }
5485 files_free = EXPL_ALLOC_INC;
5486 }
5487 slash_adjust(p);
5488 if (dir)
5489 {
5490 /* For a directory we add a '/', unless it's already
5491 * there. */
5492 len = STRLEN(p);
5493 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5494 {
5495 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005496 if (!after_pathsep((*file)[*num_file],
5497 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 {
5499 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005500 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501 }
5502 }
5503 }
5504 else
5505 {
5506 (*file)[*num_file] = vim_strsave(p);
5507 }
5508
5509 /*
5510 * Error message already given by either alloc or vim_strsave.
5511 * Should return FAIL, but returning OK works also.
5512 */
5513 if ((*file)[*num_file] == NULL)
5514 break;
5515 (*num_file)++;
5516 }
5517 _fnexplodefree((char **)expl_files);
5518 }
5519 }
5520 return OK;
5521
5522#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005523 /*
5524 * This is the non-OS/2 implementation (really Unix).
5525 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526 int j;
5527 char_u *tempname;
5528 char_u *command;
5529 FILE *fd;
5530 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005531#define STYLE_ECHO 0 /* use "echo", the default */
5532#define STYLE_GLOB 1 /* use "glob", for csh */
5533#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5534#define STYLE_PRINT 3 /* use "print -N", for zsh */
5535#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5536 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 int shell_style = STYLE_ECHO;
5538 int check_spaces;
5539 static int did_find_nul = FALSE;
5540 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005541 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005542 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544 *num_file = 0; /* default: no files found */
5545 *file = NULL;
5546
5547 /*
5548 * If there are no wildcards, just copy the names to allocated memory.
5549 * Saves a lot of time, because we don't have to start a new shell.
5550 */
5551 if (!have_wildcard(num_pat, pat))
5552 return save_patterns(num_pat, pat, num_file, file);
5553
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005554# ifdef HAVE_SANDBOX
5555 /* Don't allow any shell command in the sandbox. */
5556 if (sandbox != 0 && check_secure())
5557 return FAIL;
5558# endif
5559
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 /*
5561 * Don't allow the use of backticks in secure and restricted mode.
5562 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005563 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564 for (i = 0; i < num_pat; ++i)
5565 if (vim_strchr(pat[i], '`') != NULL
5566 && (check_restricted() || check_secure()))
5567 return FAIL;
5568
5569 /*
5570 * get a name for the temp file
5571 */
5572 if ((tempname = vim_tempname('o')) == NULL)
5573 {
5574 EMSG(_(e_notmp));
5575 return FAIL;
5576 }
5577
5578 /*
5579 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005580 * file.
5581 * STYLE_BT: NL separated
5582 * If expanding `cmd` execute it directly.
5583 * STYLE_GLOB: NUL separated
5584 * If we use *csh, "glob" will work better than "echo".
5585 * STYLE_PRINT: NL or NUL separated
5586 * If we use *zsh, "print -N" will work better than "glob".
5587 * STYLE_VIMGLOB: NL separated
5588 * If we use *sh*, we define "vimglob()".
5589 * STYLE_ECHO: space separated.
5590 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 */
5592 if (num_pat == 1 && *pat[0] == '`'
5593 && (len = STRLEN(pat[0])) > 2
5594 && *(pat[0] + len - 1) == '`')
5595 shell_style = STYLE_BT;
5596 else if ((len = STRLEN(p_sh)) >= 3)
5597 {
5598 if (STRCMP(p_sh + len - 3, "csh") == 0)
5599 shell_style = STYLE_GLOB;
5600 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5601 shell_style = STYLE_PRINT;
5602 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005603 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5604 "sh") != NULL)
5605 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606
Bram Moolenaarc7247912008-01-13 12:54:11 +00005607 /* Compute the length of the command. We need 2 extra bytes: for the
5608 * optional '&' and for the NUL.
5609 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005611 if (shell_style == STYLE_VIMGLOB)
5612 len += STRLEN(sh_vimglob_func);
5613
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005614 for (i = 0; i < num_pat; ++i)
5615 {
5616 /* Count the length of the patterns in the same way as they are put in
5617 * "command" below. */
5618#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005620#else
5621 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005622 for (j = 0; pat[i][j] != NUL; ++j)
5623 {
5624 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5625 ++len; /* may add a backslash */
5626 ++len;
5627 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005628#endif
5629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630 command = alloc(len);
5631 if (command == NULL)
5632 {
5633 /* out of memory */
5634 vim_free(tempname);
5635 return FAIL;
5636 }
5637
5638 /*
5639 * Build the shell command:
5640 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5641 * recognizes this).
5642 * - Add the shell command to print the expanded names.
5643 * - Add the temp file name.
5644 * - Add the file name patterns.
5645 */
5646 if (shell_style == STYLE_BT)
5647 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005648 /* change `command; command& ` to (command; command ) */
5649 STRCPY(command, "(");
5650 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005652 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 while (p > command && vim_iswhite(*p))
5654 --p;
5655 if (*p == '&') /* remove trailing '&' */
5656 {
5657 ampersent = TRUE;
5658 *p = ' ';
5659 }
5660 STRCAT(command, ">");
5661 }
5662 else
5663 {
5664 if (flags & EW_NOTFOUND)
5665 STRCPY(command, "set nonomatch; ");
5666 else
5667 STRCPY(command, "unset nonomatch; ");
5668 if (shell_style == STYLE_GLOB)
5669 STRCAT(command, "glob >");
5670 else if (shell_style == STYLE_PRINT)
5671 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005672 else if (shell_style == STYLE_VIMGLOB)
5673 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674 else
5675 STRCAT(command, "echo >");
5676 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005677
Bram Moolenaar071d4272004-06-13 20:20:40 +00005678 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005679
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 if (shell_style != STYLE_BT)
5681 for (i = 0; i < num_pat; ++i)
5682 {
5683 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005684 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005685 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686#ifdef USE_SYSTEM
5687 STRCAT(command, " \"");
5688 STRCAT(command, pat[i]);
5689 STRCAT(command, "\"");
5690#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005691 int intick = FALSE;
5692
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 p = command + STRLEN(command);
5694 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005695 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005696 {
5697 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005698 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005699 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5700 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005701 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005702 * backslash inside backticks, before a special character
5703 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005704 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005705 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5706 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005707 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005708 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005709 }
5710 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005711 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005712 /* Put a backslash before a special character, but not
5713 * when inside ``. */
5714 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005715
5716 /* Copy one character. */
5717 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 *p = NUL;
5720#endif
5721 }
5722 if (flags & EW_SILENT)
5723 show_shell_mess = FALSE;
5724 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005725 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726
5727 /*
5728 * Using zsh -G: If a pattern has no matches, it is just deleted from
5729 * the argument list, otherwise zsh gives an error message and doesn't
5730 * expand any other pattern.
5731 */
5732 if (shell_style == STYLE_PRINT)
5733 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5734
5735 /*
5736 * If we use -f then shell variables set in .cshrc won't get expanded.
5737 * vi can do it, so we will too, but it is only necessary if there is a "$"
5738 * in one of the patterns, otherwise we can still use the fast option.
5739 */
5740 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5741 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5742
5743 /*
5744 * execute the shell command
5745 */
5746 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5747
5748 /* When running in the background, give it some time to create the temp
5749 * file, but don't wait for it to finish. */
5750 if (ampersent)
5751 mch_delay(10L, TRUE);
5752
5753 extra_shell_arg = NULL; /* cleanup */
5754 show_shell_mess = TRUE;
5755 vim_free(command);
5756
Bram Moolenaarc7247912008-01-13 12:54:11 +00005757 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 {
5759 mch_remove(tempname);
5760 vim_free(tempname);
5761 /*
5762 * With interactive completion, the error message is not printed.
5763 * However with USE_SYSTEM, I don't know how to turn off error messages
5764 * from the shell, so screen may still get messed up -- webb.
5765 */
5766#ifndef USE_SYSTEM
5767 if (!(flags & EW_SILENT))
5768#endif
5769 {
5770 redraw_later_clear(); /* probably messed up screen */
5771 msg_putchar('\n'); /* clear bottom line quickly */
5772 cmdline_row = Rows - 1; /* continue on last line */
5773#ifdef USE_SYSTEM
5774 if (!(flags & EW_SILENT))
5775#endif
5776 {
5777 MSG(_(e_wildexpand));
5778 msg_start(); /* don't overwrite this message */
5779 }
5780 }
5781 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5782 * EW_NOTFOUND is given */
5783 if (shell_style == STYLE_BT)
5784 return FAIL;
5785 goto notfound;
5786 }
5787
5788 /*
5789 * read the names from the file into memory
5790 */
5791 fd = fopen((char *)tempname, READBIN);
5792 if (fd == NULL)
5793 {
5794 /* Something went wrong, perhaps a file name with a special char. */
5795 if (!(flags & EW_SILENT))
5796 {
5797 MSG(_(e_wildexpand));
5798 msg_start(); /* don't overwrite this message */
5799 }
5800 vim_free(tempname);
5801 goto notfound;
5802 }
5803 fseek(fd, 0L, SEEK_END);
5804 len = ftell(fd); /* get size of temp file */
5805 fseek(fd, 0L, SEEK_SET);
5806 buffer = alloc(len + 1);
5807 if (buffer == NULL)
5808 {
5809 /* out of memory */
5810 mch_remove(tempname);
5811 vim_free(tempname);
5812 fclose(fd);
5813 return FAIL;
5814 }
5815 i = fread((char *)buffer, 1, len, fd);
5816 fclose(fd);
5817 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005818 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 {
5820 /* unexpected read error */
5821 EMSG2(_(e_notread), tempname);
5822 vim_free(tempname);
5823 vim_free(buffer);
5824 return FAIL;
5825 }
5826 vim_free(tempname);
5827
Bram Moolenaarc7247912008-01-13 12:54:11 +00005828# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5830 p = buffer;
5831 for (i = 0; i < len; ++i)
5832 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5833 *p++ = buffer[i];
5834 len = p - buffer;
5835# endif
5836
5837
5838 /* file names are separated with Space */
5839 if (shell_style == STYLE_ECHO)
5840 {
5841 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5842 p = buffer;
5843 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5844 {
5845 while (*p != ' ' && *p != '\n')
5846 ++p;
5847 p = skipwhite(p); /* skip to next entry */
5848 }
5849 }
5850 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005851 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852 {
5853 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5854 p = buffer;
5855 for (i = 0; *p != NUL; ++i) /* count number of entries */
5856 {
5857 while (*p != '\n' && *p != NUL)
5858 ++p;
5859 if (*p != NUL)
5860 ++p;
5861 p = skipwhite(p); /* skip leading white space */
5862 }
5863 }
5864 /* file names are separated with NUL */
5865 else
5866 {
5867 /*
5868 * Some versions of zsh use spaces instead of NULs to separate
5869 * results. Only do this when there is no NUL before the end of the
5870 * buffer, otherwise we would never be able to use file names with
5871 * embedded spaces when zsh does use NULs.
5872 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5873 * don't check for spaces again.
5874 */
5875 check_spaces = FALSE;
5876 if (shell_style == STYLE_PRINT && !did_find_nul)
5877 {
5878 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02005879 buffer[len] = NUL;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005880 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 did_find_nul = TRUE;
5882 else
5883 check_spaces = TRUE;
5884 }
5885
5886 /*
5887 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5888 * already is one, for STYLE_GLOB it needs to be added.
5889 */
5890 if (len && buffer[len - 1] == NUL)
5891 --len;
5892 else
5893 buffer[len] = NUL;
5894 i = 0;
5895 for (p = buffer; p < buffer + len; ++p)
5896 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5897 {
5898 ++i;
5899 *p = NUL;
5900 }
5901 if (len)
5902 ++i; /* count last entry */
5903 }
5904 if (i == 0)
5905 {
5906 /*
5907 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5908 * /bin/sh will happily expand it to nothing rather than returning an
5909 * error; and hey, it's good to check anyway -- webb.
5910 */
5911 vim_free(buffer);
5912 goto notfound;
5913 }
5914 *num_file = i;
5915 *file = (char_u **)alloc(sizeof(char_u *) * i);
5916 if (*file == NULL)
5917 {
5918 /* out of memory */
5919 vim_free(buffer);
5920 return FAIL;
5921 }
5922
5923 /*
5924 * Isolate the individual file names.
5925 */
5926 p = buffer;
5927 for (i = 0; i < *num_file; ++i)
5928 {
5929 (*file)[i] = p;
5930 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005931 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5932 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005934 while (!(shell_style == STYLE_ECHO && *p == ' ')
5935 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 ++p;
5937 if (p == buffer + len) /* last entry */
5938 *p = NUL;
5939 else
5940 {
5941 *p++ = NUL;
5942 p = skipwhite(p); /* skip to next entry */
5943 }
5944 }
5945 else /* NUL separates */
5946 {
5947 while (*p && p < buffer + len) /* skip entry */
5948 ++p;
5949 ++p; /* skip NUL */
5950 }
5951 }
5952
5953 /*
5954 * Move the file names to allocated memory.
5955 */
5956 for (j = 0, i = 0; i < *num_file; ++i)
5957 {
5958 /* Require the files to exist. Helps when using /bin/sh */
5959 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5960 continue;
5961
5962 /* check if this entry should be included */
5963 dir = (mch_isdir((*file)[i]));
5964 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5965 continue;
5966
Bram Moolenaara2031822006-03-07 22:29:51 +00005967 /* Skip files that are not executable if we check for that. */
5968 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5969 continue;
5970
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5972 if (p)
5973 {
5974 STRCPY(p, (*file)[i]);
5975 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005976 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 (*file)[j++] = p;
5978 }
5979 }
5980 vim_free(buffer);
5981 *num_file = j;
5982
5983 if (*num_file == 0) /* rejected all entries */
5984 {
5985 vim_free(*file);
5986 *file = NULL;
5987 goto notfound;
5988 }
5989
5990 return OK;
5991
5992notfound:
5993 if (flags & EW_NOTFOUND)
5994 return save_patterns(num_pat, pat, num_file, file);
5995 return FAIL;
5996
5997#endif /* __EMX__ */
5998}
5999
6000#endif /* VMS */
6001
6002#ifndef __EMX__
6003 static int
6004save_patterns(num_pat, pat, num_file, file)
6005 int num_pat;
6006 char_u **pat;
6007 int *num_file;
6008 char_u ***file;
6009{
6010 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006011 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012
6013 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6014 if (*file == NULL)
6015 return FAIL;
6016 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006017 {
6018 s = vim_strsave(pat[i]);
6019 if (s != NULL)
6020 /* Be compatible with expand_filename(): halve the number of
6021 * backslashes. */
6022 backslash_halve(s);
6023 (*file)[i] = s;
6024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025 *num_file = num_pat;
6026 return OK;
6027}
6028#endif
6029
6030
6031/*
6032 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6033 * expand.
6034 */
6035 int
6036mch_has_exp_wildcard(p)
6037 char_u *p;
6038{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006039 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 {
6041#ifndef OS2
6042 if (*p == '\\' && p[1] != NUL)
6043 ++p;
6044 else
6045#endif
6046 if (vim_strchr((char_u *)
6047#ifdef VMS
6048 "*?%"
6049#else
6050# ifdef OS2
6051 "*?"
6052# else
6053 "*?[{'"
6054# endif
6055#endif
6056 , *p) != NULL)
6057 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 }
6059 return FALSE;
6060}
6061
6062/*
6063 * Return TRUE if the string "p" contains a wildcard.
6064 * Don't recognize '~' at the end as a wildcard.
6065 */
6066 int
6067mch_has_wildcard(p)
6068 char_u *p;
6069{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006070 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 {
6072#ifndef OS2
6073 if (*p == '\\' && p[1] != NUL)
6074 ++p;
6075 else
6076#endif
6077 if (vim_strchr((char_u *)
6078#ifdef VMS
6079 "*?%$"
6080#else
6081# ifdef OS2
6082# ifdef VIM_BACKTICK
6083 "*?$`"
6084# else
6085 "*?$"
6086# endif
6087# else
6088 "*?[{`'$"
6089# endif
6090#endif
6091 , *p) != NULL
6092 || (*p == '~' && p[1] != NUL))
6093 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 }
6095 return FALSE;
6096}
6097
6098#ifndef __EMX__
6099 static int
6100have_wildcard(num, file)
6101 int num;
6102 char_u **file;
6103{
6104 int i;
6105
6106 for (i = 0; i < num; i++)
6107 if (mch_has_wildcard(file[i]))
6108 return 1;
6109 return 0;
6110}
6111
6112 static int
6113have_dollars(num, file)
6114 int num;
6115 char_u **file;
6116{
6117 int i;
6118
6119 for (i = 0; i < num; i++)
6120 if (vim_strchr(file[i], '$') != NULL)
6121 return TRUE;
6122 return FALSE;
6123}
6124#endif /* ifndef __EMX__ */
6125
6126#ifndef HAVE_RENAME
6127/*
6128 * Scaled-down version of rename(), which is missing in Xenix.
6129 * This version can only move regular files and will fail if the
6130 * destination exists.
6131 */
6132 int
6133mch_rename(src, dest)
6134 const char *src, *dest;
6135{
6136 struct stat st;
6137
6138 if (stat(dest, &st) >= 0) /* fail if destination exists */
6139 return -1;
6140 if (link(src, dest) != 0) /* link file to new name */
6141 return -1;
6142 if (mch_remove(src) == 0) /* delete link to old name */
6143 return 0;
6144 return -1;
6145}
6146#endif /* !HAVE_RENAME */
6147
6148#ifdef FEAT_MOUSE_GPM
6149/*
6150 * Initializes connection with gpm (if it isn't already opened)
6151 * Return 1 if succeeded (or connection already opened), 0 if failed
6152 */
6153 static int
6154gpm_open()
6155{
6156 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6157
6158 if (!gpm_flag)
6159 {
6160 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6161 gpm_connect.defaultMask = ~GPM_HARD;
6162 /* Default handling for mouse move*/
6163 gpm_connect.minMod = 0; /* Handle any modifier keys */
6164 gpm_connect.maxMod = 0xffff;
6165 if (Gpm_Open(&gpm_connect, 0) > 0)
6166 {
6167 /* gpm library tries to handling TSTP causes
6168 * problems. Anyways, we close connection to Gpm whenever
6169 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006170 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006172# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006174# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 return 1; /* succeed */
6176 }
6177 if (gpm_fd == -2)
6178 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6179 return 0;
6180 }
6181 return 1; /* already open */
6182}
6183
6184/*
6185 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 */
6187 static void
6188gpm_close()
6189{
6190 if (gpm_flag && gpm_fd >= 0) /* if Open */
6191 Gpm_Close();
6192}
6193
6194/* Reads gpm event and adds special keys to input buf. Returns length of
6195 * generated key sequence.
6196 * This function is made after gui_send_mouse_event
6197 */
6198 static int
6199mch_gpm_process()
6200{
6201 int button;
6202 static Gpm_Event gpm_event;
6203 char_u string[6];
6204 int_u vim_modifiers;
6205 int row,col;
6206 unsigned char buttons_mask;
6207 unsigned char gpm_modifiers;
6208 static unsigned char old_buttons = 0;
6209
6210 Gpm_GetEvent(&gpm_event);
6211
6212#ifdef FEAT_GUI
6213 /* Don't put events in the input queue now. */
6214 if (hold_gui_events)
6215 return 0;
6216#endif
6217
6218 row = gpm_event.y - 1;
6219 col = gpm_event.x - 1;
6220
6221 string[0] = ESC; /* Our termcode */
6222 string[1] = 'M';
6223 string[2] = 'G';
6224 switch (GPM_BARE_EVENTS(gpm_event.type))
6225 {
6226 case GPM_DRAG:
6227 string[3] = MOUSE_DRAG;
6228 break;
6229 case GPM_DOWN:
6230 buttons_mask = gpm_event.buttons & ~old_buttons;
6231 old_buttons = gpm_event.buttons;
6232 switch (buttons_mask)
6233 {
6234 case GPM_B_LEFT:
6235 button = MOUSE_LEFT;
6236 break;
6237 case GPM_B_MIDDLE:
6238 button = MOUSE_MIDDLE;
6239 break;
6240 case GPM_B_RIGHT:
6241 button = MOUSE_RIGHT;
6242 break;
6243 default:
6244 return 0;
6245 /*Don't know what to do. Can more than one button be
6246 * reported in one event? */
6247 }
6248 string[3] = (char_u)(button | 0x20);
6249 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6250 break;
6251 case GPM_UP:
6252 string[3] = MOUSE_RELEASE;
6253 old_buttons &= ~gpm_event.buttons;
6254 break;
6255 default:
6256 return 0;
6257 }
6258 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6259 gpm_modifiers = gpm_event.modifiers;
6260 vim_modifiers = 0x0;
6261 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6262 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6263 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6264 */
6265 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6266 vim_modifiers |= MOUSE_SHIFT;
6267
6268 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6269 vim_modifiers |= MOUSE_CTRL;
6270 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6271 vim_modifiers |= MOUSE_ALT;
6272 string[3] |= vim_modifiers;
6273 string[4] = (char_u)(col + ' ' + 1);
6274 string[5] = (char_u)(row + ' ' + 1);
6275 add_to_input_buf(string, 6);
6276 return 6;
6277}
6278#endif /* FEAT_MOUSE_GPM */
6279
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006280#ifdef FEAT_SYSMOUSE
6281/*
6282 * Initialize connection with sysmouse.
6283 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6284 * output, any sysmouse output than will be processed via sig_sysmouse().
6285 * Return OK if succeeded, FAIL if failed.
6286 */
6287 static int
6288sysmouse_open()
6289{
6290 struct mouse_info mouse;
6291
6292 mouse.operation = MOUSE_MODE;
6293 mouse.u.mode.mode = 0;
6294 mouse.u.mode.signal = SIGUSR2;
6295 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6296 {
6297 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6298 mouse.operation = MOUSE_SHOW;
6299 ioctl(1, CONS_MOUSECTL, &mouse);
6300 return OK;
6301 }
6302 return FAIL;
6303}
6304
6305/*
6306 * Stop processing SIGUSR2 signals, and also make sure that
6307 * virtual console do not send us any sysmouse related signal.
6308 */
6309 static void
6310sysmouse_close()
6311{
6312 struct mouse_info mouse;
6313
6314 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6315 mouse.operation = MOUSE_MODE;
6316 mouse.u.mode.mode = 0;
6317 mouse.u.mode.signal = 0;
6318 ioctl(1, CONS_MOUSECTL, &mouse);
6319}
6320
6321/*
6322 * Gets info from sysmouse and adds special keys to input buf.
6323 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006324 static RETSIGTYPE
6325sig_sysmouse SIGDEFARG(sigarg)
6326{
6327 struct mouse_info mouse;
6328 struct video_info video;
6329 char_u string[6];
6330 int row, col;
6331 int button;
6332 int buttons;
6333 static int oldbuttons = 0;
6334
6335#ifdef FEAT_GUI
6336 /* Don't put events in the input queue now. */
6337 if (hold_gui_events)
6338 return;
6339#endif
6340
6341 mouse.operation = MOUSE_GETINFO;
6342 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6343 && ioctl(1, FBIO_MODEINFO, &video) != -1
6344 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6345 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6346 {
6347 row = mouse.u.data.y / video.vi_cheight;
6348 col = mouse.u.data.x / video.vi_cwidth;
6349 buttons = mouse.u.data.buttons;
6350 string[0] = ESC; /* Our termcode */
6351 string[1] = 'M';
6352 string[2] = 'S';
6353 if (oldbuttons == buttons && buttons != 0)
6354 {
6355 button = MOUSE_DRAG;
6356 }
6357 else
6358 {
6359 switch (buttons)
6360 {
6361 case 0:
6362 button = MOUSE_RELEASE;
6363 break;
6364 case 1:
6365 button = MOUSE_LEFT;
6366 break;
6367 case 2:
6368 button = MOUSE_MIDDLE;
6369 break;
6370 case 4:
6371 button = MOUSE_RIGHT;
6372 break;
6373 default:
6374 return;
6375 }
6376 oldbuttons = buttons;
6377 }
6378 string[3] = (char_u)(button);
6379 string[4] = (char_u)(col + ' ' + 1);
6380 string[5] = (char_u)(row + ' ' + 1);
6381 add_to_input_buf(string, 6);
6382 }
6383 return;
6384}
6385#endif /* FEAT_SYSMOUSE */
6386
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387#if defined(FEAT_LIBCALL) || defined(PROTO)
6388typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6389typedef char_u * (*INTPROCSTR)__ARGS((int));
6390typedef int (*STRPROCINT)__ARGS((char_u *));
6391typedef int (*INTPROCINT)__ARGS((int));
6392
6393/*
6394 * Call a DLL routine which takes either a string or int param
6395 * and returns an allocated string.
6396 */
6397 int
6398mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6399 char_u *libname;
6400 char_u *funcname;
6401 char_u *argstring; /* NULL when using a argint */
6402 int argint;
6403 char_u **string_result;/* NULL when using number_result */
6404 int *number_result;
6405{
6406# if defined(USE_DLOPEN)
6407 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006408 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409# else
6410 shl_t hinstLib;
6411# endif
6412 STRPROCSTR ProcAdd;
6413 INTPROCSTR ProcAddI;
6414 char_u *retval_str = NULL;
6415 int retval_int = 0;
6416 int success = FALSE;
6417
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006418 /*
6419 * Get a handle to the DLL module.
6420 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006422 /* First clear any error, it's not cleared by the dlopen() call. */
6423 (void)dlerror();
6424
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 hinstLib = dlopen((char *)libname, RTLD_LAZY
6426# ifdef RTLD_LOCAL
6427 | RTLD_LOCAL
6428# endif
6429 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006430 if (hinstLib == NULL)
6431 {
6432 /* "dlerr" must be used before dlclose() */
6433 dlerr = (char *)dlerror();
6434 if (dlerr != NULL)
6435 EMSG2(_("dlerror = \"%s\""), dlerr);
6436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437# else
6438 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6439# endif
6440
6441 /* If the handle is valid, try to get the function address. */
6442 if (hinstLib != NULL)
6443 {
6444# ifdef HAVE_SETJMP_H
6445 /*
6446 * Catch a crash when calling the library function. For example when
6447 * using a number where a string pointer is expected.
6448 */
6449 mch_startjmp();
6450 if (SETJMP(lc_jump_env) != 0)
6451 {
6452 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006453# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006454 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006455# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 mch_didjmp();
6457 }
6458 else
6459# endif
6460 {
6461 retval_str = NULL;
6462 retval_int = 0;
6463
6464 if (argstring != NULL)
6465 {
6466# if defined(USE_DLOPEN)
6467 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006468 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469# else
6470 if (shl_findsym(&hinstLib, (const char *)funcname,
6471 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6472 ProcAdd = NULL;
6473# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006474 if ((success = (ProcAdd != NULL
6475# if defined(USE_DLOPEN)
6476 && dlerr == NULL
6477# endif
6478 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 {
6480 if (string_result == NULL)
6481 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6482 else
6483 retval_str = (ProcAdd)(argstring);
6484 }
6485 }
6486 else
6487 {
6488# if defined(USE_DLOPEN)
6489 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006490 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491# else
6492 if (shl_findsym(&hinstLib, (const char *)funcname,
6493 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6494 ProcAddI = NULL;
6495# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006496 if ((success = (ProcAddI != NULL
6497# if defined(USE_DLOPEN)
6498 && dlerr == NULL
6499# endif
6500 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 {
6502 if (string_result == NULL)
6503 retval_int = ((INTPROCINT)ProcAddI)(argint);
6504 else
6505 retval_str = (ProcAddI)(argint);
6506 }
6507 }
6508
6509 /* Save the string before we free the library. */
6510 /* Assume that a "1" or "-1" result is an illegal pointer. */
6511 if (string_result == NULL)
6512 *number_result = retval_int;
6513 else if (retval_str != NULL
6514 && retval_str != (char_u *)1
6515 && retval_str != (char_u *)-1)
6516 *string_result = vim_strsave(retval_str);
6517 }
6518
6519# ifdef HAVE_SETJMP_H
6520 mch_endjmp();
6521# ifdef SIGHASARG
6522 if (lc_signal != 0)
6523 {
6524 int i;
6525
6526 /* try to find the name of this signal */
6527 for (i = 0; signal_info[i].sig != -1; i++)
6528 if (lc_signal == signal_info[i].sig)
6529 break;
6530 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6531 }
6532# endif
6533# endif
6534
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006536 /* "dlerr" must be used before dlclose() */
6537 if (dlerr != NULL)
6538 EMSG2(_("dlerror = \"%s\""), dlerr);
6539
6540 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 (void)dlclose(hinstLib);
6542# else
6543 (void)shl_unload(hinstLib);
6544# endif
6545 }
6546
6547 if (!success)
6548 {
6549 EMSG2(_(e_libcall), funcname);
6550 return FAIL;
6551 }
6552
6553 return OK;
6554}
6555#endif
6556
6557#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6558static int xterm_trace = -1; /* default: disabled */
6559static int xterm_button;
6560
6561/*
6562 * Setup a dummy window for X selections in a terminal.
6563 */
6564 void
6565setup_term_clip()
6566{
6567 int z = 0;
6568 char *strp = "";
6569 Widget AppShell;
6570
6571 if (!x_connect_to_server())
6572 return;
6573
6574 open_app_context();
6575 if (app_context != NULL && xterm_Shell == (Widget)0)
6576 {
6577 int (*oldhandler)();
6578#if defined(HAVE_SETJMP_H)
6579 int (*oldIOhandler)();
6580#endif
6581# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6582 struct timeval start_tv;
6583
6584 if (p_verbose > 0)
6585 gettimeofday(&start_tv, NULL);
6586# endif
6587
6588 /* Ignore X errors while opening the display */
6589 oldhandler = XSetErrorHandler(x_error_check);
6590
6591#if defined(HAVE_SETJMP_H)
6592 /* Ignore X IO errors while opening the display */
6593 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6594 mch_startjmp();
6595 if (SETJMP(lc_jump_env) != 0)
6596 {
6597 mch_didjmp();
6598 xterm_dpy = NULL;
6599 }
6600 else
6601#endif
6602 {
6603 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6604 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6605#if defined(HAVE_SETJMP_H)
6606 mch_endjmp();
6607#endif
6608 }
6609
6610#if defined(HAVE_SETJMP_H)
6611 /* Now handle X IO errors normally. */
6612 (void)XSetIOErrorHandler(oldIOhandler);
6613#endif
6614 /* Now handle X errors normally. */
6615 (void)XSetErrorHandler(oldhandler);
6616
6617 if (xterm_dpy == NULL)
6618 {
6619 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006620 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 return;
6622 }
6623
6624 /* Catch terminating error of the X server connection. */
6625 (void)XSetIOErrorHandler(x_IOerror_handler);
6626
6627# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6628 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006629 {
6630 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006632 verbose_leave();
6633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634# endif
6635
6636 /* Create a Shell to make converters work. */
6637 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6638 applicationShellWidgetClass, xterm_dpy,
6639 NULL);
6640 if (AppShell == (Widget)0)
6641 return;
6642 xterm_Shell = XtVaCreatePopupShell("VIM",
6643 topLevelShellWidgetClass, AppShell,
6644 XtNmappedWhenManaged, 0,
6645 XtNwidth, 1,
6646 XtNheight, 1,
6647 NULL);
6648 if (xterm_Shell == (Widget)0)
6649 return;
6650
6651 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006652 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 if (x11_display == NULL)
6654 x11_display = xterm_dpy;
6655
6656 XtRealizeWidget(xterm_Shell);
6657 XSync(xterm_dpy, False);
6658 xterm_update();
6659 }
6660 if (xterm_Shell != (Widget)0)
6661 {
6662 clip_init(TRUE);
6663 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6664 x11_window = (Window)atol(strp);
6665 /* Check if $WINDOWID is valid. */
6666 if (test_x11_window(xterm_dpy) == FAIL)
6667 x11_window = 0;
6668 if (x11_window != 0)
6669 xterm_trace = 0;
6670 }
6671}
6672
6673 void
6674start_xterm_trace(button)
6675 int button;
6676{
6677 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6678 return;
6679 xterm_trace = 1;
6680 xterm_button = button;
6681 do_xterm_trace();
6682}
6683
6684
6685 void
6686stop_xterm_trace()
6687{
6688 if (xterm_trace < 0)
6689 return;
6690 xterm_trace = 0;
6691}
6692
6693/*
6694 * Query the xterm pointer and generate mouse termcodes if necessary
6695 * return TRUE if dragging is active, else FALSE
6696 */
6697 static int
6698do_xterm_trace()
6699{
6700 Window root, child;
6701 int root_x, root_y;
6702 int win_x, win_y;
6703 int row, col;
6704 int_u mask_return;
6705 char_u buf[50];
6706 char_u *strp;
6707 long got_hints;
6708 static char_u *mouse_code;
6709 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6710 static int prev_row = 0, prev_col = 0;
6711 static XSizeHints xterm_hints;
6712
6713 if (xterm_trace <= 0)
6714 return FALSE;
6715
6716 if (xterm_trace == 1)
6717 {
6718 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006719 * have changed recently. */
6720 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6721 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 || xterm_hints.width_inc <= 1
6723 || xterm_hints.height_inc <= 1)
6724 {
6725 xterm_trace = -1; /* Not enough data -- disable tracing */
6726 return FALSE;
6727 }
6728
6729 /* Rely on the same mouse code for the duration of this */
6730 mouse_code = find_termcode(mouse_name);
6731 prev_row = mouse_row;
6732 prev_row = mouse_col;
6733 xterm_trace = 2;
6734
6735 /* Find the offset of the chars, there might be a scrollbar on the
6736 * left of the window and/or a menu on the top (eterm etc.) */
6737 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6738 &win_x, &win_y, &mask_return);
6739 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6740 - (xterm_hints.height_inc / 2);
6741 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6742 xterm_hints.y = 2;
6743 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6744 - (xterm_hints.width_inc / 2);
6745 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6746 xterm_hints.x = 2;
6747 return TRUE;
6748 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006749 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 {
6751 xterm_trace = 0;
6752 return FALSE;
6753 }
6754
6755 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6756 &win_x, &win_y, &mask_return);
6757
6758 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6759 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6760 if (row == prev_row && col == prev_col)
6761 return TRUE;
6762
6763 STRCPY(buf, mouse_code);
6764 strp = buf + STRLEN(buf);
6765 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6766 *strp++ = (char_u)(col + ' ' + 1);
6767 *strp++ = (char_u)(row + ' ' + 1);
6768 *strp = 0;
6769 add_to_input_buf(buf, STRLEN(buf));
6770
6771 prev_row = row;
6772 prev_col = col;
6773 return TRUE;
6774}
6775
6776# if defined(FEAT_GUI) || defined(PROTO)
6777/*
6778 * Destroy the display, window and app_context. Required for GTK.
6779 */
6780 void
6781clear_xterm_clip()
6782{
6783 if (xterm_Shell != (Widget)0)
6784 {
6785 XtDestroyWidget(xterm_Shell);
6786 xterm_Shell = (Widget)0;
6787 }
6788 if (xterm_dpy != NULL)
6789 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006790# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 /* Lesstif and Solaris crash here, lose some memory */
6792 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006793# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 if (x11_display == xterm_dpy)
6795 x11_display = NULL;
6796 xterm_dpy = NULL;
6797 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006798# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 if (app_context != (XtAppContext)NULL)
6800 {
6801 /* Lesstif and Solaris crash here, lose some memory */
6802 XtDestroyApplicationContext(app_context);
6803 app_context = (XtAppContext)NULL;
6804 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006805# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806}
6807# endif
6808
6809/*
6810 * Catch up with any queued X events. This may put keyboard input into the
6811 * input buffer, call resize call-backs, trigger timers etc. If there is
6812 * nothing in the X event queue (& no timers pending), then we return
6813 * immediately.
6814 */
6815 static void
6816xterm_update()
6817{
6818 XEvent event;
6819
6820 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6821 {
6822 XtAppNextEvent(app_context, &event);
6823#ifdef FEAT_CLIENTSERVER
6824 {
6825 XPropertyEvent *e = (XPropertyEvent *)&event;
6826
6827 if (e->type == PropertyNotify && e->window == commWindow
6828 && e->atom == commProperty && e->state == PropertyNewValue)
6829 serverEventProc(xterm_dpy, &event);
6830 }
6831#endif
6832 XtDispatchEvent(&event);
6833 }
6834}
6835
6836 int
6837clip_xterm_own_selection(cbd)
6838 VimClipboard *cbd;
6839{
6840 if (xterm_Shell != (Widget)0)
6841 return clip_x11_own_selection(xterm_Shell, cbd);
6842 return FAIL;
6843}
6844
6845 void
6846clip_xterm_lose_selection(cbd)
6847 VimClipboard *cbd;
6848{
6849 if (xterm_Shell != (Widget)0)
6850 clip_x11_lose_selection(xterm_Shell, cbd);
6851}
6852
6853 void
6854clip_xterm_request_selection(cbd)
6855 VimClipboard *cbd;
6856{
6857 if (xterm_Shell != (Widget)0)
6858 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6859}
6860
6861 void
6862clip_xterm_set_selection(cbd)
6863 VimClipboard *cbd;
6864{
6865 clip_x11_set_selection(cbd);
6866}
6867#endif
6868
6869
6870#if defined(USE_XSMP) || defined(PROTO)
6871/*
6872 * Code for X Session Management Protocol.
6873 */
6874static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6875static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6876static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6877static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6878static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6879
6880
6881# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6882static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6883
6884/*
6885 * This is our chance to ask the user if they want to save,
6886 * or abort the logout
6887 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 static void
6889xsmp_handle_interaction(smc_conn, client_data)
6890 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006891 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892{
6893 cmdmod_T save_cmdmod;
6894 int cancel_shutdown = False;
6895
6896 save_cmdmod = cmdmod;
6897 cmdmod.confirm = TRUE;
6898 if (check_changed_any(FALSE))
6899 /* Mustn't logout */
6900 cancel_shutdown = True;
6901 cmdmod = save_cmdmod;
6902 setcursor(); /* position cursor */
6903 out_flush();
6904
6905 /* Done interaction */
6906 SmcInteractDone(smc_conn, cancel_shutdown);
6907
6908 /* Finish off
6909 * Only end save-yourself here if we're not cancelling shutdown;
6910 * we'll get a cancelled callback later in which we'll end it.
6911 * Hopefully get around glitchy SMs (like GNOME-1)
6912 */
6913 if (!cancel_shutdown)
6914 {
6915 xsmp.save_yourself = False;
6916 SmcSaveYourselfDone(smc_conn, True);
6917 }
6918}
6919# endif
6920
6921/*
6922 * Callback that starts save-yourself.
6923 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 static void
6925xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6926 shutdown, interact_style, fast)
6927 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006928 SmPointer client_data UNUSED;
6929 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006931 int interact_style UNUSED;
6932 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933{
6934 /* Handle already being in saveyourself */
6935 if (xsmp.save_yourself)
6936 SmcSaveYourselfDone(smc_conn, True);
6937 xsmp.save_yourself = True;
6938 xsmp.shutdown = shutdown;
6939
6940 /* First up, preserve all files */
6941 out_flush();
6942 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6943
6944 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006945 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946
6947# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6948 /* Now see if we can ask about unsaved files */
6949 if (shutdown && !fast && gui.in_use)
6950 /* Need to interact with user, but need SM's permission */
6951 SmcInteractRequest(smc_conn, SmDialogError,
6952 xsmp_handle_interaction, client_data);
6953 else
6954# endif
6955 {
6956 /* Can stop the cycle here */
6957 SmcSaveYourselfDone(smc_conn, True);
6958 xsmp.save_yourself = False;
6959 }
6960}
6961
6962
6963/*
6964 * Callback to warn us of imminent death.
6965 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 static void
6967xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006968 SmcConn smc_conn UNUSED;
6969 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970{
6971 xsmp_close();
6972
6973 /* quit quickly leaving swapfiles for modified buffers behind */
6974 getout_preserve_modified(0);
6975}
6976
6977
6978/*
6979 * Callback to tell us that save-yourself has completed.
6980 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981 static void
6982xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006983 SmcConn smc_conn UNUSED;
6984 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985{
6986 xsmp.save_yourself = False;
6987}
6988
6989
6990/*
6991 * Callback to tell us that an instigated shutdown was cancelled
6992 * (maybe even by us)
6993 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 static void
6995xsmp_shutdown_cancelled(smc_conn, client_data)
6996 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006997 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998{
6999 if (xsmp.save_yourself)
7000 SmcSaveYourselfDone(smc_conn, True);
7001 xsmp.save_yourself = False;
7002 xsmp.shutdown = False;
7003}
7004
7005
7006/*
7007 * Callback to tell us that a new ICE connection has been established.
7008 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 static void
7010xsmp_ice_connection(iceConn, clientData, opening, watchData)
7011 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007012 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007014 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015{
7016 /* Intercept creation of ICE connection fd */
7017 if (opening)
7018 {
7019 xsmp_icefd = IceConnectionNumber(iceConn);
7020 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7021 }
7022}
7023
7024
7025/* Handle any ICE processing that's required; return FAIL if SM lost */
7026 int
7027xsmp_handle_requests()
7028{
7029 Bool rep;
7030
7031 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7032 == IceProcessMessagesIOError)
7033 {
7034 /* Lost ICE */
7035 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007036 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 xsmp_close();
7038 return FAIL;
7039 }
7040 else
7041 return OK;
7042}
7043
7044static int dummy;
7045
7046/* Set up X Session Management Protocol */
7047 void
7048xsmp_init(void)
7049{
7050 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 SmcCallbacks smcallbacks;
7052#if 0
7053 SmPropValue smname;
7054 SmProp smnameprop;
7055 SmProp *smprops[1];
7056#endif
7057
7058 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007059 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060
7061 xsmp.save_yourself = xsmp.shutdown = False;
7062
7063 /* Set up SM callbacks - must have all, even if they're not used */
7064 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7065 smcallbacks.save_yourself.client_data = NULL;
7066 smcallbacks.die.callback = xsmp_die;
7067 smcallbacks.die.client_data = NULL;
7068 smcallbacks.save_complete.callback = xsmp_save_complete;
7069 smcallbacks.save_complete.client_data = NULL;
7070 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7071 smcallbacks.shutdown_cancelled.client_data = NULL;
7072
7073 /* Set up a watch on ICE connection creations. The "dummy" argument is
7074 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7075 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7076 {
7077 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007078 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 return;
7080 }
7081
7082 /* Create an SM connection */
7083 xsmp.smcconn = SmcOpenConnection(
7084 NULL,
7085 NULL,
7086 SmProtoMajor,
7087 SmProtoMinor,
7088 SmcSaveYourselfProcMask | SmcDieProcMask
7089 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7090 &smcallbacks,
7091 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007092 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 sizeof(errorstring),
7094 errorstring);
7095 if (xsmp.smcconn == NULL)
7096 {
7097 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007098
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007100 {
7101 vim_snprintf(errorreport, sizeof(errorreport),
7102 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7103 verb_msg((char_u *)errorreport);
7104 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 return;
7106 }
7107 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7108
7109#if 0
7110 /* ID ourselves */
7111 smname.value = "vim";
7112 smname.length = 3;
7113 smnameprop.name = "SmProgram";
7114 smnameprop.type = "SmARRAY8";
7115 smnameprop.num_vals = 1;
7116 smnameprop.vals = &smname;
7117
7118 smprops[0] = &smnameprop;
7119 SmcSetProperties(xsmp.smcconn, 1, smprops);
7120#endif
7121}
7122
7123
7124/* Shut down XSMP comms. */
7125 void
7126xsmp_close()
7127{
7128 if (xsmp_icefd != -1)
7129 {
7130 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007131 if (xsmp.clientid != NULL)
7132 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007133 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 xsmp_icefd = -1;
7135 }
7136}
7137#endif /* USE_XSMP */
7138
7139
7140#ifdef EBCDIC
7141/* Translate character to its CTRL- value */
7142char CtrlTable[] =
7143{
7144/* 00 - 5E */
7145 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7146 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7147 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7148 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7149 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7150 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7151/* ^ */ 0x1E,
7152/* - */ 0x1F,
7153/* 61 - 6C */
7154 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7155/* _ */ 0x1F,
7156/* 6E - 80 */
7157 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7158/* a */ 0x01,
7159/* b */ 0x02,
7160/* c */ 0x03,
7161/* d */ 0x37,
7162/* e */ 0x2D,
7163/* f */ 0x2E,
7164/* g */ 0x2F,
7165/* h */ 0x16,
7166/* i */ 0x05,
7167/* 8A - 90 */
7168 0, 0, 0, 0, 0, 0, 0,
7169/* j */ 0x15,
7170/* k */ 0x0B,
7171/* l */ 0x0C,
7172/* m */ 0x0D,
7173/* n */ 0x0E,
7174/* o */ 0x0F,
7175/* p */ 0x10,
7176/* q */ 0x11,
7177/* r */ 0x12,
7178/* 9A - A1 */
7179 0, 0, 0, 0, 0, 0, 0, 0,
7180/* s */ 0x13,
7181/* t */ 0x3C,
7182/* u */ 0x3D,
7183/* v */ 0x32,
7184/* w */ 0x26,
7185/* x */ 0x18,
7186/* y */ 0x19,
7187/* z */ 0x3F,
7188/* AA - AC */
7189 0, 0, 0,
7190/* [ */ 0x27,
7191/* AE - BC */
7192 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7193/* ] */ 0x1D,
7194/* BE - C0 */ 0, 0, 0,
7195/* A */ 0x01,
7196/* B */ 0x02,
7197/* C */ 0x03,
7198/* D */ 0x37,
7199/* E */ 0x2D,
7200/* F */ 0x2E,
7201/* G */ 0x2F,
7202/* H */ 0x16,
7203/* I */ 0x05,
7204/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7205/* J */ 0x15,
7206/* K */ 0x0B,
7207/* L */ 0x0C,
7208/* M */ 0x0D,
7209/* N */ 0x0E,
7210/* O */ 0x0F,
7211/* P */ 0x10,
7212/* Q */ 0x11,
7213/* R */ 0x12,
7214/* DA - DF */ 0, 0, 0, 0, 0, 0,
7215/* \ */ 0x1C,
7216/* E1 */ 0,
7217/* S */ 0x13,
7218/* T */ 0x3C,
7219/* U */ 0x3D,
7220/* V */ 0x32,
7221/* W */ 0x26,
7222/* X */ 0x18,
7223/* Y */ 0x19,
7224/* Z */ 0x3F,
7225/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7226 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7227};
7228
7229char MetaCharTable[]=
7230{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7231 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7232 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7233 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7234 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7235};
7236
7237
7238/* TODO: Use characters NOT numbers!!! */
7239char CtrlCharTable[]=
7240{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7241 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7242 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7243 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7244 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7245};
7246
7247
7248#endif