blob: 78e9914b16cc5a0766452bf5419a4713d730c8b4 [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 Moolenaar5bd32f42014-04-02 14:05:38 +020049#ifdef HAVE_SMACK
50# include <attr/xattr.h>
51# include <linux/xattr.h>
52# ifndef SMACK_LABEL_LEN
53# define SMACK_LABEL_LEN 1024
54# endif
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057/*
58 * Use this prototype for select, some include files have a wrong prototype
59 */
Bram Moolenaar311d9822007-02-27 15:48:28 +000060#ifndef __TANDEM
61# undef select
62# ifdef __BEOS__
63# define select beos_select
64# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#endif
66
Bram Moolenaara2442432007-04-26 14:26:37 +000067#ifdef __CYGWIN__
68# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000069# include <cygwin/version.h>
70# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
71 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010072# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
73# define WIN32_LEAN_AND_MEAN
74# include <windows.h>
75# include "winclip.pro"
76# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000077# endif
78#endif
79
Bram Moolenaar071d4272004-06-13 20:20:40 +000080#if defined(HAVE_SELECT)
81extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
82#endif
83
84#ifdef FEAT_MOUSE_GPM
85# include <gpm.h>
86/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
87 * I just copied relevant defines here. A cleaner solution would be to put gpm
88 * code into separate file and include there linux/keyboard.h
89 */
90/* #include <linux/keyboard.h> */
91# define KG_SHIFT 0
92# define KG_CTRL 2
93# define KG_ALT 3
94# define KG_ALTGR 1
95# define KG_SHIFTL 4
96# define KG_SHIFTR 5
97# define KG_CTRLL 6
98# define KG_CTRLR 7
99# define KG_CAPSSHIFT 8
100
101static void gpm_close __ARGS((void));
102static int gpm_open __ARGS((void));
103static int mch_gpm_process __ARGS((void));
104#endif
105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000106#ifdef FEAT_SYSMOUSE
107# include <sys/consio.h>
108# include <sys/fbio.h>
109
110static int sysmouse_open __ARGS((void));
111static void sysmouse_close __ARGS((void));
112static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG);
113#endif
114
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115/*
116 * end of autoconf section. To be extended...
117 */
118
119/* Are the following #ifdefs still required? And why? Is that for X11? */
120
121#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
122# ifdef SIGWINCH
123# undef SIGWINCH
124# endif
125# ifdef TIOCGWINSZ
126# undef TIOCGWINSZ
127# endif
128#endif
129
130#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
131# define SIGWINCH SIGWINDOW
132#endif
133
134#ifdef FEAT_X11
135# include <X11/Xlib.h>
136# include <X11/Xutil.h>
137# include <X11/Xatom.h>
138# ifdef FEAT_XCLIPBOARD
139# include <X11/Intrinsic.h>
140# include <X11/Shell.h>
141# include <X11/StringDefs.h>
142static Widget xterm_Shell = (Widget)0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +0100143static void clip_update __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000144static void xterm_update __ARGS((void));
145# endif
146
147# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
148Window x11_window = 0;
149# endif
150Display *x11_display = NULL;
151
152# ifdef FEAT_TITLE
153static int get_x11_windis __ARGS((void));
154static void set_x11_title __ARGS((char_u *));
155static void set_x11_icon __ARGS((char_u *));
156# endif
157#endif
158
159#ifdef FEAT_TITLE
160static int get_x11_title __ARGS((int));
161static int get_x11_icon __ARGS((int));
162
163static char_u *oldtitle = NULL;
164static int did_set_title = FALSE;
165static char_u *oldicon = NULL;
166static int did_set_icon = FALSE;
167#endif
168
169static void may_core_dump __ARGS((void));
170
Bram Moolenaar205b8862011-09-07 15:04:31 +0200171#ifdef HAVE_UNION_WAIT
172typedef union wait waitstatus;
173#else
174typedef int waitstatus;
175#endif
Bram Moolenaar9f118812011-09-08 23:24:14 +0200176static pid_t wait4pid __ARGS((pid_t, waitstatus *));
Bram Moolenaar205b8862011-09-07 15:04:31 +0200177
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178static int WaitForChar __ARGS((long));
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100179#if defined(__BEOS__) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180int RealWaitForChar __ARGS((int, long, int *));
181#else
182static int RealWaitForChar __ARGS((int, long, int *));
183#endif
184
185#ifdef FEAT_XCLIPBOARD
186static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000187# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000188#endif
189
190static void handle_resize __ARGS((void));
191
192#if defined(SIGWINCH)
193static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
194#endif
195#if defined(SIGINT)
196static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
197#endif
198#if defined(SIGPWR)
199static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
200#endif
201#if defined(SIGALRM) && defined(FEAT_X11) \
202 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
203# define SET_SIG_ALARM
204static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000205/* volatile because it is used in signal handler sig_alarm(). */
206static volatile int sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207#endif
208static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
209
Bram Moolenaardf177f62005-02-22 08:39:57 +0000210static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211static void set_signals __ARGS((void));
212static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
213#ifndef __EMX__
214static int have_wildcard __ARGS((int, char_u **));
215static int have_dollars __ARGS((int, char_u **));
216#endif
217
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218#ifndef __EMX__
219static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
220#endif
221
222#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000223# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224#endif
225
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000226/* volatile because it is used in signal handler sig_winch(). */
227static volatile int do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228#ifndef __EMX__
229static char_u *extra_shell_arg = NULL;
230static int show_shell_mess = TRUE;
231#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000232/* volatile because it is used in signal handler deathtrap(). */
233static volatile int deadly_signal = 0; /* The signal we caught */
234/* volatile because it is used in signal handler deathtrap(). */
235static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
238
239#ifdef USE_XSMP
240typedef struct
241{
242 SmcConn smcconn; /* The SM connection ID */
243 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200244 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245 Bool save_yourself; /* If we're in the middle of a save_yourself */
246 Bool shutdown; /* If we're in shutdown mode */
247} xsmp_config_T;
248
249static xsmp_config_T xsmp;
250#endif
251
252#ifdef SYS_SIGLIST_DECLARED
253/*
254 * I have seen
255 * extern char *_sys_siglist[NSIG];
256 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
257 * that describe the signals. That is nearly what we want here. But
258 * autoconf does only check for sys_siglist (without the underscore), I
259 * do not want to change everything today.... jw.
260 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
261 */
262#endif
263
264static struct signalinfo
265{
266 int sig; /* Signal number, eg. SIGSEGV etc */
267 char *name; /* Signal name (not char_u!). */
268 char deadly; /* Catch as a deadly signal? */
269} signal_info[] =
270{
271#ifdef SIGHUP
272 {SIGHUP, "HUP", TRUE},
273#endif
274#ifdef SIGQUIT
275 {SIGQUIT, "QUIT", TRUE},
276#endif
277#ifdef SIGILL
278 {SIGILL, "ILL", TRUE},
279#endif
280#ifdef SIGTRAP
281 {SIGTRAP, "TRAP", TRUE},
282#endif
283#ifdef SIGABRT
284 {SIGABRT, "ABRT", TRUE},
285#endif
286#ifdef SIGEMT
287 {SIGEMT, "EMT", TRUE},
288#endif
289#ifdef SIGFPE
290 {SIGFPE, "FPE", TRUE},
291#endif
292#ifdef SIGBUS
293 {SIGBUS, "BUS", TRUE},
294#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100295#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
296 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297 {SIGSEGV, "SEGV", TRUE},
298#endif
299#ifdef SIGSYS
300 {SIGSYS, "SYS", TRUE},
301#endif
302#ifdef SIGALRM
303 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
304#endif
305#ifdef SIGTERM
306 {SIGTERM, "TERM", TRUE},
307#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100308#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309 {SIGVTALRM, "VTALRM", TRUE},
310#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000311#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
312 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
313 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314 {SIGPROF, "PROF", TRUE},
315#endif
316#ifdef SIGXCPU
317 {SIGXCPU, "XCPU", TRUE},
318#endif
319#ifdef SIGXFSZ
320 {SIGXFSZ, "XFSZ", TRUE},
321#endif
322#ifdef SIGUSR1
323 {SIGUSR1, "USR1", TRUE},
324#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000325#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
326 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 {SIGUSR2, "USR2", TRUE},
328#endif
329#ifdef SIGINT
330 {SIGINT, "INT", FALSE},
331#endif
332#ifdef SIGWINCH
333 {SIGWINCH, "WINCH", FALSE},
334#endif
335#ifdef SIGTSTP
336 {SIGTSTP, "TSTP", FALSE},
337#endif
338#ifdef SIGPIPE
339 {SIGPIPE, "PIPE", FALSE},
340#endif
341 {-1, "Unknown!", FALSE}
342};
343
Bram Moolenaar25724922009-07-14 15:38:41 +0000344 int
345mch_chdir(path)
346 char *path;
347{
348 if (p_verbose >= 5)
349 {
350 verbose_enter();
351 smsg((char_u *)"chdir(%s)", path);
352 verbose_leave();
353 }
354# ifdef VMS
355 return chdir(vms_fixfilename(path));
356# else
357 return chdir(path);
358# endif
359}
360
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000361/*
362 * Write s[len] to the screen.
363 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 void
365mch_write(s, len)
366 char_u *s;
367 int len;
368{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000369 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 if (p_wd) /* Unix is too fast, slow down a bit more */
371 RealWaitForChar(read_cmd_fd, p_wd, NULL);
372}
373
374/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000375 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 * Get a characters from the keyboard.
377 * Return the number of characters that are available.
378 * If wtime == 0 do not wait for characters.
379 * If wtime == n wait a short time for characters.
380 * If wtime == -1 wait forever for characters.
381 */
382 int
383mch_inchar(buf, maxlen, wtime, tb_change_cnt)
384 char_u *buf;
385 int maxlen;
386 long wtime; /* don't use "time", MIPS cannot handle it */
387 int tb_change_cnt;
388{
389 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390
Bram Moolenaar67c53842010-05-22 18:28:27 +0200391#ifdef FEAT_NETBEANS_INTG
392 /* Process the queued netbeans messages. */
Bram Moolenaarb26e6322010-05-22 21:34:09 +0200393 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200394#endif
395
Bram Moolenaar071d4272004-06-13 20:20:40 +0000396 /* Check if window changed size while we were busy, perhaps the ":set
397 * columns=99" command was used. */
398 while (do_resize)
399 handle_resize();
400
401 if (wtime >= 0)
402 {
403 while (WaitForChar(wtime) == 0) /* no character available */
404 {
405 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200408#ifdef FEAT_NETBEANS_INTG
409 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200410 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200411#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 }
413 }
414 else /* wtime == -1 */
415 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 /*
417 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000418 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 * Also done when interrupted by SIGWINCH.
420 */
421 if (WaitForChar(p_ut) == 0)
422 {
423#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +0000424 if (trigger_cursorhold() && maxlen >= 3
425 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000427 buf[0] = K_SPECIAL;
428 buf[1] = KS_EXTRA;
429 buf[2] = (int)KE_CURSORHOLD;
430 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000433 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434 }
435 }
436
437 for (;;) /* repeat until we got a character */
438 {
439 while (do_resize) /* window changed size */
440 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200441
442#ifdef FEAT_NETBEANS_INTG
443 /* Process the queued netbeans messages. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +0200444 netbeans_parse_messages();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200445#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200447 * We want to be interrupted by the winch signal
448 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200450 if (WaitForChar(-1L) == 0)
451 {
452 if (do_resize) /* interrupted by SIGWINCH signal */
453 handle_resize();
454 return 0;
455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456
457 /* If input was put directly in typeahead buffer bail out here. */
458 if (typebuf_changed(tb_change_cnt))
459 return 0;
460
461 /*
462 * For some terminals we only get one character at a time.
463 * We want the get all available characters, so we could keep on
464 * trying until none is available
465 * For some other terminals this is quite slow, that's why we don't do
466 * it.
467 */
468 len = read_from_input_buf(buf, (long)maxlen);
469 if (len > 0)
470 {
471#ifdef OS2
472 int i;
473
474 for (i = 0; i < len; i++)
475 if (buf[i] == 0)
476 buf[i] = K_NUL;
477#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 return len;
479 }
480 }
481}
482
483 static void
484handle_resize()
485{
486 do_resize = FALSE;
487 shell_resized();
488}
489
490/*
491 * return non-zero if a character is available
492 */
493 int
494mch_char_avail()
495{
496 return WaitForChar(0L);
497}
498
499#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
500# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000501# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502# endif
503# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
504# include <sys/sysctl.h>
505# endif
506# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
507# include <sys/sysinfo.h>
508# endif
509
510/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000511 * Return total amount of memory available in Kbyte.
512 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 long_u
515mch_total_mem(special)
Bram Moolenaar78a15312009-05-15 19:33:18 +0000516 int special UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517{
518# ifdef __EMX__
Bram Moolenaar914572a2007-05-01 11:37:47 +0000519 return ulimit(3, 0L) >> 10; /* always 32MB? */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520# else
521 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000522 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523
524# ifdef HAVE_SYSCTL
525 int mib[2], physmem;
526 size_t len;
527
528 /* BSD way of getting the amount of RAM available. */
529 mib[0] = CTL_HW;
530 mib[1] = HW_USERMEM;
531 len = sizeof(physmem);
532 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
533 mem = (long_u)physmem;
534# endif
535
536# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
537 if (mem == 0)
538 {
539 struct sysinfo sinfo;
540
541 /* Linux way of getting amount of RAM available */
542 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000543 {
544# ifdef HAVE_SYSINFO_MEM_UNIT
545 /* avoid overflow as much as possible */
546 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
547 {
548 sinfo.mem_unit = sinfo.mem_unit >> 1;
549 --shiftright;
550 }
551 mem = sinfo.totalram * sinfo.mem_unit;
552# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 mem = sinfo.totalram;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000554# endif
555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556 }
557# endif
558
559# ifdef HAVE_SYSCONF
560 if (mem == 0)
561 {
562 long pagesize, pagecount;
563
564 /* Solaris way of getting amount of RAM available */
565 pagesize = sysconf(_SC_PAGESIZE);
566 pagecount = sysconf(_SC_PHYS_PAGES);
567 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000568 {
569 /* avoid overflow as much as possible */
570 while (shiftright > 0 && (pagesize & 1) == 0)
571 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000572 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000573 --shiftright;
574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000575 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577 }
578# endif
579
580 /* Return the minimum of the physical memory and the user limit, because
581 * using more than the user limit may cause Vim to be terminated. */
582# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
583 {
584 struct rlimit rlp;
585
586 if (getrlimit(RLIMIT_DATA, &rlp) == 0
587 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
588# ifdef RLIM_INFINITY
589 && rlp.rlim_cur != RLIM_INFINITY
590# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000591 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000593 {
594 mem = (long_u)rlp.rlim_cur;
595 shiftright = 10;
596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597 }
598# endif
599
600 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000601 return mem >> shiftright;
602 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603# endif
604}
605#endif
606
607 void
608mch_delay(msec, ignoreinput)
609 long msec;
610 int ignoreinput;
611{
612 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000613#ifdef FEAT_MZSCHEME
614 long total = msec; /* remember original value */
615#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616
617 if (ignoreinput)
618 {
619 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000620 * here. But we don't want QUIT to kill us (CTRL-\ used in a
621 * shell may produce SIGQUIT). */
622 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 old_tmode = curr_tmode;
624 if (curr_tmode == TMODE_RAW)
625 settmode(TMODE_SLEEP);
626
627 /*
628 * Everybody sleeps in a different way...
629 * Prefer nanosleep(), some versions of usleep() can only sleep up to
630 * one second.
631 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000632#ifdef FEAT_MZSCHEME
633 do
634 {
635 /* if total is large enough, wait by portions in p_mzq */
636 if (total > p_mzq)
637 msec = p_mzq;
638 else
639 msec = total;
640 total -= msec;
641#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642#ifdef HAVE_NANOSLEEP
643 {
644 struct timespec ts;
645
646 ts.tv_sec = msec / 1000;
647 ts.tv_nsec = (msec % 1000) * 1000000;
648 (void)nanosleep(&ts, NULL);
649 }
650#else
651# ifdef HAVE_USLEEP
652 while (msec >= 1000)
653 {
654 usleep((unsigned int)(999 * 1000));
655 msec -= 999;
656 }
657 usleep((unsigned int)(msec * 1000));
658# else
659# ifndef HAVE_SELECT
660 poll(NULL, 0, (int)msec);
661# else
662# ifdef __EMX__
663 _sleep2(msec);
664# else
665 {
666 struct timeval tv;
667
668 tv.tv_sec = msec / 1000;
669 tv.tv_usec = (msec % 1000) * 1000;
670 /*
671 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
672 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
673 */
674 select(0, NULL, NULL, NULL, &tv);
675 }
676# endif /* __EMX__ */
677# endif /* HAVE_SELECT */
678# endif /* HAVE_NANOSLEEP */
679#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000680#ifdef FEAT_MZSCHEME
681 }
682 while (total > 0);
683#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000686 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687 }
688 else
689 WaitForChar(msec);
690}
691
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000692#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
694# define HAVE_CHECK_STACK_GROWTH
695/*
696 * Support for checking for an almost-out-of-stack-space situation.
697 */
698
699/*
700 * Return a pointer to an item on the stack. Used to find out if the stack
701 * grows up or down.
702 */
703static void check_stack_growth __ARGS((char *p));
704static int stack_grows_downwards;
705
706/*
707 * Find out if the stack grows upwards or downwards.
708 * "p" points to a variable on the stack of the caller.
709 */
710 static void
711check_stack_growth(p)
712 char *p;
713{
714 int i;
715
716 stack_grows_downwards = (p > (char *)&i);
717}
718#endif
719
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000720#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721static char *stack_limit = NULL;
722
723#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
724# include <pthread.h>
725# include <pthread_np.h>
726#endif
727
728/*
729 * Find out until how var the stack can grow without getting into trouble.
730 * Called when starting up and when switching to the signal stack in
731 * deathtrap().
732 */
733 static void
734get_stack_limit()
735{
736 struct rlimit rlp;
737 int i;
738 long lim;
739
740 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
741 * limit doesn't fit in a long (rlim_cur might be "long long"). */
742 if (getrlimit(RLIMIT_STACK, &rlp) == 0
743 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
744# ifdef RLIM_INFINITY
745 && rlp.rlim_cur != RLIM_INFINITY
746# endif
747 )
748 {
749 lim = (long)rlp.rlim_cur;
750#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
751 {
752 pthread_attr_t attr;
753 size_t size;
754
755 /* On FreeBSD the initial thread always has a fixed stack size, no
756 * matter what the limits are set to. Normally it's 1 Mbyte. */
757 pthread_attr_init(&attr);
758 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
759 {
760 pthread_attr_getstacksize(&attr, &size);
761 if (lim > (long)size)
762 lim = (long)size;
763 }
764 pthread_attr_destroy(&attr);
765 }
766#endif
767 if (stack_grows_downwards)
768 {
769 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
770 if (stack_limit >= (char *)&i)
771 /* overflow, set to 1/16 of current stack position */
772 stack_limit = (char *)((long)&i / 16L);
773 }
774 else
775 {
776 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
777 if (stack_limit <= (char *)&i)
778 stack_limit = NULL; /* overflow */
779 }
780 }
781}
782
783/*
784 * Return FAIL when running out of stack space.
785 * "p" must point to any variable local to the caller that's on the stack.
786 */
787 int
788mch_stackcheck(p)
789 char *p;
790{
791 if (stack_limit != NULL)
792 {
793 if (stack_grows_downwards)
794 {
795 if (p < stack_limit)
796 return FAIL;
797 }
798 else if (p > stack_limit)
799 return FAIL;
800 }
801 return OK;
802}
803#endif
804
805#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
806/*
807 * Support for using the signal stack.
808 * This helps when we run out of stack space, which causes a SIGSEGV. The
809 * signal handler then must run on another stack, since the normal stack is
810 * completely full.
811 */
812
Bram Moolenaar39766a72013-11-03 00:41:00 +0100813#if defined(HAVE_AVAILABILITYMACROS_H)
Bram Moolenaar4cc95d12013-11-02 21:49:32 +0100814# include <AvailabilityMacros.h>
815#endif
816
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817#ifndef SIGSTKSZ
818# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
819#endif
820
821# ifdef HAVE_SIGALTSTACK
822static stack_t sigstk; /* for sigaltstack() */
823# else
824static struct sigstack sigstk; /* for sigstack() */
825# endif
826
827static void init_signal_stack __ARGS((void));
828static char *signal_stack;
829
830 static void
831init_signal_stack()
832{
833 if (signal_stack != NULL)
834 {
835# ifdef HAVE_SIGALTSTACK
Bram Moolenaar1a3d0862007-08-30 09:47:38 +0000836# if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
837 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
839 * "struct sigaltstack" needs to be declared. */
840 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
841# endif
842
843# ifdef HAVE_SS_BASE
844 sigstk.ss_base = signal_stack;
845# else
846 sigstk.ss_sp = signal_stack;
847# endif
848 sigstk.ss_size = SIGSTKSZ;
849 sigstk.ss_flags = 0;
850 (void)sigaltstack(&sigstk, NULL);
851# else
852 sigstk.ss_sp = signal_stack;
853 if (stack_grows_downwards)
854 sigstk.ss_sp += SIGSTKSZ - 1;
855 sigstk.ss_onstack = 0;
856 (void)sigstack(&sigstk, NULL);
857# endif
858 }
859}
860#endif
861
862/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000863 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 * will barf when the second argument to signal() is ``wrong''.
865 * Let me try it with a few tricky defines from my own osdef.h (jw).
866 */
867#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 static RETSIGTYPE
869sig_winch SIGDEFARG(sigarg)
870{
871 /* this is not required on all systems, but it doesn't hurt anybody */
872 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
873 do_resize = TRUE;
874 SIGRETURN;
875}
876#endif
877
878#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 static RETSIGTYPE
880catch_sigint SIGDEFARG(sigarg)
881{
882 /* this is not required on all systems, but it doesn't hurt anybody */
883 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
884 got_int = TRUE;
885 SIGRETURN;
886}
887#endif
888
889#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 static RETSIGTYPE
891catch_sigpwr SIGDEFARG(sigarg)
892{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000893 /* this is not required on all systems, but it doesn't hurt anybody */
894 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 /*
896 * I'm not sure we get the SIGPWR signal when the system is really going
897 * down or when the batteries are almost empty. Just preserve the swap
898 * files and don't exit, that can't do any harm.
899 */
900 ml_sync_all(FALSE, FALSE);
901 SIGRETURN;
902}
903#endif
904
905#ifdef SET_SIG_ALARM
906/*
907 * signal function for alarm().
908 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 static RETSIGTYPE
910sig_alarm SIGDEFARG(sigarg)
911{
912 /* doesn't do anything, just to break a system call */
913 sig_alarm_called = TRUE;
914 SIGRETURN;
915}
916#endif
917
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000918#if (defined(HAVE_SETJMP_H) \
919 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
920 || defined(FEAT_LIBCALL))) \
921 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922/*
923 * A simplistic version of setjmp() that only allows one level of using.
924 * Don't call twice before calling mch_endjmp()!.
925 * Usage:
926 * mch_startjmp();
927 * if (SETJMP(lc_jump_env) != 0)
928 * {
929 * mch_didjmp();
930 * EMSG("crash!");
931 * }
932 * else
933 * {
934 * do_the_work;
935 * mch_endjmp();
936 * }
937 * Note: Can't move SETJMP() here, because a function calling setjmp() must
938 * not return before the saved environment is used.
939 * Returns OK for normal return, FAIL when the protected code caused a
940 * problem and LONGJMP() was used.
941 */
942 void
943mch_startjmp()
944{
945#ifdef SIGHASARG
946 lc_signal = 0;
947#endif
948 lc_active = TRUE;
949}
950
951 void
952mch_endjmp()
953{
954 lc_active = FALSE;
955}
956
957 void
958mch_didjmp()
959{
960# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
961 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
962 * otherwise catching the signal only works once. */
963 init_signal_stack();
964# endif
965}
966#endif
967
968/*
969 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200970 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +0200972 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
973 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974 */
975 static RETSIGTYPE
976deathtrap SIGDEFARG(sigarg)
977{
978 static int entered = 0; /* count the number of times we got here.
979 Note: when memory has been corrupted
980 this may get an arbitrary value! */
981#ifdef SIGHASARG
982 int i;
983#endif
984
985#if defined(HAVE_SETJMP_H)
986 /*
987 * Catch a crash in protected code.
988 * Restores the environment saved in lc_jump_env, which looks like
989 * SETJMP() returns 1.
990 */
991 if (lc_active)
992 {
993# if defined(SIGHASARG)
994 lc_signal = sigarg;
995# endif
996 lc_active = FALSE; /* don't jump again */
997 LONGJMP(lc_jump_env, 1);
998 /* NOTREACHED */
999 }
1000#endif
1001
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001002#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001003# ifdef SIGQUIT
1004 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1005 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1006 * pressing CTRL-\, but we don't want Vim to exit then. */
1007 if (in_mch_delay && sigarg == SIGQUIT)
1008 SIGRETURN;
1009# endif
1010
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001011 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1012 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1013 * free(). Calling free() again may then cause a crash. */
1014 if (entered == 0
1015 && (0
1016# ifdef SIGHUP
1017 || sigarg == SIGHUP
1018# endif
1019# ifdef SIGQUIT
1020 || sigarg == SIGQUIT
1021# endif
1022# ifdef SIGTERM
1023 || sigarg == SIGTERM
1024# endif
1025# ifdef SIGPWR
1026 || sigarg == SIGPWR
1027# endif
1028# ifdef SIGUSR1
1029 || sigarg == SIGUSR1
1030# endif
1031# ifdef SIGUSR2
1032 || sigarg == SIGUSR2
1033# endif
1034 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001035 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001036 SIGRETURN;
1037#endif
1038
Bram Moolenaar071d4272004-06-13 20:20:40 +00001039 /* Remember how often we have been called. */
1040 ++entered;
1041
1042#ifdef FEAT_EVAL
1043 /* Set the v:dying variable. */
1044 set_vim_var_nr(VV_DYING, (long)entered);
1045#endif
1046
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001047#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 /* Since we are now using the signal stack, need to reset the stack
1049 * limit. Otherwise using a regexp will fail. */
1050 get_stack_limit();
1051#endif
1052
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001053#if 0
1054 /* This is for opening gdb the moment Vim crashes.
1055 * You need to manually adjust the file name and Vim executable name.
1056 * Suggested by SungHyun Nam. */
1057 {
1058# define VI_GDB_FILE "/tmp/vimgdb"
1059# define VIM_NAME "/usr/bin/vim"
1060 FILE *fp = fopen(VI_GDB_FILE, "w");
1061 if (fp)
1062 {
1063 fprintf(fp,
1064 "file %s\n"
1065 "attach %d\n"
1066 "set height 1000\n"
1067 "bt full\n"
1068 , VIM_NAME, getpid());
1069 fclose(fp);
1070 system("xterm -e gdb -x "VI_GDB_FILE);
1071 unlink(VI_GDB_FILE);
1072 }
1073 }
1074#endif
1075
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076#ifdef SIGHASARG
1077 /* try to find the name of this signal */
1078 for (i = 0; signal_info[i].sig != -1; i++)
1079 if (sigarg == signal_info[i].sig)
1080 break;
1081 deadly_signal = sigarg;
1082#endif
1083
1084 full_screen = FALSE; /* don't write message to the GUI, it might be
1085 * part of the problem... */
1086 /*
1087 * If something goes wrong after entering here, we may get here again.
1088 * When this happens, give a message and try to exit nicely (resetting the
1089 * terminal mode, etc.)
1090 * When this happens twice, just exit, don't even try to give a message,
1091 * stack may be corrupt or something weird.
1092 * When this still happens again (or memory was corrupted in such a way
1093 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1094 */
1095 if (entered >= 3)
1096 {
1097 reset_signals(); /* don't catch any signals anymore */
1098 may_core_dump();
1099 if (entered >= 4)
1100 _exit(8);
1101 exit(7);
1102 }
1103 if (entered == 2)
1104 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001105 /* No translation, it may call malloc(). */
1106 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107 out_flush();
1108 getout(1);
1109 }
1110
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001111 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001113 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 signal_info[i].name);
1115#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001116 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001118
1119 /* Preserve files and exit. This sets the really_exiting flag to prevent
1120 * calling free(). */
1121 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122
Bram Moolenaar009b2592004-10-24 19:18:58 +00001123#ifdef NBDEBUG
1124 reset_signals();
1125 may_core_dump();
1126 abort();
1127#endif
1128
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 SIGRETURN;
1130}
1131
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001132#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133/*
1134 * On Solaris with multi-threading, suspending might not work immediately.
1135 * Catch the SIGCONT signal, which will be used as an indication whether the
1136 * suspending has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001137 *
1138 * On Linux, signal is not always handled immediately either.
1139 * See https://bugs.launchpad.net/bugs/291373
1140 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001141 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001143static volatile int sigcont_received;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1145
1146/*
1147 * signal handler for SIGCONT
1148 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149 static RETSIGTYPE
1150sigcont_handler SIGDEFARG(sigarg)
1151{
1152 sigcont_received = TRUE;
1153 SIGRETURN;
1154}
1155#endif
1156
Bram Moolenaar62b42182010-09-21 22:09:37 +02001157# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1158static void loose_clipboard __ARGS((void));
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001159# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001160static void save_clipboard __ARGS((void));
1161static void restore_clipboard __ARGS((void));
1162
1163static void *clip_star_save = NULL;
1164static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001165# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001166
1167/*
1168 * Called when Vim is going to sleep or execute a shell command.
1169 * We can't respond to requests for the X selections. Lose them, otherwise
1170 * other applications will hang. But first copy the text to cut buffer 0.
1171 */
1172 static void
1173loose_clipboard()
1174{
1175 if (clip_star.owned || clip_plus.owned)
1176 {
1177 x11_export_final_selection();
1178 if (clip_star.owned)
1179 clip_lose_selection(&clip_star);
1180 if (clip_plus.owned)
1181 clip_lose_selection(&clip_plus);
1182 if (x11_display != NULL)
1183 XFlush(x11_display);
1184 }
1185}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001186
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001187# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001188/*
1189 * Save clipboard text to restore later.
1190 */
1191 static void
1192save_clipboard()
1193{
1194 if (clip_star.owned)
1195 clip_star_save = get_register('*', TRUE);
1196 if (clip_plus.owned)
1197 clip_plus_save = get_register('+', TRUE);
1198}
1199
1200/*
1201 * Restore clipboard text if no one own the X selection.
1202 */
1203 static void
1204restore_clipboard()
1205{
1206 if (clip_star_save != NULL)
1207 {
1208 if (!clip_gen_owner_exists(&clip_star))
1209 put_register('*', clip_star_save);
1210 else
1211 free_register(clip_star_save);
1212 clip_star_save = NULL;
1213 }
1214 if (clip_plus_save != NULL)
1215 {
1216 if (!clip_gen_owner_exists(&clip_plus))
1217 put_register('+', clip_plus_save);
1218 else
1219 free_register(clip_plus_save);
1220 clip_plus_save = NULL;
1221 }
1222}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001223# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001224#endif
1225
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226/*
1227 * If the machine has job control, use it to suspend the program,
1228 * otherwise fake it by starting a new shell.
1229 */
1230 void
1231mch_suspend()
1232{
1233 /* BeOS does have SIGTSTP, but it doesn't work. */
1234#if defined(SIGTSTP) && !defined(__BEOS__)
1235 out_flush(); /* needed to make cursor visible on some systems */
1236 settmode(TMODE_COOK);
1237 out_flush(); /* needed to disable mouse on some systems */
1238
1239# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001240 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241# endif
1242
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001243# if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244 sigcont_received = FALSE;
1245# endif
1246 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001247# if defined(_REENTRANT) && defined(SIGCONT)
1248 /*
1249 * Wait for the SIGCONT signal to be handled. It generally happens
1250 * immediately, but somehow not all the time. Do not call pause()
1251 * because there would be race condition which would hang Vim if
1252 * signal happened in between the test of sigcont_received and the
1253 * call to pause(). If signal is not yet received, call sleep(0)
1254 * to just yield CPU. Signal should then be received. If somehow
1255 * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting
1256 * further if signal is not received after 1+2+3+4 ms (not expected
1257 * to happen).
1258 */
1259 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001260 long wait_time;
1261 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001262 /* Loop is not entered most of the time */
Bram Moolenaar262735e2009-07-14 10:20:22 +00001263 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265# endif
1266
1267# ifdef FEAT_TITLE
1268 /*
1269 * Set oldtitle to NULL, so the current title is obtained again.
1270 */
1271 vim_free(oldtitle);
1272 oldtitle = NULL;
1273# endif
1274 settmode(TMODE_RAW);
1275 need_check_timestamps = TRUE;
1276 did_check_timestamps = FALSE;
1277#else
1278 suspend_shell();
1279#endif
1280}
1281
1282 void
1283mch_init()
1284{
1285 Columns = 80;
1286 Rows = 24;
1287
1288 out_flush();
1289 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001290
Bram Moolenaar56718732006-03-15 22:53:57 +00001291#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001292 mac_conv_init();
1293#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001294#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1295 win_clip_init();
1296#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297}
1298
1299 static void
1300set_signals()
1301{
1302#if defined(SIGWINCH)
1303 /*
1304 * WINDOW CHANGE signal is handled with sig_winch().
1305 */
1306 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1307#endif
1308
1309 /*
1310 * We want the STOP signal to work, to make mch_suspend() work.
1311 * For "rvim" the STOP signal is ignored.
1312 */
1313#ifdef SIGTSTP
1314 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1315#endif
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001316#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 signal(SIGCONT, sigcont_handler);
1318#endif
1319
1320 /*
1321 * We want to ignore breaking of PIPEs.
1322 */
1323#ifdef SIGPIPE
1324 signal(SIGPIPE, SIG_IGN);
1325#endif
1326
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001328 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329#endif
1330
1331 /*
1332 * Ignore alarm signals (Perl's alarm() generates it).
1333 */
1334#ifdef SIGALRM
1335 signal(SIGALRM, SIG_IGN);
1336#endif
1337
1338 /*
1339 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1340 * work will be lost.
1341 */
1342#ifdef SIGPWR
1343 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1344#endif
1345
1346 /*
1347 * Arrange for other signals to gracefully shutdown Vim.
1348 */
1349 catch_signals(deathtrap, SIG_ERR);
1350
1351#if defined(FEAT_GUI) && defined(SIGHUP)
1352 /*
1353 * When the GUI is running, ignore the hangup signal.
1354 */
1355 if (gui.in_use)
1356 signal(SIGHUP, SIG_IGN);
1357#endif
1358}
1359
Bram Moolenaardf177f62005-02-22 08:39:57 +00001360#if defined(SIGINT) || defined(PROTO)
1361/*
1362 * Catch CTRL-C (only works while in Cooked mode).
1363 */
1364 static void
1365catch_int_signal()
1366{
1367 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1368}
1369#endif
1370
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371 void
1372reset_signals()
1373{
1374 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001375#if defined(_REENTRANT) && defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376 /* SIGCONT isn't in the list, because its default action is ignore */
1377 signal(SIGCONT, SIG_DFL);
1378#endif
1379}
1380
1381 static void
1382catch_signals(func_deadly, func_other)
1383 RETSIGTYPE (*func_deadly)();
1384 RETSIGTYPE (*func_other)();
1385{
1386 int i;
1387
1388 for (i = 0; signal_info[i].sig != -1; i++)
1389 if (signal_info[i].deadly)
1390 {
1391#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1392 struct sigaction sa;
1393
1394 /* Setup to use the alternate stack for the signal function. */
1395 sa.sa_handler = func_deadly;
1396 sigemptyset(&sa.sa_mask);
1397# if defined(__linux__) && defined(_REENTRANT)
1398 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1399 * thread handling in combination with using the alternate stack:
1400 * pthread library functions try to use the stack pointer to
1401 * identify the current thread, causing a SEGV signal, which
1402 * recursively calls deathtrap() and hangs. */
1403 sa.sa_flags = 0;
1404# else
1405 sa.sa_flags = SA_ONSTACK;
1406# endif
1407 sigaction(signal_info[i].sig, &sa, NULL);
1408#else
1409# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1410 struct sigvec sv;
1411
1412 /* Setup to use the alternate stack for the signal function. */
1413 sv.sv_handler = func_deadly;
1414 sv.sv_mask = 0;
1415 sv.sv_flags = SV_ONSTACK;
1416 sigvec(signal_info[i].sig, &sv, NULL);
1417# else
1418 signal(signal_info[i].sig, func_deadly);
1419# endif
1420#endif
1421 }
1422 else if (func_other != SIG_ERR)
1423 signal(signal_info[i].sig, func_other);
1424}
1425
1426/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001427 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001428 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1429 * return TRUE
1430 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1431 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001432 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001433 * Returns TRUE when Vim should exit.
1434 */
1435 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001436vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001437 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001438{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001439 static int got_signal = 0;
1440 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001441
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001442 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001443 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001444 case SIGNAL_BLOCK: blocked = TRUE;
1445 break;
1446
1447 case SIGNAL_UNBLOCK: blocked = FALSE;
1448 if (got_signal != 0)
1449 {
1450 kill(getpid(), got_signal);
1451 got_signal = 0;
1452 }
1453 break;
1454
1455 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001456 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001457 got_signal = sig;
1458#ifdef SIGPWR
1459 if (sig != SIGPWR)
1460#endif
1461 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001462 break;
1463 }
1464 return FALSE;
1465}
1466
1467/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 * Check_win checks whether we have an interactive stdout.
1469 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 int
1471mch_check_win(argc, argv)
Bram Moolenaar78a15312009-05-15 19:33:18 +00001472 int argc UNUSED;
1473 char **argv UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474{
1475#ifdef OS2
1476 /*
1477 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1478 * name, mostly it's just "vim" and found in the path, which is unusable.
1479 */
1480 if (mch_isFullName(argv[0]))
1481 exe_name = vim_strsave((char_u *)argv[0]);
1482#endif
1483 if (isatty(1))
1484 return OK;
1485 return FAIL;
1486}
1487
1488/*
1489 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1490 */
1491 int
1492mch_input_isatty()
1493{
1494 if (isatty(read_cmd_fd))
1495 return TRUE;
1496 return FALSE;
1497}
1498
1499#ifdef FEAT_X11
1500
1501# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1502 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1503
1504static void xopen_message __ARGS((struct timeval *tvp));
1505
1506/*
1507 * Give a message about the elapsed time for opening the X window.
1508 */
1509 static void
1510xopen_message(tvp)
1511 struct timeval *tvp; /* must contain start time */
1512{
1513 struct timeval end_tv;
1514
1515 /* Compute elapsed time. */
1516 gettimeofday(&end_tv, NULL);
1517 smsg((char_u *)_("Opening the X display took %ld msec"),
1518 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001519 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520}
1521# endif
1522#endif
1523
1524#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1525/*
1526 * A few functions shared by X11 title and clipboard code.
1527 */
1528static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1529static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1530static int x_connect_to_server __ARGS((void));
1531static int test_x11_window __ARGS((Display *dpy));
1532
1533static int got_x_error = FALSE;
1534
1535/*
1536 * X Error handler, otherwise X just exits! (very rude) -- webb
1537 */
1538 static int
1539x_error_handler(dpy, error_event)
1540 Display *dpy;
1541 XErrorEvent *error_event;
1542{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001543 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 STRCAT(IObuff, _("\nVim: Got X error\n"));
1545
1546 /* We cannot print a message and continue, because no X calls are allowed
1547 * here (causes my system to hang). Silently continuing might be an
1548 * alternative... */
1549 preserve_exit(); /* preserve files and exit */
1550
1551 return 0; /* NOTREACHED */
1552}
1553
1554/*
1555 * Another X Error handler, just used to check for errors.
1556 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 static int
1558x_error_check(dpy, error_event)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001559 Display *dpy UNUSED;
1560 XErrorEvent *error_event UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561{
1562 got_x_error = TRUE;
1563 return 0;
1564}
1565
1566#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1567# if defined(HAVE_SETJMP_H)
1568/*
1569 * An X IO Error handler, used to catch error while opening the display.
1570 */
1571static int x_IOerror_check __ARGS((Display *dpy));
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 static int
1574x_IOerror_check(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001575 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576{
1577 /* This function should not return, it causes exit(). Longjump instead. */
1578 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001579# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001580 return 0; /* avoid the compiler complains about missing return value */
1581# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582}
1583# endif
1584
1585/*
1586 * An X IO Error handler, used to catch terminal errors.
1587 */
1588static int x_IOerror_handler __ARGS((Display *dpy));
1589
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 static int
1591x_IOerror_handler(dpy)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00001592 Display *dpy UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593{
1594 xterm_dpy = NULL;
1595 x11_window = 0;
1596 x11_display = NULL;
1597 xterm_Shell = (Widget)0;
1598
1599 /* This function should not return, it causes exit(). Longjump instead. */
1600 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001601# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001602 return 0; /* avoid the compiler complains about missing return value */
1603# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604}
1605#endif
1606
1607/*
1608 * Return TRUE when connection to the X server is desired.
1609 */
1610 static int
1611x_connect_to_server()
1612{
1613 regmatch_T regmatch;
1614
1615#if defined(FEAT_CLIENTSERVER)
1616 if (x_force_connect)
1617 return TRUE;
1618#endif
1619 if (x_no_connect)
1620 return FALSE;
1621
1622 /* Check for a match with "exclude:" from 'clipboard'. */
1623 if (clip_exclude_prog != NULL)
1624 {
1625 regmatch.rm_ic = FALSE; /* Don't ignore case */
1626 regmatch.regprog = clip_exclude_prog;
1627 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1628 return FALSE;
1629 }
1630 return TRUE;
1631}
1632
1633/*
1634 * Test if "dpy" and x11_window are valid by getting the window title.
1635 * I don't actually want it yet, so there may be a simpler call to use, but
1636 * this will cause the error handler x_error_check() to be called if anything
1637 * is wrong, such as the window pointer being invalid (as can happen when the
1638 * user changes his DISPLAY, but not his WINDOWID) -- webb
1639 */
1640 static int
1641test_x11_window(dpy)
1642 Display *dpy;
1643{
1644 int (*old_handler)();
1645 XTextProperty text_prop;
1646
1647 old_handler = XSetErrorHandler(x_error_check);
1648 got_x_error = FALSE;
1649 if (XGetWMName(dpy, x11_window, &text_prop))
1650 XFree((void *)text_prop.value);
1651 XSync(dpy, False);
1652 (void)XSetErrorHandler(old_handler);
1653
1654 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001655 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656
1657 return (got_x_error ? FAIL : OK);
1658}
1659#endif
1660
1661#ifdef FEAT_TITLE
1662
1663#ifdef FEAT_X11
1664
1665static int get_x11_thing __ARGS((int get_title, int test_only));
1666
1667/*
1668 * try to get x11 window and display
1669 *
1670 * return FAIL for failure, OK otherwise
1671 */
1672 static int
1673get_x11_windis()
1674{
1675 char *winid;
1676 static int result = -1;
1677#define XD_NONE 0 /* x11_display not set here */
1678#define XD_HERE 1 /* x11_display opened here */
1679#define XD_GUI 2 /* x11_display used from gui.dpy */
1680#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1681 static int x11_display_from = XD_NONE;
1682 static int did_set_error_handler = FALSE;
1683
1684 if (!did_set_error_handler)
1685 {
1686 /* X just exits if it finds an error otherwise! */
1687 (void)XSetErrorHandler(x_error_handler);
1688 did_set_error_handler = TRUE;
1689 }
1690
Bram Moolenaar9372a112005-12-06 19:59:18 +00001691#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 if (gui.in_use)
1693 {
1694 /*
1695 * If the X11 display was opened here before, for the window where Vim
1696 * was started, close that one now to avoid a memory leak.
1697 */
1698 if (x11_display_from == XD_HERE && x11_display != NULL)
1699 {
1700 XCloseDisplay(x11_display);
1701 x11_display_from = XD_NONE;
1702 }
1703 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1704 {
1705 x11_display_from = XD_GUI;
1706 return OK;
1707 }
1708 x11_display = NULL;
1709 return FAIL;
1710 }
1711 else if (x11_display_from == XD_GUI)
1712 {
1713 /* GUI must have stopped somehow, clear x11_display */
1714 x11_window = 0;
1715 x11_display = NULL;
1716 x11_display_from = XD_NONE;
1717 }
1718#endif
1719
1720 /* When started with the "-X" argument, don't try connecting. */
1721 if (!x_connect_to_server())
1722 return FAIL;
1723
1724 /*
1725 * If WINDOWID not set, should try another method to find out
1726 * what the current window number is. The only code I know for
1727 * this is very complicated.
1728 * We assume that zero is invalid for WINDOWID.
1729 */
1730 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1731 x11_window = (Window)atol(winid);
1732
1733#ifdef FEAT_XCLIPBOARD
1734 if (xterm_dpy != NULL && x11_window != 0)
1735 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001736 /* We may have checked it already, but Gnome terminal can move us to
1737 * another window, so we need to check every time. */
1738 if (x11_display_from != XD_XTERM)
1739 {
1740 /*
1741 * If the X11 display was opened here before, for the window where
1742 * Vim was started, close that one now to avoid a memory leak.
1743 */
1744 if (x11_display_from == XD_HERE && x11_display != NULL)
1745 XCloseDisplay(x11_display);
1746 x11_display = xterm_dpy;
1747 x11_display_from = XD_XTERM;
1748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 if (test_x11_window(x11_display) == FAIL)
1750 {
1751 /* probably bad $WINDOWID */
1752 x11_window = 0;
1753 x11_display = NULL;
1754 x11_display_from = XD_NONE;
1755 return FAIL;
1756 }
1757 return OK;
1758 }
1759#endif
1760
1761 if (x11_window == 0 || x11_display == NULL)
1762 result = -1;
1763
1764 if (result != -1) /* Have already been here and set this */
1765 return result; /* Don't do all these X calls again */
1766
1767 if (x11_window != 0 && x11_display == NULL)
1768 {
1769#ifdef SET_SIG_ALARM
1770 RETSIGTYPE (*sig_save)();
1771#endif
1772#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1773 struct timeval start_tv;
1774
1775 if (p_verbose > 0)
1776 gettimeofday(&start_tv, NULL);
1777#endif
1778
1779#ifdef SET_SIG_ALARM
1780 /*
1781 * Opening the Display may hang if the DISPLAY setting is wrong, or
1782 * the network connection is bad. Set an alarm timer to get out.
1783 */
1784 sig_alarm_called = FALSE;
1785 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1786 (RETSIGTYPE (*)())sig_alarm);
1787 alarm(2);
1788#endif
1789 x11_display = XOpenDisplay(NULL);
1790
1791#ifdef SET_SIG_ALARM
1792 alarm(0);
1793 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1794 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001795 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796#endif
1797 if (x11_display != NULL)
1798 {
1799# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1800 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001801 {
1802 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001804 verbose_leave();
1805 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806# endif
1807 if (test_x11_window(x11_display) == FAIL)
1808 {
1809 /* Maybe window id is bad */
1810 x11_window = 0;
1811 XCloseDisplay(x11_display);
1812 x11_display = NULL;
1813 }
1814 else
1815 x11_display_from = XD_HERE;
1816 }
1817 }
1818 if (x11_window == 0 || x11_display == NULL)
1819 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001820
1821# ifdef FEAT_EVAL
1822 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1823# endif
1824
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 return (result = OK);
1826}
1827
1828/*
1829 * Determine original x11 Window Title
1830 */
1831 static int
1832get_x11_title(test_only)
1833 int test_only;
1834{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001835 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836}
1837
1838/*
1839 * Determine original x11 Window icon
1840 */
1841 static int
1842get_x11_icon(test_only)
1843 int test_only;
1844{
1845 int retval = FALSE;
1846
1847 retval = get_x11_thing(FALSE, test_only);
1848
1849 /* could not get old icon, use terminal name */
1850 if (oldicon == NULL && !test_only)
1851 {
1852 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001853 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001855 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 }
1857
1858 return retval;
1859}
1860
1861 static int
1862get_x11_thing(get_title, test_only)
1863 int get_title; /* get title string */
1864 int test_only;
1865{
1866 XTextProperty text_prop;
1867 int retval = FALSE;
1868 Status status;
1869
1870 if (get_x11_windis() == OK)
1871 {
1872 /* Get window/icon name if any */
1873 if (get_title)
1874 status = XGetWMName(x11_display, x11_window, &text_prop);
1875 else
1876 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1877
1878 /*
1879 * If terminal is xterm, then x11_window may be a child window of the
1880 * outer xterm window that actually contains the window/icon name, so
1881 * keep traversing up the tree until a window with a title/icon is
1882 * found.
1883 */
1884 /* Previously this was only done for xterm and alikes. I don't see a
1885 * reason why it would fail for other terminal emulators.
1886 * if (term_is_xterm) */
1887 {
1888 Window root;
1889 Window parent;
1890 Window win = x11_window;
1891 Window *children;
1892 unsigned int num_children;
1893
1894 while (!status || text_prop.value == NULL)
1895 {
1896 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1897 &num_children))
1898 break;
1899 if (children)
1900 XFree((void *)children);
1901 if (parent == root || parent == 0)
1902 break;
1903
1904 win = parent;
1905 if (get_title)
1906 status = XGetWMName(x11_display, win, &text_prop);
1907 else
1908 status = XGetWMIconName(x11_display, win, &text_prop);
1909 }
1910 }
1911 if (status && text_prop.value != NULL)
1912 {
1913 retval = TRUE;
1914 if (!test_only)
1915 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001916#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1917 if (text_prop.encoding == XA_STRING
1918# ifdef FEAT_MBYTE
1919 && !has_mbyte
1920# endif
1921 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 {
1923#endif
1924 if (get_title)
1925 oldtitle = vim_strsave((char_u *)text_prop.value);
1926 else
1927 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001928#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 }
1930 else
1931 {
1932 char **cl;
1933 Status transform_status;
1934 int n = 0;
1935
1936 transform_status = XmbTextPropertyToTextList(x11_display,
1937 &text_prop,
1938 &cl, &n);
1939 if (transform_status >= Success && n > 0 && cl[0])
1940 {
1941 if (get_title)
1942 oldtitle = vim_strsave((char_u *) cl[0]);
1943 else
1944 oldicon = vim_strsave((char_u *) cl[0]);
1945 XFreeStringList(cl);
1946 }
1947 else
1948 {
1949 if (get_title)
1950 oldtitle = vim_strsave((char_u *)text_prop.value);
1951 else
1952 oldicon = vim_strsave((char_u *)text_prop.value);
1953 }
1954 }
1955#endif
1956 }
1957 XFree((void *)text_prop.value);
1958 }
1959 }
1960 return retval;
1961}
1962
1963/* Are Xutf8 functions available? Avoid error from old compilers. */
1964#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1965# if X_HAVE_UTF8_STRING
1966# define USE_UTF8_STRING
1967# endif
1968#endif
1969
1970/*
1971 * Set x11 Window Title
1972 *
1973 * get_x11_windis() must be called before this and have returned OK
1974 */
1975 static void
1976set_x11_title(title)
1977 char_u *title;
1978{
1979 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1980 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1981 * supported everywhere and STRING doesn't work for multi-byte titles.
1982 */
1983#ifdef USE_UTF8_STRING
1984 if (enc_utf8)
1985 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1986 NULL, NULL, 0, NULL, NULL, NULL);
1987 else
1988#endif
1989 {
1990#if XtSpecificationRelease >= 4
1991# ifdef FEAT_XFONTSET
1992 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1993 NULL, NULL, 0, NULL, NULL, NULL);
1994# else
1995 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001996 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997
1998 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001999 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 XSetWMProperties(x11_display, x11_window, &text_prop,
2001 NULL, NULL, 0, NULL, NULL, NULL);
2002# endif
2003#else
2004 XStoreName(x11_display, x11_window, (char *)title);
2005#endif
2006 }
2007 XFlush(x11_display);
2008}
2009
2010/*
2011 * Set x11 Window icon
2012 *
2013 * get_x11_windis() must be called before this and have returned OK
2014 */
2015 static void
2016set_x11_icon(icon)
2017 char_u *icon;
2018{
2019 /* See above for comments about using X*SetWMProperties(). */
2020#ifdef USE_UTF8_STRING
2021 if (enc_utf8)
2022 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2023 NULL, 0, NULL, NULL, NULL);
2024 else
2025#endif
2026 {
2027#if XtSpecificationRelease >= 4
2028# ifdef FEAT_XFONTSET
2029 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2030 NULL, 0, NULL, NULL, NULL);
2031# else
2032 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002033 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002035 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2037 NULL, 0, NULL, NULL, NULL);
2038# endif
2039#else
2040 XSetIconName(x11_display, x11_window, (char *)icon);
2041#endif
2042 }
2043 XFlush(x11_display);
2044}
2045
2046#else /* FEAT_X11 */
2047
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 static int
2049get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002050 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051{
2052 return FALSE;
2053}
2054
2055 static int
2056get_x11_icon(test_only)
2057 int test_only;
2058{
2059 if (!test_only)
2060 {
2061 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002062 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002064 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 }
2066 return FALSE;
2067}
2068
2069#endif /* FEAT_X11 */
2070
2071 int
2072mch_can_restore_title()
2073{
2074 return get_x11_title(TRUE);
2075}
2076
2077 int
2078mch_can_restore_icon()
2079{
2080 return get_x11_icon(TRUE);
2081}
2082
2083/*
2084 * Set the window title and icon.
2085 */
2086 void
2087mch_settitle(title, icon)
2088 char_u *title;
2089 char_u *icon;
2090{
2091 int type = 0;
2092 static int recursive = 0;
2093
2094 if (T_NAME == NULL) /* no terminal name (yet) */
2095 return;
2096 if (title == NULL && icon == NULL) /* nothing to do */
2097 return;
2098
2099 /* When one of the X11 functions causes a deadly signal, we get here again
2100 * recursively. Avoid hanging then (something is probably locked). */
2101 if (recursive)
2102 return;
2103 ++recursive;
2104
2105 /*
2106 * if the window ID and the display is known, we may use X11 calls
2107 */
2108#ifdef FEAT_X11
2109 if (get_x11_windis() == OK)
2110 type = 1;
2111#else
2112# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2113 if (gui.in_use)
2114 type = 1;
2115# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116#endif
2117
2118 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002119 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 * than x11 calls, because the x11 calls don't always work
2121 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122 if ((type || *T_TS != NUL) && title != NULL)
2123 {
2124 if (oldtitle == NULL
2125#ifdef FEAT_GUI
2126 && !gui.in_use
2127#endif
2128 ) /* first call but not in GUI, save title */
2129 (void)get_x11_title(FALSE);
2130
2131 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2132 term_settitle(title);
2133#ifdef FEAT_X11
2134 else
2135# ifdef FEAT_GUI_GTK
2136 if (!gui.in_use) /* don't do this if GTK+ is running */
2137# endif
2138 set_x11_title(title); /* x11 */
2139#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002140#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002141 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2142 else
2143 gui_mch_settitle(title, icon);
2144#endif
2145 did_set_title = TRUE;
2146 }
2147
2148 if ((type || *T_CIS != NUL) && icon != NULL)
2149 {
2150 if (oldicon == NULL
2151#ifdef FEAT_GUI
2152 && !gui.in_use
2153#endif
2154 ) /* first call, save icon */
2155 get_x11_icon(FALSE);
2156
2157 if (*T_CIS != NUL)
2158 {
2159 out_str(T_CIS); /* set icon start */
2160 out_str_nf(icon);
2161 out_str(T_CIE); /* set icon end */
2162 out_flush();
2163 }
2164#ifdef FEAT_X11
2165 else
2166# ifdef FEAT_GUI_GTK
2167 if (!gui.in_use) /* don't do this if GTK+ is running */
2168# endif
2169 set_x11_icon(icon); /* x11 */
2170#endif
2171 did_set_icon = TRUE;
2172 }
2173 --recursive;
2174}
2175
2176/*
2177 * Restore the window/icon title.
2178 * "which" is one of:
2179 * 1 only restore title
2180 * 2 only restore icon
2181 * 3 restore title and icon
2182 */
2183 void
2184mch_restore_title(which)
2185 int which;
2186{
2187 /* only restore the title or icon when it has been set */
2188 mch_settitle(((which & 1) && did_set_title) ?
2189 (oldtitle ? oldtitle : p_titleold) : NULL,
2190 ((which & 2) && did_set_icon) ? oldicon : NULL);
2191}
2192
2193#endif /* FEAT_TITLE */
2194
2195/*
2196 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002197 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 */
2199 int
2200vim_is_xterm(name)
2201 char_u *name;
2202{
2203 if (name == NULL)
2204 return FALSE;
2205 return (STRNICMP(name, "xterm", 5) == 0
2206 || STRNICMP(name, "nxterm", 6) == 0
2207 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002208 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 || STRNICMP(name, "rxvt", 4) == 0
2210 || STRCMP(name, "builtin_xterm") == 0);
2211}
2212
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002213#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2214/*
2215 * Return TRUE if "name" appears to be that of a terminal
2216 * known to support the xterm-style mouse protocol.
2217 * Relies on term_is_xterm having been set to its correct value.
2218 */
2219 int
2220use_xterm_like_mouse(name)
2221 char_u *name;
2222{
2223 return (name != NULL
2224 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2225}
2226#endif
2227
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2229/*
2230 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2231 * Return 1 for "xterm".
2232 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002233 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002234 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 */
2236 int
2237use_xterm_mouse()
2238{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002239 if (ttym_flags == TTYM_SGR)
2240 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002241 if (ttym_flags == TTYM_URXVT)
2242 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 if (ttym_flags == TTYM_XTERM2)
2244 return 2;
2245 if (ttym_flags == TTYM_XTERM)
2246 return 1;
2247 return 0;
2248}
2249#endif
2250
2251 int
2252vim_is_iris(name)
2253 char_u *name;
2254{
2255 if (name == NULL)
2256 return FALSE;
2257 return (STRNICMP(name, "iris-ansi", 9) == 0
2258 || STRCMP(name, "builtin_iris-ansi") == 0);
2259}
2260
2261 int
2262vim_is_vt300(name)
2263 char_u *name;
2264{
2265 if (name == NULL)
2266 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002267 /* catch VT100 - VT5xx */
2268 return ((STRNICMP(name, "vt", 2) == 0
2269 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270 || STRCMP(name, "builtin_vt320") == 0);
2271}
2272
2273/*
2274 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2275 * This should include all windowed terminal emulators.
2276 */
2277 int
2278vim_is_fastterm(name)
2279 char_u *name;
2280{
2281 if (name == NULL)
2282 return FALSE;
2283 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2284 return TRUE;
2285 return ( STRNICMP(name, "hpterm", 6) == 0
2286 || STRNICMP(name, "sun-cmd", 7) == 0
2287 || STRNICMP(name, "screen", 6) == 0
2288 || STRNICMP(name, "dtterm", 6) == 0);
2289}
2290
2291/*
2292 * Insert user name in s[len].
2293 * Return OK if a name found.
2294 */
2295 int
2296mch_get_user_name(s, len)
2297 char_u *s;
2298 int len;
2299{
2300#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002301 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 return OK;
2303#else
2304 return mch_get_uname(getuid(), s, len);
2305#endif
2306}
2307
2308/*
2309 * Insert user name for "uid" in s[len].
2310 * Return OK if a name found.
2311 */
2312 int
2313mch_get_uname(uid, s, len)
2314 uid_t uid;
2315 char_u *s;
2316 int len;
2317{
2318#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2319 struct passwd *pw;
2320
2321 if ((pw = getpwuid(uid)) != NULL
2322 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2323 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002324 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 return OK;
2326 }
2327#endif
2328 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2329 return FAIL; /* a number is not a name */
2330}
2331
2332/*
2333 * Insert host name is s[len].
2334 */
2335
2336#ifdef HAVE_SYS_UTSNAME_H
2337 void
2338mch_get_host_name(s, len)
2339 char_u *s;
2340 int len;
2341{
2342 struct utsname vutsname;
2343
2344 if (uname(&vutsname) < 0)
2345 *s = NUL;
2346 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002347 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348}
2349#else /* HAVE_SYS_UTSNAME_H */
2350
2351# ifdef HAVE_SYS_SYSTEMINFO_H
2352# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2353# endif
2354
2355 void
2356mch_get_host_name(s, len)
2357 char_u *s;
2358 int len;
2359{
2360# ifdef VAXC
2361 vaxc$gethostname((char *)s, len);
2362# else
2363 gethostname((char *)s, len);
2364# endif
2365 s[len - 1] = NUL; /* make sure it's terminated */
2366}
2367#endif /* HAVE_SYS_UTSNAME_H */
2368
2369/*
2370 * return process ID
2371 */
2372 long
2373mch_get_pid()
2374{
2375 return (long)getpid();
2376}
2377
2378#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2379static char *strerror __ARGS((int));
2380
2381 static char *
2382strerror(err)
2383 int err;
2384{
2385 extern int sys_nerr;
2386 extern char *sys_errlist[];
2387 static char er[20];
2388
2389 if (err > 0 && err < sys_nerr)
2390 return (sys_errlist[err]);
2391 sprintf(er, "Error %d", err);
2392 return er;
2393}
2394#endif
2395
2396/*
2397 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2398 * Return OK for success, FAIL for failure.
2399 */
2400 int
2401mch_dirname(buf, len)
2402 char_u *buf;
2403 int len;
2404{
2405#if defined(USE_GETCWD)
2406 if (getcwd((char *)buf, len) == NULL)
2407 {
2408 STRCPY(buf, strerror(errno));
2409 return FAIL;
2410 }
2411 return OK;
2412#else
2413 return (getwd((char *)buf) != NULL ? OK : FAIL);
2414#endif
2415}
2416
2417#if defined(OS2) || defined(PROTO)
2418/*
2419 * Replace all slashes by backslashes.
2420 * When 'shellslash' set do it the other way around.
2421 */
2422 void
2423slash_adjust(p)
2424 char_u *p;
2425{
2426 while (*p)
2427 {
2428 if (*p == psepcN)
2429 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002430 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 }
2432}
2433#endif
2434
2435/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002436 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 *
2438 * return FAIL for failure, OK for success
2439 */
2440 int
2441mch_FullName(fname, buf, len, force)
2442 char_u *fname, *buf;
2443 int len;
2444 int force; /* also expand when already absolute path */
2445{
2446 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002447#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002449#endif
2450#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 int fd = -1;
2452 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002453#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 char_u olddir[MAXPATHL];
2455 char_u *p;
2456 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002457#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002458 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2459 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002460#endif
2461
Bram Moolenaar38323e42007-03-06 19:22:53 +00002462#ifdef VMS
2463 fname = vms_fixfilename(fname);
2464#endif
2465
Bram Moolenaara2442432007-04-26 14:26:37 +00002466#ifdef __CYGWIN__
2467 /*
2468 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2469 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002470# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2471 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2472# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002473 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002474# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002475 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002476#endif
2477
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 /* expand it if forced or not an absolute path */
2479 if (force || !mch_isFullName(fname))
2480 {
2481 /*
2482 * If the file name has a path, change to that directory for a moment,
2483 * and then do the getwd() (and get back to where we were).
2484 * This will get the correct path name with "../" things.
2485 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002486#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 only_drive = 0;
2488 if (((p = vim_strrchr(fname, '/')) != NULL)
2489 || ((p = vim_strrchr(fname, '\\')) != NULL)
2490 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002491#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002493#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002495#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 /*
2497 * Use fchdir() if possible, it's said to be faster and more
2498 * reliable. But on SunOS 4 it might not work. Check this by
2499 * doing a fchdir() right now.
2500 */
2501 if (!dont_fchdir)
2502 {
2503 fd = open(".", O_RDONLY | O_EXTRA, 0);
2504 if (fd >= 0 && fchdir(fd) < 0)
2505 {
2506 close(fd);
2507 fd = -1;
2508 dont_fchdir = TRUE; /* don't try again */
2509 }
2510 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002511#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512
2513 /* Only change directory when we are sure we can return to where
2514 * we are now. After doing "su" chdir(".") might not work. */
2515 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002516#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 (mch_dirname(olddir, MAXPATHL) == FAIL
2520 || mch_chdir((char *)olddir) != 0))
2521 {
2522 p = NULL; /* can't get current dir: don't chdir */
2523 retval = FAIL;
2524 }
2525 else
2526 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002527#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 /*
2529 * compensate for case where ':' from "D:" was the only
2530 * path separator detected in the file name; the _next_
2531 * character has to be removed, and then restored later.
2532 */
2533 if (only_drive)
2534 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002535#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 /* The directory is copied into buf[], to be able to remove
2537 * the file name without changing it (could be a string in
2538 * read-only memory) */
2539 if (p - fname >= len)
2540 retval = FAIL;
2541 else
2542 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002543 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 if (mch_chdir((char *)buf))
2545 retval = FAIL;
2546 else
2547 fname = p + 1;
2548 *buf = NUL;
2549 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002550#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 if (only_drive)
2552 {
2553 p--;
2554 if (retval != FAIL)
2555 fname--;
2556 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002557#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 }
2559 }
2560 if (mch_dirname(buf, len) == FAIL)
2561 {
2562 retval = FAIL;
2563 *buf = NUL;
2564 }
2565 if (p != NULL)
2566 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002567#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 if (fd >= 0)
2569 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002570 if (p_verbose >= 5)
2571 {
2572 verbose_enter();
2573 MSG("fchdir() to previous dir");
2574 verbose_leave();
2575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 l = fchdir(fd);
2577 close(fd);
2578 }
2579 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002580#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 l = mch_chdir((char *)olddir);
2582 if (l != 0)
2583 EMSG(_(e_prev_dir));
2584 }
2585
2586 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002587 if (l >= len - 1)
2588 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002589#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002590 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002592 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002593#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002595
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002597 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 return FAIL;
2599
2600 /* Do not append ".", "/dir/." is equal to "/dir". */
2601 if (STRCMP(fname, ".") != 0)
2602 STRCAT(buf, fname);
2603
2604 return OK;
2605}
2606
2607/*
2608 * Return TRUE if "fname" does not depend on the current directory.
2609 */
2610 int
2611mch_isFullName(fname)
2612 char_u *fname;
2613{
2614#ifdef __EMX__
2615 return _fnisabs(fname);
2616#else
2617# ifdef VMS
2618 return ( fname[0] == '/' || fname[0] == '.' ||
2619 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2620 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2621 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2622# else
2623 return (*fname == '/' || *fname == '~');
2624# endif
2625#endif
2626}
2627
Bram Moolenaar24552be2005-12-10 20:17:30 +00002628#if defined(USE_FNAME_CASE) || defined(PROTO)
2629/*
2630 * Set the case of the file name, if it already exists. This will cause the
2631 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002632 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002633 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002634 void
2635fname_case(name, len)
2636 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002637 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002638{
2639 struct stat st;
2640 char_u *slash, *tail;
2641 DIR *dirp;
2642 struct dirent *dp;
2643
2644 if (lstat((char *)name, &st) >= 0)
2645 {
2646 /* Open the directory where the file is located. */
2647 slash = vim_strrchr(name, '/');
2648 if (slash == NULL)
2649 {
2650 dirp = opendir(".");
2651 tail = name;
2652 }
2653 else
2654 {
2655 *slash = NUL;
2656 dirp = opendir((char *)name);
2657 *slash = '/';
2658 tail = slash + 1;
2659 }
2660
2661 if (dirp != NULL)
2662 {
2663 while ((dp = readdir(dirp)) != NULL)
2664 {
2665 /* Only accept names that differ in case and are the same byte
2666 * length. TODO: accept different length name. */
2667 if (STRICMP(tail, dp->d_name) == 0
2668 && STRLEN(tail) == STRLEN(dp->d_name))
2669 {
2670 char_u newname[MAXPATHL + 1];
2671 struct stat st2;
2672
2673 /* Verify the inode is equal. */
2674 vim_strncpy(newname, name, MAXPATHL);
2675 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2676 MAXPATHL - (tail - name));
2677 if (lstat((char *)newname, &st2) >= 0
2678 && st.st_ino == st2.st_ino
2679 && st.st_dev == st2.st_dev)
2680 {
2681 STRCPY(tail, dp->d_name);
2682 break;
2683 }
2684 }
2685 }
2686
2687 closedir(dirp);
2688 }
2689 }
2690}
2691#endif
2692
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693/*
2694 * Get file permissions for 'name'.
2695 * Returns -1 when it doesn't exist.
2696 */
2697 long
2698mch_getperm(name)
2699 char_u *name;
2700{
2701 struct stat statb;
2702
2703 /* Keep the #ifdef outside of stat(), it may be a macro. */
2704#ifdef VMS
2705 if (stat((char *)vms_fixfilename(name), &statb))
2706#else
2707 if (stat((char *)name, &statb))
2708#endif
2709 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002710#ifdef __INTERIX
2711 /* The top bit makes the value negative, which means the file doesn't
2712 * exist. Remove the bit, we don't use it. */
2713 return statb.st_mode & ~S_ADDACE;
2714#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002716#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717}
2718
2719/*
2720 * set file permission for 'name' to 'perm'
2721 *
2722 * return FAIL for failure, OK otherwise
2723 */
2724 int
2725mch_setperm(name, perm)
2726 char_u *name;
2727 long perm;
2728{
2729 return (chmod((char *)
2730#ifdef VMS
2731 vms_fixfilename(name),
2732#else
2733 name,
2734#endif
2735 (mode_t)perm) == 0 ? OK : FAIL);
2736}
2737
2738#if defined(HAVE_ACL) || defined(PROTO)
2739# ifdef HAVE_SYS_ACL_H
2740# include <sys/acl.h>
2741# endif
2742# ifdef HAVE_SYS_ACCESS_H
2743# include <sys/access.h>
2744# endif
2745
2746# ifdef HAVE_SOLARIS_ACL
2747typedef struct vim_acl_solaris_T {
2748 int acl_cnt;
2749 aclent_t *acl_entry;
2750} vim_acl_solaris_T;
2751# endif
2752
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002753#if defined(HAVE_SELINUX) || defined(PROTO)
2754/*
2755 * Copy security info from "from_file" to "to_file".
2756 */
2757 void
2758mch_copy_sec(from_file, to_file)
2759 char_u *from_file;
2760 char_u *to_file;
2761{
2762 if (from_file == NULL)
2763 return;
2764
2765 if (selinux_enabled == -1)
2766 selinux_enabled = is_selinux_enabled();
2767
2768 if (selinux_enabled > 0)
2769 {
2770 security_context_t from_context = NULL;
2771 security_context_t to_context = NULL;
2772
2773 if (getfilecon((char *)from_file, &from_context) < 0)
2774 {
2775 /* If the filesystem doesn't support extended attributes,
2776 the original had no special security context and the
2777 target cannot have one either. */
2778 if (errno == EOPNOTSUPP)
2779 return;
2780
2781 MSG_PUTS(_("\nCould not get security context for "));
2782 msg_outtrans(from_file);
2783 msg_putchar('\n');
2784 return;
2785 }
2786 if (getfilecon((char *)to_file, &to_context) < 0)
2787 {
2788 MSG_PUTS(_("\nCould not get security context for "));
2789 msg_outtrans(to_file);
2790 msg_putchar('\n');
2791 freecon (from_context);
2792 return ;
2793 }
2794 if (strcmp(from_context, to_context) != 0)
2795 {
2796 if (setfilecon((char *)to_file, from_context) < 0)
2797 {
2798 MSG_PUTS(_("\nCould not set security context for "));
2799 msg_outtrans(to_file);
2800 msg_putchar('\n');
2801 }
2802 }
2803 freecon(to_context);
2804 freecon(from_context);
2805 }
2806}
2807#endif /* HAVE_SELINUX */
2808
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002809#if defined(HAVE_SMACK) && !defined(PROTO)
2810/*
2811 * Copy security info from "from_file" to "to_file".
2812 */
2813 void
2814mch_copy_sec(from_file, to_file)
2815 char_u *from_file;
2816 char_u *to_file;
2817{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002818 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002819 {
2820 XATTR_NAME_SMACK,
2821 XATTR_NAME_SMACKEXEC,
2822 XATTR_NAME_SMACKMMAP
2823 };
2824
2825 char buffer[SMACK_LABEL_LEN];
2826 const char *name;
2827 int index;
2828 int ret;
2829 ssize_t size;
2830
2831 if (from_file == NULL)
2832 return;
2833
2834 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2835 / sizeof(smack_copied_attributes)[0]) ; index++)
2836 {
2837 /* get the name of the attribute to copy */
2838 name = smack_copied_attributes[index];
2839
2840 /* get the value of the attribute in buffer */
2841 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2842 if (size >= 0)
2843 {
2844 /* copy the attribute value of buffer */
2845 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2846 if (ret < 0)
2847 {
2848 MSG_PUTS(_("Could not set security context "));
2849 MSG_PUTS(name);
2850 MSG_PUTS(_(" for "));
2851 msg_outtrans(to_file);
2852 msg_putchar('\n');
2853 }
2854 }
2855 else
2856 {
2857 /* what reason of not having the attribute value? */
2858 switch (errno)
2859 {
2860 case ENOTSUP:
2861 /* extended attributes aren't supported or enabled */
2862 /* should a message be echoed? not sure... */
2863 return; /* leave because it isn't usefull to continue */
2864
2865 case ERANGE:
2866 default:
2867 /* no enough size OR unexpected error */
2868 MSG_PUTS(_("Could not get security context "));
2869 MSG_PUTS(name);
2870 MSG_PUTS(_(" for "));
2871 msg_outtrans(from_file);
2872 MSG_PUTS(_(". Removing it!\n"));
2873 /* FALLTHROUGH to remove the attribute */
2874
2875 case ENODATA:
2876 /* no attribute of this name */
2877 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002878 /* Silently ignore errors, apparently this happens when
2879 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002880 break;
2881 }
2882 }
2883 }
2884}
2885#endif /* HAVE_SMACK */
2886
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887/*
2888 * Return a pointer to the ACL of file "fname" in allocated memory.
2889 * Return NULL if the ACL is not available for whatever reason.
2890 */
2891 vim_acl_T
2892mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002893 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
2895 vim_acl_T ret = NULL;
2896#ifdef HAVE_POSIX_ACL
2897 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2898#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002899#ifdef HAVE_SOLARIS_ZFS_ACL
2900 acl_t *aclent;
2901
2902 if (acl_get((char *)fname, 0, &aclent) < 0)
2903 return NULL;
2904 ret = (vim_acl_T)aclent;
2905#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906#ifdef HAVE_SOLARIS_ACL
2907 vim_acl_solaris_T *aclent;
2908
2909 aclent = malloc(sizeof(vim_acl_solaris_T));
2910 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2911 {
2912 free(aclent);
2913 return NULL;
2914 }
2915 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2916 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2917 {
2918 free(aclent->acl_entry);
2919 free(aclent);
2920 return NULL;
2921 }
2922 ret = (vim_acl_T)aclent;
2923#else
2924#if defined(HAVE_AIX_ACL)
2925 int aclsize;
2926 struct acl *aclent;
2927
2928 aclsize = sizeof(struct acl);
2929 aclent = malloc(aclsize);
2930 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2931 {
2932 if (errno == ENOSPC)
2933 {
2934 aclsize = aclent->acl_len;
2935 aclent = realloc(aclent, aclsize);
2936 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2937 {
2938 free(aclent);
2939 return NULL;
2940 }
2941 }
2942 else
2943 {
2944 free(aclent);
2945 return NULL;
2946 }
2947 }
2948 ret = (vim_acl_T)aclent;
2949#endif /* HAVE_AIX_ACL */
2950#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002951#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952#endif /* HAVE_POSIX_ACL */
2953 return ret;
2954}
2955
2956/*
2957 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2958 */
2959 void
2960mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002961 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 vim_acl_T aclent;
2963{
2964 if (aclent == NULL)
2965 return;
2966#ifdef HAVE_POSIX_ACL
2967 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2968#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002969#ifdef HAVE_SOLARIS_ZFS_ACL
2970 acl_set((char *)fname, (acl_t *)aclent);
2971#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972#ifdef HAVE_SOLARIS_ACL
2973 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2974 ((vim_acl_solaris_T *)aclent)->acl_entry);
2975#else
2976#ifdef HAVE_AIX_ACL
2977 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2978#endif /* HAVE_AIX_ACL */
2979#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002980#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981#endif /* HAVE_POSIX_ACL */
2982}
2983
2984 void
2985mch_free_acl(aclent)
2986 vim_acl_T aclent;
2987{
2988 if (aclent == NULL)
2989 return;
2990#ifdef HAVE_POSIX_ACL
2991 acl_free((acl_t)aclent);
2992#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002993#ifdef HAVE_SOLARIS_ZFS_ACL
2994 acl_free((acl_t *)aclent);
2995#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996#ifdef HAVE_SOLARIS_ACL
2997 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2998 free(aclent);
2999#else
3000#ifdef HAVE_AIX_ACL
3001 free(aclent);
3002#endif /* HAVE_AIX_ACL */
3003#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003004#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005#endif /* HAVE_POSIX_ACL */
3006}
3007#endif
3008
3009/*
3010 * Set hidden flag for "name".
3011 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 void
3013mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003014 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015{
3016 /* can't hide a file */
3017}
3018
3019/*
3020 * return TRUE if "name" is a directory
3021 * return FALSE if "name" is not a directory
3022 * return FALSE for error
3023 */
3024 int
3025mch_isdir(name)
3026 char_u *name;
3027{
3028 struct stat statb;
3029
3030 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3031 return FALSE;
3032 if (stat((char *)name, &statb))
3033 return FALSE;
3034#ifdef _POSIX_SOURCE
3035 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3036#else
3037 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3038#endif
3039}
3040
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041static int executable_file __ARGS((char_u *name));
3042
3043/*
3044 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3045 */
3046 static int
3047executable_file(name)
3048 char_u *name;
3049{
3050 struct stat st;
3051
3052 if (stat((char *)name, &st))
3053 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003054#ifdef VMS
3055 /* Like on Unix system file can have executable rights but not necessarily
3056 * be an executable, but on Unix is not a default for an ordianry file to
3057 * have an executable flag - on VMS it is in most cases.
3058 * Therefore, this check does not have any sense - let keep us to the
3059 * conventions instead:
3060 * *.COM and *.EXE files are the executables - the rest are not. This is
3061 * not ideal but better then it was.
3062 */
3063 int vms_executable = 0;
3064 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3065 {
3066 if (strstr(vms_tolower((char*)name),".exe") != NULL
3067 || strstr(vms_tolower((char*)name),".com")!= NULL)
3068 vms_executable = 1;
3069 }
3070 return vms_executable;
3071#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003073#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074}
3075
3076/*
3077 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
3078 * Return -1 if unknown.
3079 */
3080 int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003081mch_can_exe(name, path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 char_u *name;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003083 char_u **path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084{
3085 char_u *buf;
3086 char_u *p, *e;
3087 int retval;
3088
3089 /* If it's an absolute or relative path don't need to use $PATH. */
3090 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
3091 || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003092 {
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003093 if (executable_file(name))
3094 {
3095 if (path != NULL)
3096 {
3097 if (name[0] == '.')
3098 *path = FullName_save(name, TRUE);
3099 else
3100 *path = vim_strsave(name);
3101 }
3102 return TRUE;
3103 }
3104 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003105 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106
3107 p = (char_u *)getenv("PATH");
3108 if (p == NULL || *p == NUL)
3109 return -1;
3110 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3111 if (buf == NULL)
3112 return -1;
3113
3114 /*
3115 * Walk through all entries in $PATH to check if "name" exists there and
3116 * is an executable file.
3117 */
3118 for (;;)
3119 {
3120 e = (char_u *)strchr((char *)p, ':');
3121 if (e == NULL)
3122 e = p + STRLEN(p);
3123 if (e - p <= 1) /* empty entry means current dir */
3124 STRCPY(buf, "./");
3125 else
3126 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003127 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 add_pathsep(buf);
3129 }
3130 STRCAT(buf, name);
3131 retval = executable_file(buf);
3132 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003133 {
3134 if (path != NULL)
3135 {
3136 if (buf[0] == '.')
3137 *path = FullName_save(buf, TRUE);
3138 else
3139 *path = vim_strsave(buf);
3140 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003142 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143
3144 if (*e != ':')
3145 break;
3146 p = e + 1;
3147 }
3148
3149 vim_free(buf);
3150 return retval;
3151}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152
3153/*
3154 * Check what "name" is:
3155 * NODE_NORMAL: file or directory (or doesn't exist)
3156 * NODE_WRITABLE: writable device, socket, fifo, etc.
3157 * NODE_OTHER: non-writable things
3158 */
3159 int
3160mch_nodetype(name)
3161 char_u *name;
3162{
3163 struct stat st;
3164
3165 if (stat((char *)name, &st))
3166 return NODE_NORMAL;
3167 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3168 return NODE_NORMAL;
3169#ifndef OS2
3170 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3171 return NODE_OTHER;
3172#endif
3173 /* Everything else is writable? */
3174 return NODE_WRITABLE;
3175}
3176
3177 void
3178mch_early_init()
3179{
3180#ifdef HAVE_CHECK_STACK_GROWTH
3181 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 check_stack_growth((char *)&i);
3184
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003185# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 get_stack_limit();
3187# endif
3188
3189#endif
3190
3191 /*
3192 * Setup an alternative stack for signals. Helps to catch signals when
3193 * running out of stack space.
3194 * Use of sigaltstack() is preferred, it's more portable.
3195 * Ignore any errors.
3196 */
3197#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003198 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 init_signal_stack();
3200#endif
3201}
3202
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003203#if defined(EXITFREE) || defined(PROTO)
3204 void
3205mch_free_mem()
3206{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003207# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3208 if (clip_star.owned)
3209 clip_lose_selection(&clip_star);
3210 if (clip_plus.owned)
3211 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003212# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003213# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003214 if (xterm_Shell != (Widget)0)
3215 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003216# ifndef LESSTIF_VERSION
3217 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003218 if (xterm_dpy != NULL)
3219 XtCloseDisplay(xterm_dpy);
3220 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003221 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003222 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003223# ifdef FEAT_X11
3224 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3225# endif
3226 }
3227# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003228# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003229# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003230 if (x11_display != NULL
3231# ifdef FEAT_XCLIPBOARD
3232 && x11_display != xterm_dpy
3233# endif
3234 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003235 XCloseDisplay(x11_display);
3236# endif
3237# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3238 vim_free(signal_stack);
3239 signal_stack = NULL;
3240# endif
3241# ifdef FEAT_TITLE
3242 vim_free(oldtitle);
3243 vim_free(oldicon);
3244# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003245}
3246#endif
3247
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248static void exit_scroll __ARGS((void));
3249
3250/*
3251 * Output a newline when exiting.
3252 * Make sure the newline goes to the same stream as the text.
3253 */
3254 static void
3255exit_scroll()
3256{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003257 if (silent_mode)
3258 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 if (newline_on_exit || msg_didout)
3260 {
3261 if (msg_use_printf())
3262 {
3263 if (info_message)
3264 mch_msg("\n");
3265 else
3266 mch_errmsg("\r\n");
3267 }
3268 else
3269 out_char('\n');
3270 }
3271 else
3272 {
3273 restore_cterm_colors(); /* get original colors back */
3274 msg_clr_eos_force(); /* clear the rest of the display */
3275 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3276 }
3277}
3278
3279 void
3280mch_exit(r)
3281 int r;
3282{
3283 exiting = TRUE;
3284
3285#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3286 x11_export_final_selection();
3287#endif
3288
3289#ifdef FEAT_GUI
3290 if (!gui.in_use)
3291#endif
3292 {
3293 settmode(TMODE_COOK);
3294#ifdef FEAT_TITLE
3295 mch_restore_title(3); /* restore xterm title and icon name */
3296#endif
3297 /*
3298 * When t_ti is not empty but it doesn't cause swapping terminal
3299 * pages, need to output a newline when msg_didout is set. But when
3300 * t_ti does swap pages it should not go to the shell page. Do this
3301 * before stoptermcap().
3302 */
3303 if (swapping_screen() && !newline_on_exit)
3304 exit_scroll();
3305
3306 /* Stop termcap: May need to check for T_CRV response, which
3307 * requires RAW mode. */
3308 stoptermcap();
3309
3310 /*
3311 * A newline is only required after a message in the alternate screen.
3312 * This is set to TRUE by wait_return().
3313 */
3314 if (!swapping_screen() || newline_on_exit)
3315 exit_scroll();
3316
3317 /* Cursor may have been switched off without calling starttermcap()
3318 * when doing "vim -u vimrc" and vimrc contains ":q". */
3319 if (full_screen)
3320 cursor_on();
3321 }
3322 out_flush();
3323 ml_close_all(TRUE); /* remove all memfiles */
3324 may_core_dump();
3325#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 gui_exit(r);
3328#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003329
Bram Moolenaar56718732006-03-15 22:53:57 +00003330#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003331 mac_conv_cleanup();
3332#endif
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334#ifdef __QNX__
3335 /* A core dump won't be created if the signal handler
3336 * doesn't return, so we can't call exit() */
3337 if (deadly_signal != 0)
3338 return;
3339#endif
3340
Bram Moolenaar009b2592004-10-24 19:18:58 +00003341#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003342 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003343#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003344
3345#ifdef EXITFREE
3346 free_all_mem();
3347#endif
3348
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 exit(r);
3350}
3351
3352 static void
3353may_core_dump()
3354{
3355 if (deadly_signal != 0)
3356 {
3357 signal(deadly_signal, SIG_DFL);
3358 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3359 }
3360}
3361
3362#ifndef VMS
3363
3364 void
3365mch_settmode(tmode)
3366 int tmode;
3367{
3368 static int first = TRUE;
3369
3370 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3371#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3372 /*
3373 * for "new" tty systems
3374 */
3375# ifdef HAVE_TERMIOS_H
3376 static struct termios told;
3377 struct termios tnew;
3378# else
3379 static struct termio told;
3380 struct termio tnew;
3381# endif
3382
3383 if (first)
3384 {
3385 first = FALSE;
3386# if defined(HAVE_TERMIOS_H)
3387 tcgetattr(read_cmd_fd, &told);
3388# else
3389 ioctl(read_cmd_fd, TCGETA, &told);
3390# endif
3391 }
3392
3393 tnew = told;
3394 if (tmode == TMODE_RAW)
3395 {
3396 /*
3397 * ~ICRNL enables typing ^V^M
3398 */
3399 tnew.c_iflag &= ~ICRNL;
3400 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3401# if defined(IEXTEN) && !defined(__MINT__)
3402 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3403 /* but it breaks function keys on MINT */
3404# endif
3405 );
3406# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3407 tnew.c_oflag &= ~ONLCR;
3408# endif
3409 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3410 tnew.c_cc[VTIME] = 0; /* don't wait */
3411 }
3412 else if (tmode == TMODE_SLEEP)
3413 tnew.c_lflag &= ~(ECHO);
3414
3415# if defined(HAVE_TERMIOS_H)
3416 {
3417 int n = 10;
3418
3419 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3420 * few times. */
3421 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3422 && errno == EINTR && n > 0)
3423 --n;
3424 }
3425# else
3426 ioctl(read_cmd_fd, TCSETA, &tnew);
3427# endif
3428
3429#else
3430
3431 /*
3432 * for "old" tty systems
3433 */
3434# ifndef TIOCSETN
3435# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3436# endif
3437 static struct sgttyb ttybold;
3438 struct sgttyb ttybnew;
3439
3440 if (first)
3441 {
3442 first = FALSE;
3443 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3444 }
3445
3446 ttybnew = ttybold;
3447 if (tmode == TMODE_RAW)
3448 {
3449 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3450 ttybnew.sg_flags |= RAW;
3451 }
3452 else if (tmode == TMODE_SLEEP)
3453 ttybnew.sg_flags &= ~(ECHO);
3454 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3455#endif
3456 curr_tmode = tmode;
3457}
3458
3459/*
3460 * Try to get the code for "t_kb" from the stty setting
3461 *
3462 * Even if termcap claims a backspace key, the user's setting *should*
3463 * prevail. stty knows more about reality than termcap does, and if
3464 * somebody's usual erase key is DEL (which, for most BSD users, it will
3465 * be), they're going to get really annoyed if their erase key starts
3466 * doing forward deletes for no reason. (Eric Fischer)
3467 */
3468 void
3469get_stty()
3470{
3471 char_u buf[2];
3472 char_u *p;
3473
3474 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3475#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3476 /* for "new" tty systems */
3477# ifdef HAVE_TERMIOS_H
3478 struct termios keys;
3479# else
3480 struct termio keys;
3481# endif
3482
3483# if defined(HAVE_TERMIOS_H)
3484 if (tcgetattr(read_cmd_fd, &keys) != -1)
3485# else
3486 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3487# endif
3488 {
3489 buf[0] = keys.c_cc[VERASE];
3490 intr_char = keys.c_cc[VINTR];
3491#else
3492 /* for "old" tty systems */
3493 struct sgttyb keys;
3494
3495 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3496 {
3497 buf[0] = keys.sg_erase;
3498 intr_char = keys.sg_kill;
3499#endif
3500 buf[1] = NUL;
3501 add_termcode((char_u *)"kb", buf, FALSE);
3502
3503 /*
3504 * If <BS> and <DEL> are now the same, redefine <DEL>.
3505 */
3506 p = find_termcode((char_u *)"kD");
3507 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3508 do_fixdel(NULL);
3509 }
3510#if 0
3511 } /* to keep cindent happy */
3512#endif
3513}
3514
3515#endif /* VMS */
3516
3517#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3518/*
3519 * Set mouse clicks on or off.
3520 */
3521 void
3522mch_setmouse(on)
3523 int on;
3524{
3525 static int ison = FALSE;
3526 int xterm_mouse_vers;
3527
3528 if (on == ison) /* return quickly if nothing to do */
3529 return;
3530
3531 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003532
3533# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003534 if (ttym_flags == TTYM_URXVT)
3535 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003536 out_str_nf((char_u *)
3537 (on
3538 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3539 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3540 ison = on;
3541 }
3542# endif
3543
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003544# ifdef FEAT_MOUSE_SGR
3545 if (ttym_flags == TTYM_SGR)
3546 {
3547 out_str_nf((char_u *)
3548 (on
3549 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3550 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3551 ison = on;
3552 }
3553# endif
3554
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 if (xterm_mouse_vers > 0)
3556 {
3557 if (on) /* enable mouse events, use mouse tracking if available */
3558 out_str_nf((char_u *)
3559 (xterm_mouse_vers > 1
3560 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3561 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3562 else /* disable mouse events, could probably always send the same */
3563 out_str_nf((char_u *)
3564 (xterm_mouse_vers > 1
3565 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3566 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3567 ison = on;
3568 }
3569
3570# ifdef FEAT_MOUSE_DEC
3571 else if (ttym_flags == TTYM_DEC)
3572 {
3573 if (on) /* enable mouse events */
3574 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3575 else /* disable mouse events */
3576 out_str_nf((char_u *)"\033['z");
3577 ison = on;
3578 }
3579# endif
3580
3581# ifdef FEAT_MOUSE_GPM
3582 else
3583 {
3584 if (on)
3585 {
3586 if (gpm_open())
3587 ison = TRUE;
3588 }
3589 else
3590 {
3591 gpm_close();
3592 ison = FALSE;
3593 }
3594 }
3595# endif
3596
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003597# ifdef FEAT_SYSMOUSE
3598 else
3599 {
3600 if (on)
3601 {
3602 if (sysmouse_open() == OK)
3603 ison = TRUE;
3604 }
3605 else
3606 {
3607 sysmouse_close();
3608 ison = FALSE;
3609 }
3610 }
3611# endif
3612
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613# ifdef FEAT_MOUSE_JSB
3614 else
3615 {
3616 if (on)
3617 {
3618 /* D - Enable Mouse up/down messages
3619 * L - Enable Left Button Reporting
3620 * M - Enable Middle Button Reporting
3621 * R - Enable Right Button Reporting
3622 * K - Enable SHIFT and CTRL key Reporting
3623 * + - Enable Advanced messaging of mouse moves and up/down messages
3624 * Q - Quiet No Ack
3625 * # - Numeric value of mouse pointer required
3626 * 0 = Multiview 2000 cursor, used as standard
3627 * 1 = Windows Arrow
3628 * 2 = Windows I Beam
3629 * 3 = Windows Hour Glass
3630 * 4 = Windows Cross Hair
3631 * 5 = Windows UP Arrow
3632 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003633# ifdef JSBTERM_MOUSE_NONADVANCED
3634 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3636 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003637# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3639 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003640# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641 ison = TRUE;
3642 }
3643 else
3644 {
3645 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3646 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3647 ison = FALSE;
3648 }
3649 }
3650# endif
3651# ifdef FEAT_MOUSE_PTERM
3652 else
3653 {
3654 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3655 if (on)
3656 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3657 else
3658 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3659 ison = on;
3660 }
3661# endif
3662}
3663
3664/*
3665 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3666 */
3667 void
3668check_mouse_termcode()
3669{
Bram Moolenaar90013c62014-05-22 18:14:31 +02003670 xterm_conflict_mouse = FALSE;
3671
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672# ifdef FEAT_MOUSE_XTERM
3673 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003674# ifdef FEAT_MOUSE_URXVT
3675 && use_xterm_mouse() != 3
3676# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677# ifdef FEAT_GUI
3678 && !gui.in_use
3679# endif
3680 )
3681 {
3682 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003683 ? IF_EB("\233M", CSI_STR "M")
3684 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685 if (*p_mouse != NUL)
3686 {
3687 /* force mouse off and maybe on to send possibly new mouse
3688 * activation sequence to the xterm, with(out) drag tracing. */
3689 mch_setmouse(FALSE);
3690 setmouse();
3691 }
3692 }
3693 else
3694 del_mouse_termcode(KS_MOUSE);
3695# endif
3696
3697# ifdef FEAT_MOUSE_GPM
3698 if (!use_xterm_mouse()
3699# ifdef FEAT_GUI
3700 && !gui.in_use
3701# endif
3702 )
3703 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3704# endif
3705
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003706# ifdef FEAT_SYSMOUSE
3707 if (!use_xterm_mouse()
3708# ifdef FEAT_GUI
3709 && !gui.in_use
3710# endif
3711 )
3712 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3713# endif
3714
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715# ifdef FEAT_MOUSE_JSB
Bram Moolenaar90013c62014-05-22 18:14:31 +02003716 /* There is no conflict, but it was disabled for xterm before. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717 if (!use_xterm_mouse()
3718# ifdef FEAT_GUI
3719 && !gui.in_use
3720# endif
3721 )
3722 set_mouse_termcode(KS_JSBTERM_MOUSE,
3723 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3724 else
3725 del_mouse_termcode(KS_JSBTERM_MOUSE);
3726# endif
3727
3728# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003729 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 * define it in the GUI or when using an xterm. */
3731 if (!use_xterm_mouse()
3732# ifdef FEAT_GUI
3733 && !gui.in_use
3734# endif
3735 )
3736 set_mouse_termcode(KS_NETTERM_MOUSE,
3737 (char_u *)IF_EB("\033}", ESC_STR "}"));
3738 else
3739 del_mouse_termcode(KS_NETTERM_MOUSE);
3740# endif
3741
3742# ifdef FEAT_MOUSE_DEC
Bram Moolenaar90013c62014-05-22 18:14:31 +02003743 /* Conflicts with xterm mouse: "\033[" and "\033[M".
3744 * Also conflicts with the xterm termresponse, skip this if it was
3745 * requested already. */
3746 if (!use_xterm_mouse() && !did_request_esc_sequence()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747# ifdef FEAT_GUI
3748 && !gui.in_use
3749# endif
3750 )
Bram Moolenaar90013c62014-05-22 18:14:31 +02003751 {
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003752 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3753 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar90013c62014-05-22 18:14:31 +02003754 xterm_conflict_mouse = TRUE;
3755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 else
3757 del_mouse_termcode(KS_DEC_MOUSE);
3758# endif
3759# ifdef FEAT_MOUSE_PTERM
3760 /* same as the dec mouse */
Bram Moolenaar90013c62014-05-22 18:14:31 +02003761 if (!use_xterm_mouse() && !did_request_esc_sequence()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762# ifdef FEAT_GUI
3763 && !gui.in_use
3764# endif
3765 )
Bram Moolenaar90013c62014-05-22 18:14:31 +02003766 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767 set_mouse_termcode(KS_PTERM_MOUSE,
3768 (char_u *) IF_EB("\033[", ESC_STR "["));
Bram Moolenaar90013c62014-05-22 18:14:31 +02003769 xterm_conflict_mouse = TRUE;
3770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 else
3772 del_mouse_termcode(KS_PTERM_MOUSE);
3773# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003774# ifdef FEAT_MOUSE_URXVT
3775 /* same as the dec mouse */
Bram Moolenaar90013c62014-05-22 18:14:31 +02003776 if (use_xterm_mouse() == 3 && !did_request_esc_sequence()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003777# ifdef FEAT_GUI
3778 && !gui.in_use
3779# endif
3780 )
3781 {
3782 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3783 ? IF_EB("\233", CSI_STR)
3784 : IF_EB("\033[", ESC_STR "[")));
3785
3786 if (*p_mouse != NUL)
3787 {
3788 mch_setmouse(FALSE);
3789 setmouse();
3790 }
Bram Moolenaar90013c62014-05-22 18:14:31 +02003791 xterm_conflict_mouse = TRUE;
Bram Moolenaarc8427482011-10-20 21:09:35 +02003792 }
3793 else
3794 del_mouse_termcode(KS_URXVT_MOUSE);
3795# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003796# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003797 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003798 if (use_xterm_mouse() == 4
3799# ifdef FEAT_GUI
3800 && !gui.in_use
3801# endif
3802 )
3803 {
3804 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3805 ? IF_EB("\233<", CSI_STR "<")
3806 : IF_EB("\033[<", ESC_STR "[<")));
3807
3808 if (*p_mouse != NUL)
3809 {
3810 mch_setmouse(FALSE);
3811 setmouse();
3812 }
3813 }
3814 else
3815 del_mouse_termcode(KS_SGR_MOUSE);
3816# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817}
3818#endif
3819
3820/*
3821 * set screen mode, always fails.
3822 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 int
3824mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003825 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826{
3827 EMSG(_(e_screenmode));
3828 return FAIL;
3829}
3830
3831#ifndef VMS
3832
3833/*
3834 * Try to get the current window size:
3835 * 1. with an ioctl(), most accurate method
3836 * 2. from the environment variables LINES and COLUMNS
3837 * 3. from the termcap
3838 * 4. keep using the old values
3839 * Return OK when size could be determined, FAIL otherwise.
3840 */
3841 int
3842mch_get_shellsize()
3843{
3844 long rows = 0;
3845 long columns = 0;
3846 char_u *p;
3847
3848 /*
3849 * For OS/2 use _scrsize().
3850 */
3851# ifdef __EMX__
3852 {
3853 int s[2];
3854
3855 _scrsize(s);
3856 columns = s[0];
3857 rows = s[1];
3858 }
3859# endif
3860
3861 /*
3862 * 1. try using an ioctl. It is the most accurate method.
3863 *
3864 * Try using TIOCGWINSZ first, some systems that have it also define
3865 * TIOCGSIZE but don't have a struct ttysize.
3866 */
3867# ifdef TIOCGWINSZ
3868 {
3869 struct winsize ws;
3870 int fd = 1;
3871
3872 /* When stdout is not a tty, use stdin for the ioctl(). */
3873 if (!isatty(fd) && isatty(read_cmd_fd))
3874 fd = read_cmd_fd;
3875 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3876 {
3877 columns = ws.ws_col;
3878 rows = ws.ws_row;
3879 }
3880 }
3881# else /* TIOCGWINSZ */
3882# ifdef TIOCGSIZE
3883 {
3884 struct ttysize ts;
3885 int fd = 1;
3886
3887 /* When stdout is not a tty, use stdin for the ioctl(). */
3888 if (!isatty(fd) && isatty(read_cmd_fd))
3889 fd = read_cmd_fd;
3890 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3891 {
3892 columns = ts.ts_cols;
3893 rows = ts.ts_lines;
3894 }
3895 }
3896# endif /* TIOCGSIZE */
3897# endif /* TIOCGWINSZ */
3898
3899 /*
3900 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003901 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3902 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003904 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 {
3906 if ((p = (char_u *)getenv("LINES")))
3907 rows = atoi((char *)p);
3908 if ((p = (char_u *)getenv("COLUMNS")))
3909 columns = atoi((char *)p);
3910 }
3911
3912#ifdef HAVE_TGETENT
3913 /*
3914 * 3. try reading "co" and "li" entries from termcap
3915 */
3916 if (columns == 0 || rows == 0)
3917 getlinecol(&columns, &rows);
3918#endif
3919
3920 /*
3921 * 4. If everything fails, use the old values
3922 */
3923 if (columns <= 0 || rows <= 0)
3924 return FAIL;
3925
3926 Rows = rows;
3927 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003928 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 return OK;
3930}
3931
3932/*
3933 * Try to set the window size to Rows and Columns.
3934 */
3935 void
3936mch_set_shellsize()
3937{
3938 if (*T_CWS)
3939 {
3940 /*
3941 * NOTE: if you get an error here that term_set_winsize() is
3942 * undefined, check the output of configure. It could probably not
3943 * find a ncurses, termcap or termlib library.
3944 */
3945 term_set_winsize((int)Rows, (int)Columns);
3946 out_flush();
3947 screen_start(); /* don't know where cursor is now */
3948 }
3949}
3950
3951#endif /* VMS */
3952
3953/*
3954 * Rows and/or Columns has changed.
3955 */
3956 void
3957mch_new_shellsize()
3958{
3959 /* Nothing to do. */
3960}
3961
Bram Moolenaar205b8862011-09-07 15:04:31 +02003962/*
3963 * Wait for process "child" to end.
3964 * Return "child" if it exited properly, <= 0 on error.
3965 */
3966 static pid_t
3967wait4pid(child, status)
3968 pid_t child;
3969 waitstatus *status;
3970{
3971 pid_t wait_pid = 0;
3972
3973 while (wait_pid != child)
3974 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003975 /* When compiled with Python threads are probably used, in which case
3976 * wait() sometimes hangs for no obvious reason. Use waitpid()
3977 * instead and loop (like the GUI). Also needed for other interfaces,
3978 * they might call system(). */
3979# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003980 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003981# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003982 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003983# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003984 if (wait_pid == 0)
3985 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003986 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003987 mch_delay(10L, TRUE);
3988 continue;
3989 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003990 if (wait_pid <= 0
3991# ifdef ECHILD
3992 && errno == ECHILD
3993# endif
3994 )
3995 break;
3996 }
3997 return wait_pid;
3998}
3999
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000 int
4001mch_call_shell(cmd, options)
4002 char_u *cmd;
4003 int options; /* SHELL_*, see vim.h */
4004{
4005#ifdef VMS
4006 char *ifn = NULL;
4007 char *ofn = NULL;
4008#endif
4009 int tmode = cur_tmode;
4010#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
4011 int x;
4012# ifndef __EMX__
4013 char_u *newcmd; /* only needed for unix */
4014# else
4015 /*
4016 * Set the preferred shell in the EMXSHELL environment variable (but
4017 * only if it is different from what is already in the environment).
4018 * Emx then takes care of whether to use "/c" or "-c" in an
4019 * intelligent way. Simply pass the whole thing to emx's system() call.
4020 * Emx also starts an interactive shell if system() is passed an empty
4021 * string.
4022 */
4023 char_u *p, *old;
4024
4025 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4026 {
4027 /* should check HAVE_SETENV, but I know we don't have it. */
4028 p = alloc(10 + strlen(p_sh));
4029 if (p)
4030 {
4031 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4032 putenv((char *)p); /* don't free the pointer! */
4033 }
4034 }
4035# endif
4036
4037 out_flush();
4038
4039 if (options & SHELL_COOKED)
4040 settmode(TMODE_COOK); /* set to normal mode */
4041
Bram Moolenaar62b42182010-09-21 22:09:37 +02004042# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004043 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004044 loose_clipboard();
4045# endif
4046
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047# ifdef __EMX__
4048 if (cmd == NULL)
4049 x = system(""); /* this starts an interactive shell in emx */
4050 else
4051 x = system((char *)cmd);
4052 /* system() returns -1 when error occurs in starting shell */
4053 if (x == -1 && !emsg_silent)
4054 {
4055 MSG_PUTS(_("\nCannot execute shell "));
4056 msg_outtrans(p_sh);
4057 msg_putchar('\n');
4058 }
4059# else /* not __EMX__ */
4060 if (cmd == NULL)
4061 x = system((char *)p_sh);
4062 else
4063 {
4064# ifdef VMS
4065 if (ofn = strchr((char *)cmd, '>'))
4066 *ofn++ = '\0';
4067 if (ifn = strchr((char *)cmd, '<'))
4068 {
4069 char *p;
4070
4071 *ifn++ = '\0';
4072 p = strchr(ifn,' '); /* chop off any trailing spaces */
4073 if (p)
4074 *p = '\0';
4075 }
4076 if (ofn)
4077 x = vms_sys((char *)cmd, ofn, ifn);
4078 else
4079 x = system((char *)cmd);
4080# else
4081 newcmd = lalloc(STRLEN(p_sh)
4082 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4083 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4084 if (newcmd == NULL)
4085 x = 0;
4086 else
4087 {
4088 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4089 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4090 (char *)p_shcf,
4091 (char *)cmd);
4092 x = system((char *)newcmd);
4093 vim_free(newcmd);
4094 }
4095# endif
4096 }
4097# ifdef VMS
4098 x = vms_sys_status(x);
4099# endif
4100 if (emsg_silent)
4101 ;
4102 else if (x == 127)
4103 MSG_PUTS(_("\nCannot execute shell sh\n"));
4104# endif /* __EMX__ */
4105 else if (x && !(options & SHELL_SILENT))
4106 {
4107 MSG_PUTS(_("\nshell returned "));
4108 msg_outnum((long)x);
4109 msg_putchar('\n');
4110 }
4111
4112 if (tmode == TMODE_RAW)
4113 settmode(TMODE_RAW); /* set to raw mode */
4114# ifdef FEAT_TITLE
4115 resettitle();
4116# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004117# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4118 restore_clipboard();
4119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 return x;
4121
4122#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4123
Bram Moolenaardf177f62005-02-22 08:39:57 +00004124# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4125 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126
4127 char_u *newcmd = NULL;
4128 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004129 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 pid_t wait_pid = 0;
4131# ifdef HAVE_UNION_WAIT
4132 union wait status;
4133# else
4134 int status = -1;
4135# endif
4136 int retval = -1;
4137 char **argv = NULL;
4138 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004139 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 int i;
4141 char_u *p;
4142 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004144# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 int pty_slave_fd = -1;
4146 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004147# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004148 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 int fd_fromshell[2];
4150 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004151# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004153# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 static char envbuf_Rows[20];
4155 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004157 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158
Bram Moolenaar62b42182010-09-21 22:09:37 +02004159 newcmd = vim_strsave(p_sh);
4160 if (newcmd == NULL) /* out of memory */
4161 goto error;
4162
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 out_flush();
4164 if (options & SHELL_COOKED)
4165 settmode(TMODE_COOK); /* set to normal mode */
4166
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004167 /*
4168 * Do this loop twice:
4169 * 1: find number of arguments
4170 * 2: separate them and build argv[]
4171 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 for (i = 0; i < 2; ++i)
4173 {
4174 p = newcmd;
4175 inquote = FALSE;
4176 argc = 0;
4177 for (;;)
4178 {
4179 if (i == 1)
4180 argv[argc] = (char *)p;
4181 ++argc;
4182 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4183 {
4184 if (*p == '"')
4185 inquote = !inquote;
4186 ++p;
4187 }
4188 if (*p == NUL)
4189 break;
4190 if (i == 1)
4191 *p++ = NUL;
4192 p = skipwhite(p);
4193 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004194 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004196 /*
4197 * Account for possible multiple args in p_shcf.
4198 */
4199 p = p_shcf;
4200 for (;;)
4201 {
4202 p = skiptowhite(p);
4203 if (*p == NUL)
4204 break;
4205 ++argc;
4206 p = skipwhite(p);
4207 }
4208
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4210 if (argv == NULL) /* out of memory */
4211 goto error;
4212 }
4213 }
4214 if (cmd != NULL)
4215 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004216 char_u *s;
4217
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218 if (extra_shell_arg != NULL)
4219 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004220
4221 /* Break 'shellcmdflag' into white separated parts. This doesn't
4222 * handle quoted strings, they are very unlikely to appear. */
4223 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4224 if (p_shcf_copy == NULL) /* out of memory */
4225 goto error;
4226 s = p_shcf_copy;
4227 p = p_shcf;
4228 while (*p != NUL)
4229 {
4230 argv[argc++] = (char *)s;
4231 while (*p && *p != ' ' && *p != TAB)
4232 *s++ = *p++;
4233 *s++ = NUL;
4234 p = skipwhite(p);
4235 }
4236
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 argv[argc++] = (char *)cmd;
4238 }
4239 argv[argc] = NULL;
4240
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004242 * For the GUI, when writing the output into the buffer and when reading
4243 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4244 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004246 if ((options & (SHELL_READ|SHELL_WRITE))
4247# ifdef FEAT_GUI
4248 || (gui.in_use && show_shell_mess)
4249# endif
4250 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004252# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 /*
4254 * Try to open a master pty.
4255 * If this works, open the slave pty.
4256 * If the slave can't be opened, close the master pty.
4257 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004258 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 {
4260 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004261 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004263 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4264 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4265 * adding O_NOCTTY always works when defined. */
4266#ifdef O_NOCTTY
4267 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4268#else
4269 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4270#endif
4271 if (pty_slave_fd < 0)
4272 {
4273 close(pty_master_fd);
4274 pty_master_fd = -1;
4275 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276 }
4277 }
4278 /*
4279 * If not opening a pty or it didn't work, try using pipes.
4280 */
4281 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004282# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 {
4284 pipe_error = (pipe(fd_toshell) < 0);
4285 if (!pipe_error) /* pipe create OK */
4286 {
4287 pipe_error = (pipe(fd_fromshell) < 0);
4288 if (pipe_error) /* pipe create failed */
4289 {
4290 close(fd_toshell[0]);
4291 close(fd_toshell[1]);
4292 }
4293 }
4294 if (pipe_error)
4295 {
4296 MSG_PUTS(_("\nCannot create pipes\n"));
4297 out_flush();
4298 }
4299 }
4300 }
4301
4302 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 {
4304# ifdef __BEOS__
4305 beos_cleanup_read_thread();
4306# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004307
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4309 {
4310 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004311 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004313 || (gui.in_use && show_shell_mess)
4314# endif
4315 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004317# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 if (pty_master_fd >= 0) /* close the pseudo tty */
4319 {
4320 close(pty_master_fd);
4321 close(pty_slave_fd);
4322 }
4323 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004324# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325 {
4326 close(fd_toshell[0]);
4327 close(fd_toshell[1]);
4328 close(fd_fromshell[0]);
4329 close(fd_fromshell[1]);
4330 }
4331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332 }
4333 else if (pid == 0) /* child */
4334 {
4335 reset_signals(); /* handle signals normally */
4336
4337 if (!show_shell_mess || (options & SHELL_EXPAND))
4338 {
4339 int fd;
4340
4341 /*
4342 * Don't want to show any message from the shell. Can't just
4343 * close stdout and stderr though, because some systems will
4344 * break if you try to write to them after that, so we must
4345 * use dup() to replace them with something else -- webb
4346 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4347 * waiting for input.
4348 */
4349 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4350 fclose(stdin);
4351 fclose(stdout);
4352 fclose(stderr);
4353
4354 /*
4355 * If any of these open()'s and dup()'s fail, we just continue
4356 * anyway. It's not fatal, and on most systems it will make
4357 * no difference at all. On a few it will cause the execvp()
4358 * to exit with a non-zero status even when the completion
4359 * could be done, which is nothing too serious. If the open()
4360 * or dup() failed we'd just do the same thing ourselves
4361 * anyway -- webb
4362 */
4363 if (fd >= 0)
4364 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004365 ignored = dup(fd); /* To replace stdin (fd 0) */
4366 ignored = dup(fd); /* To replace stdout (fd 1) */
4367 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368
4369 /* Don't need this now that we've duplicated it */
4370 close(fd);
4371 }
4372 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004373 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004375 || gui.in_use
4376# endif
4377 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 {
4379
Bram Moolenaardf177f62005-02-22 08:39:57 +00004380# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004381 /* Create our own process group, so that the child and all its
4382 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004383 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004384 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004385 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004386 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004387# if defined(SIGHUP)
4388 /* When doing "!xterm&" and 'shell' is bash: the shell
4389 * will exit and send SIGHUP to all processes in its
4390 * group, killing the just started process. Ignore SIGHUP
4391 * to avoid that. (suggested by Simon Schubert)
4392 */
4393 signal(SIGHUP, SIG_IGN);
4394# endif
4395 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004396# endif
4397# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004398 if (pty_slave_fd >= 0)
4399 {
4400 /* push stream discipline modules */
4401 if (options & SHELL_COOKED)
4402 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004404 /* Try to become controlling tty (probably doesn't work,
4405 * unless run by root) */
4406 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004408 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004409# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004411# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 setenv("TERM", "dumb", 1);
4413 sprintf((char *)envbuf, "%ld", Rows);
4414 setenv("ROWS", (char *)envbuf, 1);
4415 sprintf((char *)envbuf, "%ld", Rows);
4416 setenv("LINES", (char *)envbuf, 1);
4417 sprintf((char *)envbuf, "%ld", Columns);
4418 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004419# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420 /*
4421 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004422 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423 */
4424 putenv("TERM=dumb");
4425 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4426 putenv(envbuf_Rows);
4427 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4428 putenv(envbuf_Rows);
4429 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4430 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004431# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432
Bram Moolenaara5792f52005-11-23 21:25:05 +00004433 /*
4434 * stderr is only redirected when using the GUI, so that a
4435 * program like gpg can still access the terminal to get a
4436 * passphrase using stderr.
4437 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004438# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 if (pty_master_fd >= 0)
4440 {
4441 close(pty_master_fd); /* close master side of pty */
4442
4443 /* set up stdin/stdout/stderr for the child */
4444 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004445 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004447 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004448 if (gui.in_use)
4449 {
4450 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004451 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453
4454 close(pty_slave_fd); /* has been dupped, close it now */
4455 }
4456 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458 {
4459 /* set up stdin for the child */
4460 close(fd_toshell[1]);
4461 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004462 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 close(fd_toshell[0]);
4464
4465 /* set up stdout for the child */
4466 close(fd_fromshell[0]);
4467 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004468 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469 close(fd_fromshell[1]);
4470
Bram Moolenaara5792f52005-11-23 21:25:05 +00004471# ifdef FEAT_GUI
4472 if (gui.in_use)
4473 {
4474 /* set up stderr for the child */
4475 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004476 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004477 }
4478# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 }
4480 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004481
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 /*
4483 * There is no type cast for the argv, because the type may be
4484 * different on different machines. This may cause a warning
4485 * message with strict compilers, don't worry about it.
4486 * Call _exit() instead of exit() to avoid closing the connection
4487 * to the X server (esp. with GTK, which uses atexit()).
4488 */
4489 execvp(argv[0], argv);
4490 _exit(EXEC_FAILED); /* exec failed, return failure code */
4491 }
4492 else /* parent */
4493 {
4494 /*
4495 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004496 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 */
4498 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004499 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500
4501 /*
4502 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004503 * This is also used to pipe stdin/stdout to/from the external
4504 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004506 if ((options & (SHELL_READ|SHELL_WRITE))
4507# ifdef FEAT_GUI
4508 || (gui.in_use && show_shell_mess)
4509# endif
4510 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004511 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004512# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004514# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004516# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4518 int ta_len = 0; /* valid bytes in ta_buf[] */
4519 int len;
4520 int p_more_save;
4521 int old_State;
4522 int c;
4523 int toshell_fd;
4524 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004525 garray_T ga;
4526 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004527# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4528 struct timeval start_tv;
4529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530
Bram Moolenaardf177f62005-02-22 08:39:57 +00004531# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532 if (pty_master_fd >= 0)
4533 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 fromshell_fd = pty_master_fd;
4535 toshell_fd = dup(pty_master_fd);
4536 }
4537 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 {
4540 close(fd_toshell[0]);
4541 close(fd_fromshell[1]);
4542 toshell_fd = fd_toshell[1];
4543 fromshell_fd = fd_fromshell[0];
4544 }
4545
4546 /*
4547 * Write to the child if there are typed characters.
4548 * Read from the child if there are characters available.
4549 * Repeat the reading a few times if more characters are
4550 * available. Need to check for typed keys now and then, but
4551 * not too often (delays when no chars are available).
4552 * This loop is quit if no characters can be read from the pty
4553 * (WaitForChar detected special condition), or there are no
4554 * characters available and the child has exited.
4555 * Only check if the child has exited when there is no more
4556 * output. The child may exit before all the output has
4557 * been printed.
4558 *
4559 * Currently this busy loops!
4560 * This can probably dead-lock when the write blocks!
4561 */
4562 p_more_save = p_more;
4563 p_more = FALSE;
4564 old_State = State;
4565 State = EXTERNCMD; /* don't redraw at window resize */
4566
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004567 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004568 {
4569 /* Fork a process that will write the lines to the
4570 * external program. */
4571 if ((wpid = fork()) == -1)
4572 {
4573 MSG_PUTS(_("\nCannot fork\n"));
4574 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004575 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004576 {
4577 linenr_T lnum = curbuf->b_op_start.lnum;
4578 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004579 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004580 size_t l;
4581
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004582 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004583 for (;;)
4584 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004585 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004586 if (l == 0)
4587 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004588 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004589 /* NL -> NUL translation */
4590 len = write(toshell_fd, "", (size_t)1);
4591 else
4592 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004593 char_u *s = vim_strchr(lp + written, NL);
4594
Bram Moolenaar89d40322006-08-29 15:30:07 +00004595 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004596 s == NULL ? l
4597 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004598 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004599 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004600 {
4601 /* Finished a line, add a NL, unless this line
4602 * should not have one. */
4603 if (lnum != curbuf->b_op_end.lnum
4604 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004605 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004606 && (lnum !=
4607 curbuf->b_ml.ml_line_count
4608 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004609 ignored = write(toshell_fd, "\n",
4610 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004611 ++lnum;
4612 if (lnum > curbuf->b_op_end.lnum)
4613 {
4614 /* finished all the lines, close pipe */
4615 close(toshell_fd);
4616 toshell_fd = -1;
4617 break;
4618 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004619 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004620 written = 0;
4621 }
4622 else if (len > 0)
4623 written += len;
4624 }
4625 _exit(0);
4626 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004627 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004628 {
4629 close(toshell_fd);
4630 toshell_fd = -1;
4631 }
4632 }
4633
4634 if (options & SHELL_READ)
4635 ga_init2(&ga, 1, BUFLEN);
4636
4637 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004638# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4639 gettimeofday(&start_tv, NULL);
4640# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004641 for (;;)
4642 {
4643 /*
4644 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004645 * if there are any.
4646 * Don't do this if we are expanding wild cards (would eat
4647 * typeahead).
4648 * Don't do this when filtering and terminal is in cooked
4649 * mode, the shell command will handle the I/O. Avoids
4650 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004651 * Don't get characters when the child has already
4652 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004653 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004654 * while (noread_cnt > 4), avoids that ":r !ls" eats
4655 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 */
4657 len = 0;
4658 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004659 && ((options &
4660 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4661 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004662# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004663 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004664# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004665 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004666 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004667 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004669 if (ta_len == 0)
4670 {
4671 /* Get extra characters when we don't have any.
4672 * Reset the counter and timer. */
4673 noread_cnt = 0;
4674# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4675 gettimeofday(&start_tv, NULL);
4676# endif
4677 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4678 }
4679 if (ta_len > 0 || len > 0)
4680 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 /*
4682 * For pipes:
4683 * Check for CTRL-C: send interrupt signal to child.
4684 * Check for CTRL-D: EOF, close pipe to child.
4685 */
4686 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4687 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004688# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 /*
4690 * Send SIGINT to the child's group or all
4691 * processes in our group.
4692 */
4693 if (ta_buf[ta_len] == Ctrl_C
4694 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004695 {
4696# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004698# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004701 if (wpid > 0)
4702 kill(wpid, SIGINT);
4703 }
4704# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705 if (pty_master_fd < 0 && toshell_fd >= 0
4706 && ta_buf[ta_len] == Ctrl_D)
4707 {
4708 close(toshell_fd);
4709 toshell_fd = -1;
4710 }
4711 }
4712
4713 /* replace K_BS by <BS> and K_DEL by <DEL> */
4714 for (i = ta_len; i < ta_len + len; ++i)
4715 {
4716 if (ta_buf[i] == CSI && len - i > 2)
4717 {
4718 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4719 if (c == K_DEL || c == K_KDEL || c == K_BS)
4720 {
4721 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4722 (size_t)(len - i - 2));
4723 if (c == K_DEL || c == K_KDEL)
4724 ta_buf[i] = DEL;
4725 else
4726 ta_buf[i] = Ctrl_H;
4727 len -= 2;
4728 }
4729 }
4730 else if (ta_buf[i] == '\r')
4731 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004732# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004734 i += (*mb_ptr2len_len)(ta_buf + i,
4735 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004736# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 }
4738
4739 /*
4740 * For pipes: echo the typed characters.
4741 * For a pty this does not seem to work.
4742 */
4743 if (pty_master_fd < 0)
4744 {
4745 for (i = ta_len; i < ta_len + len; ++i)
4746 {
4747 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4748 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004749# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750 else if (has_mbyte)
4751 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004752 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753
4754 msg_outtrans_len(ta_buf + i, l);
4755 i += l - 1;
4756 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 else
4759 msg_outtrans_len(ta_buf + i, 1);
4760 }
4761 windgoto(msg_row, msg_col);
4762 out_flush();
4763 }
4764
4765 ta_len += len;
4766
4767 /*
4768 * Write the characters to the child, unless EOF has
4769 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004770 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004771 * When writing buffer lines, drop the typed
4772 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004774 if (options & SHELL_WRITE)
4775 ta_len = 0;
4776 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 {
4778 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4779 if (len > 0)
4780 {
4781 ta_len -= len;
4782 mch_memmove(ta_buf, ta_buf + len, ta_len);
4783 }
4784 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 }
4787
Bram Moolenaardf177f62005-02-22 08:39:57 +00004788 if (got_int)
4789 {
4790 /* CTRL-C sends a signal to the child, we ignore it
4791 * ourselves */
4792# ifdef HAVE_SETSID
4793 kill(-pid, SIGINT);
4794# else
4795 kill(0, SIGINT);
4796# endif
4797 if (wpid > 0)
4798 kill(wpid, SIGINT);
4799 got_int = FALSE;
4800 }
4801
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 /*
4803 * Check if the child has any characters to be printed.
4804 * Read them and write them to our window. Repeat this as
4805 * long as there is something to do, avoid the 10ms wait
4806 * for mch_inchar(), or sending typeahead characters to
4807 * the external process.
4808 * TODO: This should handle escape sequences, compatible
4809 * to some terminal (vt52?).
4810 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004811 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4813 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004814 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004815# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004817# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004819# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820 );
4821 if (len <= 0) /* end of file or error */
4822 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004823
4824 noread_cnt = 0;
4825 if (options & SHELL_READ)
4826 {
4827 /* Do NUL -> NL translation, append NL separated
4828 * lines to the current buffer. */
4829 for (i = 0; i < len; ++i)
4830 {
4831 if (buffer[i] == NL)
4832 append_ga_line(&ga);
4833 else if (buffer[i] == NUL)
4834 ga_append(&ga, NL);
4835 else
4836 ga_append(&ga, buffer[i]);
4837 }
4838 }
4839# ifdef FEAT_MBYTE
4840 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 {
4842 int l;
4843
Bram Moolenaardf177f62005-02-22 08:39:57 +00004844 len += buffer_off;
4845 buffer[len] = NUL;
4846
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 /* Check if the last character in buffer[] is
4848 * incomplete, keep these bytes for the next
4849 * round. */
4850 for (p = buffer; p < buffer + len; p += l)
4851 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004852 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853 if (l == 0)
4854 l = 1; /* NUL byte? */
4855 else if (MB_BYTE2LEN(*p) != l)
4856 break;
4857 }
4858 if (p == buffer) /* no complete character */
4859 {
4860 /* avoid getting stuck at an illegal byte */
4861 if (len >= 12)
4862 ++p;
4863 else
4864 {
4865 buffer_off = len;
4866 continue;
4867 }
4868 }
4869 c = *p;
4870 *p = NUL;
4871 msg_puts(buffer);
4872 if (p < buffer + len)
4873 {
4874 *p = c;
4875 buffer_off = (buffer + len) - p;
4876 mch_memmove(buffer, p, buffer_off);
4877 continue;
4878 }
4879 buffer_off = 0;
4880 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004881# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 {
4884 buffer[len] = NUL;
4885 msg_puts(buffer);
4886 }
4887
4888 windgoto(msg_row, msg_col);
4889 cursor_on();
4890 out_flush();
4891 if (got_int)
4892 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004893
4894# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4895 {
4896 struct timeval now_tv;
4897 long msec;
4898
4899 /* Avoid that we keep looping here without
4900 * checking for a CTRL-C for a long time. Don't
4901 * break out too often to avoid losing typeahead. */
4902 gettimeofday(&now_tv, NULL);
4903 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4904 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4905 if (msec > 2000)
4906 {
4907 noread_cnt = 5;
4908 break;
4909 }
4910 }
4911# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 }
4913
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004914 /* If we already detected the child has finished break the
4915 * loop now. */
4916 if (wait_pid == pid)
4917 break;
4918
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 /*
4920 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004921 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004923# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004924 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004925# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004927# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4929 || (wait_pid == pid && WIFEXITED(status)))
4930 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004931 /* Don't break the loop yet, try reading more
4932 * characters from "fromshell_fd" first. When using
4933 * pipes there might still be something to read and
4934 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004937 else
4938 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004939
Bram Moolenaar95a51352013-03-21 22:53:50 +01004940# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004941 /* Handle any X events, e.g. serving the clipboard. */
4942 clip_update();
4943# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 }
4945finished:
4946 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004947 if (options & SHELL_READ)
4948 {
4949 if (ga.ga_len > 0)
4950 {
4951 append_ga_line(&ga);
4952 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004953 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004954 }
4955 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004956 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004957 ga_clear(&ga);
4958 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 /*
4961 * Give all typeahead that wasn't used back to ui_inchar().
4962 */
4963 if (ta_len)
4964 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 State = old_State;
4966 if (toshell_fd >= 0)
4967 close(toshell_fd);
4968 close(fromshell_fd);
4969 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004970# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004971 else
4972 {
4973 /*
4974 * Similar to the loop above, but only handle X events, no
4975 * I/O.
4976 */
4977 for (;;)
4978 {
4979 if (got_int)
4980 {
4981 /* CTRL-C sends a signal to the child, we ignore it
4982 * ourselves */
4983# ifdef HAVE_SETSID
4984 kill(-pid, SIGINT);
4985# else
4986 kill(0, SIGINT);
4987# endif
4988 got_int = FALSE;
4989 }
4990# ifdef __NeXT__
4991 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4992# else
4993 wait_pid = waitpid(pid, &status, WNOHANG);
4994# endif
4995 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4996 || (wait_pid == pid && WIFEXITED(status)))
4997 {
4998 wait_pid = pid;
4999 break;
5000 }
5001
5002 /* Handle any X events, e.g. serving the clipboard. */
5003 clip_update();
5004
5005 mch_delay(10L, TRUE);
5006 }
5007 }
5008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009
5010 /*
5011 * Wait until our child has exited.
5012 * Ignore wait() returning pids of other children and returning
5013 * because of some signal like SIGWINCH.
5014 * Don't wait if wait_pid was already set above, indicating the
5015 * child already exited.
5016 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005017 if (wait_pid != pid)
5018 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019
Bram Moolenaar624891f2010-10-13 16:22:09 +02005020# ifdef FEAT_GUI
5021 /* Close slave side of pty. Only do this after the child has
5022 * exited, otherwise the child may hang when it tries to write on
5023 * the pty. */
5024 if (pty_master_fd >= 0)
5025 close(pty_slave_fd);
5026# endif
5027
Bram Moolenaardf177f62005-02-22 08:39:57 +00005028 /* Make sure the child that writes to the external program is
5029 * dead. */
5030 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005031 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005032 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005033 wait4pid(wpid, NULL);
5034 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005035
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036 /*
5037 * Set to raw mode right now, otherwise a CTRL-C after
5038 * catch_signals() will kill Vim.
5039 */
5040 if (tmode == TMODE_RAW)
5041 settmode(TMODE_RAW);
5042 did_settmode = TRUE;
5043 set_signals();
5044
5045 if (WIFEXITED(status))
5046 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005047 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005049 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 {
5051 if (retval == EXEC_FAILED)
5052 {
5053 MSG_PUTS(_("\nCannot execute shell "));
5054 msg_outtrans(p_sh);
5055 msg_putchar('\n');
5056 }
5057 else if (!(options & SHELL_SILENT))
5058 {
5059 MSG_PUTS(_("\nshell returned "));
5060 msg_outnum((long)retval);
5061 msg_putchar('\n');
5062 }
5063 }
5064 }
5065 else
5066 MSG_PUTS(_("\nCommand terminated\n"));
5067 }
5068 }
5069 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005070 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071
5072error:
5073 if (!did_settmode)
5074 if (tmode == TMODE_RAW)
5075 settmode(TMODE_RAW); /* set to raw mode */
5076# ifdef FEAT_TITLE
5077 resettitle();
5078# endif
5079 vim_free(newcmd);
5080
5081 return retval;
5082
5083#endif /* USE_SYSTEM */
5084}
5085
5086/*
5087 * Check for CTRL-C typed by reading all available characters.
5088 * In cooked mode we should get SIGINT, no need to check.
5089 */
5090 void
5091mch_breakcheck()
5092{
5093 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
5094 fill_input_buf(FALSE);
5095}
5096
5097/*
5098 * Wait "msec" msec until a character is available from the keyboard or from
5099 * inbuf[]. msec == -1 will block forever.
5100 * When a GUI is being used, this will never get called -- webb
5101 */
5102 static int
5103WaitForChar(msec)
5104 long msec;
5105{
5106#ifdef FEAT_MOUSE_GPM
5107 int gpm_process_wanted;
5108#endif
5109#ifdef FEAT_XCLIPBOARD
5110 int rest;
5111#endif
5112 int avail;
5113
5114 if (input_available()) /* something in inbuf[] */
5115 return 1;
5116
5117#if defined(FEAT_MOUSE_DEC)
5118 /* May need to query the mouse position. */
5119 if (WantQueryMouse)
5120 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005121 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5123 }
5124#endif
5125
5126 /*
5127 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5128 * events. This is a bit complicated, because they might both be defined.
5129 */
5130#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5131# ifdef FEAT_XCLIPBOARD
5132 rest = 0;
5133 if (do_xterm_trace())
5134 rest = msec;
5135# endif
5136 do
5137 {
5138# ifdef FEAT_XCLIPBOARD
5139 if (rest != 0)
5140 {
5141 msec = XT_TRACE_DELAY;
5142 if (rest >= 0 && rest < XT_TRACE_DELAY)
5143 msec = rest;
5144 if (rest >= 0)
5145 rest -= msec;
5146 }
5147# endif
5148# ifdef FEAT_MOUSE_GPM
5149 gpm_process_wanted = 0;
5150 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5151# else
5152 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5153# endif
5154 if (!avail)
5155 {
5156 if (input_available())
5157 return 1;
5158# ifdef FEAT_XCLIPBOARD
5159 if (rest == 0 || !do_xterm_trace())
5160# endif
5161 break;
5162 }
5163 }
5164 while (FALSE
5165# ifdef FEAT_MOUSE_GPM
5166 || (gpm_process_wanted && mch_gpm_process() == 0)
5167# endif
5168# ifdef FEAT_XCLIPBOARD
5169 || (!avail && rest != 0)
5170# endif
5171 );
5172
5173#else
5174 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5175#endif
5176 return avail;
5177}
5178
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005179#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180/*
5181 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005182 * "msec" == 0 will check for characters once.
5183 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184 * When a GUI is being used, this will not be used for input -- webb
5185 * Returns also, when a request from Sniff is waiting -- toni.
5186 * Or when a Linux GPM mouse event is waiting.
5187 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188#if defined(__BEOS__)
5189 int
5190#else
5191 static int
5192#endif
5193RealWaitForChar(fd, msec, check_for_gpm)
5194 int fd;
5195 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005196 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197{
5198 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005199#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005200 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005201#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005202#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 static int busy = FALSE;
5204
5205 /* May retry getting characters after an event was handled. */
5206# define MAY_LOOP
5207
5208# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5209 /* Remember at what time we started, so that we know how much longer we
5210 * should wait after being interrupted. */
5211# define USE_START_TV
5212 struct timeval start_tv;
5213
5214 if (msec > 0 && (
5215# ifdef FEAT_XCLIPBOARD
5216 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005217# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 ||
5219# endif
5220# endif
5221# ifdef USE_XSMP
5222 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005223# ifdef FEAT_MZSCHEME
5224 ||
5225# endif
5226# endif
5227# ifdef FEAT_MZSCHEME
5228 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229# endif
5230 ))
5231 gettimeofday(&start_tv, NULL);
5232# endif
5233
5234 /* Handle being called recursively. This may happen for the session
5235 * manager stuff, it may save the file, which does a breakcheck. */
5236 if (busy)
5237 return 0;
5238#endif
5239
5240#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005241 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005242#endif
5243 {
5244#ifdef MAY_LOOP
5245 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005246# ifdef FEAT_MZSCHEME
5247 int mzquantum_used = FALSE;
5248# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249#endif
5250#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005251 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252 int nfd;
5253# ifdef FEAT_XCLIPBOARD
5254 int xterm_idx = -1;
5255# endif
5256# ifdef FEAT_MOUSE_GPM
5257 int gpm_idx = -1;
5258# endif
5259# ifdef USE_XSMP
5260 int xsmp_idx = -1;
5261# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005262# ifdef FEAT_NETBEANS_INTG
5263 int nb_idx = -1;
5264# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005265 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005267# ifdef FEAT_MZSCHEME
5268 mzvim_check_threads();
5269 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5270 {
5271 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5272 mzquantum_used = TRUE;
5273 }
5274# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005275 fds[0].fd = fd;
5276 fds[0].events = POLLIN;
5277 nfd = 1;
5278
5279# ifdef FEAT_SNIFF
5280# define SNIFF_IDX 1
5281 if (want_sniff_request)
5282 {
5283 fds[SNIFF_IDX].fd = fd_from_sniff;
5284 fds[SNIFF_IDX].events = POLLIN;
5285 nfd++;
5286 }
5287# endif
5288# ifdef FEAT_XCLIPBOARD
5289 if (xterm_Shell != (Widget)0)
5290 {
5291 xterm_idx = nfd;
5292 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5293 fds[nfd].events = POLLIN;
5294 nfd++;
5295 }
5296# endif
5297# ifdef FEAT_MOUSE_GPM
5298 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5299 {
5300 gpm_idx = nfd;
5301 fds[nfd].fd = gpm_fd;
5302 fds[nfd].events = POLLIN;
5303 nfd++;
5304 }
5305# endif
5306# ifdef USE_XSMP
5307 if (xsmp_icefd != -1)
5308 {
5309 xsmp_idx = nfd;
5310 fds[nfd].fd = xsmp_icefd;
5311 fds[nfd].events = POLLIN;
5312 nfd++;
5313 }
5314# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005315#ifdef FEAT_NETBEANS_INTG
5316 if (nb_fd != -1)
5317 {
5318 nb_idx = nfd;
5319 fds[nfd].fd = nb_fd;
5320 fds[nfd].events = POLLIN;
5321 nfd++;
5322 }
5323#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005324
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005325 ret = poll(fds, nfd, towait);
5326# ifdef FEAT_MZSCHEME
5327 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005328 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005329 finished = FALSE;
5330# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005331
5332# ifdef FEAT_SNIFF
5333 if (ret < 0)
5334 sniff_disconnect(1);
5335 else if (want_sniff_request)
5336 {
5337 if (fds[SNIFF_IDX].revents & POLLHUP)
5338 sniff_disconnect(1);
5339 if (fds[SNIFF_IDX].revents & POLLIN)
5340 sniff_request_waiting = 1;
5341 }
5342# endif
5343# ifdef FEAT_XCLIPBOARD
5344 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5345 {
5346 xterm_update(); /* Maybe we should hand out clipboard */
5347 if (--ret == 0 && !input_available())
5348 /* Try again */
5349 finished = FALSE;
5350 }
5351# endif
5352# ifdef FEAT_MOUSE_GPM
5353 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5354 {
5355 *check_for_gpm = 1;
5356 }
5357# endif
5358# ifdef USE_XSMP
5359 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5360 {
5361 if (fds[xsmp_idx].revents & POLLIN)
5362 {
5363 busy = TRUE;
5364 xsmp_handle_requests();
5365 busy = FALSE;
5366 }
5367 else if (fds[xsmp_idx].revents & POLLHUP)
5368 {
5369 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005370 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 xsmp_close();
5372 }
5373 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005374 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 }
5376# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005377#ifdef FEAT_NETBEANS_INTG
5378 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5379 {
5380 netbeans_read();
5381 --ret;
5382 }
5383#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384
5385
5386#else /* HAVE_SELECT */
5387
5388 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005389 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 fd_set rfds, efds;
5391 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005392 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005394# ifdef FEAT_MZSCHEME
5395 mzvim_check_threads();
5396 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5397 {
5398 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5399 mzquantum_used = TRUE;
5400 }
5401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402# ifdef __EMX__
5403 /* don't check for incoming chars if not in raw mode, because select()
5404 * always returns TRUE then (in some version of emx.dll) */
5405 if (curr_tmode != TMODE_RAW)
5406 return 0;
5407# endif
5408
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005409 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005410 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005411 tv.tv_sec = towait / 1000;
5412 tv.tv_usec = (towait % 1000) * (1000000/1000);
5413 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005415 else
5416 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417
5418 /*
5419 * Select on ready for reading and exceptional condition (end of file).
5420 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005421select_eintr:
5422 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 FD_ZERO(&efds);
5424 FD_SET(fd, &rfds);
5425# if !defined(__QNX__) && !defined(__CYGWIN32__)
5426 /* For QNX select() always returns 1 if this is set. Why? */
5427 FD_SET(fd, &efds);
5428# endif
5429 maxfd = fd;
5430
5431# ifdef FEAT_SNIFF
5432 if (want_sniff_request)
5433 {
5434 FD_SET(fd_from_sniff, &rfds);
5435 FD_SET(fd_from_sniff, &efds);
5436 if (maxfd < fd_from_sniff)
5437 maxfd = fd_from_sniff;
5438 }
5439# endif
5440# ifdef FEAT_XCLIPBOARD
5441 if (xterm_Shell != (Widget)0)
5442 {
5443 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5444 if (maxfd < ConnectionNumber(xterm_dpy))
5445 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005446
5447 /* An event may have already been read but not handled. In
5448 * particulary, XFlush may cause this. */
5449 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450 }
5451# endif
5452# ifdef FEAT_MOUSE_GPM
5453 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5454 {
5455 FD_SET(gpm_fd, &rfds);
5456 FD_SET(gpm_fd, &efds);
5457 if (maxfd < gpm_fd)
5458 maxfd = gpm_fd;
5459 }
5460# endif
5461# ifdef USE_XSMP
5462 if (xsmp_icefd != -1)
5463 {
5464 FD_SET(xsmp_icefd, &rfds);
5465 FD_SET(xsmp_icefd, &efds);
5466 if (maxfd < xsmp_icefd)
5467 maxfd = xsmp_icefd;
5468 }
5469# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005470# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005471 if (nb_fd != -1)
5472 {
5473 FD_SET(nb_fd, &rfds);
5474 if (maxfd < nb_fd)
5475 maxfd = nb_fd;
5476 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005477# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005479 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005480# ifdef EINTR
5481 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005482 {
5483 /* Check whether window has been resized, EINTR may be caused by
5484 * SIGWINCH. */
5485 if (do_resize)
5486 handle_resize();
5487
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005488 /* Interrupted by a signal, need to try again. We ignore msec
5489 * here, because we do want to check even after a timeout if
5490 * characters are available. Needed for reading output of an
5491 * external command after the process has finished. */
5492 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005493 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005494# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005495# ifdef __TANDEM
5496 if (ret == -1 && errno == ENOTSUP)
5497 {
5498 FD_ZERO(&rfds);
5499 FD_ZERO(&efds);
5500 ret = 0;
5501 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005502# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005503# ifdef FEAT_MZSCHEME
5504 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005505 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005506 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507# endif
5508
5509# ifdef FEAT_SNIFF
5510 if (ret < 0 )
5511 sniff_disconnect(1);
5512 else if (ret > 0 && want_sniff_request)
5513 {
5514 if (FD_ISSET(fd_from_sniff, &efds))
5515 sniff_disconnect(1);
5516 if (FD_ISSET(fd_from_sniff, &rfds))
5517 sniff_request_waiting = 1;
5518 }
5519# endif
5520# ifdef FEAT_XCLIPBOARD
5521 if (ret > 0 && xterm_Shell != (Widget)0
5522 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5523 {
5524 xterm_update(); /* Maybe we should hand out clipboard */
5525 /* continue looping when we only got the X event and the input
5526 * buffer is empty */
5527 if (--ret == 0 && !input_available())
5528 {
5529 /* Try again */
5530 finished = FALSE;
5531 }
5532 }
5533# endif
5534# ifdef FEAT_MOUSE_GPM
5535 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5536 {
5537 if (FD_ISSET(gpm_fd, &efds))
5538 gpm_close();
5539 else if (FD_ISSET(gpm_fd, &rfds))
5540 *check_for_gpm = 1;
5541 }
5542# endif
5543# ifdef USE_XSMP
5544 if (ret > 0 && xsmp_icefd != -1)
5545 {
5546 if (FD_ISSET(xsmp_icefd, &efds))
5547 {
5548 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005549 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 xsmp_close();
5551 if (--ret == 0)
5552 finished = FALSE; /* keep going if event was only one */
5553 }
5554 else if (FD_ISSET(xsmp_icefd, &rfds))
5555 {
5556 busy = TRUE;
5557 xsmp_handle_requests();
5558 busy = FALSE;
5559 if (--ret == 0)
5560 finished = FALSE; /* keep going if event was only one */
5561 }
5562 }
5563# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005564#ifdef FEAT_NETBEANS_INTG
5565 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5566 {
5567 netbeans_read();
5568 --ret;
5569 }
5570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571
5572#endif /* HAVE_SELECT */
5573
5574#ifdef MAY_LOOP
5575 if (finished || msec == 0)
5576 break;
5577
5578 /* We're going to loop around again, find out for how long */
5579 if (msec > 0)
5580 {
5581# ifdef USE_START_TV
5582 struct timeval mtv;
5583
5584 /* Compute remaining wait time. */
5585 gettimeofday(&mtv, NULL);
5586 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5587 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5588# else
5589 /* Guess we got interrupted halfway. */
5590 msec = msec / 2;
5591# endif
5592 if (msec <= 0)
5593 break; /* waited long enough */
5594 }
5595#endif
5596 }
5597
5598 return (ret > 0);
5599}
5600
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005603 * Expand a path into all matching files and/or directories. Handles "*",
5604 * "?", "[a-z]", "**", etc.
5605 * "path" has backslashes before chars that are not to be expanded.
5606 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 */
5608 int
5609mch_expandpath(gap, path, flags)
5610 garray_T *gap;
5611 char_u *path;
5612 int flags; /* EW_* flags */
5613{
Bram Moolenaar02743632005-07-25 20:42:36 +00005614 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615}
5616#endif
5617
5618/*
5619 * mch_expand_wildcards() - this code does wild-card pattern matching using
5620 * the shell
5621 *
5622 * return OK for success, FAIL for error (you may lose some memory) and put
5623 * an error message in *file.
5624 *
5625 * num_pat is number of input patterns
5626 * pat is array of pointers to input patterns
5627 * num_file is pointer to number of matched file names
5628 * file is pointer to array of pointers to matched file names
5629 */
5630
5631#ifndef SEEK_SET
5632# define SEEK_SET 0
5633#endif
5634#ifndef SEEK_END
5635# define SEEK_END 2
5636#endif
5637
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005638#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005639
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 int
5641mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5642 int num_pat;
5643 char_u **pat;
5644 int *num_file;
5645 char_u ***file;
5646 int flags; /* EW_* flags */
5647{
5648 int i;
5649 size_t len;
5650 char_u *p;
5651 int dir;
5652#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005653 /*
5654 * This is the OS/2 implementation.
5655 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656# define EXPL_ALLOC_INC 16
5657 char_u **expl_files;
5658 size_t files_alloced, files_free;
5659 char_u *buf;
5660 int has_wildcard;
5661
5662 *num_file = 0; /* default: no files found */
5663 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5664 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5665 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5666 if (*file == NULL)
5667 return FAIL;
5668
5669 for (; num_pat > 0; num_pat--, pat++)
5670 {
5671 expl_files = NULL;
5672 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5673 /* expand environment var or home dir */
5674 buf = expand_env_save(*pat);
5675 else
5676 buf = vim_strsave(*pat);
5677 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005678 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679 if (has_wildcard) /* yes, so expand them */
5680 expl_files = (char_u **)_fnexplode(buf);
5681
5682 /*
5683 * return value of buf if no wildcards left,
5684 * OR if no match AND EW_NOTFOUND is set.
5685 */
5686 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5687 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5688 { /* simply save the current contents of *buf */
5689 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5690 if (expl_files != NULL)
5691 {
5692 expl_files[0] = vim_strsave(buf);
5693 expl_files[1] = NULL;
5694 }
5695 }
5696 vim_free(buf);
5697
5698 /*
5699 * Count number of names resulting from expansion,
5700 * At the same time add a backslash to the end of names that happen to
5701 * be directories, and replace slashes with backslashes.
5702 */
5703 if (expl_files)
5704 {
5705 for (i = 0; (p = expl_files[i]) != NULL; i++)
5706 {
5707 dir = mch_isdir(p);
5708 /* If we don't want dirs and this is one, skip it */
5709 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5710 continue;
5711
Bram Moolenaara2031822006-03-07 22:29:51 +00005712 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02005713 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p, NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00005714 continue;
5715
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 if (--files_free == 0)
5717 {
5718 /* need more room in table of pointers */
5719 files_alloced += EXPL_ALLOC_INC;
5720 *file = (char_u **)vim_realloc(*file,
5721 sizeof(char_u **) * files_alloced);
5722 if (*file == NULL)
5723 {
5724 EMSG(_(e_outofmem));
5725 *num_file = 0;
5726 return FAIL;
5727 }
5728 files_free = EXPL_ALLOC_INC;
5729 }
5730 slash_adjust(p);
5731 if (dir)
5732 {
5733 /* For a directory we add a '/', unless it's already
5734 * there. */
5735 len = STRLEN(p);
5736 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5737 {
5738 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005739 if (!after_pathsep((*file)[*num_file],
5740 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 {
5742 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005743 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 }
5745 }
5746 }
5747 else
5748 {
5749 (*file)[*num_file] = vim_strsave(p);
5750 }
5751
5752 /*
5753 * Error message already given by either alloc or vim_strsave.
5754 * Should return FAIL, but returning OK works also.
5755 */
5756 if ((*file)[*num_file] == NULL)
5757 break;
5758 (*num_file)++;
5759 }
5760 _fnexplodefree((char **)expl_files);
5761 }
5762 }
5763 return OK;
5764
5765#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005766 /*
5767 * This is the non-OS/2 implementation (really Unix).
5768 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 int j;
5770 char_u *tempname;
5771 char_u *command;
5772 FILE *fd;
5773 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005774#define STYLE_ECHO 0 /* use "echo", the default */
5775#define STYLE_GLOB 1 /* use "glob", for csh */
5776#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5777#define STYLE_PRINT 3 /* use "print -N", for zsh */
5778#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5779 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780 int shell_style = STYLE_ECHO;
5781 int check_spaces;
5782 static int did_find_nul = FALSE;
5783 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005784 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005785 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786
5787 *num_file = 0; /* default: no files found */
5788 *file = NULL;
5789
5790 /*
5791 * If there are no wildcards, just copy the names to allocated memory.
5792 * Saves a lot of time, because we don't have to start a new shell.
5793 */
5794 if (!have_wildcard(num_pat, pat))
5795 return save_patterns(num_pat, pat, num_file, file);
5796
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005797# ifdef HAVE_SANDBOX
5798 /* Don't allow any shell command in the sandbox. */
5799 if (sandbox != 0 && check_secure())
5800 return FAIL;
5801# endif
5802
Bram Moolenaar071d4272004-06-13 20:20:40 +00005803 /*
5804 * Don't allow the use of backticks in secure and restricted mode.
5805 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005806 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807 for (i = 0; i < num_pat; ++i)
5808 if (vim_strchr(pat[i], '`') != NULL
5809 && (check_restricted() || check_secure()))
5810 return FAIL;
5811
5812 /*
5813 * get a name for the temp file
5814 */
5815 if ((tempname = vim_tempname('o')) == NULL)
5816 {
5817 EMSG(_(e_notmp));
5818 return FAIL;
5819 }
5820
5821 /*
5822 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005823 * file.
5824 * STYLE_BT: NL separated
5825 * If expanding `cmd` execute it directly.
5826 * STYLE_GLOB: NUL separated
5827 * If we use *csh, "glob" will work better than "echo".
5828 * STYLE_PRINT: NL or NUL separated
5829 * If we use *zsh, "print -N" will work better than "glob".
5830 * STYLE_VIMGLOB: NL separated
5831 * If we use *sh*, we define "vimglob()".
5832 * STYLE_ECHO: space separated.
5833 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834 */
5835 if (num_pat == 1 && *pat[0] == '`'
5836 && (len = STRLEN(pat[0])) > 2
5837 && *(pat[0] + len - 1) == '`')
5838 shell_style = STYLE_BT;
5839 else if ((len = STRLEN(p_sh)) >= 3)
5840 {
5841 if (STRCMP(p_sh + len - 3, "csh") == 0)
5842 shell_style = STYLE_GLOB;
5843 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5844 shell_style = STYLE_PRINT;
5845 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005846 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5847 "sh") != NULL)
5848 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849
Bram Moolenaarc7247912008-01-13 12:54:11 +00005850 /* Compute the length of the command. We need 2 extra bytes: for the
5851 * optional '&' and for the NUL.
5852 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005854 if (shell_style == STYLE_VIMGLOB)
5855 len += STRLEN(sh_vimglob_func);
5856
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005857 for (i = 0; i < num_pat; ++i)
5858 {
5859 /* Count the length of the patterns in the same way as they are put in
5860 * "command" below. */
5861#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005863#else
5864 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005865 for (j = 0; pat[i][j] != NUL; ++j)
5866 {
5867 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5868 ++len; /* may add a backslash */
5869 ++len;
5870 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005871#endif
5872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873 command = alloc(len);
5874 if (command == NULL)
5875 {
5876 /* out of memory */
5877 vim_free(tempname);
5878 return FAIL;
5879 }
5880
5881 /*
5882 * Build the shell command:
5883 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5884 * recognizes this).
5885 * - Add the shell command to print the expanded names.
5886 * - Add the temp file name.
5887 * - Add the file name patterns.
5888 */
5889 if (shell_style == STYLE_BT)
5890 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005891 /* change `command; command& ` to (command; command ) */
5892 STRCPY(command, "(");
5893 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005895 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 while (p > command && vim_iswhite(*p))
5897 --p;
5898 if (*p == '&') /* remove trailing '&' */
5899 {
5900 ampersent = TRUE;
5901 *p = ' ';
5902 }
5903 STRCAT(command, ">");
5904 }
5905 else
5906 {
5907 if (flags & EW_NOTFOUND)
5908 STRCPY(command, "set nonomatch; ");
5909 else
5910 STRCPY(command, "unset nonomatch; ");
5911 if (shell_style == STYLE_GLOB)
5912 STRCAT(command, "glob >");
5913 else if (shell_style == STYLE_PRINT)
5914 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005915 else if (shell_style == STYLE_VIMGLOB)
5916 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 else
5918 STRCAT(command, "echo >");
5919 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005920
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005922
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923 if (shell_style != STYLE_BT)
5924 for (i = 0; i < num_pat; ++i)
5925 {
5926 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005927 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005928 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929#ifdef USE_SYSTEM
5930 STRCAT(command, " \"");
5931 STRCAT(command, pat[i]);
5932 STRCAT(command, "\"");
5933#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005934 int intick = FALSE;
5935
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 p = command + STRLEN(command);
5937 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005938 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005939 {
5940 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005941 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005942 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5943 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005944 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005945 * backslash inside backticks, before a special character
5946 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005947 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005948 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5949 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005950 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005951 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005952 }
5953 else if (!intick && vim_strchr(SHELL_SPECIAL,
Bram Moolenaar582fd852005-03-28 20:58:01 +00005954 pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005955 /* Put a backslash before a special character, but not
5956 * when inside ``. */
5957 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005958
5959 /* Copy one character. */
5960 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005961 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962 *p = NUL;
5963#endif
5964 }
5965 if (flags & EW_SILENT)
5966 show_shell_mess = FALSE;
5967 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005968 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969
5970 /*
5971 * Using zsh -G: If a pattern has no matches, it is just deleted from
5972 * the argument list, otherwise zsh gives an error message and doesn't
5973 * expand any other pattern.
5974 */
5975 if (shell_style == STYLE_PRINT)
5976 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5977
5978 /*
5979 * If we use -f then shell variables set in .cshrc won't get expanded.
5980 * vi can do it, so we will too, but it is only necessary if there is a "$"
5981 * in one of the patterns, otherwise we can still use the fast option.
5982 */
5983 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5984 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5985
5986 /*
5987 * execute the shell command
5988 */
5989 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5990
5991 /* When running in the background, give it some time to create the temp
5992 * file, but don't wait for it to finish. */
5993 if (ampersent)
5994 mch_delay(10L, TRUE);
5995
5996 extra_shell_arg = NULL; /* cleanup */
5997 show_shell_mess = TRUE;
5998 vim_free(command);
5999
Bram Moolenaarc7247912008-01-13 12:54:11 +00006000 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001 {
6002 mch_remove(tempname);
6003 vim_free(tempname);
6004 /*
6005 * With interactive completion, the error message is not printed.
6006 * However with USE_SYSTEM, I don't know how to turn off error messages
6007 * from the shell, so screen may still get messed up -- webb.
6008 */
6009#ifndef USE_SYSTEM
6010 if (!(flags & EW_SILENT))
6011#endif
6012 {
6013 redraw_later_clear(); /* probably messed up screen */
6014 msg_putchar('\n'); /* clear bottom line quickly */
6015 cmdline_row = Rows - 1; /* continue on last line */
6016#ifdef USE_SYSTEM
6017 if (!(flags & EW_SILENT))
6018#endif
6019 {
6020 MSG(_(e_wildexpand));
6021 msg_start(); /* don't overwrite this message */
6022 }
6023 }
6024 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6025 * EW_NOTFOUND is given */
6026 if (shell_style == STYLE_BT)
6027 return FAIL;
6028 goto notfound;
6029 }
6030
6031 /*
6032 * read the names from the file into memory
6033 */
6034 fd = fopen((char *)tempname, READBIN);
6035 if (fd == NULL)
6036 {
6037 /* Something went wrong, perhaps a file name with a special char. */
6038 if (!(flags & EW_SILENT))
6039 {
6040 MSG(_(e_wildexpand));
6041 msg_start(); /* don't overwrite this message */
6042 }
6043 vim_free(tempname);
6044 goto notfound;
6045 }
6046 fseek(fd, 0L, SEEK_END);
6047 len = ftell(fd); /* get size of temp file */
6048 fseek(fd, 0L, SEEK_SET);
6049 buffer = alloc(len + 1);
6050 if (buffer == NULL)
6051 {
6052 /* out of memory */
6053 mch_remove(tempname);
6054 vim_free(tempname);
6055 fclose(fd);
6056 return FAIL;
6057 }
6058 i = fread((char *)buffer, 1, len, fd);
6059 fclose(fd);
6060 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006061 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 {
6063 /* unexpected read error */
6064 EMSG2(_(e_notread), tempname);
6065 vim_free(tempname);
6066 vim_free(buffer);
6067 return FAIL;
6068 }
6069 vim_free(tempname);
6070
Bram Moolenaarc7247912008-01-13 12:54:11 +00006071# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6073 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006074 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6076 *p++ = buffer[i];
6077 len = p - buffer;
6078# endif
6079
6080
6081 /* file names are separated with Space */
6082 if (shell_style == STYLE_ECHO)
6083 {
6084 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6085 p = buffer;
6086 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6087 {
6088 while (*p != ' ' && *p != '\n')
6089 ++p;
6090 p = skipwhite(p); /* skip to next entry */
6091 }
6092 }
6093 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006094 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 {
6096 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6097 p = buffer;
6098 for (i = 0; *p != NUL; ++i) /* count number of entries */
6099 {
6100 while (*p != '\n' && *p != NUL)
6101 ++p;
6102 if (*p != NUL)
6103 ++p;
6104 p = skipwhite(p); /* skip leading white space */
6105 }
6106 }
6107 /* file names are separated with NUL */
6108 else
6109 {
6110 /*
6111 * Some versions of zsh use spaces instead of NULs to separate
6112 * results. Only do this when there is no NUL before the end of the
6113 * buffer, otherwise we would never be able to use file names with
6114 * embedded spaces when zsh does use NULs.
6115 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6116 * don't check for spaces again.
6117 */
6118 check_spaces = FALSE;
6119 if (shell_style == STYLE_PRINT && !did_find_nul)
6120 {
6121 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006122 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006123 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 did_find_nul = TRUE;
6125 else
6126 check_spaces = TRUE;
6127 }
6128
6129 /*
6130 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6131 * already is one, for STYLE_GLOB it needs to be added.
6132 */
6133 if (len && buffer[len - 1] == NUL)
6134 --len;
6135 else
6136 buffer[len] = NUL;
6137 i = 0;
6138 for (p = buffer; p < buffer + len; ++p)
6139 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6140 {
6141 ++i;
6142 *p = NUL;
6143 }
6144 if (len)
6145 ++i; /* count last entry */
6146 }
6147 if (i == 0)
6148 {
6149 /*
6150 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6151 * /bin/sh will happily expand it to nothing rather than returning an
6152 * error; and hey, it's good to check anyway -- webb.
6153 */
6154 vim_free(buffer);
6155 goto notfound;
6156 }
6157 *num_file = i;
6158 *file = (char_u **)alloc(sizeof(char_u *) * i);
6159 if (*file == NULL)
6160 {
6161 /* out of memory */
6162 vim_free(buffer);
6163 return FAIL;
6164 }
6165
6166 /*
6167 * Isolate the individual file names.
6168 */
6169 p = buffer;
6170 for (i = 0; i < *num_file; ++i)
6171 {
6172 (*file)[i] = p;
6173 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006174 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6175 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006177 while (!(shell_style == STYLE_ECHO && *p == ' ')
6178 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 ++p;
6180 if (p == buffer + len) /* last entry */
6181 *p = NUL;
6182 else
6183 {
6184 *p++ = NUL;
6185 p = skipwhite(p); /* skip to next entry */
6186 }
6187 }
6188 else /* NUL separates */
6189 {
6190 while (*p && p < buffer + len) /* skip entry */
6191 ++p;
6192 ++p; /* skip NUL */
6193 }
6194 }
6195
6196 /*
6197 * Move the file names to allocated memory.
6198 */
6199 for (j = 0, i = 0; i < *num_file; ++i)
6200 {
6201 /* Require the files to exist. Helps when using /bin/sh */
6202 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6203 continue;
6204
6205 /* check if this entry should be included */
6206 dir = (mch_isdir((*file)[i]));
6207 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6208 continue;
6209
Bram Moolenaara2031822006-03-07 22:29:51 +00006210 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006211 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i], NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00006212 continue;
6213
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6215 if (p)
6216 {
6217 STRCPY(p, (*file)[i]);
6218 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006219 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 (*file)[j++] = p;
6221 }
6222 }
6223 vim_free(buffer);
6224 *num_file = j;
6225
6226 if (*num_file == 0) /* rejected all entries */
6227 {
6228 vim_free(*file);
6229 *file = NULL;
6230 goto notfound;
6231 }
6232
6233 return OK;
6234
6235notfound:
6236 if (flags & EW_NOTFOUND)
6237 return save_patterns(num_pat, pat, num_file, file);
6238 return FAIL;
6239
6240#endif /* __EMX__ */
6241}
6242
6243#endif /* VMS */
6244
6245#ifndef __EMX__
6246 static int
6247save_patterns(num_pat, pat, num_file, file)
6248 int num_pat;
6249 char_u **pat;
6250 int *num_file;
6251 char_u ***file;
6252{
6253 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006254 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255
6256 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6257 if (*file == NULL)
6258 return FAIL;
6259 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006260 {
6261 s = vim_strsave(pat[i]);
6262 if (s != NULL)
6263 /* Be compatible with expand_filename(): halve the number of
6264 * backslashes. */
6265 backslash_halve(s);
6266 (*file)[i] = s;
6267 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 *num_file = num_pat;
6269 return OK;
6270}
6271#endif
6272
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273/*
6274 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6275 * expand.
6276 */
6277 int
6278mch_has_exp_wildcard(p)
6279 char_u *p;
6280{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006281 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 {
6283#ifndef OS2
6284 if (*p == '\\' && p[1] != NUL)
6285 ++p;
6286 else
6287#endif
6288 if (vim_strchr((char_u *)
6289#ifdef VMS
6290 "*?%"
6291#else
6292# ifdef OS2
6293 "*?"
6294# else
6295 "*?[{'"
6296# endif
6297#endif
6298 , *p) != NULL)
6299 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 }
6301 return FALSE;
6302}
6303
6304/*
6305 * Return TRUE if the string "p" contains a wildcard.
6306 * Don't recognize '~' at the end as a wildcard.
6307 */
6308 int
6309mch_has_wildcard(p)
6310 char_u *p;
6311{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006312 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 {
6314#ifndef OS2
6315 if (*p == '\\' && p[1] != NUL)
6316 ++p;
6317 else
6318#endif
6319 if (vim_strchr((char_u *)
6320#ifdef VMS
6321 "*?%$"
6322#else
6323# ifdef OS2
6324# ifdef VIM_BACKTICK
6325 "*?$`"
6326# else
6327 "*?$"
6328# endif
6329# else
6330 "*?[{`'$"
6331# endif
6332#endif
6333 , *p) != NULL
6334 || (*p == '~' && p[1] != NUL))
6335 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 }
6337 return FALSE;
6338}
6339
6340#ifndef __EMX__
6341 static int
6342have_wildcard(num, file)
6343 int num;
6344 char_u **file;
6345{
6346 int i;
6347
6348 for (i = 0; i < num; i++)
6349 if (mch_has_wildcard(file[i]))
6350 return 1;
6351 return 0;
6352}
6353
6354 static int
6355have_dollars(num, file)
6356 int num;
6357 char_u **file;
6358{
6359 int i;
6360
6361 for (i = 0; i < num; i++)
6362 if (vim_strchr(file[i], '$') != NULL)
6363 return TRUE;
6364 return FALSE;
6365}
6366#endif /* ifndef __EMX__ */
6367
6368#ifndef HAVE_RENAME
6369/*
6370 * Scaled-down version of rename(), which is missing in Xenix.
6371 * This version can only move regular files and will fail if the
6372 * destination exists.
6373 */
6374 int
6375mch_rename(src, dest)
6376 const char *src, *dest;
6377{
6378 struct stat st;
6379
6380 if (stat(dest, &st) >= 0) /* fail if destination exists */
6381 return -1;
6382 if (link(src, dest) != 0) /* link file to new name */
6383 return -1;
6384 if (mch_remove(src) == 0) /* delete link to old name */
6385 return 0;
6386 return -1;
6387}
6388#endif /* !HAVE_RENAME */
6389
6390#ifdef FEAT_MOUSE_GPM
6391/*
6392 * Initializes connection with gpm (if it isn't already opened)
6393 * Return 1 if succeeded (or connection already opened), 0 if failed
6394 */
6395 static int
6396gpm_open()
6397{
6398 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6399
6400 if (!gpm_flag)
6401 {
6402 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6403 gpm_connect.defaultMask = ~GPM_HARD;
6404 /* Default handling for mouse move*/
6405 gpm_connect.minMod = 0; /* Handle any modifier keys */
6406 gpm_connect.maxMod = 0xffff;
6407 if (Gpm_Open(&gpm_connect, 0) > 0)
6408 {
6409 /* gpm library tries to handling TSTP causes
6410 * problems. Anyways, we close connection to Gpm whenever
6411 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006412 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006414# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006415 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006416# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 return 1; /* succeed */
6418 }
6419 if (gpm_fd == -2)
6420 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6421 return 0;
6422 }
6423 return 1; /* already open */
6424}
6425
6426/*
6427 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 */
6429 static void
6430gpm_close()
6431{
6432 if (gpm_flag && gpm_fd >= 0) /* if Open */
6433 Gpm_Close();
6434}
6435
6436/* Reads gpm event and adds special keys to input buf. Returns length of
6437 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006438 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439 */
6440 static int
6441mch_gpm_process()
6442{
6443 int button;
6444 static Gpm_Event gpm_event;
6445 char_u string[6];
6446 int_u vim_modifiers;
6447 int row,col;
6448 unsigned char buttons_mask;
6449 unsigned char gpm_modifiers;
6450 static unsigned char old_buttons = 0;
6451
6452 Gpm_GetEvent(&gpm_event);
6453
6454#ifdef FEAT_GUI
6455 /* Don't put events in the input queue now. */
6456 if (hold_gui_events)
6457 return 0;
6458#endif
6459
6460 row = gpm_event.y - 1;
6461 col = gpm_event.x - 1;
6462
6463 string[0] = ESC; /* Our termcode */
6464 string[1] = 'M';
6465 string[2] = 'G';
6466 switch (GPM_BARE_EVENTS(gpm_event.type))
6467 {
6468 case GPM_DRAG:
6469 string[3] = MOUSE_DRAG;
6470 break;
6471 case GPM_DOWN:
6472 buttons_mask = gpm_event.buttons & ~old_buttons;
6473 old_buttons = gpm_event.buttons;
6474 switch (buttons_mask)
6475 {
6476 case GPM_B_LEFT:
6477 button = MOUSE_LEFT;
6478 break;
6479 case GPM_B_MIDDLE:
6480 button = MOUSE_MIDDLE;
6481 break;
6482 case GPM_B_RIGHT:
6483 button = MOUSE_RIGHT;
6484 break;
6485 default:
6486 return 0;
6487 /*Don't know what to do. Can more than one button be
6488 * reported in one event? */
6489 }
6490 string[3] = (char_u)(button | 0x20);
6491 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6492 break;
6493 case GPM_UP:
6494 string[3] = MOUSE_RELEASE;
6495 old_buttons &= ~gpm_event.buttons;
6496 break;
6497 default:
6498 return 0;
6499 }
6500 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6501 gpm_modifiers = gpm_event.modifiers;
6502 vim_modifiers = 0x0;
6503 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6504 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6505 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6506 */
6507 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6508 vim_modifiers |= MOUSE_SHIFT;
6509
6510 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6511 vim_modifiers |= MOUSE_CTRL;
6512 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6513 vim_modifiers |= MOUSE_ALT;
6514 string[3] |= vim_modifiers;
6515 string[4] = (char_u)(col + ' ' + 1);
6516 string[5] = (char_u)(row + ' ' + 1);
6517 add_to_input_buf(string, 6);
6518 return 6;
6519}
6520#endif /* FEAT_MOUSE_GPM */
6521
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006522#ifdef FEAT_SYSMOUSE
6523/*
6524 * Initialize connection with sysmouse.
6525 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6526 * output, any sysmouse output than will be processed via sig_sysmouse().
6527 * Return OK if succeeded, FAIL if failed.
6528 */
6529 static int
6530sysmouse_open()
6531{
6532 struct mouse_info mouse;
6533
6534 mouse.operation = MOUSE_MODE;
6535 mouse.u.mode.mode = 0;
6536 mouse.u.mode.signal = SIGUSR2;
6537 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6538 {
6539 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6540 mouse.operation = MOUSE_SHOW;
6541 ioctl(1, CONS_MOUSECTL, &mouse);
6542 return OK;
6543 }
6544 return FAIL;
6545}
6546
6547/*
6548 * Stop processing SIGUSR2 signals, and also make sure that
6549 * virtual console do not send us any sysmouse related signal.
6550 */
6551 static void
6552sysmouse_close()
6553{
6554 struct mouse_info mouse;
6555
6556 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6557 mouse.operation = MOUSE_MODE;
6558 mouse.u.mode.mode = 0;
6559 mouse.u.mode.signal = 0;
6560 ioctl(1, CONS_MOUSECTL, &mouse);
6561}
6562
6563/*
6564 * Gets info from sysmouse and adds special keys to input buf.
6565 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006566 static RETSIGTYPE
6567sig_sysmouse SIGDEFARG(sigarg)
6568{
6569 struct mouse_info mouse;
6570 struct video_info video;
6571 char_u string[6];
6572 int row, col;
6573 int button;
6574 int buttons;
6575 static int oldbuttons = 0;
6576
6577#ifdef FEAT_GUI
6578 /* Don't put events in the input queue now. */
6579 if (hold_gui_events)
6580 return;
6581#endif
6582
6583 mouse.operation = MOUSE_GETINFO;
6584 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6585 && ioctl(1, FBIO_MODEINFO, &video) != -1
6586 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6587 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6588 {
6589 row = mouse.u.data.y / video.vi_cheight;
6590 col = mouse.u.data.x / video.vi_cwidth;
6591 buttons = mouse.u.data.buttons;
6592 string[0] = ESC; /* Our termcode */
6593 string[1] = 'M';
6594 string[2] = 'S';
6595 if (oldbuttons == buttons && buttons != 0)
6596 {
6597 button = MOUSE_DRAG;
6598 }
6599 else
6600 {
6601 switch (buttons)
6602 {
6603 case 0:
6604 button = MOUSE_RELEASE;
6605 break;
6606 case 1:
6607 button = MOUSE_LEFT;
6608 break;
6609 case 2:
6610 button = MOUSE_MIDDLE;
6611 break;
6612 case 4:
6613 button = MOUSE_RIGHT;
6614 break;
6615 default:
6616 return;
6617 }
6618 oldbuttons = buttons;
6619 }
6620 string[3] = (char_u)(button);
6621 string[4] = (char_u)(col + ' ' + 1);
6622 string[5] = (char_u)(row + ' ' + 1);
6623 add_to_input_buf(string, 6);
6624 }
6625 return;
6626}
6627#endif /* FEAT_SYSMOUSE */
6628
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629#if defined(FEAT_LIBCALL) || defined(PROTO)
6630typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6631typedef char_u * (*INTPROCSTR)__ARGS((int));
6632typedef int (*STRPROCINT)__ARGS((char_u *));
6633typedef int (*INTPROCINT)__ARGS((int));
6634
6635/*
6636 * Call a DLL routine which takes either a string or int param
6637 * and returns an allocated string.
6638 */
6639 int
6640mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6641 char_u *libname;
6642 char_u *funcname;
6643 char_u *argstring; /* NULL when using a argint */
6644 int argint;
6645 char_u **string_result;/* NULL when using number_result */
6646 int *number_result;
6647{
6648# if defined(USE_DLOPEN)
6649 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006650 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651# else
6652 shl_t hinstLib;
6653# endif
6654 STRPROCSTR ProcAdd;
6655 INTPROCSTR ProcAddI;
6656 char_u *retval_str = NULL;
6657 int retval_int = 0;
6658 int success = FALSE;
6659
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006660 /*
6661 * Get a handle to the DLL module.
6662 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006664 /* First clear any error, it's not cleared by the dlopen() call. */
6665 (void)dlerror();
6666
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 hinstLib = dlopen((char *)libname, RTLD_LAZY
6668# ifdef RTLD_LOCAL
6669 | RTLD_LOCAL
6670# endif
6671 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006672 if (hinstLib == NULL)
6673 {
6674 /* "dlerr" must be used before dlclose() */
6675 dlerr = (char *)dlerror();
6676 if (dlerr != NULL)
6677 EMSG2(_("dlerror = \"%s\""), dlerr);
6678 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679# else
6680 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6681# endif
6682
6683 /* If the handle is valid, try to get the function address. */
6684 if (hinstLib != NULL)
6685 {
6686# ifdef HAVE_SETJMP_H
6687 /*
6688 * Catch a crash when calling the library function. For example when
6689 * using a number where a string pointer is expected.
6690 */
6691 mch_startjmp();
6692 if (SETJMP(lc_jump_env) != 0)
6693 {
6694 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006695# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006696 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006697# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 mch_didjmp();
6699 }
6700 else
6701# endif
6702 {
6703 retval_str = NULL;
6704 retval_int = 0;
6705
6706 if (argstring != NULL)
6707 {
6708# if defined(USE_DLOPEN)
6709 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006710 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711# else
6712 if (shl_findsym(&hinstLib, (const char *)funcname,
6713 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6714 ProcAdd = NULL;
6715# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006716 if ((success = (ProcAdd != NULL
6717# if defined(USE_DLOPEN)
6718 && dlerr == NULL
6719# endif
6720 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 {
6722 if (string_result == NULL)
6723 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6724 else
6725 retval_str = (ProcAdd)(argstring);
6726 }
6727 }
6728 else
6729 {
6730# if defined(USE_DLOPEN)
6731 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006732 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733# else
6734 if (shl_findsym(&hinstLib, (const char *)funcname,
6735 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6736 ProcAddI = NULL;
6737# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006738 if ((success = (ProcAddI != NULL
6739# if defined(USE_DLOPEN)
6740 && dlerr == NULL
6741# endif
6742 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 {
6744 if (string_result == NULL)
6745 retval_int = ((INTPROCINT)ProcAddI)(argint);
6746 else
6747 retval_str = (ProcAddI)(argint);
6748 }
6749 }
6750
6751 /* Save the string before we free the library. */
6752 /* Assume that a "1" or "-1" result is an illegal pointer. */
6753 if (string_result == NULL)
6754 *number_result = retval_int;
6755 else if (retval_str != NULL
6756 && retval_str != (char_u *)1
6757 && retval_str != (char_u *)-1)
6758 *string_result = vim_strsave(retval_str);
6759 }
6760
6761# ifdef HAVE_SETJMP_H
6762 mch_endjmp();
6763# ifdef SIGHASARG
6764 if (lc_signal != 0)
6765 {
6766 int i;
6767
6768 /* try to find the name of this signal */
6769 for (i = 0; signal_info[i].sig != -1; i++)
6770 if (lc_signal == signal_info[i].sig)
6771 break;
6772 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6773 }
6774# endif
6775# endif
6776
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006778 /* "dlerr" must be used before dlclose() */
6779 if (dlerr != NULL)
6780 EMSG2(_("dlerror = \"%s\""), dlerr);
6781
6782 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 (void)dlclose(hinstLib);
6784# else
6785 (void)shl_unload(hinstLib);
6786# endif
6787 }
6788
6789 if (!success)
6790 {
6791 EMSG2(_(e_libcall), funcname);
6792 return FAIL;
6793 }
6794
6795 return OK;
6796}
6797#endif
6798
6799#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6800static int xterm_trace = -1; /* default: disabled */
6801static int xterm_button;
6802
6803/*
6804 * Setup a dummy window for X selections in a terminal.
6805 */
6806 void
6807setup_term_clip()
6808{
6809 int z = 0;
6810 char *strp = "";
6811 Widget AppShell;
6812
6813 if (!x_connect_to_server())
6814 return;
6815
6816 open_app_context();
6817 if (app_context != NULL && xterm_Shell == (Widget)0)
6818 {
6819 int (*oldhandler)();
6820#if defined(HAVE_SETJMP_H)
6821 int (*oldIOhandler)();
6822#endif
6823# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6824 struct timeval start_tv;
6825
6826 if (p_verbose > 0)
6827 gettimeofday(&start_tv, NULL);
6828# endif
6829
6830 /* Ignore X errors while opening the display */
6831 oldhandler = XSetErrorHandler(x_error_check);
6832
6833#if defined(HAVE_SETJMP_H)
6834 /* Ignore X IO errors while opening the display */
6835 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6836 mch_startjmp();
6837 if (SETJMP(lc_jump_env) != 0)
6838 {
6839 mch_didjmp();
6840 xterm_dpy = NULL;
6841 }
6842 else
6843#endif
6844 {
6845 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6846 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6847#if defined(HAVE_SETJMP_H)
6848 mch_endjmp();
6849#endif
6850 }
6851
6852#if defined(HAVE_SETJMP_H)
6853 /* Now handle X IO errors normally. */
6854 (void)XSetIOErrorHandler(oldIOhandler);
6855#endif
6856 /* Now handle X errors normally. */
6857 (void)XSetErrorHandler(oldhandler);
6858
6859 if (xterm_dpy == NULL)
6860 {
6861 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006862 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 return;
6864 }
6865
6866 /* Catch terminating error of the X server connection. */
6867 (void)XSetIOErrorHandler(x_IOerror_handler);
6868
6869# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6870 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006871 {
6872 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006874 verbose_leave();
6875 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876# endif
6877
6878 /* Create a Shell to make converters work. */
6879 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6880 applicationShellWidgetClass, xterm_dpy,
6881 NULL);
6882 if (AppShell == (Widget)0)
6883 return;
6884 xterm_Shell = XtVaCreatePopupShell("VIM",
6885 topLevelShellWidgetClass, AppShell,
6886 XtNmappedWhenManaged, 0,
6887 XtNwidth, 1,
6888 XtNheight, 1,
6889 NULL);
6890 if (xterm_Shell == (Widget)0)
6891 return;
6892
6893 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006894 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 if (x11_display == NULL)
6896 x11_display = xterm_dpy;
6897
6898 XtRealizeWidget(xterm_Shell);
6899 XSync(xterm_dpy, False);
6900 xterm_update();
6901 }
6902 if (xterm_Shell != (Widget)0)
6903 {
6904 clip_init(TRUE);
6905 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6906 x11_window = (Window)atol(strp);
6907 /* Check if $WINDOWID is valid. */
6908 if (test_x11_window(xterm_dpy) == FAIL)
6909 x11_window = 0;
6910 if (x11_window != 0)
6911 xterm_trace = 0;
6912 }
6913}
6914
6915 void
6916start_xterm_trace(button)
6917 int button;
6918{
6919 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6920 return;
6921 xterm_trace = 1;
6922 xterm_button = button;
6923 do_xterm_trace();
6924}
6925
6926
6927 void
6928stop_xterm_trace()
6929{
6930 if (xterm_trace < 0)
6931 return;
6932 xterm_trace = 0;
6933}
6934
6935/*
6936 * Query the xterm pointer and generate mouse termcodes if necessary
6937 * return TRUE if dragging is active, else FALSE
6938 */
6939 static int
6940do_xterm_trace()
6941{
6942 Window root, child;
6943 int root_x, root_y;
6944 int win_x, win_y;
6945 int row, col;
6946 int_u mask_return;
6947 char_u buf[50];
6948 char_u *strp;
6949 long got_hints;
6950 static char_u *mouse_code;
6951 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6952 static int prev_row = 0, prev_col = 0;
6953 static XSizeHints xterm_hints;
6954
6955 if (xterm_trace <= 0)
6956 return FALSE;
6957
6958 if (xterm_trace == 1)
6959 {
6960 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006961 * have changed recently. */
6962 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6963 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 || xterm_hints.width_inc <= 1
6965 || xterm_hints.height_inc <= 1)
6966 {
6967 xterm_trace = -1; /* Not enough data -- disable tracing */
6968 return FALSE;
6969 }
6970
6971 /* Rely on the same mouse code for the duration of this */
6972 mouse_code = find_termcode(mouse_name);
6973 prev_row = mouse_row;
6974 prev_row = mouse_col;
6975 xterm_trace = 2;
6976
6977 /* Find the offset of the chars, there might be a scrollbar on the
6978 * left of the window and/or a menu on the top (eterm etc.) */
6979 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6980 &win_x, &win_y, &mask_return);
6981 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6982 - (xterm_hints.height_inc / 2);
6983 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6984 xterm_hints.y = 2;
6985 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6986 - (xterm_hints.width_inc / 2);
6987 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6988 xterm_hints.x = 2;
6989 return TRUE;
6990 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006991 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 {
6993 xterm_trace = 0;
6994 return FALSE;
6995 }
6996
6997 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6998 &win_x, &win_y, &mask_return);
6999
7000 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7001 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7002 if (row == prev_row && col == prev_col)
7003 return TRUE;
7004
7005 STRCPY(buf, mouse_code);
7006 strp = buf + STRLEN(buf);
7007 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7008 *strp++ = (char_u)(col + ' ' + 1);
7009 *strp++ = (char_u)(row + ' ' + 1);
7010 *strp = 0;
7011 add_to_input_buf(buf, STRLEN(buf));
7012
7013 prev_row = row;
7014 prev_col = col;
7015 return TRUE;
7016}
7017
7018# if defined(FEAT_GUI) || defined(PROTO)
7019/*
7020 * Destroy the display, window and app_context. Required for GTK.
7021 */
7022 void
7023clear_xterm_clip()
7024{
7025 if (xterm_Shell != (Widget)0)
7026 {
7027 XtDestroyWidget(xterm_Shell);
7028 xterm_Shell = (Widget)0;
7029 }
7030 if (xterm_dpy != NULL)
7031 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007032# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 /* Lesstif and Solaris crash here, lose some memory */
7034 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007035# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 if (x11_display == xterm_dpy)
7037 x11_display = NULL;
7038 xterm_dpy = NULL;
7039 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007040# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 if (app_context != (XtAppContext)NULL)
7042 {
7043 /* Lesstif and Solaris crash here, lose some memory */
7044 XtDestroyApplicationContext(app_context);
7045 app_context = (XtAppContext)NULL;
7046 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007047# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048}
7049# endif
7050
7051/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007052 * Catch up with GUI or X events.
7053 */
7054 static void
7055clip_update()
7056{
7057# ifdef FEAT_GUI
7058 if (gui.in_use)
7059 gui_mch_update();
7060 else
7061# endif
7062 if (xterm_Shell != (Widget)0)
7063 xterm_update();
7064}
7065
7066/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 * Catch up with any queued X events. This may put keyboard input into the
7068 * input buffer, call resize call-backs, trigger timers etc. If there is
7069 * nothing in the X event queue (& no timers pending), then we return
7070 * immediately.
7071 */
7072 static void
7073xterm_update()
7074{
7075 XEvent event;
7076
7077 while (XtAppPending(app_context) && !vim_is_input_buf_full())
7078 {
7079 XtAppNextEvent(app_context, &event);
7080#ifdef FEAT_CLIENTSERVER
7081 {
7082 XPropertyEvent *e = (XPropertyEvent *)&event;
7083
7084 if (e->type == PropertyNotify && e->window == commWindow
7085 && e->atom == commProperty && e->state == PropertyNewValue)
7086 serverEventProc(xterm_dpy, &event);
7087 }
7088#endif
7089 XtDispatchEvent(&event);
7090 }
7091}
7092
7093 int
7094clip_xterm_own_selection(cbd)
7095 VimClipboard *cbd;
7096{
7097 if (xterm_Shell != (Widget)0)
7098 return clip_x11_own_selection(xterm_Shell, cbd);
7099 return FAIL;
7100}
7101
7102 void
7103clip_xterm_lose_selection(cbd)
7104 VimClipboard *cbd;
7105{
7106 if (xterm_Shell != (Widget)0)
7107 clip_x11_lose_selection(xterm_Shell, cbd);
7108}
7109
7110 void
7111clip_xterm_request_selection(cbd)
7112 VimClipboard *cbd;
7113{
7114 if (xterm_Shell != (Widget)0)
7115 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7116}
7117
7118 void
7119clip_xterm_set_selection(cbd)
7120 VimClipboard *cbd;
7121{
7122 clip_x11_set_selection(cbd);
7123}
7124#endif
7125
7126
7127#if defined(USE_XSMP) || defined(PROTO)
7128/*
7129 * Code for X Session Management Protocol.
7130 */
7131static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
7132static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
7133static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
7134static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
7135static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
7136
7137
7138# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7139static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7140
7141/*
7142 * This is our chance to ask the user if they want to save,
7143 * or abort the logout
7144 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 static void
7146xsmp_handle_interaction(smc_conn, client_data)
7147 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007148 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149{
7150 cmdmod_T save_cmdmod;
7151 int cancel_shutdown = False;
7152
7153 save_cmdmod = cmdmod;
7154 cmdmod.confirm = TRUE;
7155 if (check_changed_any(FALSE))
7156 /* Mustn't logout */
7157 cancel_shutdown = True;
7158 cmdmod = save_cmdmod;
7159 setcursor(); /* position cursor */
7160 out_flush();
7161
7162 /* Done interaction */
7163 SmcInteractDone(smc_conn, cancel_shutdown);
7164
7165 /* Finish off
7166 * Only end save-yourself here if we're not cancelling shutdown;
7167 * we'll get a cancelled callback later in which we'll end it.
7168 * Hopefully get around glitchy SMs (like GNOME-1)
7169 */
7170 if (!cancel_shutdown)
7171 {
7172 xsmp.save_yourself = False;
7173 SmcSaveYourselfDone(smc_conn, True);
7174 }
7175}
7176# endif
7177
7178/*
7179 * Callback that starts save-yourself.
7180 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 static void
7182xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7183 shutdown, interact_style, fast)
7184 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007185 SmPointer client_data UNUSED;
7186 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007187 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007188 int interact_style UNUSED;
7189 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190{
7191 /* Handle already being in saveyourself */
7192 if (xsmp.save_yourself)
7193 SmcSaveYourselfDone(smc_conn, True);
7194 xsmp.save_yourself = True;
7195 xsmp.shutdown = shutdown;
7196
7197 /* First up, preserve all files */
7198 out_flush();
7199 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7200
7201 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007202 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203
7204# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7205 /* Now see if we can ask about unsaved files */
7206 if (shutdown && !fast && gui.in_use)
7207 /* Need to interact with user, but need SM's permission */
7208 SmcInteractRequest(smc_conn, SmDialogError,
7209 xsmp_handle_interaction, client_data);
7210 else
7211# endif
7212 {
7213 /* Can stop the cycle here */
7214 SmcSaveYourselfDone(smc_conn, True);
7215 xsmp.save_yourself = False;
7216 }
7217}
7218
7219
7220/*
7221 * Callback to warn us of imminent death.
7222 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 static void
7224xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007225 SmcConn smc_conn UNUSED;
7226 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227{
7228 xsmp_close();
7229
7230 /* quit quickly leaving swapfiles for modified buffers behind */
7231 getout_preserve_modified(0);
7232}
7233
7234
7235/*
7236 * Callback to tell us that save-yourself has completed.
7237 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 static void
7239xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007240 SmcConn smc_conn UNUSED;
7241 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242{
7243 xsmp.save_yourself = False;
7244}
7245
7246
7247/*
7248 * Callback to tell us that an instigated shutdown was cancelled
7249 * (maybe even by us)
7250 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 static void
7252xsmp_shutdown_cancelled(smc_conn, client_data)
7253 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007254 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255{
7256 if (xsmp.save_yourself)
7257 SmcSaveYourselfDone(smc_conn, True);
7258 xsmp.save_yourself = False;
7259 xsmp.shutdown = False;
7260}
7261
7262
7263/*
7264 * Callback to tell us that a new ICE connection has been established.
7265 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 static void
7267xsmp_ice_connection(iceConn, clientData, opening, watchData)
7268 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007269 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007271 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272{
7273 /* Intercept creation of ICE connection fd */
7274 if (opening)
7275 {
7276 xsmp_icefd = IceConnectionNumber(iceConn);
7277 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7278 }
7279}
7280
7281
7282/* Handle any ICE processing that's required; return FAIL if SM lost */
7283 int
7284xsmp_handle_requests()
7285{
7286 Bool rep;
7287
7288 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7289 == IceProcessMessagesIOError)
7290 {
7291 /* Lost ICE */
7292 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007293 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 xsmp_close();
7295 return FAIL;
7296 }
7297 else
7298 return OK;
7299}
7300
7301static int dummy;
7302
7303/* Set up X Session Management Protocol */
7304 void
7305xsmp_init(void)
7306{
7307 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308 SmcCallbacks smcallbacks;
7309#if 0
7310 SmPropValue smname;
7311 SmProp smnameprop;
7312 SmProp *smprops[1];
7313#endif
7314
7315 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007316 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317
7318 xsmp.save_yourself = xsmp.shutdown = False;
7319
7320 /* Set up SM callbacks - must have all, even if they're not used */
7321 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7322 smcallbacks.save_yourself.client_data = NULL;
7323 smcallbacks.die.callback = xsmp_die;
7324 smcallbacks.die.client_data = NULL;
7325 smcallbacks.save_complete.callback = xsmp_save_complete;
7326 smcallbacks.save_complete.client_data = NULL;
7327 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7328 smcallbacks.shutdown_cancelled.client_data = NULL;
7329
7330 /* Set up a watch on ICE connection creations. The "dummy" argument is
7331 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7332 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7333 {
7334 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007335 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 return;
7337 }
7338
7339 /* Create an SM connection */
7340 xsmp.smcconn = SmcOpenConnection(
7341 NULL,
7342 NULL,
7343 SmProtoMajor,
7344 SmProtoMinor,
7345 SmcSaveYourselfProcMask | SmcDieProcMask
7346 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7347 &smcallbacks,
7348 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007349 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 sizeof(errorstring),
7351 errorstring);
7352 if (xsmp.smcconn == NULL)
7353 {
7354 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007355
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007357 {
7358 vim_snprintf(errorreport, sizeof(errorreport),
7359 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7360 verb_msg((char_u *)errorreport);
7361 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 return;
7363 }
7364 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7365
7366#if 0
7367 /* ID ourselves */
7368 smname.value = "vim";
7369 smname.length = 3;
7370 smnameprop.name = "SmProgram";
7371 smnameprop.type = "SmARRAY8";
7372 smnameprop.num_vals = 1;
7373 smnameprop.vals = &smname;
7374
7375 smprops[0] = &smnameprop;
7376 SmcSetProperties(xsmp.smcconn, 1, smprops);
7377#endif
7378}
7379
7380
7381/* Shut down XSMP comms. */
7382 void
7383xsmp_close()
7384{
7385 if (xsmp_icefd != -1)
7386 {
7387 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007388 if (xsmp.clientid != NULL)
7389 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007390 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 xsmp_icefd = -1;
7392 }
7393}
7394#endif /* USE_XSMP */
7395
7396
7397#ifdef EBCDIC
7398/* Translate character to its CTRL- value */
7399char CtrlTable[] =
7400{
7401/* 00 - 5E */
7402 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7403 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7404 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7405 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7406 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7407 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7408/* ^ */ 0x1E,
7409/* - */ 0x1F,
7410/* 61 - 6C */
7411 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7412/* _ */ 0x1F,
7413/* 6E - 80 */
7414 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7415/* a */ 0x01,
7416/* b */ 0x02,
7417/* c */ 0x03,
7418/* d */ 0x37,
7419/* e */ 0x2D,
7420/* f */ 0x2E,
7421/* g */ 0x2F,
7422/* h */ 0x16,
7423/* i */ 0x05,
7424/* 8A - 90 */
7425 0, 0, 0, 0, 0, 0, 0,
7426/* j */ 0x15,
7427/* k */ 0x0B,
7428/* l */ 0x0C,
7429/* m */ 0x0D,
7430/* n */ 0x0E,
7431/* o */ 0x0F,
7432/* p */ 0x10,
7433/* q */ 0x11,
7434/* r */ 0x12,
7435/* 9A - A1 */
7436 0, 0, 0, 0, 0, 0, 0, 0,
7437/* s */ 0x13,
7438/* t */ 0x3C,
7439/* u */ 0x3D,
7440/* v */ 0x32,
7441/* w */ 0x26,
7442/* x */ 0x18,
7443/* y */ 0x19,
7444/* z */ 0x3F,
7445/* AA - AC */
7446 0, 0, 0,
7447/* [ */ 0x27,
7448/* AE - BC */
7449 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7450/* ] */ 0x1D,
7451/* BE - C0 */ 0, 0, 0,
7452/* A */ 0x01,
7453/* B */ 0x02,
7454/* C */ 0x03,
7455/* D */ 0x37,
7456/* E */ 0x2D,
7457/* F */ 0x2E,
7458/* G */ 0x2F,
7459/* H */ 0x16,
7460/* I */ 0x05,
7461/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7462/* J */ 0x15,
7463/* K */ 0x0B,
7464/* L */ 0x0C,
7465/* M */ 0x0D,
7466/* N */ 0x0E,
7467/* O */ 0x0F,
7468/* P */ 0x10,
7469/* Q */ 0x11,
7470/* R */ 0x12,
7471/* DA - DF */ 0, 0, 0, 0, 0, 0,
7472/* \ */ 0x1C,
7473/* E1 */ 0,
7474/* S */ 0x13,
7475/* T */ 0x3C,
7476/* U */ 0x3D,
7477/* V */ 0x32,
7478/* W */ 0x26,
7479/* X */ 0x18,
7480/* Y */ 0x19,
7481/* Z */ 0x3F,
7482/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7483 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7484};
7485
7486char MetaCharTable[]=
7487{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7488 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7489 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7490 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7491 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7492};
7493
7494
7495/* TODO: Use characters NOT numbers!!! */
7496char CtrlCharTable[]=
7497{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7498 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7499 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7500 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7501 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7502};
7503
7504
7505#endif