blob: 150bdad6d833d5c92a1b143410671620fa8c563b [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 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 fromshell_fd = pty_master_fd;
4172 toshell_fd = dup(pty_master_fd);
4173 }
4174 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004175# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 {
4177 close(fd_toshell[0]);
4178 close(fd_fromshell[1]);
4179 toshell_fd = fd_toshell[1];
4180 fromshell_fd = fd_fromshell[0];
4181 }
4182
4183 /*
4184 * Write to the child if there are typed characters.
4185 * Read from the child if there are characters available.
4186 * Repeat the reading a few times if more characters are
4187 * available. Need to check for typed keys now and then, but
4188 * not too often (delays when no chars are available).
4189 * This loop is quit if no characters can be read from the pty
4190 * (WaitForChar detected special condition), or there are no
4191 * characters available and the child has exited.
4192 * Only check if the child has exited when there is no more
4193 * output. The child may exit before all the output has
4194 * been printed.
4195 *
4196 * Currently this busy loops!
4197 * This can probably dead-lock when the write blocks!
4198 */
4199 p_more_save = p_more;
4200 p_more = FALSE;
4201 old_State = State;
4202 State = EXTERNCMD; /* don't redraw at window resize */
4203
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004204 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004205 {
4206 /* Fork a process that will write the lines to the
4207 * external program. */
4208 if ((wpid = fork()) == -1)
4209 {
4210 MSG_PUTS(_("\nCannot fork\n"));
4211 }
4212 else if (wpid == 0)
4213 {
4214 linenr_T lnum = curbuf->b_op_start.lnum;
4215 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004216 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004217 char_u *s;
4218 size_t l;
4219
4220 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004221 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004222 for (;;)
4223 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004224 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004225 if (l == 0)
4226 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004227 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004228 /* NL -> NUL translation */
4229 len = write(toshell_fd, "", (size_t)1);
4230 else
4231 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004232 s = vim_strchr(lp + written, NL);
4233 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004234 s == NULL ? l
4235 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004236 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004237 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004238 {
4239 /* Finished a line, add a NL, unless this line
4240 * should not have one. */
4241 if (lnum != curbuf->b_op_end.lnum
4242 || !curbuf->b_p_bin
4243 || (lnum != write_no_eol_lnum
4244 && (lnum !=
4245 curbuf->b_ml.ml_line_count
4246 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004247 ignored = write(toshell_fd, "\n",
4248 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004249 ++lnum;
4250 if (lnum > curbuf->b_op_end.lnum)
4251 {
4252 /* finished all the lines, close pipe */
4253 close(toshell_fd);
4254 toshell_fd = -1;
4255 break;
4256 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004257 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004258 written = 0;
4259 }
4260 else if (len > 0)
4261 written += len;
4262 }
4263 _exit(0);
4264 }
4265 else
4266 {
4267 close(toshell_fd);
4268 toshell_fd = -1;
4269 }
4270 }
4271
4272 if (options & SHELL_READ)
4273 ga_init2(&ga, 1, BUFLEN);
4274
4275 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004276# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4277 gettimeofday(&start_tv, NULL);
4278# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279 for (;;)
4280 {
4281 /*
4282 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004283 * if there are any.
4284 * Don't do this if we are expanding wild cards (would eat
4285 * typeahead).
4286 * Don't do this when filtering and terminal is in cooked
4287 * mode, the shell command will handle the I/O. Avoids
4288 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004289 * Don't get characters when the child has already
4290 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004291 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004292 * while (noread_cnt > 4), avoids that ":r !ls" eats
4293 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 */
4295 len = 0;
4296 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004297 && ((options &
4298 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4299 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004300# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004301 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004302# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004303 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004304 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004305 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004307 if (ta_len == 0)
4308 {
4309 /* Get extra characters when we don't have any.
4310 * Reset the counter and timer. */
4311 noread_cnt = 0;
4312# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4313 gettimeofday(&start_tv, NULL);
4314# endif
4315 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4316 }
4317 if (ta_len > 0 || len > 0)
4318 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 /*
4320 * For pipes:
4321 * Check for CTRL-C: send interrupt signal to child.
4322 * Check for CTRL-D: EOF, close pipe to child.
4323 */
4324 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4325 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004326# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327 /*
4328 * Send SIGINT to the child's group or all
4329 * processes in our group.
4330 */
4331 if (ta_buf[ta_len] == Ctrl_C
4332 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004333 {
4334# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004336# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004339 if (wpid > 0)
4340 kill(wpid, SIGINT);
4341 }
4342# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 if (pty_master_fd < 0 && toshell_fd >= 0
4344 && ta_buf[ta_len] == Ctrl_D)
4345 {
4346 close(toshell_fd);
4347 toshell_fd = -1;
4348 }
4349 }
4350
4351 /* replace K_BS by <BS> and K_DEL by <DEL> */
4352 for (i = ta_len; i < ta_len + len; ++i)
4353 {
4354 if (ta_buf[i] == CSI && len - i > 2)
4355 {
4356 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4357 if (c == K_DEL || c == K_KDEL || c == K_BS)
4358 {
4359 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4360 (size_t)(len - i - 2));
4361 if (c == K_DEL || c == K_KDEL)
4362 ta_buf[i] = DEL;
4363 else
4364 ta_buf[i] = Ctrl_H;
4365 len -= 2;
4366 }
4367 }
4368 else if (ta_buf[i] == '\r')
4369 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004370# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004372 i += (*mb_ptr2len_len)(ta_buf + i,
4373 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004374# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375 }
4376
4377 /*
4378 * For pipes: echo the typed characters.
4379 * For a pty this does not seem to work.
4380 */
4381 if (pty_master_fd < 0)
4382 {
4383 for (i = ta_len; i < ta_len + len; ++i)
4384 {
4385 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4386 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004387# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388 else if (has_mbyte)
4389 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004390 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391
4392 msg_outtrans_len(ta_buf + i, l);
4393 i += l - 1;
4394 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004395# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396 else
4397 msg_outtrans_len(ta_buf + i, 1);
4398 }
4399 windgoto(msg_row, msg_col);
4400 out_flush();
4401 }
4402
4403 ta_len += len;
4404
4405 /*
4406 * Write the characters to the child, unless EOF has
4407 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004408 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004409 * When writing buffer lines, drop the typed
4410 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004412 if (options & SHELL_WRITE)
4413 ta_len = 0;
4414 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 {
4416 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4417 if (len > 0)
4418 {
4419 ta_len -= len;
4420 mch_memmove(ta_buf, ta_buf + len, ta_len);
4421 }
4422 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004423 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004424 }
4425
Bram Moolenaardf177f62005-02-22 08:39:57 +00004426 if (got_int)
4427 {
4428 /* CTRL-C sends a signal to the child, we ignore it
4429 * ourselves */
4430# ifdef HAVE_SETSID
4431 kill(-pid, SIGINT);
4432# else
4433 kill(0, SIGINT);
4434# endif
4435 if (wpid > 0)
4436 kill(wpid, SIGINT);
4437 got_int = FALSE;
4438 }
4439
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 /*
4441 * Check if the child has any characters to be printed.
4442 * Read them and write them to our window. Repeat this as
4443 * long as there is something to do, avoid the 10ms wait
4444 * for mch_inchar(), or sending typeahead characters to
4445 * the external process.
4446 * TODO: This should handle escape sequences, compatible
4447 * to some terminal (vt52?).
4448 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004449 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4451 {
4452 len = read(fromshell_fd, (char *)buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004453# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004455# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458 );
4459 if (len <= 0) /* end of file or error */
4460 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004461
4462 noread_cnt = 0;
4463 if (options & SHELL_READ)
4464 {
4465 /* Do NUL -> NL translation, append NL separated
4466 * lines to the current buffer. */
4467 for (i = 0; i < len; ++i)
4468 {
4469 if (buffer[i] == NL)
4470 append_ga_line(&ga);
4471 else if (buffer[i] == NUL)
4472 ga_append(&ga, NL);
4473 else
4474 ga_append(&ga, buffer[i]);
4475 }
4476 }
4477# ifdef FEAT_MBYTE
4478 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 {
4480 int l;
4481
Bram Moolenaardf177f62005-02-22 08:39:57 +00004482 len += buffer_off;
4483 buffer[len] = NUL;
4484
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485 /* Check if the last character in buffer[] is
4486 * incomplete, keep these bytes for the next
4487 * round. */
4488 for (p = buffer; p < buffer + len; p += l)
4489 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004490 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491 if (l == 0)
4492 l = 1; /* NUL byte? */
4493 else if (MB_BYTE2LEN(*p) != l)
4494 break;
4495 }
4496 if (p == buffer) /* no complete character */
4497 {
4498 /* avoid getting stuck at an illegal byte */
4499 if (len >= 12)
4500 ++p;
4501 else
4502 {
4503 buffer_off = len;
4504 continue;
4505 }
4506 }
4507 c = *p;
4508 *p = NUL;
4509 msg_puts(buffer);
4510 if (p < buffer + len)
4511 {
4512 *p = c;
4513 buffer_off = (buffer + len) - p;
4514 mch_memmove(buffer, p, buffer_off);
4515 continue;
4516 }
4517 buffer_off = 0;
4518 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004519# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 {
4522 buffer[len] = NUL;
4523 msg_puts(buffer);
4524 }
4525
4526 windgoto(msg_row, msg_col);
4527 cursor_on();
4528 out_flush();
4529 if (got_int)
4530 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004531
4532# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4533 {
4534 struct timeval now_tv;
4535 long msec;
4536
4537 /* Avoid that we keep looping here without
4538 * checking for a CTRL-C for a long time. Don't
4539 * break out too often to avoid losing typeahead. */
4540 gettimeofday(&now_tv, NULL);
4541 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4542 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4543 if (msec > 2000)
4544 {
4545 noread_cnt = 5;
4546 break;
4547 }
4548 }
4549# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 }
4551
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004552 /* If we already detected the child has finished break the
4553 * loop now. */
4554 if (wait_pid == pid)
4555 break;
4556
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 /*
4558 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004559 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004561# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004563# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004565# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4567 || (wait_pid == pid && WIFEXITED(status)))
4568 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004569 /* Don't break the loop yet, try reading more
4570 * characters from "fromshell_fd" first. When using
4571 * pipes there might still be something to read and
4572 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004575 else
4576 wait_pid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 }
4578finished:
4579 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004580 if (options & SHELL_READ)
4581 {
4582 if (ga.ga_len > 0)
4583 {
4584 append_ga_line(&ga);
4585 /* remember that the NL was missing */
4586 write_no_eol_lnum = curwin->w_cursor.lnum;
4587 }
4588 else
4589 write_no_eol_lnum = 0;
4590 ga_clear(&ga);
4591 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592
Bram Moolenaar071d4272004-06-13 20:20:40 +00004593 /*
4594 * Give all typeahead that wasn't used back to ui_inchar().
4595 */
4596 if (ta_len)
4597 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 State = old_State;
4599 if (toshell_fd >= 0)
4600 close(toshell_fd);
4601 close(fromshell_fd);
4602 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603
4604 /*
4605 * Wait until our child has exited.
4606 * Ignore wait() returning pids of other children and returning
4607 * because of some signal like SIGWINCH.
4608 * Don't wait if wait_pid was already set above, indicating the
4609 * child already exited.
4610 */
4611 while (wait_pid != pid)
4612 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004613# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614 /* Ugly hack: when compiled with Python threads are probably
4615 * used, in which case wait() sometimes hangs for no obvious
4616 * reason. Use waitpid() instead and loop (like the GUI). */
4617# ifdef __NeXT__
4618 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4619# else
4620 wait_pid = waitpid(pid, &status, WNOHANG);
4621# endif
4622 if (wait_pid == 0)
4623 {
4624 /* Wait for 1/100 sec before trying again. */
4625 mch_delay(10L, TRUE);
4626 continue;
4627 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004628# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004630# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 if (wait_pid <= 0
4632# ifdef ECHILD
4633 && errno == ECHILD
4634# endif
4635 )
4636 break;
4637 }
4638
Bram Moolenaar624891f2010-10-13 16:22:09 +02004639# ifdef FEAT_GUI
4640 /* Close slave side of pty. Only do this after the child has
4641 * exited, otherwise the child may hang when it tries to write on
4642 * the pty. */
4643 if (pty_master_fd >= 0)
4644 close(pty_slave_fd);
4645# endif
4646
Bram Moolenaardf177f62005-02-22 08:39:57 +00004647 /* Make sure the child that writes to the external program is
4648 * dead. */
4649 if (wpid > 0)
4650 kill(wpid, SIGKILL);
4651
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652 /*
4653 * Set to raw mode right now, otherwise a CTRL-C after
4654 * catch_signals() will kill Vim.
4655 */
4656 if (tmode == TMODE_RAW)
4657 settmode(TMODE_RAW);
4658 did_settmode = TRUE;
4659 set_signals();
4660
4661 if (WIFEXITED(status))
4662 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004663 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 retval = WEXITSTATUS(status);
4665 if (retval && !emsg_silent)
4666 {
4667 if (retval == EXEC_FAILED)
4668 {
4669 MSG_PUTS(_("\nCannot execute shell "));
4670 msg_outtrans(p_sh);
4671 msg_putchar('\n');
4672 }
4673 else if (!(options & SHELL_SILENT))
4674 {
4675 MSG_PUTS(_("\nshell returned "));
4676 msg_outnum((long)retval);
4677 msg_putchar('\n');
4678 }
4679 }
4680 }
4681 else
4682 MSG_PUTS(_("\nCommand terminated\n"));
4683 }
4684 }
4685 vim_free(argv);
4686
4687error:
4688 if (!did_settmode)
4689 if (tmode == TMODE_RAW)
4690 settmode(TMODE_RAW); /* set to raw mode */
4691# ifdef FEAT_TITLE
4692 resettitle();
4693# endif
4694 vim_free(newcmd);
4695
4696 return retval;
4697
4698#endif /* USE_SYSTEM */
4699}
4700
4701/*
4702 * Check for CTRL-C typed by reading all available characters.
4703 * In cooked mode we should get SIGINT, no need to check.
4704 */
4705 void
4706mch_breakcheck()
4707{
4708 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4709 fill_input_buf(FALSE);
4710}
4711
4712/*
4713 * Wait "msec" msec until a character is available from the keyboard or from
4714 * inbuf[]. msec == -1 will block forever.
4715 * When a GUI is being used, this will never get called -- webb
4716 */
4717 static int
4718WaitForChar(msec)
4719 long msec;
4720{
4721#ifdef FEAT_MOUSE_GPM
4722 int gpm_process_wanted;
4723#endif
4724#ifdef FEAT_XCLIPBOARD
4725 int rest;
4726#endif
4727 int avail;
4728
4729 if (input_available()) /* something in inbuf[] */
4730 return 1;
4731
4732#if defined(FEAT_MOUSE_DEC)
4733 /* May need to query the mouse position. */
4734 if (WantQueryMouse)
4735 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004736 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4738 }
4739#endif
4740
4741 /*
4742 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4743 * events. This is a bit complicated, because they might both be defined.
4744 */
4745#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4746# ifdef FEAT_XCLIPBOARD
4747 rest = 0;
4748 if (do_xterm_trace())
4749 rest = msec;
4750# endif
4751 do
4752 {
4753# ifdef FEAT_XCLIPBOARD
4754 if (rest != 0)
4755 {
4756 msec = XT_TRACE_DELAY;
4757 if (rest >= 0 && rest < XT_TRACE_DELAY)
4758 msec = rest;
4759 if (rest >= 0)
4760 rest -= msec;
4761 }
4762# endif
4763# ifdef FEAT_MOUSE_GPM
4764 gpm_process_wanted = 0;
4765 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4766# else
4767 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4768# endif
4769 if (!avail)
4770 {
4771 if (input_available())
4772 return 1;
4773# ifdef FEAT_XCLIPBOARD
4774 if (rest == 0 || !do_xterm_trace())
4775# endif
4776 break;
4777 }
4778 }
4779 while (FALSE
4780# ifdef FEAT_MOUSE_GPM
4781 || (gpm_process_wanted && mch_gpm_process() == 0)
4782# endif
4783# ifdef FEAT_XCLIPBOARD
4784 || (!avail && rest != 0)
4785# endif
4786 );
4787
4788#else
4789 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4790#endif
4791 return avail;
4792}
4793
4794/*
4795 * Wait "msec" msec until a character is available from file descriptor "fd".
4796 * Time == -1 will block forever.
4797 * When a GUI is being used, this will not be used for input -- webb
4798 * Returns also, when a request from Sniff is waiting -- toni.
4799 * Or when a Linux GPM mouse event is waiting.
4800 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801#if defined(__BEOS__)
4802 int
4803#else
4804 static int
4805#endif
4806RealWaitForChar(fd, msec, check_for_gpm)
4807 int fd;
4808 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00004809 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810{
4811 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02004812#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02004813 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02004814#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004815#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 static int busy = FALSE;
4817
4818 /* May retry getting characters after an event was handled. */
4819# define MAY_LOOP
4820
4821# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4822 /* Remember at what time we started, so that we know how much longer we
4823 * should wait after being interrupted. */
4824# define USE_START_TV
4825 struct timeval start_tv;
4826
4827 if (msec > 0 && (
4828# ifdef FEAT_XCLIPBOARD
4829 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004830# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 ||
4832# endif
4833# endif
4834# ifdef USE_XSMP
4835 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004836# ifdef FEAT_MZSCHEME
4837 ||
4838# endif
4839# endif
4840# ifdef FEAT_MZSCHEME
4841 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842# endif
4843 ))
4844 gettimeofday(&start_tv, NULL);
4845# endif
4846
4847 /* Handle being called recursively. This may happen for the session
4848 * manager stuff, it may save the file, which does a breakcheck. */
4849 if (busy)
4850 return 0;
4851#endif
4852
4853#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004854 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855#endif
4856 {
4857#ifdef MAY_LOOP
4858 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004859# ifdef FEAT_MZSCHEME
4860 int mzquantum_used = FALSE;
4861# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862#endif
4863#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02004864 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865 int nfd;
4866# ifdef FEAT_XCLIPBOARD
4867 int xterm_idx = -1;
4868# endif
4869# ifdef FEAT_MOUSE_GPM
4870 int gpm_idx = -1;
4871# endif
4872# ifdef USE_XSMP
4873 int xsmp_idx = -1;
4874# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004875# ifdef FEAT_NETBEANS_INTG
4876 int nb_idx = -1;
4877# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004878 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004880# ifdef FEAT_MZSCHEME
4881 mzvim_check_threads();
4882 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4883 {
4884 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4885 mzquantum_used = TRUE;
4886 }
4887# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 fds[0].fd = fd;
4889 fds[0].events = POLLIN;
4890 nfd = 1;
4891
4892# ifdef FEAT_SNIFF
4893# define SNIFF_IDX 1
4894 if (want_sniff_request)
4895 {
4896 fds[SNIFF_IDX].fd = fd_from_sniff;
4897 fds[SNIFF_IDX].events = POLLIN;
4898 nfd++;
4899 }
4900# endif
4901# ifdef FEAT_XCLIPBOARD
4902 if (xterm_Shell != (Widget)0)
4903 {
4904 xterm_idx = nfd;
4905 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4906 fds[nfd].events = POLLIN;
4907 nfd++;
4908 }
4909# endif
4910# ifdef FEAT_MOUSE_GPM
4911 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4912 {
4913 gpm_idx = nfd;
4914 fds[nfd].fd = gpm_fd;
4915 fds[nfd].events = POLLIN;
4916 nfd++;
4917 }
4918# endif
4919# ifdef USE_XSMP
4920 if (xsmp_icefd != -1)
4921 {
4922 xsmp_idx = nfd;
4923 fds[nfd].fd = xsmp_icefd;
4924 fds[nfd].events = POLLIN;
4925 nfd++;
4926 }
4927# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004928#ifdef FEAT_NETBEANS_INTG
4929 if (nb_fd != -1)
4930 {
4931 nb_idx = nfd;
4932 fds[nfd].fd = nb_fd;
4933 fds[nfd].events = POLLIN;
4934 nfd++;
4935 }
4936#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004938 ret = poll(fds, nfd, towait);
4939# ifdef FEAT_MZSCHEME
4940 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00004941 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004942 finished = FALSE;
4943# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944
4945# ifdef FEAT_SNIFF
4946 if (ret < 0)
4947 sniff_disconnect(1);
4948 else if (want_sniff_request)
4949 {
4950 if (fds[SNIFF_IDX].revents & POLLHUP)
4951 sniff_disconnect(1);
4952 if (fds[SNIFF_IDX].revents & POLLIN)
4953 sniff_request_waiting = 1;
4954 }
4955# endif
4956# ifdef FEAT_XCLIPBOARD
4957 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4958 {
4959 xterm_update(); /* Maybe we should hand out clipboard */
4960 if (--ret == 0 && !input_available())
4961 /* Try again */
4962 finished = FALSE;
4963 }
4964# endif
4965# ifdef FEAT_MOUSE_GPM
4966 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4967 {
4968 *check_for_gpm = 1;
4969 }
4970# endif
4971# ifdef USE_XSMP
4972 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4973 {
4974 if (fds[xsmp_idx].revents & POLLIN)
4975 {
4976 busy = TRUE;
4977 xsmp_handle_requests();
4978 busy = FALSE;
4979 }
4980 else if (fds[xsmp_idx].revents & POLLHUP)
4981 {
4982 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004983 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 xsmp_close();
4985 }
4986 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004987 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 }
4989# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02004990#ifdef FEAT_NETBEANS_INTG
4991 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
4992 {
4993 netbeans_read();
4994 --ret;
4995 }
4996#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997
4998
4999#else /* HAVE_SELECT */
5000
5001 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005002 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003 fd_set rfds, efds;
5004 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005005 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005007# ifdef FEAT_MZSCHEME
5008 mzvim_check_threads();
5009 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5010 {
5011 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5012 mzquantum_used = TRUE;
5013 }
5014# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005015# ifdef __EMX__
5016 /* don't check for incoming chars if not in raw mode, because select()
5017 * always returns TRUE then (in some version of emx.dll) */
5018 if (curr_tmode != TMODE_RAW)
5019 return 0;
5020# endif
5021
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005022 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005024 tv.tv_sec = towait / 1000;
5025 tv.tv_usec = (towait % 1000) * (1000000/1000);
5026 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005028 else
5029 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030
5031 /*
5032 * Select on ready for reading and exceptional condition (end of file).
5033 */
5034 FD_ZERO(&rfds); /* calls bzero() on a sun */
5035 FD_ZERO(&efds);
5036 FD_SET(fd, &rfds);
5037# if !defined(__QNX__) && !defined(__CYGWIN32__)
5038 /* For QNX select() always returns 1 if this is set. Why? */
5039 FD_SET(fd, &efds);
5040# endif
5041 maxfd = fd;
5042
5043# ifdef FEAT_SNIFF
5044 if (want_sniff_request)
5045 {
5046 FD_SET(fd_from_sniff, &rfds);
5047 FD_SET(fd_from_sniff, &efds);
5048 if (maxfd < fd_from_sniff)
5049 maxfd = fd_from_sniff;
5050 }
5051# endif
5052# ifdef FEAT_XCLIPBOARD
5053 if (xterm_Shell != (Widget)0)
5054 {
5055 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5056 if (maxfd < ConnectionNumber(xterm_dpy))
5057 maxfd = ConnectionNumber(xterm_dpy);
5058 }
5059# endif
5060# ifdef FEAT_MOUSE_GPM
5061 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5062 {
5063 FD_SET(gpm_fd, &rfds);
5064 FD_SET(gpm_fd, &efds);
5065 if (maxfd < gpm_fd)
5066 maxfd = gpm_fd;
5067 }
5068# endif
5069# ifdef USE_XSMP
5070 if (xsmp_icefd != -1)
5071 {
5072 FD_SET(xsmp_icefd, &rfds);
5073 FD_SET(xsmp_icefd, &efds);
5074 if (maxfd < xsmp_icefd)
5075 maxfd = xsmp_icefd;
5076 }
5077# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005078#ifdef FEAT_NETBEANS_INTG
5079 if (nb_fd != -1)
5080 {
5081 FD_SET(nb_fd, &rfds);
5082 if (maxfd < nb_fd)
5083 maxfd = nb_fd;
5084 }
5085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086
5087# ifdef OLD_VMS
5088 /* Old VMS as v6.2 and older have broken select(). It waits more than
5089 * required. Should not be used */
5090 ret = 0;
5091# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005092 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
5093# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005094# ifdef __TANDEM
5095 if (ret == -1 && errno == ENOTSUP)
5096 {
5097 FD_ZERO(&rfds);
5098 FD_ZERO(&efds);
5099 ret = 0;
5100 }
5101#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005102# ifdef FEAT_MZSCHEME
5103 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005104 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005105 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106# endif
5107
5108# ifdef FEAT_SNIFF
5109 if (ret < 0 )
5110 sniff_disconnect(1);
5111 else if (ret > 0 && want_sniff_request)
5112 {
5113 if (FD_ISSET(fd_from_sniff, &efds))
5114 sniff_disconnect(1);
5115 if (FD_ISSET(fd_from_sniff, &rfds))
5116 sniff_request_waiting = 1;
5117 }
5118# endif
5119# ifdef FEAT_XCLIPBOARD
5120 if (ret > 0 && xterm_Shell != (Widget)0
5121 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5122 {
5123 xterm_update(); /* Maybe we should hand out clipboard */
5124 /* continue looping when we only got the X event and the input
5125 * buffer is empty */
5126 if (--ret == 0 && !input_available())
5127 {
5128 /* Try again */
5129 finished = FALSE;
5130 }
5131 }
5132# endif
5133# ifdef FEAT_MOUSE_GPM
5134 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5135 {
5136 if (FD_ISSET(gpm_fd, &efds))
5137 gpm_close();
5138 else if (FD_ISSET(gpm_fd, &rfds))
5139 *check_for_gpm = 1;
5140 }
5141# endif
5142# ifdef USE_XSMP
5143 if (ret > 0 && xsmp_icefd != -1)
5144 {
5145 if (FD_ISSET(xsmp_icefd, &efds))
5146 {
5147 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005148 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 xsmp_close();
5150 if (--ret == 0)
5151 finished = FALSE; /* keep going if event was only one */
5152 }
5153 else if (FD_ISSET(xsmp_icefd, &rfds))
5154 {
5155 busy = TRUE;
5156 xsmp_handle_requests();
5157 busy = FALSE;
5158 if (--ret == 0)
5159 finished = FALSE; /* keep going if event was only one */
5160 }
5161 }
5162# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005163#ifdef FEAT_NETBEANS_INTG
5164 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5165 {
5166 netbeans_read();
5167 --ret;
5168 }
5169#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170
5171#endif /* HAVE_SELECT */
5172
5173#ifdef MAY_LOOP
5174 if (finished || msec == 0)
5175 break;
5176
5177 /* We're going to loop around again, find out for how long */
5178 if (msec > 0)
5179 {
5180# ifdef USE_START_TV
5181 struct timeval mtv;
5182
5183 /* Compute remaining wait time. */
5184 gettimeofday(&mtv, NULL);
5185 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5186 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5187# else
5188 /* Guess we got interrupted halfway. */
5189 msec = msec / 2;
5190# endif
5191 if (msec <= 0)
5192 break; /* waited long enough */
5193 }
5194#endif
5195 }
5196
5197 return (ret > 0);
5198}
5199
5200#ifndef VMS
5201
5202#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005204 * Expand a path into all matching files and/or directories. Handles "*",
5205 * "?", "[a-z]", "**", etc.
5206 * "path" has backslashes before chars that are not to be expanded.
5207 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 */
5209 int
5210mch_expandpath(gap, path, flags)
5211 garray_T *gap;
5212 char_u *path;
5213 int flags; /* EW_* flags */
5214{
Bram Moolenaar02743632005-07-25 20:42:36 +00005215 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216}
5217#endif
5218
5219/*
5220 * mch_expand_wildcards() - this code does wild-card pattern matching using
5221 * the shell
5222 *
5223 * return OK for success, FAIL for error (you may lose some memory) and put
5224 * an error message in *file.
5225 *
5226 * num_pat is number of input patterns
5227 * pat is array of pointers to input patterns
5228 * num_file is pointer to number of matched file names
5229 * file is pointer to array of pointers to matched file names
5230 */
5231
5232#ifndef SEEK_SET
5233# define SEEK_SET 0
5234#endif
5235#ifndef SEEK_END
5236# define SEEK_END 2
5237#endif
5238
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005239#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005240
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 int
5242mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5243 int num_pat;
5244 char_u **pat;
5245 int *num_file;
5246 char_u ***file;
5247 int flags; /* EW_* flags */
5248{
5249 int i;
5250 size_t len;
5251 char_u *p;
5252 int dir;
5253#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005254 /*
5255 * This is the OS/2 implementation.
5256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257# define EXPL_ALLOC_INC 16
5258 char_u **expl_files;
5259 size_t files_alloced, files_free;
5260 char_u *buf;
5261 int has_wildcard;
5262
5263 *num_file = 0; /* default: no files found */
5264 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5265 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5266 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5267 if (*file == NULL)
5268 return FAIL;
5269
5270 for (; num_pat > 0; num_pat--, pat++)
5271 {
5272 expl_files = NULL;
5273 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5274 /* expand environment var or home dir */
5275 buf = expand_env_save(*pat);
5276 else
5277 buf = vim_strsave(*pat);
5278 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005279 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280 if (has_wildcard) /* yes, so expand them */
5281 expl_files = (char_u **)_fnexplode(buf);
5282
5283 /*
5284 * return value of buf if no wildcards left,
5285 * OR if no match AND EW_NOTFOUND is set.
5286 */
5287 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5288 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5289 { /* simply save the current contents of *buf */
5290 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5291 if (expl_files != NULL)
5292 {
5293 expl_files[0] = vim_strsave(buf);
5294 expl_files[1] = NULL;
5295 }
5296 }
5297 vim_free(buf);
5298
5299 /*
5300 * Count number of names resulting from expansion,
5301 * At the same time add a backslash to the end of names that happen to
5302 * be directories, and replace slashes with backslashes.
5303 */
5304 if (expl_files)
5305 {
5306 for (i = 0; (p = expl_files[i]) != NULL; i++)
5307 {
5308 dir = mch_isdir(p);
5309 /* If we don't want dirs and this is one, skip it */
5310 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5311 continue;
5312
Bram Moolenaara2031822006-03-07 22:29:51 +00005313 /* Skip files that are not executable if we check for that. */
5314 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5315 continue;
5316
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317 if (--files_free == 0)
5318 {
5319 /* need more room in table of pointers */
5320 files_alloced += EXPL_ALLOC_INC;
5321 *file = (char_u **)vim_realloc(*file,
5322 sizeof(char_u **) * files_alloced);
5323 if (*file == NULL)
5324 {
5325 EMSG(_(e_outofmem));
5326 *num_file = 0;
5327 return FAIL;
5328 }
5329 files_free = EXPL_ALLOC_INC;
5330 }
5331 slash_adjust(p);
5332 if (dir)
5333 {
5334 /* For a directory we add a '/', unless it's already
5335 * there. */
5336 len = STRLEN(p);
5337 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5338 {
5339 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005340 if (!after_pathsep((*file)[*num_file],
5341 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 {
5343 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005344 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 }
5346 }
5347 }
5348 else
5349 {
5350 (*file)[*num_file] = vim_strsave(p);
5351 }
5352
5353 /*
5354 * Error message already given by either alloc or vim_strsave.
5355 * Should return FAIL, but returning OK works also.
5356 */
5357 if ((*file)[*num_file] == NULL)
5358 break;
5359 (*num_file)++;
5360 }
5361 _fnexplodefree((char **)expl_files);
5362 }
5363 }
5364 return OK;
5365
5366#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005367 /*
5368 * This is the non-OS/2 implementation (really Unix).
5369 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370 int j;
5371 char_u *tempname;
5372 char_u *command;
5373 FILE *fd;
5374 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005375#define STYLE_ECHO 0 /* use "echo", the default */
5376#define STYLE_GLOB 1 /* use "glob", for csh */
5377#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5378#define STYLE_PRINT 3 /* use "print -N", for zsh */
5379#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5380 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381 int shell_style = STYLE_ECHO;
5382 int check_spaces;
5383 static int did_find_nul = FALSE;
5384 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005385 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005386 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387
5388 *num_file = 0; /* default: no files found */
5389 *file = NULL;
5390
5391 /*
5392 * If there are no wildcards, just copy the names to allocated memory.
5393 * Saves a lot of time, because we don't have to start a new shell.
5394 */
5395 if (!have_wildcard(num_pat, pat))
5396 return save_patterns(num_pat, pat, num_file, file);
5397
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005398# ifdef HAVE_SANDBOX
5399 /* Don't allow any shell command in the sandbox. */
5400 if (sandbox != 0 && check_secure())
5401 return FAIL;
5402# endif
5403
Bram Moolenaar071d4272004-06-13 20:20:40 +00005404 /*
5405 * Don't allow the use of backticks in secure and restricted mode.
5406 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005407 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 for (i = 0; i < num_pat; ++i)
5409 if (vim_strchr(pat[i], '`') != NULL
5410 && (check_restricted() || check_secure()))
5411 return FAIL;
5412
5413 /*
5414 * get a name for the temp file
5415 */
5416 if ((tempname = vim_tempname('o')) == NULL)
5417 {
5418 EMSG(_(e_notmp));
5419 return FAIL;
5420 }
5421
5422 /*
5423 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005424 * file.
5425 * STYLE_BT: NL separated
5426 * If expanding `cmd` execute it directly.
5427 * STYLE_GLOB: NUL separated
5428 * If we use *csh, "glob" will work better than "echo".
5429 * STYLE_PRINT: NL or NUL separated
5430 * If we use *zsh, "print -N" will work better than "glob".
5431 * STYLE_VIMGLOB: NL separated
5432 * If we use *sh*, we define "vimglob()".
5433 * STYLE_ECHO: space separated.
5434 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 */
5436 if (num_pat == 1 && *pat[0] == '`'
5437 && (len = STRLEN(pat[0])) > 2
5438 && *(pat[0] + len - 1) == '`')
5439 shell_style = STYLE_BT;
5440 else if ((len = STRLEN(p_sh)) >= 3)
5441 {
5442 if (STRCMP(p_sh + len - 3, "csh") == 0)
5443 shell_style = STYLE_GLOB;
5444 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5445 shell_style = STYLE_PRINT;
5446 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005447 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5448 "sh") != NULL)
5449 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450
Bram Moolenaarc7247912008-01-13 12:54:11 +00005451 /* Compute the length of the command. We need 2 extra bytes: for the
5452 * optional '&' and for the NUL.
5453 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005455 if (shell_style == STYLE_VIMGLOB)
5456 len += STRLEN(sh_vimglob_func);
5457
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005458 for (i = 0; i < num_pat; ++i)
5459 {
5460 /* Count the length of the patterns in the same way as they are put in
5461 * "command" below. */
5462#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005464#else
5465 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005466 for (j = 0; pat[i][j] != NUL; ++j)
5467 {
5468 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5469 ++len; /* may add a backslash */
5470 ++len;
5471 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005472#endif
5473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 command = alloc(len);
5475 if (command == NULL)
5476 {
5477 /* out of memory */
5478 vim_free(tempname);
5479 return FAIL;
5480 }
5481
5482 /*
5483 * Build the shell command:
5484 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5485 * recognizes this).
5486 * - Add the shell command to print the expanded names.
5487 * - Add the temp file name.
5488 * - Add the file name patterns.
5489 */
5490 if (shell_style == STYLE_BT)
5491 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005492 /* change `command; command& ` to (command; command ) */
5493 STRCPY(command, "(");
5494 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005496 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 while (p > command && vim_iswhite(*p))
5498 --p;
5499 if (*p == '&') /* remove trailing '&' */
5500 {
5501 ampersent = TRUE;
5502 *p = ' ';
5503 }
5504 STRCAT(command, ">");
5505 }
5506 else
5507 {
5508 if (flags & EW_NOTFOUND)
5509 STRCPY(command, "set nonomatch; ");
5510 else
5511 STRCPY(command, "unset nonomatch; ");
5512 if (shell_style == STYLE_GLOB)
5513 STRCAT(command, "glob >");
5514 else if (shell_style == STYLE_PRINT)
5515 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005516 else if (shell_style == STYLE_VIMGLOB)
5517 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 else
5519 STRCAT(command, "echo >");
5520 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005521
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005523
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 if (shell_style != STYLE_BT)
5525 for (i = 0; i < num_pat; ++i)
5526 {
5527 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005528 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005529 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005530#ifdef USE_SYSTEM
5531 STRCAT(command, " \"");
5532 STRCAT(command, pat[i]);
5533 STRCAT(command, "\"");
5534#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005535 int intick = FALSE;
5536
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 p = command + STRLEN(command);
5538 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005539 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005540 {
5541 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005542 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005543 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5544 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005545 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005546 * backslash inside backticks, before a special character
5547 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005548 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005549 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5550 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005551 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005552 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005553 }
5554 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005555 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005556 /* Put a backslash before a special character, but not
5557 * when inside ``. */
5558 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005559
5560 /* Copy one character. */
5561 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 *p = NUL;
5564#endif
5565 }
5566 if (flags & EW_SILENT)
5567 show_shell_mess = FALSE;
5568 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005569 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570
5571 /*
5572 * Using zsh -G: If a pattern has no matches, it is just deleted from
5573 * the argument list, otherwise zsh gives an error message and doesn't
5574 * expand any other pattern.
5575 */
5576 if (shell_style == STYLE_PRINT)
5577 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5578
5579 /*
5580 * If we use -f then shell variables set in .cshrc won't get expanded.
5581 * vi can do it, so we will too, but it is only necessary if there is a "$"
5582 * in one of the patterns, otherwise we can still use the fast option.
5583 */
5584 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5585 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5586
5587 /*
5588 * execute the shell command
5589 */
5590 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5591
5592 /* When running in the background, give it some time to create the temp
5593 * file, but don't wait for it to finish. */
5594 if (ampersent)
5595 mch_delay(10L, TRUE);
5596
5597 extra_shell_arg = NULL; /* cleanup */
5598 show_shell_mess = TRUE;
5599 vim_free(command);
5600
Bram Moolenaarc7247912008-01-13 12:54:11 +00005601 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 {
5603 mch_remove(tempname);
5604 vim_free(tempname);
5605 /*
5606 * With interactive completion, the error message is not printed.
5607 * However with USE_SYSTEM, I don't know how to turn off error messages
5608 * from the shell, so screen may still get messed up -- webb.
5609 */
5610#ifndef USE_SYSTEM
5611 if (!(flags & EW_SILENT))
5612#endif
5613 {
5614 redraw_later_clear(); /* probably messed up screen */
5615 msg_putchar('\n'); /* clear bottom line quickly */
5616 cmdline_row = Rows - 1; /* continue on last line */
5617#ifdef USE_SYSTEM
5618 if (!(flags & EW_SILENT))
5619#endif
5620 {
5621 MSG(_(e_wildexpand));
5622 msg_start(); /* don't overwrite this message */
5623 }
5624 }
5625 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5626 * EW_NOTFOUND is given */
5627 if (shell_style == STYLE_BT)
5628 return FAIL;
5629 goto notfound;
5630 }
5631
5632 /*
5633 * read the names from the file into memory
5634 */
5635 fd = fopen((char *)tempname, READBIN);
5636 if (fd == NULL)
5637 {
5638 /* Something went wrong, perhaps a file name with a special char. */
5639 if (!(flags & EW_SILENT))
5640 {
5641 MSG(_(e_wildexpand));
5642 msg_start(); /* don't overwrite this message */
5643 }
5644 vim_free(tempname);
5645 goto notfound;
5646 }
5647 fseek(fd, 0L, SEEK_END);
5648 len = ftell(fd); /* get size of temp file */
5649 fseek(fd, 0L, SEEK_SET);
5650 buffer = alloc(len + 1);
5651 if (buffer == NULL)
5652 {
5653 /* out of memory */
5654 mch_remove(tempname);
5655 vim_free(tempname);
5656 fclose(fd);
5657 return FAIL;
5658 }
5659 i = fread((char *)buffer, 1, len, fd);
5660 fclose(fd);
5661 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00005662 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005663 {
5664 /* unexpected read error */
5665 EMSG2(_(e_notread), tempname);
5666 vim_free(tempname);
5667 vim_free(buffer);
5668 return FAIL;
5669 }
5670 vim_free(tempname);
5671
Bram Moolenaarc7247912008-01-13 12:54:11 +00005672# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5674 p = buffer;
5675 for (i = 0; i < len; ++i)
5676 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5677 *p++ = buffer[i];
5678 len = p - buffer;
5679# endif
5680
5681
5682 /* file names are separated with Space */
5683 if (shell_style == STYLE_ECHO)
5684 {
5685 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5686 p = buffer;
5687 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5688 {
5689 while (*p != ' ' && *p != '\n')
5690 ++p;
5691 p = skipwhite(p); /* skip to next entry */
5692 }
5693 }
5694 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005695 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 {
5697 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5698 p = buffer;
5699 for (i = 0; *p != NUL; ++i) /* count number of entries */
5700 {
5701 while (*p != '\n' && *p != NUL)
5702 ++p;
5703 if (*p != NUL)
5704 ++p;
5705 p = skipwhite(p); /* skip leading white space */
5706 }
5707 }
5708 /* file names are separated with NUL */
5709 else
5710 {
5711 /*
5712 * Some versions of zsh use spaces instead of NULs to separate
5713 * results. Only do this when there is no NUL before the end of the
5714 * buffer, otherwise we would never be able to use file names with
5715 * embedded spaces when zsh does use NULs.
5716 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5717 * don't check for spaces again.
5718 */
5719 check_spaces = FALSE;
5720 if (shell_style == STYLE_PRINT && !did_find_nul)
5721 {
5722 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaar78a15312009-05-15 19:33:18 +00005723 if (len && (int)STRLEN(buffer) < (int)len - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 did_find_nul = TRUE;
5725 else
5726 check_spaces = TRUE;
5727 }
5728
5729 /*
5730 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5731 * already is one, for STYLE_GLOB it needs to be added.
5732 */
5733 if (len && buffer[len - 1] == NUL)
5734 --len;
5735 else
5736 buffer[len] = NUL;
5737 i = 0;
5738 for (p = buffer; p < buffer + len; ++p)
5739 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5740 {
5741 ++i;
5742 *p = NUL;
5743 }
5744 if (len)
5745 ++i; /* count last entry */
5746 }
5747 if (i == 0)
5748 {
5749 /*
5750 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5751 * /bin/sh will happily expand it to nothing rather than returning an
5752 * error; and hey, it's good to check anyway -- webb.
5753 */
5754 vim_free(buffer);
5755 goto notfound;
5756 }
5757 *num_file = i;
5758 *file = (char_u **)alloc(sizeof(char_u *) * i);
5759 if (*file == NULL)
5760 {
5761 /* out of memory */
5762 vim_free(buffer);
5763 return FAIL;
5764 }
5765
5766 /*
5767 * Isolate the individual file names.
5768 */
5769 p = buffer;
5770 for (i = 0; i < *num_file; ++i)
5771 {
5772 (*file)[i] = p;
5773 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005774 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5775 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00005777 while (!(shell_style == STYLE_ECHO && *p == ' ')
5778 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 ++p;
5780 if (p == buffer + len) /* last entry */
5781 *p = NUL;
5782 else
5783 {
5784 *p++ = NUL;
5785 p = skipwhite(p); /* skip to next entry */
5786 }
5787 }
5788 else /* NUL separates */
5789 {
5790 while (*p && p < buffer + len) /* skip entry */
5791 ++p;
5792 ++p; /* skip NUL */
5793 }
5794 }
5795
5796 /*
5797 * Move the file names to allocated memory.
5798 */
5799 for (j = 0, i = 0; i < *num_file; ++i)
5800 {
5801 /* Require the files to exist. Helps when using /bin/sh */
5802 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5803 continue;
5804
5805 /* check if this entry should be included */
5806 dir = (mch_isdir((*file)[i]));
5807 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5808 continue;
5809
Bram Moolenaara2031822006-03-07 22:29:51 +00005810 /* Skip files that are not executable if we check for that. */
5811 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5812 continue;
5813
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5815 if (p)
5816 {
5817 STRCPY(p, (*file)[i]);
5818 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00005819 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 (*file)[j++] = p;
5821 }
5822 }
5823 vim_free(buffer);
5824 *num_file = j;
5825
5826 if (*num_file == 0) /* rejected all entries */
5827 {
5828 vim_free(*file);
5829 *file = NULL;
5830 goto notfound;
5831 }
5832
5833 return OK;
5834
5835notfound:
5836 if (flags & EW_NOTFOUND)
5837 return save_patterns(num_pat, pat, num_file, file);
5838 return FAIL;
5839
5840#endif /* __EMX__ */
5841}
5842
5843#endif /* VMS */
5844
5845#ifndef __EMX__
5846 static int
5847save_patterns(num_pat, pat, num_file, file)
5848 int num_pat;
5849 char_u **pat;
5850 int *num_file;
5851 char_u ***file;
5852{
5853 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005854 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005855
5856 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5857 if (*file == NULL)
5858 return FAIL;
5859 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005860 {
5861 s = vim_strsave(pat[i]);
5862 if (s != NULL)
5863 /* Be compatible with expand_filename(): halve the number of
5864 * backslashes. */
5865 backslash_halve(s);
5866 (*file)[i] = s;
5867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 *num_file = num_pat;
5869 return OK;
5870}
5871#endif
5872
5873
5874/*
5875 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5876 * expand.
5877 */
5878 int
5879mch_has_exp_wildcard(p)
5880 char_u *p;
5881{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005882 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005883 {
5884#ifndef OS2
5885 if (*p == '\\' && p[1] != NUL)
5886 ++p;
5887 else
5888#endif
5889 if (vim_strchr((char_u *)
5890#ifdef VMS
5891 "*?%"
5892#else
5893# ifdef OS2
5894 "*?"
5895# else
5896 "*?[{'"
5897# endif
5898#endif
5899 , *p) != NULL)
5900 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901 }
5902 return FALSE;
5903}
5904
5905/*
5906 * Return TRUE if the string "p" contains a wildcard.
5907 * Don't recognize '~' at the end as a wildcard.
5908 */
5909 int
5910mch_has_wildcard(p)
5911 char_u *p;
5912{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005913 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 {
5915#ifndef OS2
5916 if (*p == '\\' && p[1] != NUL)
5917 ++p;
5918 else
5919#endif
5920 if (vim_strchr((char_u *)
5921#ifdef VMS
5922 "*?%$"
5923#else
5924# ifdef OS2
5925# ifdef VIM_BACKTICK
5926 "*?$`"
5927# else
5928 "*?$"
5929# endif
5930# else
5931 "*?[{`'$"
5932# endif
5933#endif
5934 , *p) != NULL
5935 || (*p == '~' && p[1] != NUL))
5936 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 }
5938 return FALSE;
5939}
5940
5941#ifndef __EMX__
5942 static int
5943have_wildcard(num, file)
5944 int num;
5945 char_u **file;
5946{
5947 int i;
5948
5949 for (i = 0; i < num; i++)
5950 if (mch_has_wildcard(file[i]))
5951 return 1;
5952 return 0;
5953}
5954
5955 static int
5956have_dollars(num, file)
5957 int num;
5958 char_u **file;
5959{
5960 int i;
5961
5962 for (i = 0; i < num; i++)
5963 if (vim_strchr(file[i], '$') != NULL)
5964 return TRUE;
5965 return FALSE;
5966}
5967#endif /* ifndef __EMX__ */
5968
5969#ifndef HAVE_RENAME
5970/*
5971 * Scaled-down version of rename(), which is missing in Xenix.
5972 * This version can only move regular files and will fail if the
5973 * destination exists.
5974 */
5975 int
5976mch_rename(src, dest)
5977 const char *src, *dest;
5978{
5979 struct stat st;
5980
5981 if (stat(dest, &st) >= 0) /* fail if destination exists */
5982 return -1;
5983 if (link(src, dest) != 0) /* link file to new name */
5984 return -1;
5985 if (mch_remove(src) == 0) /* delete link to old name */
5986 return 0;
5987 return -1;
5988}
5989#endif /* !HAVE_RENAME */
5990
5991#ifdef FEAT_MOUSE_GPM
5992/*
5993 * Initializes connection with gpm (if it isn't already opened)
5994 * Return 1 if succeeded (or connection already opened), 0 if failed
5995 */
5996 static int
5997gpm_open()
5998{
5999 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6000
6001 if (!gpm_flag)
6002 {
6003 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6004 gpm_connect.defaultMask = ~GPM_HARD;
6005 /* Default handling for mouse move*/
6006 gpm_connect.minMod = 0; /* Handle any modifier keys */
6007 gpm_connect.maxMod = 0xffff;
6008 if (Gpm_Open(&gpm_connect, 0) > 0)
6009 {
6010 /* gpm library tries to handling TSTP causes
6011 * problems. Anyways, we close connection to Gpm whenever
6012 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006013 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006015# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006017# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018 return 1; /* succeed */
6019 }
6020 if (gpm_fd == -2)
6021 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6022 return 0;
6023 }
6024 return 1; /* already open */
6025}
6026
6027/*
6028 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 */
6030 static void
6031gpm_close()
6032{
6033 if (gpm_flag && gpm_fd >= 0) /* if Open */
6034 Gpm_Close();
6035}
6036
6037/* Reads gpm event and adds special keys to input buf. Returns length of
6038 * generated key sequence.
6039 * This function is made after gui_send_mouse_event
6040 */
6041 static int
6042mch_gpm_process()
6043{
6044 int button;
6045 static Gpm_Event gpm_event;
6046 char_u string[6];
6047 int_u vim_modifiers;
6048 int row,col;
6049 unsigned char buttons_mask;
6050 unsigned char gpm_modifiers;
6051 static unsigned char old_buttons = 0;
6052
6053 Gpm_GetEvent(&gpm_event);
6054
6055#ifdef FEAT_GUI
6056 /* Don't put events in the input queue now. */
6057 if (hold_gui_events)
6058 return 0;
6059#endif
6060
6061 row = gpm_event.y - 1;
6062 col = gpm_event.x - 1;
6063
6064 string[0] = ESC; /* Our termcode */
6065 string[1] = 'M';
6066 string[2] = 'G';
6067 switch (GPM_BARE_EVENTS(gpm_event.type))
6068 {
6069 case GPM_DRAG:
6070 string[3] = MOUSE_DRAG;
6071 break;
6072 case GPM_DOWN:
6073 buttons_mask = gpm_event.buttons & ~old_buttons;
6074 old_buttons = gpm_event.buttons;
6075 switch (buttons_mask)
6076 {
6077 case GPM_B_LEFT:
6078 button = MOUSE_LEFT;
6079 break;
6080 case GPM_B_MIDDLE:
6081 button = MOUSE_MIDDLE;
6082 break;
6083 case GPM_B_RIGHT:
6084 button = MOUSE_RIGHT;
6085 break;
6086 default:
6087 return 0;
6088 /*Don't know what to do. Can more than one button be
6089 * reported in one event? */
6090 }
6091 string[3] = (char_u)(button | 0x20);
6092 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6093 break;
6094 case GPM_UP:
6095 string[3] = MOUSE_RELEASE;
6096 old_buttons &= ~gpm_event.buttons;
6097 break;
6098 default:
6099 return 0;
6100 }
6101 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6102 gpm_modifiers = gpm_event.modifiers;
6103 vim_modifiers = 0x0;
6104 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6105 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6106 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6107 */
6108 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6109 vim_modifiers |= MOUSE_SHIFT;
6110
6111 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6112 vim_modifiers |= MOUSE_CTRL;
6113 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6114 vim_modifiers |= MOUSE_ALT;
6115 string[3] |= vim_modifiers;
6116 string[4] = (char_u)(col + ' ' + 1);
6117 string[5] = (char_u)(row + ' ' + 1);
6118 add_to_input_buf(string, 6);
6119 return 6;
6120}
6121#endif /* FEAT_MOUSE_GPM */
6122
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006123#ifdef FEAT_SYSMOUSE
6124/*
6125 * Initialize connection with sysmouse.
6126 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6127 * output, any sysmouse output than will be processed via sig_sysmouse().
6128 * Return OK if succeeded, FAIL if failed.
6129 */
6130 static int
6131sysmouse_open()
6132{
6133 struct mouse_info mouse;
6134
6135 mouse.operation = MOUSE_MODE;
6136 mouse.u.mode.mode = 0;
6137 mouse.u.mode.signal = SIGUSR2;
6138 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6139 {
6140 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6141 mouse.operation = MOUSE_SHOW;
6142 ioctl(1, CONS_MOUSECTL, &mouse);
6143 return OK;
6144 }
6145 return FAIL;
6146}
6147
6148/*
6149 * Stop processing SIGUSR2 signals, and also make sure that
6150 * virtual console do not send us any sysmouse related signal.
6151 */
6152 static void
6153sysmouse_close()
6154{
6155 struct mouse_info mouse;
6156
6157 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6158 mouse.operation = MOUSE_MODE;
6159 mouse.u.mode.mode = 0;
6160 mouse.u.mode.signal = 0;
6161 ioctl(1, CONS_MOUSECTL, &mouse);
6162}
6163
6164/*
6165 * Gets info from sysmouse and adds special keys to input buf.
6166 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006167 static RETSIGTYPE
6168sig_sysmouse SIGDEFARG(sigarg)
6169{
6170 struct mouse_info mouse;
6171 struct video_info video;
6172 char_u string[6];
6173 int row, col;
6174 int button;
6175 int buttons;
6176 static int oldbuttons = 0;
6177
6178#ifdef FEAT_GUI
6179 /* Don't put events in the input queue now. */
6180 if (hold_gui_events)
6181 return;
6182#endif
6183
6184 mouse.operation = MOUSE_GETINFO;
6185 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6186 && ioctl(1, FBIO_MODEINFO, &video) != -1
6187 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6188 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6189 {
6190 row = mouse.u.data.y / video.vi_cheight;
6191 col = mouse.u.data.x / video.vi_cwidth;
6192 buttons = mouse.u.data.buttons;
6193 string[0] = ESC; /* Our termcode */
6194 string[1] = 'M';
6195 string[2] = 'S';
6196 if (oldbuttons == buttons && buttons != 0)
6197 {
6198 button = MOUSE_DRAG;
6199 }
6200 else
6201 {
6202 switch (buttons)
6203 {
6204 case 0:
6205 button = MOUSE_RELEASE;
6206 break;
6207 case 1:
6208 button = MOUSE_LEFT;
6209 break;
6210 case 2:
6211 button = MOUSE_MIDDLE;
6212 break;
6213 case 4:
6214 button = MOUSE_RIGHT;
6215 break;
6216 default:
6217 return;
6218 }
6219 oldbuttons = buttons;
6220 }
6221 string[3] = (char_u)(button);
6222 string[4] = (char_u)(col + ' ' + 1);
6223 string[5] = (char_u)(row + ' ' + 1);
6224 add_to_input_buf(string, 6);
6225 }
6226 return;
6227}
6228#endif /* FEAT_SYSMOUSE */
6229
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230#if defined(FEAT_LIBCALL) || defined(PROTO)
6231typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6232typedef char_u * (*INTPROCSTR)__ARGS((int));
6233typedef int (*STRPROCINT)__ARGS((char_u *));
6234typedef int (*INTPROCINT)__ARGS((int));
6235
6236/*
6237 * Call a DLL routine which takes either a string or int param
6238 * and returns an allocated string.
6239 */
6240 int
6241mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6242 char_u *libname;
6243 char_u *funcname;
6244 char_u *argstring; /* NULL when using a argint */
6245 int argint;
6246 char_u **string_result;/* NULL when using number_result */
6247 int *number_result;
6248{
6249# if defined(USE_DLOPEN)
6250 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006251 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252# else
6253 shl_t hinstLib;
6254# endif
6255 STRPROCSTR ProcAdd;
6256 INTPROCSTR ProcAddI;
6257 char_u *retval_str = NULL;
6258 int retval_int = 0;
6259 int success = FALSE;
6260
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006261 /*
6262 * Get a handle to the DLL module.
6263 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006265 /* First clear any error, it's not cleared by the dlopen() call. */
6266 (void)dlerror();
6267
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 hinstLib = dlopen((char *)libname, RTLD_LAZY
6269# ifdef RTLD_LOCAL
6270 | RTLD_LOCAL
6271# endif
6272 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006273 if (hinstLib == NULL)
6274 {
6275 /* "dlerr" must be used before dlclose() */
6276 dlerr = (char *)dlerror();
6277 if (dlerr != NULL)
6278 EMSG2(_("dlerror = \"%s\""), dlerr);
6279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280# else
6281 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6282# endif
6283
6284 /* If the handle is valid, try to get the function address. */
6285 if (hinstLib != NULL)
6286 {
6287# ifdef HAVE_SETJMP_H
6288 /*
6289 * Catch a crash when calling the library function. For example when
6290 * using a number where a string pointer is expected.
6291 */
6292 mch_startjmp();
6293 if (SETJMP(lc_jump_env) != 0)
6294 {
6295 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006296# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006297 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006298# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 mch_didjmp();
6300 }
6301 else
6302# endif
6303 {
6304 retval_str = NULL;
6305 retval_int = 0;
6306
6307 if (argstring != NULL)
6308 {
6309# if defined(USE_DLOPEN)
6310 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006311 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312# else
6313 if (shl_findsym(&hinstLib, (const char *)funcname,
6314 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6315 ProcAdd = NULL;
6316# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006317 if ((success = (ProcAdd != NULL
6318# if defined(USE_DLOPEN)
6319 && dlerr == NULL
6320# endif
6321 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 {
6323 if (string_result == NULL)
6324 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6325 else
6326 retval_str = (ProcAdd)(argstring);
6327 }
6328 }
6329 else
6330 {
6331# if defined(USE_DLOPEN)
6332 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006333 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334# else
6335 if (shl_findsym(&hinstLib, (const char *)funcname,
6336 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6337 ProcAddI = NULL;
6338# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006339 if ((success = (ProcAddI != NULL
6340# if defined(USE_DLOPEN)
6341 && dlerr == NULL
6342# endif
6343 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 {
6345 if (string_result == NULL)
6346 retval_int = ((INTPROCINT)ProcAddI)(argint);
6347 else
6348 retval_str = (ProcAddI)(argint);
6349 }
6350 }
6351
6352 /* Save the string before we free the library. */
6353 /* Assume that a "1" or "-1" result is an illegal pointer. */
6354 if (string_result == NULL)
6355 *number_result = retval_int;
6356 else if (retval_str != NULL
6357 && retval_str != (char_u *)1
6358 && retval_str != (char_u *)-1)
6359 *string_result = vim_strsave(retval_str);
6360 }
6361
6362# ifdef HAVE_SETJMP_H
6363 mch_endjmp();
6364# ifdef SIGHASARG
6365 if (lc_signal != 0)
6366 {
6367 int i;
6368
6369 /* try to find the name of this signal */
6370 for (i = 0; signal_info[i].sig != -1; i++)
6371 if (lc_signal == signal_info[i].sig)
6372 break;
6373 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6374 }
6375# endif
6376# endif
6377
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006379 /* "dlerr" must be used before dlclose() */
6380 if (dlerr != NULL)
6381 EMSG2(_("dlerror = \"%s\""), dlerr);
6382
6383 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 (void)dlclose(hinstLib);
6385# else
6386 (void)shl_unload(hinstLib);
6387# endif
6388 }
6389
6390 if (!success)
6391 {
6392 EMSG2(_(e_libcall), funcname);
6393 return FAIL;
6394 }
6395
6396 return OK;
6397}
6398#endif
6399
6400#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6401static int xterm_trace = -1; /* default: disabled */
6402static int xterm_button;
6403
6404/*
6405 * Setup a dummy window for X selections in a terminal.
6406 */
6407 void
6408setup_term_clip()
6409{
6410 int z = 0;
6411 char *strp = "";
6412 Widget AppShell;
6413
6414 if (!x_connect_to_server())
6415 return;
6416
6417 open_app_context();
6418 if (app_context != NULL && xterm_Shell == (Widget)0)
6419 {
6420 int (*oldhandler)();
6421#if defined(HAVE_SETJMP_H)
6422 int (*oldIOhandler)();
6423#endif
6424# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6425 struct timeval start_tv;
6426
6427 if (p_verbose > 0)
6428 gettimeofday(&start_tv, NULL);
6429# endif
6430
6431 /* Ignore X errors while opening the display */
6432 oldhandler = XSetErrorHandler(x_error_check);
6433
6434#if defined(HAVE_SETJMP_H)
6435 /* Ignore X IO errors while opening the display */
6436 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6437 mch_startjmp();
6438 if (SETJMP(lc_jump_env) != 0)
6439 {
6440 mch_didjmp();
6441 xterm_dpy = NULL;
6442 }
6443 else
6444#endif
6445 {
6446 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6447 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6448#if defined(HAVE_SETJMP_H)
6449 mch_endjmp();
6450#endif
6451 }
6452
6453#if defined(HAVE_SETJMP_H)
6454 /* Now handle X IO errors normally. */
6455 (void)XSetIOErrorHandler(oldIOhandler);
6456#endif
6457 /* Now handle X errors normally. */
6458 (void)XSetErrorHandler(oldhandler);
6459
6460 if (xterm_dpy == NULL)
6461 {
6462 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006463 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464 return;
6465 }
6466
6467 /* Catch terminating error of the X server connection. */
6468 (void)XSetIOErrorHandler(x_IOerror_handler);
6469
6470# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6471 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006472 {
6473 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006475 verbose_leave();
6476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477# endif
6478
6479 /* Create a Shell to make converters work. */
6480 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6481 applicationShellWidgetClass, xterm_dpy,
6482 NULL);
6483 if (AppShell == (Widget)0)
6484 return;
6485 xterm_Shell = XtVaCreatePopupShell("VIM",
6486 topLevelShellWidgetClass, AppShell,
6487 XtNmappedWhenManaged, 0,
6488 XtNwidth, 1,
6489 XtNheight, 1,
6490 NULL);
6491 if (xterm_Shell == (Widget)0)
6492 return;
6493
6494 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006495 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 if (x11_display == NULL)
6497 x11_display = xterm_dpy;
6498
6499 XtRealizeWidget(xterm_Shell);
6500 XSync(xterm_dpy, False);
6501 xterm_update();
6502 }
6503 if (xterm_Shell != (Widget)0)
6504 {
6505 clip_init(TRUE);
6506 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6507 x11_window = (Window)atol(strp);
6508 /* Check if $WINDOWID is valid. */
6509 if (test_x11_window(xterm_dpy) == FAIL)
6510 x11_window = 0;
6511 if (x11_window != 0)
6512 xterm_trace = 0;
6513 }
6514}
6515
6516 void
6517start_xterm_trace(button)
6518 int button;
6519{
6520 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6521 return;
6522 xterm_trace = 1;
6523 xterm_button = button;
6524 do_xterm_trace();
6525}
6526
6527
6528 void
6529stop_xterm_trace()
6530{
6531 if (xterm_trace < 0)
6532 return;
6533 xterm_trace = 0;
6534}
6535
6536/*
6537 * Query the xterm pointer and generate mouse termcodes if necessary
6538 * return TRUE if dragging is active, else FALSE
6539 */
6540 static int
6541do_xterm_trace()
6542{
6543 Window root, child;
6544 int root_x, root_y;
6545 int win_x, win_y;
6546 int row, col;
6547 int_u mask_return;
6548 char_u buf[50];
6549 char_u *strp;
6550 long got_hints;
6551 static char_u *mouse_code;
6552 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6553 static int prev_row = 0, prev_col = 0;
6554 static XSizeHints xterm_hints;
6555
6556 if (xterm_trace <= 0)
6557 return FALSE;
6558
6559 if (xterm_trace == 1)
6560 {
6561 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006562 * have changed recently. */
6563 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6564 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 || xterm_hints.width_inc <= 1
6566 || xterm_hints.height_inc <= 1)
6567 {
6568 xterm_trace = -1; /* Not enough data -- disable tracing */
6569 return FALSE;
6570 }
6571
6572 /* Rely on the same mouse code for the duration of this */
6573 mouse_code = find_termcode(mouse_name);
6574 prev_row = mouse_row;
6575 prev_row = mouse_col;
6576 xterm_trace = 2;
6577
6578 /* Find the offset of the chars, there might be a scrollbar on the
6579 * left of the window and/or a menu on the top (eterm etc.) */
6580 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6581 &win_x, &win_y, &mask_return);
6582 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6583 - (xterm_hints.height_inc / 2);
6584 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6585 xterm_hints.y = 2;
6586 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6587 - (xterm_hints.width_inc / 2);
6588 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6589 xterm_hints.x = 2;
6590 return TRUE;
6591 }
6592 if (mouse_code == NULL)
6593 {
6594 xterm_trace = 0;
6595 return FALSE;
6596 }
6597
6598 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6599 &win_x, &win_y, &mask_return);
6600
6601 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6602 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6603 if (row == prev_row && col == prev_col)
6604 return TRUE;
6605
6606 STRCPY(buf, mouse_code);
6607 strp = buf + STRLEN(buf);
6608 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6609 *strp++ = (char_u)(col + ' ' + 1);
6610 *strp++ = (char_u)(row + ' ' + 1);
6611 *strp = 0;
6612 add_to_input_buf(buf, STRLEN(buf));
6613
6614 prev_row = row;
6615 prev_col = col;
6616 return TRUE;
6617}
6618
6619# if defined(FEAT_GUI) || defined(PROTO)
6620/*
6621 * Destroy the display, window and app_context. Required for GTK.
6622 */
6623 void
6624clear_xterm_clip()
6625{
6626 if (xterm_Shell != (Widget)0)
6627 {
6628 XtDestroyWidget(xterm_Shell);
6629 xterm_Shell = (Widget)0;
6630 }
6631 if (xterm_dpy != NULL)
6632 {
Bram Moolenaare8208012008-06-20 09:59:25 +00006633# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 /* Lesstif and Solaris crash here, lose some memory */
6635 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00006636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (x11_display == xterm_dpy)
6638 x11_display = NULL;
6639 xterm_dpy = NULL;
6640 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006641# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 if (app_context != (XtAppContext)NULL)
6643 {
6644 /* Lesstif and Solaris crash here, lose some memory */
6645 XtDestroyApplicationContext(app_context);
6646 app_context = (XtAppContext)NULL;
6647 }
Bram Moolenaare8208012008-06-20 09:59:25 +00006648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649}
6650# endif
6651
6652/*
6653 * Catch up with any queued X events. This may put keyboard input into the
6654 * input buffer, call resize call-backs, trigger timers etc. If there is
6655 * nothing in the X event queue (& no timers pending), then we return
6656 * immediately.
6657 */
6658 static void
6659xterm_update()
6660{
6661 XEvent event;
6662
6663 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6664 {
6665 XtAppNextEvent(app_context, &event);
6666#ifdef FEAT_CLIENTSERVER
6667 {
6668 XPropertyEvent *e = (XPropertyEvent *)&event;
6669
6670 if (e->type == PropertyNotify && e->window == commWindow
6671 && e->atom == commProperty && e->state == PropertyNewValue)
6672 serverEventProc(xterm_dpy, &event);
6673 }
6674#endif
6675 XtDispatchEvent(&event);
6676 }
6677}
6678
6679 int
6680clip_xterm_own_selection(cbd)
6681 VimClipboard *cbd;
6682{
6683 if (xterm_Shell != (Widget)0)
6684 return clip_x11_own_selection(xterm_Shell, cbd);
6685 return FAIL;
6686}
6687
6688 void
6689clip_xterm_lose_selection(cbd)
6690 VimClipboard *cbd;
6691{
6692 if (xterm_Shell != (Widget)0)
6693 clip_x11_lose_selection(xterm_Shell, cbd);
6694}
6695
6696 void
6697clip_xterm_request_selection(cbd)
6698 VimClipboard *cbd;
6699{
6700 if (xterm_Shell != (Widget)0)
6701 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6702}
6703
6704 void
6705clip_xterm_set_selection(cbd)
6706 VimClipboard *cbd;
6707{
6708 clip_x11_set_selection(cbd);
6709}
6710#endif
6711
6712
6713#if defined(USE_XSMP) || defined(PROTO)
6714/*
6715 * Code for X Session Management Protocol.
6716 */
6717static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6718static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6719static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6720static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6721static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6722
6723
6724# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6725static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6726
6727/*
6728 * This is our chance to ask the user if they want to save,
6729 * or abort the logout
6730 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 static void
6732xsmp_handle_interaction(smc_conn, client_data)
6733 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006734 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735{
6736 cmdmod_T save_cmdmod;
6737 int cancel_shutdown = False;
6738
6739 save_cmdmod = cmdmod;
6740 cmdmod.confirm = TRUE;
6741 if (check_changed_any(FALSE))
6742 /* Mustn't logout */
6743 cancel_shutdown = True;
6744 cmdmod = save_cmdmod;
6745 setcursor(); /* position cursor */
6746 out_flush();
6747
6748 /* Done interaction */
6749 SmcInteractDone(smc_conn, cancel_shutdown);
6750
6751 /* Finish off
6752 * Only end save-yourself here if we're not cancelling shutdown;
6753 * we'll get a cancelled callback later in which we'll end it.
6754 * Hopefully get around glitchy SMs (like GNOME-1)
6755 */
6756 if (!cancel_shutdown)
6757 {
6758 xsmp.save_yourself = False;
6759 SmcSaveYourselfDone(smc_conn, True);
6760 }
6761}
6762# endif
6763
6764/*
6765 * Callback that starts save-yourself.
6766 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 static void
6768xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6769 shutdown, interact_style, fast)
6770 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006771 SmPointer client_data UNUSED;
6772 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006774 int interact_style UNUSED;
6775 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776{
6777 /* Handle already being in saveyourself */
6778 if (xsmp.save_yourself)
6779 SmcSaveYourselfDone(smc_conn, True);
6780 xsmp.save_yourself = True;
6781 xsmp.shutdown = shutdown;
6782
6783 /* First up, preserve all files */
6784 out_flush();
6785 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6786
6787 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006788 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789
6790# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6791 /* Now see if we can ask about unsaved files */
6792 if (shutdown && !fast && gui.in_use)
6793 /* Need to interact with user, but need SM's permission */
6794 SmcInteractRequest(smc_conn, SmDialogError,
6795 xsmp_handle_interaction, client_data);
6796 else
6797# endif
6798 {
6799 /* Can stop the cycle here */
6800 SmcSaveYourselfDone(smc_conn, True);
6801 xsmp.save_yourself = False;
6802 }
6803}
6804
6805
6806/*
6807 * Callback to warn us of imminent death.
6808 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006809 static void
6810xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006811 SmcConn smc_conn UNUSED;
6812 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813{
6814 xsmp_close();
6815
6816 /* quit quickly leaving swapfiles for modified buffers behind */
6817 getout_preserve_modified(0);
6818}
6819
6820
6821/*
6822 * Callback to tell us that save-yourself has completed.
6823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 static void
6825xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006826 SmcConn smc_conn UNUSED;
6827 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828{
6829 xsmp.save_yourself = False;
6830}
6831
6832
6833/*
6834 * Callback to tell us that an instigated shutdown was cancelled
6835 * (maybe even by us)
6836 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 static void
6838xsmp_shutdown_cancelled(smc_conn, client_data)
6839 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006840 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841{
6842 if (xsmp.save_yourself)
6843 SmcSaveYourselfDone(smc_conn, True);
6844 xsmp.save_yourself = False;
6845 xsmp.shutdown = False;
6846}
6847
6848
6849/*
6850 * Callback to tell us that a new ICE connection has been established.
6851 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 static void
6853xsmp_ice_connection(iceConn, clientData, opening, watchData)
6854 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006855 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006856 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006857 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858{
6859 /* Intercept creation of ICE connection fd */
6860 if (opening)
6861 {
6862 xsmp_icefd = IceConnectionNumber(iceConn);
6863 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6864 }
6865}
6866
6867
6868/* Handle any ICE processing that's required; return FAIL if SM lost */
6869 int
6870xsmp_handle_requests()
6871{
6872 Bool rep;
6873
6874 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6875 == IceProcessMessagesIOError)
6876 {
6877 /* Lost ICE */
6878 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006879 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 xsmp_close();
6881 return FAIL;
6882 }
6883 else
6884 return OK;
6885}
6886
6887static int dummy;
6888
6889/* Set up X Session Management Protocol */
6890 void
6891xsmp_init(void)
6892{
6893 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 SmcCallbacks smcallbacks;
6895#if 0
6896 SmPropValue smname;
6897 SmProp smnameprop;
6898 SmProp *smprops[1];
6899#endif
6900
6901 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006902 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903
6904 xsmp.save_yourself = xsmp.shutdown = False;
6905
6906 /* Set up SM callbacks - must have all, even if they're not used */
6907 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6908 smcallbacks.save_yourself.client_data = NULL;
6909 smcallbacks.die.callback = xsmp_die;
6910 smcallbacks.die.client_data = NULL;
6911 smcallbacks.save_complete.callback = xsmp_save_complete;
6912 smcallbacks.save_complete.client_data = NULL;
6913 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6914 smcallbacks.shutdown_cancelled.client_data = NULL;
6915
6916 /* Set up a watch on ICE connection creations. The "dummy" argument is
6917 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6918 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6919 {
6920 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006921 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 return;
6923 }
6924
6925 /* Create an SM connection */
6926 xsmp.smcconn = SmcOpenConnection(
6927 NULL,
6928 NULL,
6929 SmProtoMajor,
6930 SmProtoMinor,
6931 SmcSaveYourselfProcMask | SmcDieProcMask
6932 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6933 &smcallbacks,
6934 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00006935 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 sizeof(errorstring),
6937 errorstring);
6938 if (xsmp.smcconn == NULL)
6939 {
6940 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006941
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006943 {
6944 vim_snprintf(errorreport, sizeof(errorreport),
6945 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6946 verb_msg((char_u *)errorreport);
6947 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 return;
6949 }
6950 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6951
6952#if 0
6953 /* ID ourselves */
6954 smname.value = "vim";
6955 smname.length = 3;
6956 smnameprop.name = "SmProgram";
6957 smnameprop.type = "SmARRAY8";
6958 smnameprop.num_vals = 1;
6959 smnameprop.vals = &smname;
6960
6961 smprops[0] = &smnameprop;
6962 SmcSetProperties(xsmp.smcconn, 1, smprops);
6963#endif
6964}
6965
6966
6967/* Shut down XSMP comms. */
6968 void
6969xsmp_close()
6970{
6971 if (xsmp_icefd != -1)
6972 {
6973 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00006974 if (xsmp.clientid != NULL)
6975 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00006976 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 xsmp_icefd = -1;
6978 }
6979}
6980#endif /* USE_XSMP */
6981
6982
6983#ifdef EBCDIC
6984/* Translate character to its CTRL- value */
6985char CtrlTable[] =
6986{
6987/* 00 - 5E */
6988 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6989 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6990 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6991 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6992 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6993 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6994/* ^ */ 0x1E,
6995/* - */ 0x1F,
6996/* 61 - 6C */
6997 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6998/* _ */ 0x1F,
6999/* 6E - 80 */
7000 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7001/* a */ 0x01,
7002/* b */ 0x02,
7003/* c */ 0x03,
7004/* d */ 0x37,
7005/* e */ 0x2D,
7006/* f */ 0x2E,
7007/* g */ 0x2F,
7008/* h */ 0x16,
7009/* i */ 0x05,
7010/* 8A - 90 */
7011 0, 0, 0, 0, 0, 0, 0,
7012/* j */ 0x15,
7013/* k */ 0x0B,
7014/* l */ 0x0C,
7015/* m */ 0x0D,
7016/* n */ 0x0E,
7017/* o */ 0x0F,
7018/* p */ 0x10,
7019/* q */ 0x11,
7020/* r */ 0x12,
7021/* 9A - A1 */
7022 0, 0, 0, 0, 0, 0, 0, 0,
7023/* s */ 0x13,
7024/* t */ 0x3C,
7025/* u */ 0x3D,
7026/* v */ 0x32,
7027/* w */ 0x26,
7028/* x */ 0x18,
7029/* y */ 0x19,
7030/* z */ 0x3F,
7031/* AA - AC */
7032 0, 0, 0,
7033/* [ */ 0x27,
7034/* AE - BC */
7035 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7036/* ] */ 0x1D,
7037/* BE - C0 */ 0, 0, 0,
7038/* A */ 0x01,
7039/* B */ 0x02,
7040/* C */ 0x03,
7041/* D */ 0x37,
7042/* E */ 0x2D,
7043/* F */ 0x2E,
7044/* G */ 0x2F,
7045/* H */ 0x16,
7046/* I */ 0x05,
7047/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7048/* J */ 0x15,
7049/* K */ 0x0B,
7050/* L */ 0x0C,
7051/* M */ 0x0D,
7052/* N */ 0x0E,
7053/* O */ 0x0F,
7054/* P */ 0x10,
7055/* Q */ 0x11,
7056/* R */ 0x12,
7057/* DA - DF */ 0, 0, 0, 0, 0, 0,
7058/* \ */ 0x1C,
7059/* E1 */ 0,
7060/* S */ 0x13,
7061/* T */ 0x3C,
7062/* U */ 0x3D,
7063/* V */ 0x32,
7064/* W */ 0x26,
7065/* X */ 0x18,
7066/* Y */ 0x19,
7067/* Z */ 0x3F,
7068/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7069 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7070};
7071
7072char MetaCharTable[]=
7073{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7074 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7075 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7076 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7077 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7078};
7079
7080
7081/* TODO: Use characters NOT numbers!!! */
7082char CtrlCharTable[]=
7083{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7084 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7085 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7086 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7087 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7088};
7089
7090
7091#endif