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