blob: 6209605cfa8e667363922654b048edd7e6f1c6bc [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
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001963/* Xutf8 functions are not avaialble on older systems. Note that on some
1964 * systems X_HAVE_UTF8_STRING may be defined in a header file but
1965 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
1966 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001968# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969# define USE_UTF8_STRING
1970# endif
1971#endif
1972
1973/*
1974 * Set x11 Window Title
1975 *
1976 * get_x11_windis() must be called before this and have returned OK
1977 */
1978 static void
1979set_x11_title(title)
1980 char_u *title;
1981{
1982 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1983 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1984 * supported everywhere and STRING doesn't work for multi-byte titles.
1985 */
1986#ifdef USE_UTF8_STRING
1987 if (enc_utf8)
1988 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1989 NULL, NULL, 0, NULL, NULL, NULL);
1990 else
1991#endif
1992 {
1993#if XtSpecificationRelease >= 4
1994# ifdef FEAT_XFONTSET
1995 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1996 NULL, NULL, 0, NULL, NULL, NULL);
1997# else
1998 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001999 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000
2001 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002002 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 XSetWMProperties(x11_display, x11_window, &text_prop,
2004 NULL, NULL, 0, NULL, NULL, NULL);
2005# endif
2006#else
2007 XStoreName(x11_display, x11_window, (char *)title);
2008#endif
2009 }
2010 XFlush(x11_display);
2011}
2012
2013/*
2014 * Set x11 Window icon
2015 *
2016 * get_x11_windis() must be called before this and have returned OK
2017 */
2018 static void
2019set_x11_icon(icon)
2020 char_u *icon;
2021{
2022 /* See above for comments about using X*SetWMProperties(). */
2023#ifdef USE_UTF8_STRING
2024 if (enc_utf8)
2025 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2026 NULL, 0, NULL, NULL, NULL);
2027 else
2028#endif
2029 {
2030#if XtSpecificationRelease >= 4
2031# ifdef FEAT_XFONTSET
2032 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2033 NULL, 0, NULL, NULL, NULL);
2034# else
2035 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002036 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002038 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2040 NULL, 0, NULL, NULL, NULL);
2041# endif
2042#else
2043 XSetIconName(x11_display, x11_window, (char *)icon);
2044#endif
2045 }
2046 XFlush(x11_display);
2047}
2048
2049#else /* FEAT_X11 */
2050
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 static int
2052get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002053 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054{
2055 return FALSE;
2056}
2057
2058 static int
2059get_x11_icon(test_only)
2060 int test_only;
2061{
2062 if (!test_only)
2063 {
2064 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002065 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002067 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 }
2069 return FALSE;
2070}
2071
2072#endif /* FEAT_X11 */
2073
2074 int
2075mch_can_restore_title()
2076{
2077 return get_x11_title(TRUE);
2078}
2079
2080 int
2081mch_can_restore_icon()
2082{
2083 return get_x11_icon(TRUE);
2084}
2085
2086/*
2087 * Set the window title and icon.
2088 */
2089 void
2090mch_settitle(title, icon)
2091 char_u *title;
2092 char_u *icon;
2093{
2094 int type = 0;
2095 static int recursive = 0;
2096
2097 if (T_NAME == NULL) /* no terminal name (yet) */
2098 return;
2099 if (title == NULL && icon == NULL) /* nothing to do */
2100 return;
2101
2102 /* When one of the X11 functions causes a deadly signal, we get here again
2103 * recursively. Avoid hanging then (something is probably locked). */
2104 if (recursive)
2105 return;
2106 ++recursive;
2107
2108 /*
2109 * if the window ID and the display is known, we may use X11 calls
2110 */
2111#ifdef FEAT_X11
2112 if (get_x11_windis() == OK)
2113 type = 1;
2114#else
2115# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2116 if (gui.in_use)
2117 type = 1;
2118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119#endif
2120
2121 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002122 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123 * than x11 calls, because the x11 calls don't always work
2124 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125 if ((type || *T_TS != NUL) && title != NULL)
2126 {
2127 if (oldtitle == NULL
2128#ifdef FEAT_GUI
2129 && !gui.in_use
2130#endif
2131 ) /* first call but not in GUI, save title */
2132 (void)get_x11_title(FALSE);
2133
2134 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2135 term_settitle(title);
2136#ifdef FEAT_X11
2137 else
2138# ifdef FEAT_GUI_GTK
2139 if (!gui.in_use) /* don't do this if GTK+ is running */
2140# endif
2141 set_x11_title(title); /* x11 */
2142#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002143#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2145 else
2146 gui_mch_settitle(title, icon);
2147#endif
2148 did_set_title = TRUE;
2149 }
2150
2151 if ((type || *T_CIS != NUL) && icon != NULL)
2152 {
2153 if (oldicon == NULL
2154#ifdef FEAT_GUI
2155 && !gui.in_use
2156#endif
2157 ) /* first call, save icon */
2158 get_x11_icon(FALSE);
2159
2160 if (*T_CIS != NUL)
2161 {
2162 out_str(T_CIS); /* set icon start */
2163 out_str_nf(icon);
2164 out_str(T_CIE); /* set icon end */
2165 out_flush();
2166 }
2167#ifdef FEAT_X11
2168 else
2169# ifdef FEAT_GUI_GTK
2170 if (!gui.in_use) /* don't do this if GTK+ is running */
2171# endif
2172 set_x11_icon(icon); /* x11 */
2173#endif
2174 did_set_icon = TRUE;
2175 }
2176 --recursive;
2177}
2178
2179/*
2180 * Restore the window/icon title.
2181 * "which" is one of:
2182 * 1 only restore title
2183 * 2 only restore icon
2184 * 3 restore title and icon
2185 */
2186 void
2187mch_restore_title(which)
2188 int which;
2189{
2190 /* only restore the title or icon when it has been set */
2191 mch_settitle(((which & 1) && did_set_title) ?
2192 (oldtitle ? oldtitle : p_titleold) : NULL,
2193 ((which & 2) && did_set_icon) ? oldicon : NULL);
2194}
2195
2196#endif /* FEAT_TITLE */
2197
2198/*
2199 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002200 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 */
2202 int
2203vim_is_xterm(name)
2204 char_u *name;
2205{
2206 if (name == NULL)
2207 return FALSE;
2208 return (STRNICMP(name, "xterm", 5) == 0
2209 || STRNICMP(name, "nxterm", 6) == 0
2210 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002211 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212 || STRNICMP(name, "rxvt", 4) == 0
2213 || STRCMP(name, "builtin_xterm") == 0);
2214}
2215
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002216#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2217/*
2218 * Return TRUE if "name" appears to be that of a terminal
2219 * known to support the xterm-style mouse protocol.
2220 * Relies on term_is_xterm having been set to its correct value.
2221 */
2222 int
2223use_xterm_like_mouse(name)
2224 char_u *name;
2225{
2226 return (name != NULL
2227 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2228}
2229#endif
2230
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2232/*
2233 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2234 * Return 1 for "xterm".
2235 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002236 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002237 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 */
2239 int
2240use_xterm_mouse()
2241{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002242 if (ttym_flags == TTYM_SGR)
2243 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002244 if (ttym_flags == TTYM_URXVT)
2245 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 if (ttym_flags == TTYM_XTERM2)
2247 return 2;
2248 if (ttym_flags == TTYM_XTERM)
2249 return 1;
2250 return 0;
2251}
2252#endif
2253
2254 int
2255vim_is_iris(name)
2256 char_u *name;
2257{
2258 if (name == NULL)
2259 return FALSE;
2260 return (STRNICMP(name, "iris-ansi", 9) == 0
2261 || STRCMP(name, "builtin_iris-ansi") == 0);
2262}
2263
2264 int
2265vim_is_vt300(name)
2266 char_u *name;
2267{
2268 if (name == NULL)
2269 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002270 /* catch VT100 - VT5xx */
2271 return ((STRNICMP(name, "vt", 2) == 0
2272 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 || STRCMP(name, "builtin_vt320") == 0);
2274}
2275
2276/*
2277 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2278 * This should include all windowed terminal emulators.
2279 */
2280 int
2281vim_is_fastterm(name)
2282 char_u *name;
2283{
2284 if (name == NULL)
2285 return FALSE;
2286 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2287 return TRUE;
2288 return ( STRNICMP(name, "hpterm", 6) == 0
2289 || STRNICMP(name, "sun-cmd", 7) == 0
2290 || STRNICMP(name, "screen", 6) == 0
2291 || STRNICMP(name, "dtterm", 6) == 0);
2292}
2293
2294/*
2295 * Insert user name in s[len].
2296 * Return OK if a name found.
2297 */
2298 int
2299mch_get_user_name(s, len)
2300 char_u *s;
2301 int len;
2302{
2303#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002304 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305 return OK;
2306#else
2307 return mch_get_uname(getuid(), s, len);
2308#endif
2309}
2310
2311/*
2312 * Insert user name for "uid" in s[len].
2313 * Return OK if a name found.
2314 */
2315 int
2316mch_get_uname(uid, s, len)
2317 uid_t uid;
2318 char_u *s;
2319 int len;
2320{
2321#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2322 struct passwd *pw;
2323
2324 if ((pw = getpwuid(uid)) != NULL
2325 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2326 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002327 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 return OK;
2329 }
2330#endif
2331 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2332 return FAIL; /* a number is not a name */
2333}
2334
2335/*
2336 * Insert host name is s[len].
2337 */
2338
2339#ifdef HAVE_SYS_UTSNAME_H
2340 void
2341mch_get_host_name(s, len)
2342 char_u *s;
2343 int len;
2344{
2345 struct utsname vutsname;
2346
2347 if (uname(&vutsname) < 0)
2348 *s = NUL;
2349 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002350 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351}
2352#else /* HAVE_SYS_UTSNAME_H */
2353
2354# ifdef HAVE_SYS_SYSTEMINFO_H
2355# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2356# endif
2357
2358 void
2359mch_get_host_name(s, len)
2360 char_u *s;
2361 int len;
2362{
2363# ifdef VAXC
2364 vaxc$gethostname((char *)s, len);
2365# else
2366 gethostname((char *)s, len);
2367# endif
2368 s[len - 1] = NUL; /* make sure it's terminated */
2369}
2370#endif /* HAVE_SYS_UTSNAME_H */
2371
2372/*
2373 * return process ID
2374 */
2375 long
2376mch_get_pid()
2377{
2378 return (long)getpid();
2379}
2380
2381#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2382static char *strerror __ARGS((int));
2383
2384 static char *
2385strerror(err)
2386 int err;
2387{
2388 extern int sys_nerr;
2389 extern char *sys_errlist[];
2390 static char er[20];
2391
2392 if (err > 0 && err < sys_nerr)
2393 return (sys_errlist[err]);
2394 sprintf(er, "Error %d", err);
2395 return er;
2396}
2397#endif
2398
2399/*
2400 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2401 * Return OK for success, FAIL for failure.
2402 */
2403 int
2404mch_dirname(buf, len)
2405 char_u *buf;
2406 int len;
2407{
2408#if defined(USE_GETCWD)
2409 if (getcwd((char *)buf, len) == NULL)
2410 {
2411 STRCPY(buf, strerror(errno));
2412 return FAIL;
2413 }
2414 return OK;
2415#else
2416 return (getwd((char *)buf) != NULL ? OK : FAIL);
2417#endif
2418}
2419
2420#if defined(OS2) || defined(PROTO)
2421/*
2422 * Replace all slashes by backslashes.
2423 * When 'shellslash' set do it the other way around.
2424 */
2425 void
2426slash_adjust(p)
2427 char_u *p;
2428{
2429 while (*p)
2430 {
2431 if (*p == psepcN)
2432 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002433 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 }
2435}
2436#endif
2437
2438/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002439 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440 *
2441 * return FAIL for failure, OK for success
2442 */
2443 int
2444mch_FullName(fname, buf, len, force)
2445 char_u *fname, *buf;
2446 int len;
2447 int force; /* also expand when already absolute path */
2448{
2449 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002450#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002452#endif
2453#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 int fd = -1;
2455 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002456#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 char_u olddir[MAXPATHL];
2458 char_u *p;
2459 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002460#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002461 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2462 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002463#endif
2464
Bram Moolenaar38323e42007-03-06 19:22:53 +00002465#ifdef VMS
2466 fname = vms_fixfilename(fname);
2467#endif
2468
Bram Moolenaara2442432007-04-26 14:26:37 +00002469#ifdef __CYGWIN__
2470 /*
2471 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2472 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002473# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2474 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2475# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002476 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002477# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002478 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002479#endif
2480
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 /* expand it if forced or not an absolute path */
2482 if (force || !mch_isFullName(fname))
2483 {
2484 /*
2485 * If the file name has a path, change to that directory for a moment,
2486 * and then do the getwd() (and get back to where we were).
2487 * This will get the correct path name with "../" things.
2488 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002489#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 only_drive = 0;
2491 if (((p = vim_strrchr(fname, '/')) != NULL)
2492 || ((p = vim_strrchr(fname, '\\')) != NULL)
2493 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002494#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002498#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499 /*
2500 * Use fchdir() if possible, it's said to be faster and more
2501 * reliable. But on SunOS 4 it might not work. Check this by
2502 * doing a fchdir() right now.
2503 */
2504 if (!dont_fchdir)
2505 {
2506 fd = open(".", O_RDONLY | O_EXTRA, 0);
2507 if (fd >= 0 && fchdir(fd) < 0)
2508 {
2509 close(fd);
2510 fd = -1;
2511 dont_fchdir = TRUE; /* don't try again */
2512 }
2513 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515
2516 /* Only change directory when we are sure we can return to where
2517 * we are now. After doing "su" chdir(".") might not work. */
2518 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002519#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002521#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 (mch_dirname(olddir, MAXPATHL) == FAIL
2523 || mch_chdir((char *)olddir) != 0))
2524 {
2525 p = NULL; /* can't get current dir: don't chdir */
2526 retval = FAIL;
2527 }
2528 else
2529 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002530#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 /*
2532 * compensate for case where ':' from "D:" was the only
2533 * path separator detected in the file name; the _next_
2534 * character has to be removed, and then restored later.
2535 */
2536 if (only_drive)
2537 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002538#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 /* The directory is copied into buf[], to be able to remove
2540 * the file name without changing it (could be a string in
2541 * read-only memory) */
2542 if (p - fname >= len)
2543 retval = FAIL;
2544 else
2545 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002546 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (mch_chdir((char *)buf))
2548 retval = FAIL;
2549 else
2550 fname = p + 1;
2551 *buf = NUL;
2552 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002553#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 if (only_drive)
2555 {
2556 p--;
2557 if (retval != FAIL)
2558 fname--;
2559 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002560#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 }
2562 }
2563 if (mch_dirname(buf, len) == FAIL)
2564 {
2565 retval = FAIL;
2566 *buf = NUL;
2567 }
2568 if (p != NULL)
2569 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002570#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 if (fd >= 0)
2572 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002573 if (p_verbose >= 5)
2574 {
2575 verbose_enter();
2576 MSG("fchdir() to previous dir");
2577 verbose_leave();
2578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 l = fchdir(fd);
2580 close(fd);
2581 }
2582 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002583#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 l = mch_chdir((char *)olddir);
2585 if (l != 0)
2586 EMSG(_(e_prev_dir));
2587 }
2588
2589 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002590 if (l >= len - 1)
2591 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002592#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002593 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002595 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002596#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002598
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002600 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 return FAIL;
2602
2603 /* Do not append ".", "/dir/." is equal to "/dir". */
2604 if (STRCMP(fname, ".") != 0)
2605 STRCAT(buf, fname);
2606
2607 return OK;
2608}
2609
2610/*
2611 * Return TRUE if "fname" does not depend on the current directory.
2612 */
2613 int
2614mch_isFullName(fname)
2615 char_u *fname;
2616{
2617#ifdef __EMX__
2618 return _fnisabs(fname);
2619#else
2620# ifdef VMS
2621 return ( fname[0] == '/' || fname[0] == '.' ||
2622 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2623 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2624 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2625# else
2626 return (*fname == '/' || *fname == '~');
2627# endif
2628#endif
2629}
2630
Bram Moolenaar24552be2005-12-10 20:17:30 +00002631#if defined(USE_FNAME_CASE) || defined(PROTO)
2632/*
2633 * Set the case of the file name, if it already exists. This will cause the
2634 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002635 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002636 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002637 void
2638fname_case(name, len)
2639 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002640 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002641{
2642 struct stat st;
2643 char_u *slash, *tail;
2644 DIR *dirp;
2645 struct dirent *dp;
2646
2647 if (lstat((char *)name, &st) >= 0)
2648 {
2649 /* Open the directory where the file is located. */
2650 slash = vim_strrchr(name, '/');
2651 if (slash == NULL)
2652 {
2653 dirp = opendir(".");
2654 tail = name;
2655 }
2656 else
2657 {
2658 *slash = NUL;
2659 dirp = opendir((char *)name);
2660 *slash = '/';
2661 tail = slash + 1;
2662 }
2663
2664 if (dirp != NULL)
2665 {
2666 while ((dp = readdir(dirp)) != NULL)
2667 {
2668 /* Only accept names that differ in case and are the same byte
2669 * length. TODO: accept different length name. */
2670 if (STRICMP(tail, dp->d_name) == 0
2671 && STRLEN(tail) == STRLEN(dp->d_name))
2672 {
2673 char_u newname[MAXPATHL + 1];
2674 struct stat st2;
2675
2676 /* Verify the inode is equal. */
2677 vim_strncpy(newname, name, MAXPATHL);
2678 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2679 MAXPATHL - (tail - name));
2680 if (lstat((char *)newname, &st2) >= 0
2681 && st.st_ino == st2.st_ino
2682 && st.st_dev == st2.st_dev)
2683 {
2684 STRCPY(tail, dp->d_name);
2685 break;
2686 }
2687 }
2688 }
2689
2690 closedir(dirp);
2691 }
2692 }
2693}
2694#endif
2695
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696/*
2697 * Get file permissions for 'name'.
2698 * Returns -1 when it doesn't exist.
2699 */
2700 long
2701mch_getperm(name)
2702 char_u *name;
2703{
2704 struct stat statb;
2705
2706 /* Keep the #ifdef outside of stat(), it may be a macro. */
2707#ifdef VMS
2708 if (stat((char *)vms_fixfilename(name), &statb))
2709#else
2710 if (stat((char *)name, &statb))
2711#endif
2712 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002713#ifdef __INTERIX
2714 /* The top bit makes the value negative, which means the file doesn't
2715 * exist. Remove the bit, we don't use it. */
2716 return statb.st_mode & ~S_ADDACE;
2717#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002719#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720}
2721
2722/*
2723 * set file permission for 'name' to 'perm'
2724 *
2725 * return FAIL for failure, OK otherwise
2726 */
2727 int
2728mch_setperm(name, perm)
2729 char_u *name;
2730 long perm;
2731{
2732 return (chmod((char *)
2733#ifdef VMS
2734 vms_fixfilename(name),
2735#else
2736 name,
2737#endif
2738 (mode_t)perm) == 0 ? OK : FAIL);
2739}
2740
2741#if defined(HAVE_ACL) || defined(PROTO)
2742# ifdef HAVE_SYS_ACL_H
2743# include <sys/acl.h>
2744# endif
2745# ifdef HAVE_SYS_ACCESS_H
2746# include <sys/access.h>
2747# endif
2748
2749# ifdef HAVE_SOLARIS_ACL
2750typedef struct vim_acl_solaris_T {
2751 int acl_cnt;
2752 aclent_t *acl_entry;
2753} vim_acl_solaris_T;
2754# endif
2755
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002756#if defined(HAVE_SELINUX) || defined(PROTO)
2757/*
2758 * Copy security info from "from_file" to "to_file".
2759 */
2760 void
2761mch_copy_sec(from_file, to_file)
2762 char_u *from_file;
2763 char_u *to_file;
2764{
2765 if (from_file == NULL)
2766 return;
2767
2768 if (selinux_enabled == -1)
2769 selinux_enabled = is_selinux_enabled();
2770
2771 if (selinux_enabled > 0)
2772 {
2773 security_context_t from_context = NULL;
2774 security_context_t to_context = NULL;
2775
2776 if (getfilecon((char *)from_file, &from_context) < 0)
2777 {
2778 /* If the filesystem doesn't support extended attributes,
2779 the original had no special security context and the
2780 target cannot have one either. */
2781 if (errno == EOPNOTSUPP)
2782 return;
2783
2784 MSG_PUTS(_("\nCould not get security context for "));
2785 msg_outtrans(from_file);
2786 msg_putchar('\n');
2787 return;
2788 }
2789 if (getfilecon((char *)to_file, &to_context) < 0)
2790 {
2791 MSG_PUTS(_("\nCould not get security context for "));
2792 msg_outtrans(to_file);
2793 msg_putchar('\n');
2794 freecon (from_context);
2795 return ;
2796 }
2797 if (strcmp(from_context, to_context) != 0)
2798 {
2799 if (setfilecon((char *)to_file, from_context) < 0)
2800 {
2801 MSG_PUTS(_("\nCould not set security context for "));
2802 msg_outtrans(to_file);
2803 msg_putchar('\n');
2804 }
2805 }
2806 freecon(to_context);
2807 freecon(from_context);
2808 }
2809}
2810#endif /* HAVE_SELINUX */
2811
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002812#if defined(HAVE_SMACK) && !defined(PROTO)
2813/*
2814 * Copy security info from "from_file" to "to_file".
2815 */
2816 void
2817mch_copy_sec(from_file, to_file)
2818 char_u *from_file;
2819 char_u *to_file;
2820{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002821 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002822 {
2823 XATTR_NAME_SMACK,
2824 XATTR_NAME_SMACKEXEC,
2825 XATTR_NAME_SMACKMMAP
2826 };
2827
2828 char buffer[SMACK_LABEL_LEN];
2829 const char *name;
2830 int index;
2831 int ret;
2832 ssize_t size;
2833
2834 if (from_file == NULL)
2835 return;
2836
2837 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2838 / sizeof(smack_copied_attributes)[0]) ; index++)
2839 {
2840 /* get the name of the attribute to copy */
2841 name = smack_copied_attributes[index];
2842
2843 /* get the value of the attribute in buffer */
2844 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2845 if (size >= 0)
2846 {
2847 /* copy the attribute value of buffer */
2848 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2849 if (ret < 0)
2850 {
2851 MSG_PUTS(_("Could not set security context "));
2852 MSG_PUTS(name);
2853 MSG_PUTS(_(" for "));
2854 msg_outtrans(to_file);
2855 msg_putchar('\n');
2856 }
2857 }
2858 else
2859 {
2860 /* what reason of not having the attribute value? */
2861 switch (errno)
2862 {
2863 case ENOTSUP:
2864 /* extended attributes aren't supported or enabled */
2865 /* should a message be echoed? not sure... */
2866 return; /* leave because it isn't usefull to continue */
2867
2868 case ERANGE:
2869 default:
2870 /* no enough size OR unexpected error */
2871 MSG_PUTS(_("Could not get security context "));
2872 MSG_PUTS(name);
2873 MSG_PUTS(_(" for "));
2874 msg_outtrans(from_file);
2875 MSG_PUTS(_(". Removing it!\n"));
2876 /* FALLTHROUGH to remove the attribute */
2877
2878 case ENODATA:
2879 /* no attribute of this name */
2880 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002881 /* Silently ignore errors, apparently this happens when
2882 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002883 break;
2884 }
2885 }
2886 }
2887}
2888#endif /* HAVE_SMACK */
2889
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890/*
2891 * Return a pointer to the ACL of file "fname" in allocated memory.
2892 * Return NULL if the ACL is not available for whatever reason.
2893 */
2894 vim_acl_T
2895mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002896 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897{
2898 vim_acl_T ret = NULL;
2899#ifdef HAVE_POSIX_ACL
2900 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2901#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002902#ifdef HAVE_SOLARIS_ZFS_ACL
2903 acl_t *aclent;
2904
2905 if (acl_get((char *)fname, 0, &aclent) < 0)
2906 return NULL;
2907 ret = (vim_acl_T)aclent;
2908#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909#ifdef HAVE_SOLARIS_ACL
2910 vim_acl_solaris_T *aclent;
2911
2912 aclent = malloc(sizeof(vim_acl_solaris_T));
2913 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2914 {
2915 free(aclent);
2916 return NULL;
2917 }
2918 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2919 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2920 {
2921 free(aclent->acl_entry);
2922 free(aclent);
2923 return NULL;
2924 }
2925 ret = (vim_acl_T)aclent;
2926#else
2927#if defined(HAVE_AIX_ACL)
2928 int aclsize;
2929 struct acl *aclent;
2930
2931 aclsize = sizeof(struct acl);
2932 aclent = malloc(aclsize);
2933 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2934 {
2935 if (errno == ENOSPC)
2936 {
2937 aclsize = aclent->acl_len;
2938 aclent = realloc(aclent, aclsize);
2939 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2940 {
2941 free(aclent);
2942 return NULL;
2943 }
2944 }
2945 else
2946 {
2947 free(aclent);
2948 return NULL;
2949 }
2950 }
2951 ret = (vim_acl_T)aclent;
2952#endif /* HAVE_AIX_ACL */
2953#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002954#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955#endif /* HAVE_POSIX_ACL */
2956 return ret;
2957}
2958
2959/*
2960 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2961 */
2962 void
2963mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002964 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 vim_acl_T aclent;
2966{
2967 if (aclent == NULL)
2968 return;
2969#ifdef HAVE_POSIX_ACL
2970 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2971#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002972#ifdef HAVE_SOLARIS_ZFS_ACL
2973 acl_set((char *)fname, (acl_t *)aclent);
2974#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975#ifdef HAVE_SOLARIS_ACL
2976 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2977 ((vim_acl_solaris_T *)aclent)->acl_entry);
2978#else
2979#ifdef HAVE_AIX_ACL
2980 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2981#endif /* HAVE_AIX_ACL */
2982#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002983#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984#endif /* HAVE_POSIX_ACL */
2985}
2986
2987 void
2988mch_free_acl(aclent)
2989 vim_acl_T aclent;
2990{
2991 if (aclent == NULL)
2992 return;
2993#ifdef HAVE_POSIX_ACL
2994 acl_free((acl_t)aclent);
2995#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002996#ifdef HAVE_SOLARIS_ZFS_ACL
2997 acl_free((acl_t *)aclent);
2998#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999#ifdef HAVE_SOLARIS_ACL
3000 free(((vim_acl_solaris_T *)aclent)->acl_entry);
3001 free(aclent);
3002#else
3003#ifdef HAVE_AIX_ACL
3004 free(aclent);
3005#endif /* HAVE_AIX_ACL */
3006#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003007#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008#endif /* HAVE_POSIX_ACL */
3009}
3010#endif
3011
3012/*
3013 * Set hidden flag for "name".
3014 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015 void
3016mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003017 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018{
3019 /* can't hide a file */
3020}
3021
3022/*
3023 * return TRUE if "name" is a directory
3024 * return FALSE if "name" is not a directory
3025 * return FALSE for error
3026 */
3027 int
3028mch_isdir(name)
3029 char_u *name;
3030{
3031 struct stat statb;
3032
3033 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3034 return FALSE;
3035 if (stat((char *)name, &statb))
3036 return FALSE;
3037#ifdef _POSIX_SOURCE
3038 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3039#else
3040 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3041#endif
3042}
3043
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044static int executable_file __ARGS((char_u *name));
3045
3046/*
3047 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3048 */
3049 static int
3050executable_file(name)
3051 char_u *name;
3052{
3053 struct stat st;
3054
3055 if (stat((char *)name, &st))
3056 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003057#ifdef VMS
3058 /* Like on Unix system file can have executable rights but not necessarily
3059 * be an executable, but on Unix is not a default for an ordianry file to
3060 * have an executable flag - on VMS it is in most cases.
3061 * Therefore, this check does not have any sense - let keep us to the
3062 * conventions instead:
3063 * *.COM and *.EXE files are the executables - the rest are not. This is
3064 * not ideal but better then it was.
3065 */
3066 int vms_executable = 0;
3067 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3068 {
3069 if (strstr(vms_tolower((char*)name),".exe") != NULL
3070 || strstr(vms_tolower((char*)name),".com")!= NULL)
3071 vms_executable = 1;
3072 }
3073 return vms_executable;
3074#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003076#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077}
3078
3079/*
3080 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
3081 * Return -1 if unknown.
3082 */
3083 int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003084mch_can_exe(name, path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 char_u *name;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003086 char_u **path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087{
3088 char_u *buf;
3089 char_u *p, *e;
3090 int retval;
3091
3092 /* If it's an absolute or relative path don't need to use $PATH. */
3093 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
3094 || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003095 {
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003096 if (executable_file(name))
3097 {
3098 if (path != NULL)
3099 {
3100 if (name[0] == '.')
3101 *path = FullName_save(name, TRUE);
3102 else
3103 *path = vim_strsave(name);
3104 }
3105 return TRUE;
3106 }
3107 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109
3110 p = (char_u *)getenv("PATH");
3111 if (p == NULL || *p == NUL)
3112 return -1;
3113 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3114 if (buf == NULL)
3115 return -1;
3116
3117 /*
3118 * Walk through all entries in $PATH to check if "name" exists there and
3119 * is an executable file.
3120 */
3121 for (;;)
3122 {
3123 e = (char_u *)strchr((char *)p, ':');
3124 if (e == NULL)
3125 e = p + STRLEN(p);
3126 if (e - p <= 1) /* empty entry means current dir */
3127 STRCPY(buf, "./");
3128 else
3129 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003130 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 add_pathsep(buf);
3132 }
3133 STRCAT(buf, name);
3134 retval = executable_file(buf);
3135 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003136 {
3137 if (path != NULL)
3138 {
3139 if (buf[0] == '.')
3140 *path = FullName_save(buf, TRUE);
3141 else
3142 *path = vim_strsave(buf);
3143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003145 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146
3147 if (*e != ':')
3148 break;
3149 p = e + 1;
3150 }
3151
3152 vim_free(buf);
3153 return retval;
3154}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155
3156/*
3157 * Check what "name" is:
3158 * NODE_NORMAL: file or directory (or doesn't exist)
3159 * NODE_WRITABLE: writable device, socket, fifo, etc.
3160 * NODE_OTHER: non-writable things
3161 */
3162 int
3163mch_nodetype(name)
3164 char_u *name;
3165{
3166 struct stat st;
3167
3168 if (stat((char *)name, &st))
3169 return NODE_NORMAL;
3170 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3171 return NODE_NORMAL;
3172#ifndef OS2
3173 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3174 return NODE_OTHER;
3175#endif
3176 /* Everything else is writable? */
3177 return NODE_WRITABLE;
3178}
3179
3180 void
3181mch_early_init()
3182{
3183#ifdef HAVE_CHECK_STACK_GROWTH
3184 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 check_stack_growth((char *)&i);
3187
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003188# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189 get_stack_limit();
3190# endif
3191
3192#endif
3193
3194 /*
3195 * Setup an alternative stack for signals. Helps to catch signals when
3196 * running out of stack space.
3197 * Use of sigaltstack() is preferred, it's more portable.
3198 * Ignore any errors.
3199 */
3200#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003201 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 init_signal_stack();
3203#endif
3204}
3205
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003206#if defined(EXITFREE) || defined(PROTO)
3207 void
3208mch_free_mem()
3209{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003210# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3211 if (clip_star.owned)
3212 clip_lose_selection(&clip_star);
3213 if (clip_plus.owned)
3214 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003215# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003216# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003217 if (xterm_Shell != (Widget)0)
3218 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003219# ifndef LESSTIF_VERSION
3220 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003221 if (xterm_dpy != NULL)
3222 XtCloseDisplay(xterm_dpy);
3223 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003224 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003225 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003226# ifdef FEAT_X11
3227 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3228# endif
3229 }
3230# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003231# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003232# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003233 if (x11_display != NULL
3234# ifdef FEAT_XCLIPBOARD
3235 && x11_display != xterm_dpy
3236# endif
3237 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003238 XCloseDisplay(x11_display);
3239# endif
3240# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3241 vim_free(signal_stack);
3242 signal_stack = NULL;
3243# endif
3244# ifdef FEAT_TITLE
3245 vim_free(oldtitle);
3246 vim_free(oldicon);
3247# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003248}
3249#endif
3250
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251static void exit_scroll __ARGS((void));
3252
3253/*
3254 * Output a newline when exiting.
3255 * Make sure the newline goes to the same stream as the text.
3256 */
3257 static void
3258exit_scroll()
3259{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003260 if (silent_mode)
3261 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 if (newline_on_exit || msg_didout)
3263 {
3264 if (msg_use_printf())
3265 {
3266 if (info_message)
3267 mch_msg("\n");
3268 else
3269 mch_errmsg("\r\n");
3270 }
3271 else
3272 out_char('\n');
3273 }
3274 else
3275 {
3276 restore_cterm_colors(); /* get original colors back */
3277 msg_clr_eos_force(); /* clear the rest of the display */
3278 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3279 }
3280}
3281
3282 void
3283mch_exit(r)
3284 int r;
3285{
3286 exiting = TRUE;
3287
3288#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3289 x11_export_final_selection();
3290#endif
3291
3292#ifdef FEAT_GUI
3293 if (!gui.in_use)
3294#endif
3295 {
3296 settmode(TMODE_COOK);
3297#ifdef FEAT_TITLE
3298 mch_restore_title(3); /* restore xterm title and icon name */
3299#endif
3300 /*
3301 * When t_ti is not empty but it doesn't cause swapping terminal
3302 * pages, need to output a newline when msg_didout is set. But when
3303 * t_ti does swap pages it should not go to the shell page. Do this
3304 * before stoptermcap().
3305 */
3306 if (swapping_screen() && !newline_on_exit)
3307 exit_scroll();
3308
3309 /* Stop termcap: May need to check for T_CRV response, which
3310 * requires RAW mode. */
3311 stoptermcap();
3312
3313 /*
3314 * A newline is only required after a message in the alternate screen.
3315 * This is set to TRUE by wait_return().
3316 */
3317 if (!swapping_screen() || newline_on_exit)
3318 exit_scroll();
3319
3320 /* Cursor may have been switched off without calling starttermcap()
3321 * when doing "vim -u vimrc" and vimrc contains ":q". */
3322 if (full_screen)
3323 cursor_on();
3324 }
3325 out_flush();
3326 ml_close_all(TRUE); /* remove all memfiles */
3327 may_core_dump();
3328#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 gui_exit(r);
3331#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003332
Bram Moolenaar56718732006-03-15 22:53:57 +00003333#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003334 mac_conv_cleanup();
3335#endif
3336
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337#ifdef __QNX__
3338 /* A core dump won't be created if the signal handler
3339 * doesn't return, so we can't call exit() */
3340 if (deadly_signal != 0)
3341 return;
3342#endif
3343
Bram Moolenaar009b2592004-10-24 19:18:58 +00003344#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003345 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003346#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003347
3348#ifdef EXITFREE
3349 free_all_mem();
3350#endif
3351
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 exit(r);
3353}
3354
3355 static void
3356may_core_dump()
3357{
3358 if (deadly_signal != 0)
3359 {
3360 signal(deadly_signal, SIG_DFL);
3361 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3362 }
3363}
3364
3365#ifndef VMS
3366
3367 void
3368mch_settmode(tmode)
3369 int tmode;
3370{
3371 static int first = TRUE;
3372
3373 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3374#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3375 /*
3376 * for "new" tty systems
3377 */
3378# ifdef HAVE_TERMIOS_H
3379 static struct termios told;
3380 struct termios tnew;
3381# else
3382 static struct termio told;
3383 struct termio tnew;
3384# endif
3385
3386 if (first)
3387 {
3388 first = FALSE;
3389# if defined(HAVE_TERMIOS_H)
3390 tcgetattr(read_cmd_fd, &told);
3391# else
3392 ioctl(read_cmd_fd, TCGETA, &told);
3393# endif
3394 }
3395
3396 tnew = told;
3397 if (tmode == TMODE_RAW)
3398 {
3399 /*
3400 * ~ICRNL enables typing ^V^M
3401 */
3402 tnew.c_iflag &= ~ICRNL;
3403 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3404# if defined(IEXTEN) && !defined(__MINT__)
3405 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3406 /* but it breaks function keys on MINT */
3407# endif
3408 );
3409# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3410 tnew.c_oflag &= ~ONLCR;
3411# endif
3412 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3413 tnew.c_cc[VTIME] = 0; /* don't wait */
3414 }
3415 else if (tmode == TMODE_SLEEP)
3416 tnew.c_lflag &= ~(ECHO);
3417
3418# if defined(HAVE_TERMIOS_H)
3419 {
3420 int n = 10;
3421
3422 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3423 * few times. */
3424 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3425 && errno == EINTR && n > 0)
3426 --n;
3427 }
3428# else
3429 ioctl(read_cmd_fd, TCSETA, &tnew);
3430# endif
3431
3432#else
3433
3434 /*
3435 * for "old" tty systems
3436 */
3437# ifndef TIOCSETN
3438# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3439# endif
3440 static struct sgttyb ttybold;
3441 struct sgttyb ttybnew;
3442
3443 if (first)
3444 {
3445 first = FALSE;
3446 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3447 }
3448
3449 ttybnew = ttybold;
3450 if (tmode == TMODE_RAW)
3451 {
3452 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3453 ttybnew.sg_flags |= RAW;
3454 }
3455 else if (tmode == TMODE_SLEEP)
3456 ttybnew.sg_flags &= ~(ECHO);
3457 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3458#endif
3459 curr_tmode = tmode;
3460}
3461
3462/*
3463 * Try to get the code for "t_kb" from the stty setting
3464 *
3465 * Even if termcap claims a backspace key, the user's setting *should*
3466 * prevail. stty knows more about reality than termcap does, and if
3467 * somebody's usual erase key is DEL (which, for most BSD users, it will
3468 * be), they're going to get really annoyed if their erase key starts
3469 * doing forward deletes for no reason. (Eric Fischer)
3470 */
3471 void
3472get_stty()
3473{
3474 char_u buf[2];
3475 char_u *p;
3476
3477 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3478#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3479 /* for "new" tty systems */
3480# ifdef HAVE_TERMIOS_H
3481 struct termios keys;
3482# else
3483 struct termio keys;
3484# endif
3485
3486# if defined(HAVE_TERMIOS_H)
3487 if (tcgetattr(read_cmd_fd, &keys) != -1)
3488# else
3489 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3490# endif
3491 {
3492 buf[0] = keys.c_cc[VERASE];
3493 intr_char = keys.c_cc[VINTR];
3494#else
3495 /* for "old" tty systems */
3496 struct sgttyb keys;
3497
3498 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3499 {
3500 buf[0] = keys.sg_erase;
3501 intr_char = keys.sg_kill;
3502#endif
3503 buf[1] = NUL;
3504 add_termcode((char_u *)"kb", buf, FALSE);
3505
3506 /*
3507 * If <BS> and <DEL> are now the same, redefine <DEL>.
3508 */
3509 p = find_termcode((char_u *)"kD");
3510 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3511 do_fixdel(NULL);
3512 }
3513#if 0
3514 } /* to keep cindent happy */
3515#endif
3516}
3517
3518#endif /* VMS */
3519
3520#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3521/*
3522 * Set mouse clicks on or off.
3523 */
3524 void
3525mch_setmouse(on)
3526 int on;
3527{
3528 static int ison = FALSE;
3529 int xterm_mouse_vers;
3530
3531 if (on == ison) /* return quickly if nothing to do */
3532 return;
3533
3534 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003535
3536# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003537 if (ttym_flags == TTYM_URXVT)
3538 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003539 out_str_nf((char_u *)
3540 (on
3541 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3542 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3543 ison = on;
3544 }
3545# endif
3546
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003547# ifdef FEAT_MOUSE_SGR
3548 if (ttym_flags == TTYM_SGR)
3549 {
3550 out_str_nf((char_u *)
3551 (on
3552 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3553 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3554 ison = on;
3555 }
3556# endif
3557
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558 if (xterm_mouse_vers > 0)
3559 {
3560 if (on) /* enable mouse events, use mouse tracking if available */
3561 out_str_nf((char_u *)
3562 (xterm_mouse_vers > 1
3563 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3564 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3565 else /* disable mouse events, could probably always send the same */
3566 out_str_nf((char_u *)
3567 (xterm_mouse_vers > 1
3568 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3569 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3570 ison = on;
3571 }
3572
3573# ifdef FEAT_MOUSE_DEC
3574 else if (ttym_flags == TTYM_DEC)
3575 {
3576 if (on) /* enable mouse events */
3577 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3578 else /* disable mouse events */
3579 out_str_nf((char_u *)"\033['z");
3580 ison = on;
3581 }
3582# endif
3583
3584# ifdef FEAT_MOUSE_GPM
3585 else
3586 {
3587 if (on)
3588 {
3589 if (gpm_open())
3590 ison = TRUE;
3591 }
3592 else
3593 {
3594 gpm_close();
3595 ison = FALSE;
3596 }
3597 }
3598# endif
3599
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003600# ifdef FEAT_SYSMOUSE
3601 else
3602 {
3603 if (on)
3604 {
3605 if (sysmouse_open() == OK)
3606 ison = TRUE;
3607 }
3608 else
3609 {
3610 sysmouse_close();
3611 ison = FALSE;
3612 }
3613 }
3614# endif
3615
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616# ifdef FEAT_MOUSE_JSB
3617 else
3618 {
3619 if (on)
3620 {
3621 /* D - Enable Mouse up/down messages
3622 * L - Enable Left Button Reporting
3623 * M - Enable Middle Button Reporting
3624 * R - Enable Right Button Reporting
3625 * K - Enable SHIFT and CTRL key Reporting
3626 * + - Enable Advanced messaging of mouse moves and up/down messages
3627 * Q - Quiet No Ack
3628 * # - Numeric value of mouse pointer required
3629 * 0 = Multiview 2000 cursor, used as standard
3630 * 1 = Windows Arrow
3631 * 2 = Windows I Beam
3632 * 3 = Windows Hour Glass
3633 * 4 = Windows Cross Hair
3634 * 5 = Windows UP Arrow
3635 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003636# ifdef JSBTERM_MOUSE_NONADVANCED
3637 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3639 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003640# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3642 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644 ison = TRUE;
3645 }
3646 else
3647 {
3648 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3649 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3650 ison = FALSE;
3651 }
3652 }
3653# endif
3654# ifdef FEAT_MOUSE_PTERM
3655 else
3656 {
3657 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3658 if (on)
3659 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3660 else
3661 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3662 ison = on;
3663 }
3664# endif
3665}
3666
3667/*
3668 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3669 */
3670 void
3671check_mouse_termcode()
3672{
3673# ifdef FEAT_MOUSE_XTERM
3674 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003675# ifdef FEAT_MOUSE_URXVT
3676 && use_xterm_mouse() != 3
3677# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003678# ifdef FEAT_GUI
3679 && !gui.in_use
3680# endif
3681 )
3682 {
3683 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003684 ? IF_EB("\233M", CSI_STR "M")
3685 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686 if (*p_mouse != NUL)
3687 {
3688 /* force mouse off and maybe on to send possibly new mouse
3689 * activation sequence to the xterm, with(out) drag tracing. */
3690 mch_setmouse(FALSE);
3691 setmouse();
3692 }
3693 }
3694 else
3695 del_mouse_termcode(KS_MOUSE);
3696# endif
3697
3698# ifdef FEAT_MOUSE_GPM
3699 if (!use_xterm_mouse()
3700# ifdef FEAT_GUI
3701 && !gui.in_use
3702# endif
3703 )
3704 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3705# endif
3706
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003707# ifdef FEAT_SYSMOUSE
3708 if (!use_xterm_mouse()
3709# ifdef FEAT_GUI
3710 && !gui.in_use
3711# endif
3712 )
3713 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3714# endif
3715
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003717 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 if (!use_xterm_mouse()
3719# ifdef FEAT_GUI
3720 && !gui.in_use
3721# endif
3722 )
3723 set_mouse_termcode(KS_JSBTERM_MOUSE,
3724 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3725 else
3726 del_mouse_termcode(KS_JSBTERM_MOUSE);
3727# endif
3728
3729# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003730 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 * define it in the GUI or when using an xterm. */
3732 if (!use_xterm_mouse()
3733# ifdef FEAT_GUI
3734 && !gui.in_use
3735# endif
3736 )
3737 set_mouse_termcode(KS_NETTERM_MOUSE,
3738 (char_u *)IF_EB("\033}", ESC_STR "}"));
3739 else
3740 del_mouse_termcode(KS_NETTERM_MOUSE);
3741# endif
3742
3743# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003744 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003745 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746# ifdef FEAT_GUI
3747 && !gui.in_use
3748# endif
3749 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003750 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3751 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 else
3753 del_mouse_termcode(KS_DEC_MOUSE);
3754# endif
3755# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003756 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003757 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758# ifdef FEAT_GUI
3759 && !gui.in_use
3760# endif
3761 )
3762 set_mouse_termcode(KS_PTERM_MOUSE,
3763 (char_u *) IF_EB("\033[", ESC_STR "["));
3764 else
3765 del_mouse_termcode(KS_PTERM_MOUSE);
3766# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003767# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003768 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003769 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003770# ifdef FEAT_GUI
3771 && !gui.in_use
3772# endif
3773 )
3774 {
3775 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3776 ? IF_EB("\233", CSI_STR)
3777 : IF_EB("\033[", ESC_STR "[")));
3778
3779 if (*p_mouse != NUL)
3780 {
3781 mch_setmouse(FALSE);
3782 setmouse();
3783 }
3784 }
3785 else
3786 del_mouse_termcode(KS_URXVT_MOUSE);
3787# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003788# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003789 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003790 if (use_xterm_mouse() == 4
3791# ifdef FEAT_GUI
3792 && !gui.in_use
3793# endif
3794 )
3795 {
3796 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3797 ? IF_EB("\233<", CSI_STR "<")
3798 : IF_EB("\033[<", ESC_STR "[<")));
3799
3800 if (*p_mouse != NUL)
3801 {
3802 mch_setmouse(FALSE);
3803 setmouse();
3804 }
3805 }
3806 else
3807 del_mouse_termcode(KS_SGR_MOUSE);
3808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809}
3810#endif
3811
3812/*
3813 * set screen mode, always fails.
3814 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 int
3816mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003817 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 EMSG(_(e_screenmode));
3820 return FAIL;
3821}
3822
3823#ifndef VMS
3824
3825/*
3826 * Try to get the current window size:
3827 * 1. with an ioctl(), most accurate method
3828 * 2. from the environment variables LINES and COLUMNS
3829 * 3. from the termcap
3830 * 4. keep using the old values
3831 * Return OK when size could be determined, FAIL otherwise.
3832 */
3833 int
3834mch_get_shellsize()
3835{
3836 long rows = 0;
3837 long columns = 0;
3838 char_u *p;
3839
3840 /*
3841 * For OS/2 use _scrsize().
3842 */
3843# ifdef __EMX__
3844 {
3845 int s[2];
3846
3847 _scrsize(s);
3848 columns = s[0];
3849 rows = s[1];
3850 }
3851# endif
3852
3853 /*
3854 * 1. try using an ioctl. It is the most accurate method.
3855 *
3856 * Try using TIOCGWINSZ first, some systems that have it also define
3857 * TIOCGSIZE but don't have a struct ttysize.
3858 */
3859# ifdef TIOCGWINSZ
3860 {
3861 struct winsize ws;
3862 int fd = 1;
3863
3864 /* When stdout is not a tty, use stdin for the ioctl(). */
3865 if (!isatty(fd) && isatty(read_cmd_fd))
3866 fd = read_cmd_fd;
3867 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3868 {
3869 columns = ws.ws_col;
3870 rows = ws.ws_row;
3871 }
3872 }
3873# else /* TIOCGWINSZ */
3874# ifdef TIOCGSIZE
3875 {
3876 struct ttysize ts;
3877 int fd = 1;
3878
3879 /* When stdout is not a tty, use stdin for the ioctl(). */
3880 if (!isatty(fd) && isatty(read_cmd_fd))
3881 fd = read_cmd_fd;
3882 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3883 {
3884 columns = ts.ts_cols;
3885 rows = ts.ts_lines;
3886 }
3887 }
3888# endif /* TIOCGSIZE */
3889# endif /* TIOCGWINSZ */
3890
3891 /*
3892 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003893 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3894 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003896 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897 {
3898 if ((p = (char_u *)getenv("LINES")))
3899 rows = atoi((char *)p);
3900 if ((p = (char_u *)getenv("COLUMNS")))
3901 columns = atoi((char *)p);
3902 }
3903
3904#ifdef HAVE_TGETENT
3905 /*
3906 * 3. try reading "co" and "li" entries from termcap
3907 */
3908 if (columns == 0 || rows == 0)
3909 getlinecol(&columns, &rows);
3910#endif
3911
3912 /*
3913 * 4. If everything fails, use the old values
3914 */
3915 if (columns <= 0 || rows <= 0)
3916 return FAIL;
3917
3918 Rows = rows;
3919 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003920 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 return OK;
3922}
3923
3924/*
3925 * Try to set the window size to Rows and Columns.
3926 */
3927 void
3928mch_set_shellsize()
3929{
3930 if (*T_CWS)
3931 {
3932 /*
3933 * NOTE: if you get an error here that term_set_winsize() is
3934 * undefined, check the output of configure. It could probably not
3935 * find a ncurses, termcap or termlib library.
3936 */
3937 term_set_winsize((int)Rows, (int)Columns);
3938 out_flush();
3939 screen_start(); /* don't know where cursor is now */
3940 }
3941}
3942
3943#endif /* VMS */
3944
3945/*
3946 * Rows and/or Columns has changed.
3947 */
3948 void
3949mch_new_shellsize()
3950{
3951 /* Nothing to do. */
3952}
3953
Bram Moolenaar205b8862011-09-07 15:04:31 +02003954/*
3955 * Wait for process "child" to end.
3956 * Return "child" if it exited properly, <= 0 on error.
3957 */
3958 static pid_t
3959wait4pid(child, status)
3960 pid_t child;
3961 waitstatus *status;
3962{
3963 pid_t wait_pid = 0;
3964
3965 while (wait_pid != child)
3966 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003967 /* When compiled with Python threads are probably used, in which case
3968 * wait() sometimes hangs for no obvious reason. Use waitpid()
3969 * instead and loop (like the GUI). Also needed for other interfaces,
3970 * they might call system(). */
3971# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003972 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003973# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003974 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003975# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003976 if (wait_pid == 0)
3977 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003978 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003979 mch_delay(10L, TRUE);
3980 continue;
3981 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003982 if (wait_pid <= 0
3983# ifdef ECHILD
3984 && errno == ECHILD
3985# endif
3986 )
3987 break;
3988 }
3989 return wait_pid;
3990}
3991
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 int
3993mch_call_shell(cmd, options)
3994 char_u *cmd;
3995 int options; /* SHELL_*, see vim.h */
3996{
3997#ifdef VMS
3998 char *ifn = NULL;
3999 char *ofn = NULL;
4000#endif
4001 int tmode = cur_tmode;
4002#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
4003 int x;
4004# ifndef __EMX__
4005 char_u *newcmd; /* only needed for unix */
4006# else
4007 /*
4008 * Set the preferred shell in the EMXSHELL environment variable (but
4009 * only if it is different from what is already in the environment).
4010 * Emx then takes care of whether to use "/c" or "-c" in an
4011 * intelligent way. Simply pass the whole thing to emx's system() call.
4012 * Emx also starts an interactive shell if system() is passed an empty
4013 * string.
4014 */
4015 char_u *p, *old;
4016
4017 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4018 {
4019 /* should check HAVE_SETENV, but I know we don't have it. */
4020 p = alloc(10 + strlen(p_sh));
4021 if (p)
4022 {
4023 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4024 putenv((char *)p); /* don't free the pointer! */
4025 }
4026 }
4027# endif
4028
4029 out_flush();
4030
4031 if (options & SHELL_COOKED)
4032 settmode(TMODE_COOK); /* set to normal mode */
4033
Bram Moolenaar62b42182010-09-21 22:09:37 +02004034# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004035 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004036 loose_clipboard();
4037# endif
4038
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039# ifdef __EMX__
4040 if (cmd == NULL)
4041 x = system(""); /* this starts an interactive shell in emx */
4042 else
4043 x = system((char *)cmd);
4044 /* system() returns -1 when error occurs in starting shell */
4045 if (x == -1 && !emsg_silent)
4046 {
4047 MSG_PUTS(_("\nCannot execute shell "));
4048 msg_outtrans(p_sh);
4049 msg_putchar('\n');
4050 }
4051# else /* not __EMX__ */
4052 if (cmd == NULL)
4053 x = system((char *)p_sh);
4054 else
4055 {
4056# ifdef VMS
4057 if (ofn = strchr((char *)cmd, '>'))
4058 *ofn++ = '\0';
4059 if (ifn = strchr((char *)cmd, '<'))
4060 {
4061 char *p;
4062
4063 *ifn++ = '\0';
4064 p = strchr(ifn,' '); /* chop off any trailing spaces */
4065 if (p)
4066 *p = '\0';
4067 }
4068 if (ofn)
4069 x = vms_sys((char *)cmd, ofn, ifn);
4070 else
4071 x = system((char *)cmd);
4072# else
4073 newcmd = lalloc(STRLEN(p_sh)
4074 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4075 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4076 if (newcmd == NULL)
4077 x = 0;
4078 else
4079 {
4080 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4081 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4082 (char *)p_shcf,
4083 (char *)cmd);
4084 x = system((char *)newcmd);
4085 vim_free(newcmd);
4086 }
4087# endif
4088 }
4089# ifdef VMS
4090 x = vms_sys_status(x);
4091# endif
4092 if (emsg_silent)
4093 ;
4094 else if (x == 127)
4095 MSG_PUTS(_("\nCannot execute shell sh\n"));
4096# endif /* __EMX__ */
4097 else if (x && !(options & SHELL_SILENT))
4098 {
4099 MSG_PUTS(_("\nshell returned "));
4100 msg_outnum((long)x);
4101 msg_putchar('\n');
4102 }
4103
4104 if (tmode == TMODE_RAW)
4105 settmode(TMODE_RAW); /* set to raw mode */
4106# ifdef FEAT_TITLE
4107 resettitle();
4108# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004109# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4110 restore_clipboard();
4111# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112 return x;
4113
4114#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4115
Bram Moolenaardf177f62005-02-22 08:39:57 +00004116# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4117 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118
4119 char_u *newcmd = NULL;
4120 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004121 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 pid_t wait_pid = 0;
4123# ifdef HAVE_UNION_WAIT
4124 union wait status;
4125# else
4126 int status = -1;
4127# endif
4128 int retval = -1;
4129 char **argv = NULL;
4130 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004131 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 int i;
4133 char_u *p;
4134 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004136# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 int pty_slave_fd = -1;
4138 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004139# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004140 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 int fd_fromshell[2];
4142 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004143# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004145# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 static char envbuf_Rows[20];
4147 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004149 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150
Bram Moolenaar62b42182010-09-21 22:09:37 +02004151 newcmd = vim_strsave(p_sh);
4152 if (newcmd == NULL) /* out of memory */
4153 goto error;
4154
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 out_flush();
4156 if (options & SHELL_COOKED)
4157 settmode(TMODE_COOK); /* set to normal mode */
4158
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004159 /*
4160 * Do this loop twice:
4161 * 1: find number of arguments
4162 * 2: separate them and build argv[]
4163 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 for (i = 0; i < 2; ++i)
4165 {
4166 p = newcmd;
4167 inquote = FALSE;
4168 argc = 0;
4169 for (;;)
4170 {
4171 if (i == 1)
4172 argv[argc] = (char *)p;
4173 ++argc;
4174 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4175 {
4176 if (*p == '"')
4177 inquote = !inquote;
4178 ++p;
4179 }
4180 if (*p == NUL)
4181 break;
4182 if (i == 1)
4183 *p++ = NUL;
4184 p = skipwhite(p);
4185 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004186 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004188 /*
4189 * Account for possible multiple args in p_shcf.
4190 */
4191 p = p_shcf;
4192 for (;;)
4193 {
4194 p = skiptowhite(p);
4195 if (*p == NUL)
4196 break;
4197 ++argc;
4198 p = skipwhite(p);
4199 }
4200
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4202 if (argv == NULL) /* out of memory */
4203 goto error;
4204 }
4205 }
4206 if (cmd != NULL)
4207 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004208 char_u *s;
4209
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 if (extra_shell_arg != NULL)
4211 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004212
4213 /* Break 'shellcmdflag' into white separated parts. This doesn't
4214 * handle quoted strings, they are very unlikely to appear. */
4215 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4216 if (p_shcf_copy == NULL) /* out of memory */
4217 goto error;
4218 s = p_shcf_copy;
4219 p = p_shcf;
4220 while (*p != NUL)
4221 {
4222 argv[argc++] = (char *)s;
4223 while (*p && *p != ' ' && *p != TAB)
4224 *s++ = *p++;
4225 *s++ = NUL;
4226 p = skipwhite(p);
4227 }
4228
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229 argv[argc++] = (char *)cmd;
4230 }
4231 argv[argc] = NULL;
4232
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004234 * For the GUI, when writing the output into the buffer and when reading
4235 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4236 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004238 if ((options & (SHELL_READ|SHELL_WRITE))
4239# ifdef FEAT_GUI
4240 || (gui.in_use && show_shell_mess)
4241# endif
4242 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004244# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 /*
4246 * Try to open a master pty.
4247 * If this works, open the slave pty.
4248 * If the slave can't be opened, close the master pty.
4249 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004250 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004251 {
4252 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004253 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004255 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4256 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4257 * adding O_NOCTTY always works when defined. */
4258#ifdef O_NOCTTY
4259 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4260#else
4261 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4262#endif
4263 if (pty_slave_fd < 0)
4264 {
4265 close(pty_master_fd);
4266 pty_master_fd = -1;
4267 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004268 }
4269 }
4270 /*
4271 * If not opening a pty or it didn't work, try using pipes.
4272 */
4273 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004274# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 {
4276 pipe_error = (pipe(fd_toshell) < 0);
4277 if (!pipe_error) /* pipe create OK */
4278 {
4279 pipe_error = (pipe(fd_fromshell) < 0);
4280 if (pipe_error) /* pipe create failed */
4281 {
4282 close(fd_toshell[0]);
4283 close(fd_toshell[1]);
4284 }
4285 }
4286 if (pipe_error)
4287 {
4288 MSG_PUTS(_("\nCannot create pipes\n"));
4289 out_flush();
4290 }
4291 }
4292 }
4293
4294 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 {
4296# ifdef __BEOS__
4297 beos_cleanup_read_thread();
4298# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004299
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4301 {
4302 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004303 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004305 || (gui.in_use && show_shell_mess)
4306# endif
4307 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004308 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004309# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310 if (pty_master_fd >= 0) /* close the pseudo tty */
4311 {
4312 close(pty_master_fd);
4313 close(pty_slave_fd);
4314 }
4315 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004316# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317 {
4318 close(fd_toshell[0]);
4319 close(fd_toshell[1]);
4320 close(fd_fromshell[0]);
4321 close(fd_fromshell[1]);
4322 }
4323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 }
4325 else if (pid == 0) /* child */
4326 {
4327 reset_signals(); /* handle signals normally */
4328
4329 if (!show_shell_mess || (options & SHELL_EXPAND))
4330 {
4331 int fd;
4332
4333 /*
4334 * Don't want to show any message from the shell. Can't just
4335 * close stdout and stderr though, because some systems will
4336 * break if you try to write to them after that, so we must
4337 * use dup() to replace them with something else -- webb
4338 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4339 * waiting for input.
4340 */
4341 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4342 fclose(stdin);
4343 fclose(stdout);
4344 fclose(stderr);
4345
4346 /*
4347 * If any of these open()'s and dup()'s fail, we just continue
4348 * anyway. It's not fatal, and on most systems it will make
4349 * no difference at all. On a few it will cause the execvp()
4350 * to exit with a non-zero status even when the completion
4351 * could be done, which is nothing too serious. If the open()
4352 * or dup() failed we'd just do the same thing ourselves
4353 * anyway -- webb
4354 */
4355 if (fd >= 0)
4356 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004357 ignored = dup(fd); /* To replace stdin (fd 0) */
4358 ignored = dup(fd); /* To replace stdout (fd 1) */
4359 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360
4361 /* Don't need this now that we've duplicated it */
4362 close(fd);
4363 }
4364 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004365 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004367 || gui.in_use
4368# endif
4369 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 {
4371
Bram Moolenaardf177f62005-02-22 08:39:57 +00004372# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004373 /* Create our own process group, so that the child and all its
4374 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004375 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004376 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004377 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004378 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004379# if defined(SIGHUP)
4380 /* When doing "!xterm&" and 'shell' is bash: the shell
4381 * will exit and send SIGHUP to all processes in its
4382 * group, killing the just started process. Ignore SIGHUP
4383 * to avoid that. (suggested by Simon Schubert)
4384 */
4385 signal(SIGHUP, SIG_IGN);
4386# endif
4387 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004388# endif
4389# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004390 if (pty_slave_fd >= 0)
4391 {
4392 /* push stream discipline modules */
4393 if (options & SHELL_COOKED)
4394 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004396 /* Try to become controlling tty (probably doesn't work,
4397 * unless run by root) */
4398 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004400 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004403# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404 setenv("TERM", "dumb", 1);
4405 sprintf((char *)envbuf, "%ld", Rows);
4406 setenv("ROWS", (char *)envbuf, 1);
4407 sprintf((char *)envbuf, "%ld", Rows);
4408 setenv("LINES", (char *)envbuf, 1);
4409 sprintf((char *)envbuf, "%ld", Columns);
4410 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004411# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 /*
4413 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004414 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 */
4416 putenv("TERM=dumb");
4417 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4418 putenv(envbuf_Rows);
4419 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4420 putenv(envbuf_Rows);
4421 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4422 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004423# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004424
Bram Moolenaara5792f52005-11-23 21:25:05 +00004425 /*
4426 * stderr is only redirected when using the GUI, so that a
4427 * program like gpg can still access the terminal to get a
4428 * passphrase using stderr.
4429 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004430# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 if (pty_master_fd >= 0)
4432 {
4433 close(pty_master_fd); /* close master side of pty */
4434
4435 /* set up stdin/stdout/stderr for the child */
4436 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004437 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004439 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004440 if (gui.in_use)
4441 {
4442 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004443 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445
4446 close(pty_slave_fd); /* has been dupped, close it now */
4447 }
4448 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 {
4451 /* set up stdin for the child */
4452 close(fd_toshell[1]);
4453 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004454 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455 close(fd_toshell[0]);
4456
4457 /* set up stdout for the child */
4458 close(fd_fromshell[0]);
4459 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004460 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 close(fd_fromshell[1]);
4462
Bram Moolenaara5792f52005-11-23 21:25:05 +00004463# ifdef FEAT_GUI
4464 if (gui.in_use)
4465 {
4466 /* set up stderr for the child */
4467 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004468 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004469 }
4470# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 }
4472 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004473
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 /*
4475 * There is no type cast for the argv, because the type may be
4476 * different on different machines. This may cause a warning
4477 * message with strict compilers, don't worry about it.
4478 * Call _exit() instead of exit() to avoid closing the connection
4479 * to the X server (esp. with GTK, which uses atexit()).
4480 */
4481 execvp(argv[0], argv);
4482 _exit(EXEC_FAILED); /* exec failed, return failure code */
4483 }
4484 else /* parent */
4485 {
4486 /*
4487 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004488 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 */
4490 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004491 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
4493 /*
4494 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004495 * This is also used to pipe stdin/stdout to/from the external
4496 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004498 if ((options & (SHELL_READ|SHELL_WRITE))
4499# ifdef FEAT_GUI
4500 || (gui.in_use && show_shell_mess)
4501# endif
4502 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004504# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004506# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4510 int ta_len = 0; /* valid bytes in ta_buf[] */
4511 int len;
4512 int p_more_save;
4513 int old_State;
4514 int c;
4515 int toshell_fd;
4516 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004517 garray_T ga;
4518 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004519# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4520 struct timeval start_tv;
4521# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522
Bram Moolenaardf177f62005-02-22 08:39:57 +00004523# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 if (pty_master_fd >= 0)
4525 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 fromshell_fd = pty_master_fd;
4527 toshell_fd = dup(pty_master_fd);
4528 }
4529 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004530# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 {
4532 close(fd_toshell[0]);
4533 close(fd_fromshell[1]);
4534 toshell_fd = fd_toshell[1];
4535 fromshell_fd = fd_fromshell[0];
4536 }
4537
4538 /*
4539 * Write to the child if there are typed characters.
4540 * Read from the child if there are characters available.
4541 * Repeat the reading a few times if more characters are
4542 * available. Need to check for typed keys now and then, but
4543 * not too often (delays when no chars are available).
4544 * This loop is quit if no characters can be read from the pty
4545 * (WaitForChar detected special condition), or there are no
4546 * characters available and the child has exited.
4547 * Only check if the child has exited when there is no more
4548 * output. The child may exit before all the output has
4549 * been printed.
4550 *
4551 * Currently this busy loops!
4552 * This can probably dead-lock when the write blocks!
4553 */
4554 p_more_save = p_more;
4555 p_more = FALSE;
4556 old_State = State;
4557 State = EXTERNCMD; /* don't redraw at window resize */
4558
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004559 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004560 {
4561 /* Fork a process that will write the lines to the
4562 * external program. */
4563 if ((wpid = fork()) == -1)
4564 {
4565 MSG_PUTS(_("\nCannot fork\n"));
4566 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004567 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004568 {
4569 linenr_T lnum = curbuf->b_op_start.lnum;
4570 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004571 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004572 size_t l;
4573
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004574 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004575 for (;;)
4576 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004577 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004578 if (l == 0)
4579 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004580 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004581 /* NL -> NUL translation */
4582 len = write(toshell_fd, "", (size_t)1);
4583 else
4584 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004585 char_u *s = vim_strchr(lp + written, NL);
4586
Bram Moolenaar89d40322006-08-29 15:30:07 +00004587 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004588 s == NULL ? l
4589 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004590 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004591 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004592 {
4593 /* Finished a line, add a NL, unless this line
4594 * should not have one. */
4595 if (lnum != curbuf->b_op_end.lnum
4596 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004597 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004598 && (lnum !=
4599 curbuf->b_ml.ml_line_count
4600 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004601 ignored = write(toshell_fd, "\n",
4602 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004603 ++lnum;
4604 if (lnum > curbuf->b_op_end.lnum)
4605 {
4606 /* finished all the lines, close pipe */
4607 close(toshell_fd);
4608 toshell_fd = -1;
4609 break;
4610 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004611 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004612 written = 0;
4613 }
4614 else if (len > 0)
4615 written += len;
4616 }
4617 _exit(0);
4618 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004619 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004620 {
4621 close(toshell_fd);
4622 toshell_fd = -1;
4623 }
4624 }
4625
4626 if (options & SHELL_READ)
4627 ga_init2(&ga, 1, BUFLEN);
4628
4629 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004630# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4631 gettimeofday(&start_tv, NULL);
4632# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004633 for (;;)
4634 {
4635 /*
4636 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004637 * if there are any.
4638 * Don't do this if we are expanding wild cards (would eat
4639 * typeahead).
4640 * Don't do this when filtering and terminal is in cooked
4641 * mode, the shell command will handle the I/O. Avoids
4642 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004643 * Don't get characters when the child has already
4644 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004645 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004646 * while (noread_cnt > 4), avoids that ":r !ls" eats
4647 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648 */
4649 len = 0;
4650 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004651 && ((options &
4652 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4653 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004654# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004655 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004656# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004657 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004658 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004659 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004661 if (ta_len == 0)
4662 {
4663 /* Get extra characters when we don't have any.
4664 * Reset the counter and timer. */
4665 noread_cnt = 0;
4666# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4667 gettimeofday(&start_tv, NULL);
4668# endif
4669 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4670 }
4671 if (ta_len > 0 || len > 0)
4672 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673 /*
4674 * For pipes:
4675 * Check for CTRL-C: send interrupt signal to child.
4676 * Check for CTRL-D: EOF, close pipe to child.
4677 */
4678 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4679 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004680# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 /*
4682 * Send SIGINT to the child's group or all
4683 * processes in our group.
4684 */
4685 if (ta_buf[ta_len] == Ctrl_C
4686 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004687 {
4688# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004690# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004693 if (wpid > 0)
4694 kill(wpid, SIGINT);
4695 }
4696# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 if (pty_master_fd < 0 && toshell_fd >= 0
4698 && ta_buf[ta_len] == Ctrl_D)
4699 {
4700 close(toshell_fd);
4701 toshell_fd = -1;
4702 }
4703 }
4704
4705 /* replace K_BS by <BS> and K_DEL by <DEL> */
4706 for (i = ta_len; i < ta_len + len; ++i)
4707 {
4708 if (ta_buf[i] == CSI && len - i > 2)
4709 {
4710 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4711 if (c == K_DEL || c == K_KDEL || c == K_BS)
4712 {
4713 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4714 (size_t)(len - i - 2));
4715 if (c == K_DEL || c == K_KDEL)
4716 ta_buf[i] = DEL;
4717 else
4718 ta_buf[i] = Ctrl_H;
4719 len -= 2;
4720 }
4721 }
4722 else if (ta_buf[i] == '\r')
4723 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004724# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004726 i += (*mb_ptr2len_len)(ta_buf + i,
4727 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 }
4730
4731 /*
4732 * For pipes: echo the typed characters.
4733 * For a pty this does not seem to work.
4734 */
4735 if (pty_master_fd < 0)
4736 {
4737 for (i = ta_len; i < ta_len + len; ++i)
4738 {
4739 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4740 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004741# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 else if (has_mbyte)
4743 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004744 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745
4746 msg_outtrans_len(ta_buf + i, l);
4747 i += l - 1;
4748 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750 else
4751 msg_outtrans_len(ta_buf + i, 1);
4752 }
4753 windgoto(msg_row, msg_col);
4754 out_flush();
4755 }
4756
4757 ta_len += len;
4758
4759 /*
4760 * Write the characters to the child, unless EOF has
4761 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004762 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004763 * When writing buffer lines, drop the typed
4764 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004766 if (options & SHELL_WRITE)
4767 ta_len = 0;
4768 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 {
4770 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4771 if (len > 0)
4772 {
4773 ta_len -= len;
4774 mch_memmove(ta_buf, ta_buf + len, ta_len);
4775 }
4776 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 }
4779
Bram Moolenaardf177f62005-02-22 08:39:57 +00004780 if (got_int)
4781 {
4782 /* CTRL-C sends a signal to the child, we ignore it
4783 * ourselves */
4784# ifdef HAVE_SETSID
4785 kill(-pid, SIGINT);
4786# else
4787 kill(0, SIGINT);
4788# endif
4789 if (wpid > 0)
4790 kill(wpid, SIGINT);
4791 got_int = FALSE;
4792 }
4793
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 /*
4795 * Check if the child has any characters to be printed.
4796 * Read them and write them to our window. Repeat this as
4797 * long as there is something to do, avoid the 10ms wait
4798 * for mch_inchar(), or sending typeahead characters to
4799 * the external process.
4800 * TODO: This should handle escape sequences, compatible
4801 * to some terminal (vt52?).
4802 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004803 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4805 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004806 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004807# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004809# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004811# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 );
4813 if (len <= 0) /* end of file or error */
4814 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004815
4816 noread_cnt = 0;
4817 if (options & SHELL_READ)
4818 {
4819 /* Do NUL -> NL translation, append NL separated
4820 * lines to the current buffer. */
4821 for (i = 0; i < len; ++i)
4822 {
4823 if (buffer[i] == NL)
4824 append_ga_line(&ga);
4825 else if (buffer[i] == NUL)
4826 ga_append(&ga, NL);
4827 else
4828 ga_append(&ga, buffer[i]);
4829 }
4830 }
4831# ifdef FEAT_MBYTE
4832 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 {
4834 int l;
4835
Bram Moolenaardf177f62005-02-22 08:39:57 +00004836 len += buffer_off;
4837 buffer[len] = NUL;
4838
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839 /* Check if the last character in buffer[] is
4840 * incomplete, keep these bytes for the next
4841 * round. */
4842 for (p = buffer; p < buffer + len; p += l)
4843 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004844 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845 if (l == 0)
4846 l = 1; /* NUL byte? */
4847 else if (MB_BYTE2LEN(*p) != l)
4848 break;
4849 }
4850 if (p == buffer) /* no complete character */
4851 {
4852 /* avoid getting stuck at an illegal byte */
4853 if (len >= 12)
4854 ++p;
4855 else
4856 {
4857 buffer_off = len;
4858 continue;
4859 }
4860 }
4861 c = *p;
4862 *p = NUL;
4863 msg_puts(buffer);
4864 if (p < buffer + len)
4865 {
4866 *p = c;
4867 buffer_off = (buffer + len) - p;
4868 mch_memmove(buffer, p, buffer_off);
4869 continue;
4870 }
4871 buffer_off = 0;
4872 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004873# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 {
4876 buffer[len] = NUL;
4877 msg_puts(buffer);
4878 }
4879
4880 windgoto(msg_row, msg_col);
4881 cursor_on();
4882 out_flush();
4883 if (got_int)
4884 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004885
4886# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4887 {
4888 struct timeval now_tv;
4889 long msec;
4890
4891 /* Avoid that we keep looping here without
4892 * checking for a CTRL-C for a long time. Don't
4893 * break out too often to avoid losing typeahead. */
4894 gettimeofday(&now_tv, NULL);
4895 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4896 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4897 if (msec > 2000)
4898 {
4899 noread_cnt = 5;
4900 break;
4901 }
4902 }
4903# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 }
4905
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004906 /* If we already detected the child has finished break the
4907 * loop now. */
4908 if (wait_pid == pid)
4909 break;
4910
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 /*
4912 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004913 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004915# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004916 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004917# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004919# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4921 || (wait_pid == pid && WIFEXITED(status)))
4922 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004923 /* Don't break the loop yet, try reading more
4924 * characters from "fromshell_fd" first. When using
4925 * pipes there might still be something to read and
4926 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004929 else
4930 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004931
Bram Moolenaar95a51352013-03-21 22:53:50 +01004932# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004933 /* Handle any X events, e.g. serving the clipboard. */
4934 clip_update();
4935# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 }
4937finished:
4938 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004939 if (options & SHELL_READ)
4940 {
4941 if (ga.ga_len > 0)
4942 {
4943 append_ga_line(&ga);
4944 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004945 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004946 }
4947 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004948 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004949 ga_clear(&ga);
4950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 /*
4953 * Give all typeahead that wasn't used back to ui_inchar().
4954 */
4955 if (ta_len)
4956 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 State = old_State;
4958 if (toshell_fd >= 0)
4959 close(toshell_fd);
4960 close(fromshell_fd);
4961 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004962# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004963 else
4964 {
4965 /*
4966 * Similar to the loop above, but only handle X events, no
4967 * I/O.
4968 */
4969 for (;;)
4970 {
4971 if (got_int)
4972 {
4973 /* CTRL-C sends a signal to the child, we ignore it
4974 * ourselves */
4975# ifdef HAVE_SETSID
4976 kill(-pid, SIGINT);
4977# else
4978 kill(0, SIGINT);
4979# endif
4980 got_int = FALSE;
4981 }
4982# ifdef __NeXT__
4983 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4984# else
4985 wait_pid = waitpid(pid, &status, WNOHANG);
4986# endif
4987 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4988 || (wait_pid == pid && WIFEXITED(status)))
4989 {
4990 wait_pid = pid;
4991 break;
4992 }
4993
4994 /* Handle any X events, e.g. serving the clipboard. */
4995 clip_update();
4996
4997 mch_delay(10L, TRUE);
4998 }
4999 }
5000# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001
5002 /*
5003 * Wait until our child has exited.
5004 * Ignore wait() returning pids of other children and returning
5005 * because of some signal like SIGWINCH.
5006 * Don't wait if wait_pid was already set above, indicating the
5007 * child already exited.
5008 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005009 if (wait_pid != pid)
5010 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011
Bram Moolenaar624891f2010-10-13 16:22:09 +02005012# ifdef FEAT_GUI
5013 /* Close slave side of pty. Only do this after the child has
5014 * exited, otherwise the child may hang when it tries to write on
5015 * the pty. */
5016 if (pty_master_fd >= 0)
5017 close(pty_slave_fd);
5018# endif
5019
Bram Moolenaardf177f62005-02-22 08:39:57 +00005020 /* Make sure the child that writes to the external program is
5021 * dead. */
5022 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005023 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005024 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005025 wait4pid(wpid, NULL);
5026 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005027
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 /*
5029 * Set to raw mode right now, otherwise a CTRL-C after
5030 * catch_signals() will kill Vim.
5031 */
5032 if (tmode == TMODE_RAW)
5033 settmode(TMODE_RAW);
5034 did_settmode = TRUE;
5035 set_signals();
5036
5037 if (WIFEXITED(status))
5038 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005039 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005041 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 {
5043 if (retval == EXEC_FAILED)
5044 {
5045 MSG_PUTS(_("\nCannot execute shell "));
5046 msg_outtrans(p_sh);
5047 msg_putchar('\n');
5048 }
5049 else if (!(options & SHELL_SILENT))
5050 {
5051 MSG_PUTS(_("\nshell returned "));
5052 msg_outnum((long)retval);
5053 msg_putchar('\n');
5054 }
5055 }
5056 }
5057 else
5058 MSG_PUTS(_("\nCommand terminated\n"));
5059 }
5060 }
5061 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005062 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063
5064error:
5065 if (!did_settmode)
5066 if (tmode == TMODE_RAW)
5067 settmode(TMODE_RAW); /* set to raw mode */
5068# ifdef FEAT_TITLE
5069 resettitle();
5070# endif
5071 vim_free(newcmd);
5072
5073 return retval;
5074
5075#endif /* USE_SYSTEM */
5076}
5077
5078/*
5079 * Check for CTRL-C typed by reading all available characters.
5080 * In cooked mode we should get SIGINT, no need to check.
5081 */
5082 void
5083mch_breakcheck()
5084{
5085 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
5086 fill_input_buf(FALSE);
5087}
5088
5089/*
5090 * Wait "msec" msec until a character is available from the keyboard or from
5091 * inbuf[]. msec == -1 will block forever.
5092 * When a GUI is being used, this will never get called -- webb
5093 */
5094 static int
5095WaitForChar(msec)
5096 long msec;
5097{
5098#ifdef FEAT_MOUSE_GPM
5099 int gpm_process_wanted;
5100#endif
5101#ifdef FEAT_XCLIPBOARD
5102 int rest;
5103#endif
5104 int avail;
5105
5106 if (input_available()) /* something in inbuf[] */
5107 return 1;
5108
5109#if defined(FEAT_MOUSE_DEC)
5110 /* May need to query the mouse position. */
5111 if (WantQueryMouse)
5112 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005113 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005114 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5115 }
5116#endif
5117
5118 /*
5119 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5120 * events. This is a bit complicated, because they might both be defined.
5121 */
5122#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5123# ifdef FEAT_XCLIPBOARD
5124 rest = 0;
5125 if (do_xterm_trace())
5126 rest = msec;
5127# endif
5128 do
5129 {
5130# ifdef FEAT_XCLIPBOARD
5131 if (rest != 0)
5132 {
5133 msec = XT_TRACE_DELAY;
5134 if (rest >= 0 && rest < XT_TRACE_DELAY)
5135 msec = rest;
5136 if (rest >= 0)
5137 rest -= msec;
5138 }
5139# endif
5140# ifdef FEAT_MOUSE_GPM
5141 gpm_process_wanted = 0;
5142 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5143# else
5144 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5145# endif
5146 if (!avail)
5147 {
5148 if (input_available())
5149 return 1;
5150# ifdef FEAT_XCLIPBOARD
5151 if (rest == 0 || !do_xterm_trace())
5152# endif
5153 break;
5154 }
5155 }
5156 while (FALSE
5157# ifdef FEAT_MOUSE_GPM
5158 || (gpm_process_wanted && mch_gpm_process() == 0)
5159# endif
5160# ifdef FEAT_XCLIPBOARD
5161 || (!avail && rest != 0)
5162# endif
5163 );
5164
5165#else
5166 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5167#endif
5168 return avail;
5169}
5170
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005171#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172/*
5173 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005174 * "msec" == 0 will check for characters once.
5175 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 * When a GUI is being used, this will not be used for input -- webb
5177 * Returns also, when a request from Sniff is waiting -- toni.
5178 * Or when a Linux GPM mouse event is waiting.
5179 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180#if defined(__BEOS__)
5181 int
5182#else
5183 static int
5184#endif
5185RealWaitForChar(fd, msec, check_for_gpm)
5186 int fd;
5187 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005188 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189{
5190 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005191#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005192 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005193#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005194#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 static int busy = FALSE;
5196
5197 /* May retry getting characters after an event was handled. */
5198# define MAY_LOOP
5199
5200# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5201 /* Remember at what time we started, so that we know how much longer we
5202 * should wait after being interrupted. */
5203# define USE_START_TV
5204 struct timeval start_tv;
5205
5206 if (msec > 0 && (
5207# ifdef FEAT_XCLIPBOARD
5208 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005209# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 ||
5211# endif
5212# endif
5213# ifdef USE_XSMP
5214 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005215# ifdef FEAT_MZSCHEME
5216 ||
5217# endif
5218# endif
5219# ifdef FEAT_MZSCHEME
5220 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221# endif
5222 ))
5223 gettimeofday(&start_tv, NULL);
5224# endif
5225
5226 /* Handle being called recursively. This may happen for the session
5227 * manager stuff, it may save the file, which does a breakcheck. */
5228 if (busy)
5229 return 0;
5230#endif
5231
5232#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005233 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234#endif
5235 {
5236#ifdef MAY_LOOP
5237 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005238# ifdef FEAT_MZSCHEME
5239 int mzquantum_used = FALSE;
5240# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241#endif
5242#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005243 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244 int nfd;
5245# ifdef FEAT_XCLIPBOARD
5246 int xterm_idx = -1;
5247# endif
5248# ifdef FEAT_MOUSE_GPM
5249 int gpm_idx = -1;
5250# endif
5251# ifdef USE_XSMP
5252 int xsmp_idx = -1;
5253# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005254# ifdef FEAT_NETBEANS_INTG
5255 int nb_idx = -1;
5256# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005257 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005259# ifdef FEAT_MZSCHEME
5260 mzvim_check_threads();
5261 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5262 {
5263 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5264 mzquantum_used = TRUE;
5265 }
5266# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267 fds[0].fd = fd;
5268 fds[0].events = POLLIN;
5269 nfd = 1;
5270
5271# ifdef FEAT_SNIFF
5272# define SNIFF_IDX 1
5273 if (want_sniff_request)
5274 {
5275 fds[SNIFF_IDX].fd = fd_from_sniff;
5276 fds[SNIFF_IDX].events = POLLIN;
5277 nfd++;
5278 }
5279# endif
5280# ifdef FEAT_XCLIPBOARD
5281 if (xterm_Shell != (Widget)0)
5282 {
5283 xterm_idx = nfd;
5284 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5285 fds[nfd].events = POLLIN;
5286 nfd++;
5287 }
5288# endif
5289# ifdef FEAT_MOUSE_GPM
5290 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5291 {
5292 gpm_idx = nfd;
5293 fds[nfd].fd = gpm_fd;
5294 fds[nfd].events = POLLIN;
5295 nfd++;
5296 }
5297# endif
5298# ifdef USE_XSMP
5299 if (xsmp_icefd != -1)
5300 {
5301 xsmp_idx = nfd;
5302 fds[nfd].fd = xsmp_icefd;
5303 fds[nfd].events = POLLIN;
5304 nfd++;
5305 }
5306# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005307#ifdef FEAT_NETBEANS_INTG
5308 if (nb_fd != -1)
5309 {
5310 nb_idx = nfd;
5311 fds[nfd].fd = nb_fd;
5312 fds[nfd].events = POLLIN;
5313 nfd++;
5314 }
5315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005316
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005317 ret = poll(fds, nfd, towait);
5318# ifdef FEAT_MZSCHEME
5319 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005320 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005321 finished = FALSE;
5322# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323
5324# ifdef FEAT_SNIFF
5325 if (ret < 0)
5326 sniff_disconnect(1);
5327 else if (want_sniff_request)
5328 {
5329 if (fds[SNIFF_IDX].revents & POLLHUP)
5330 sniff_disconnect(1);
5331 if (fds[SNIFF_IDX].revents & POLLIN)
5332 sniff_request_waiting = 1;
5333 }
5334# endif
5335# ifdef FEAT_XCLIPBOARD
5336 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5337 {
5338 xterm_update(); /* Maybe we should hand out clipboard */
5339 if (--ret == 0 && !input_available())
5340 /* Try again */
5341 finished = FALSE;
5342 }
5343# endif
5344# ifdef FEAT_MOUSE_GPM
5345 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5346 {
5347 *check_for_gpm = 1;
5348 }
5349# endif
5350# ifdef USE_XSMP
5351 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5352 {
5353 if (fds[xsmp_idx].revents & POLLIN)
5354 {
5355 busy = TRUE;
5356 xsmp_handle_requests();
5357 busy = FALSE;
5358 }
5359 else if (fds[xsmp_idx].revents & POLLHUP)
5360 {
5361 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005362 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 xsmp_close();
5364 }
5365 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005366 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367 }
5368# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005369#ifdef FEAT_NETBEANS_INTG
5370 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5371 {
5372 netbeans_read();
5373 --ret;
5374 }
5375#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376
5377
5378#else /* HAVE_SELECT */
5379
5380 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005381 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005382 fd_set rfds, efds;
5383 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005384 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005386# ifdef FEAT_MZSCHEME
5387 mzvim_check_threads();
5388 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5389 {
5390 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5391 mzquantum_used = TRUE;
5392 }
5393# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005394# ifdef __EMX__
5395 /* don't check for incoming chars if not in raw mode, because select()
5396 * always returns TRUE then (in some version of emx.dll) */
5397 if (curr_tmode != TMODE_RAW)
5398 return 0;
5399# endif
5400
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005401 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005403 tv.tv_sec = towait / 1000;
5404 tv.tv_usec = (towait % 1000) * (1000000/1000);
5405 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005407 else
5408 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409
5410 /*
5411 * Select on ready for reading and exceptional condition (end of file).
5412 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005413select_eintr:
5414 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 FD_ZERO(&efds);
5416 FD_SET(fd, &rfds);
5417# if !defined(__QNX__) && !defined(__CYGWIN32__)
5418 /* For QNX select() always returns 1 if this is set. Why? */
5419 FD_SET(fd, &efds);
5420# endif
5421 maxfd = fd;
5422
5423# ifdef FEAT_SNIFF
5424 if (want_sniff_request)
5425 {
5426 FD_SET(fd_from_sniff, &rfds);
5427 FD_SET(fd_from_sniff, &efds);
5428 if (maxfd < fd_from_sniff)
5429 maxfd = fd_from_sniff;
5430 }
5431# endif
5432# ifdef FEAT_XCLIPBOARD
5433 if (xterm_Shell != (Widget)0)
5434 {
5435 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5436 if (maxfd < ConnectionNumber(xterm_dpy))
5437 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005438
5439 /* An event may have already been read but not handled. In
5440 * particulary, XFlush may cause this. */
5441 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 }
5443# endif
5444# ifdef FEAT_MOUSE_GPM
5445 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5446 {
5447 FD_SET(gpm_fd, &rfds);
5448 FD_SET(gpm_fd, &efds);
5449 if (maxfd < gpm_fd)
5450 maxfd = gpm_fd;
5451 }
5452# endif
5453# ifdef USE_XSMP
5454 if (xsmp_icefd != -1)
5455 {
5456 FD_SET(xsmp_icefd, &rfds);
5457 FD_SET(xsmp_icefd, &efds);
5458 if (maxfd < xsmp_icefd)
5459 maxfd = xsmp_icefd;
5460 }
5461# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005462# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005463 if (nb_fd != -1)
5464 {
5465 FD_SET(nb_fd, &rfds);
5466 if (maxfd < nb_fd)
5467 maxfd = nb_fd;
5468 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005469# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005470
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005471 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005472# ifdef EINTR
5473 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005474 {
5475 /* Check whether window has been resized, EINTR may be caused by
5476 * SIGWINCH. */
5477 if (do_resize)
5478 handle_resize();
5479
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005480 /* Interrupted by a signal, need to try again. We ignore msec
5481 * here, because we do want to check even after a timeout if
5482 * characters are available. Needed for reading output of an
5483 * external command after the process has finished. */
5484 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005485 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005486# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005487# ifdef __TANDEM
5488 if (ret == -1 && errno == ENOTSUP)
5489 {
5490 FD_ZERO(&rfds);
5491 FD_ZERO(&efds);
5492 ret = 0;
5493 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005494# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005495# ifdef FEAT_MZSCHEME
5496 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005497 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005498 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499# endif
5500
5501# ifdef FEAT_SNIFF
5502 if (ret < 0 )
5503 sniff_disconnect(1);
5504 else if (ret > 0 && want_sniff_request)
5505 {
5506 if (FD_ISSET(fd_from_sniff, &efds))
5507 sniff_disconnect(1);
5508 if (FD_ISSET(fd_from_sniff, &rfds))
5509 sniff_request_waiting = 1;
5510 }
5511# endif
5512# ifdef FEAT_XCLIPBOARD
5513 if (ret > 0 && xterm_Shell != (Widget)0
5514 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5515 {
5516 xterm_update(); /* Maybe we should hand out clipboard */
5517 /* continue looping when we only got the X event and the input
5518 * buffer is empty */
5519 if (--ret == 0 && !input_available())
5520 {
5521 /* Try again */
5522 finished = FALSE;
5523 }
5524 }
5525# endif
5526# ifdef FEAT_MOUSE_GPM
5527 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5528 {
5529 if (FD_ISSET(gpm_fd, &efds))
5530 gpm_close();
5531 else if (FD_ISSET(gpm_fd, &rfds))
5532 *check_for_gpm = 1;
5533 }
5534# endif
5535# ifdef USE_XSMP
5536 if (ret > 0 && xsmp_icefd != -1)
5537 {
5538 if (FD_ISSET(xsmp_icefd, &efds))
5539 {
5540 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005541 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 xsmp_close();
5543 if (--ret == 0)
5544 finished = FALSE; /* keep going if event was only one */
5545 }
5546 else if (FD_ISSET(xsmp_icefd, &rfds))
5547 {
5548 busy = TRUE;
5549 xsmp_handle_requests();
5550 busy = FALSE;
5551 if (--ret == 0)
5552 finished = FALSE; /* keep going if event was only one */
5553 }
5554 }
5555# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005556#ifdef FEAT_NETBEANS_INTG
5557 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5558 {
5559 netbeans_read();
5560 --ret;
5561 }
5562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563
5564#endif /* HAVE_SELECT */
5565
5566#ifdef MAY_LOOP
5567 if (finished || msec == 0)
5568 break;
5569
5570 /* We're going to loop around again, find out for how long */
5571 if (msec > 0)
5572 {
5573# ifdef USE_START_TV
5574 struct timeval mtv;
5575
5576 /* Compute remaining wait time. */
5577 gettimeofday(&mtv, NULL);
5578 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5579 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5580# else
5581 /* Guess we got interrupted halfway. */
5582 msec = msec / 2;
5583# endif
5584 if (msec <= 0)
5585 break; /* waited long enough */
5586 }
5587#endif
5588 }
5589
5590 return (ret > 0);
5591}
5592
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005595 * Expand a path into all matching files and/or directories. Handles "*",
5596 * "?", "[a-z]", "**", etc.
5597 * "path" has backslashes before chars that are not to be expanded.
5598 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599 */
5600 int
5601mch_expandpath(gap, path, flags)
5602 garray_T *gap;
5603 char_u *path;
5604 int flags; /* EW_* flags */
5605{
Bram Moolenaar02743632005-07-25 20:42:36 +00005606 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607}
5608#endif
5609
5610/*
5611 * mch_expand_wildcards() - this code does wild-card pattern matching using
5612 * the shell
5613 *
5614 * return OK for success, FAIL for error (you may lose some memory) and put
5615 * an error message in *file.
5616 *
5617 * num_pat is number of input patterns
5618 * pat is array of pointers to input patterns
5619 * num_file is pointer to number of matched file names
5620 * file is pointer to array of pointers to matched file names
5621 */
5622
5623#ifndef SEEK_SET
5624# define SEEK_SET 0
5625#endif
5626#ifndef SEEK_END
5627# define SEEK_END 2
5628#endif
5629
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005630#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005631
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 int
5633mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5634 int num_pat;
5635 char_u **pat;
5636 int *num_file;
5637 char_u ***file;
5638 int flags; /* EW_* flags */
5639{
5640 int i;
5641 size_t len;
5642 char_u *p;
5643 int dir;
5644#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005645 /*
5646 * This is the OS/2 implementation.
5647 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648# define EXPL_ALLOC_INC 16
5649 char_u **expl_files;
5650 size_t files_alloced, files_free;
5651 char_u *buf;
5652 int has_wildcard;
5653
5654 *num_file = 0; /* default: no files found */
5655 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5656 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5657 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5658 if (*file == NULL)
5659 return FAIL;
5660
5661 for (; num_pat > 0; num_pat--, pat++)
5662 {
5663 expl_files = NULL;
5664 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5665 /* expand environment var or home dir */
5666 buf = expand_env_save(*pat);
5667 else
5668 buf = vim_strsave(*pat);
5669 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005670 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 if (has_wildcard) /* yes, so expand them */
5672 expl_files = (char_u **)_fnexplode(buf);
5673
5674 /*
5675 * return value of buf if no wildcards left,
5676 * OR if no match AND EW_NOTFOUND is set.
5677 */
5678 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5679 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5680 { /* simply save the current contents of *buf */
5681 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5682 if (expl_files != NULL)
5683 {
5684 expl_files[0] = vim_strsave(buf);
5685 expl_files[1] = NULL;
5686 }
5687 }
5688 vim_free(buf);
5689
5690 /*
5691 * Count number of names resulting from expansion,
5692 * At the same time add a backslash to the end of names that happen to
5693 * be directories, and replace slashes with backslashes.
5694 */
5695 if (expl_files)
5696 {
5697 for (i = 0; (p = expl_files[i]) != NULL; i++)
5698 {
5699 dir = mch_isdir(p);
5700 /* If we don't want dirs and this is one, skip it */
5701 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5702 continue;
5703
Bram Moolenaara2031822006-03-07 22:29:51 +00005704 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02005705 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p, NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00005706 continue;
5707
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708 if (--files_free == 0)
5709 {
5710 /* need more room in table of pointers */
5711 files_alloced += EXPL_ALLOC_INC;
5712 *file = (char_u **)vim_realloc(*file,
5713 sizeof(char_u **) * files_alloced);
5714 if (*file == NULL)
5715 {
5716 EMSG(_(e_outofmem));
5717 *num_file = 0;
5718 return FAIL;
5719 }
5720 files_free = EXPL_ALLOC_INC;
5721 }
5722 slash_adjust(p);
5723 if (dir)
5724 {
5725 /* For a directory we add a '/', unless it's already
5726 * there. */
5727 len = STRLEN(p);
5728 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5729 {
5730 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005731 if (!after_pathsep((*file)[*num_file],
5732 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 {
5734 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005735 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005736 }
5737 }
5738 }
5739 else
5740 {
5741 (*file)[*num_file] = vim_strsave(p);
5742 }
5743
5744 /*
5745 * Error message already given by either alloc or vim_strsave.
5746 * Should return FAIL, but returning OK works also.
5747 */
5748 if ((*file)[*num_file] == NULL)
5749 break;
5750 (*num_file)++;
5751 }
5752 _fnexplodefree((char **)expl_files);
5753 }
5754 }
5755 return OK;
5756
5757#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005758 /*
5759 * This is the non-OS/2 implementation (really Unix).
5760 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 int j;
5762 char_u *tempname;
5763 char_u *command;
5764 FILE *fd;
5765 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005766#define STYLE_ECHO 0 /* use "echo", the default */
5767#define STYLE_GLOB 1 /* use "glob", for csh */
5768#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5769#define STYLE_PRINT 3 /* use "print -N", for zsh */
5770#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5771 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 int shell_style = STYLE_ECHO;
5773 int check_spaces;
5774 static int did_find_nul = FALSE;
5775 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005776 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005777 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778
5779 *num_file = 0; /* default: no files found */
5780 *file = NULL;
5781
5782 /*
5783 * If there are no wildcards, just copy the names to allocated memory.
5784 * Saves a lot of time, because we don't have to start a new shell.
5785 */
5786 if (!have_wildcard(num_pat, pat))
5787 return save_patterns(num_pat, pat, num_file, file);
5788
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005789# ifdef HAVE_SANDBOX
5790 /* Don't allow any shell command in the sandbox. */
5791 if (sandbox != 0 && check_secure())
5792 return FAIL;
5793# endif
5794
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 /*
5796 * Don't allow the use of backticks in secure and restricted mode.
5797 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005798 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 for (i = 0; i < num_pat; ++i)
5800 if (vim_strchr(pat[i], '`') != NULL
5801 && (check_restricted() || check_secure()))
5802 return FAIL;
5803
5804 /*
5805 * get a name for the temp file
5806 */
5807 if ((tempname = vim_tempname('o')) == NULL)
5808 {
5809 EMSG(_(e_notmp));
5810 return FAIL;
5811 }
5812
5813 /*
5814 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005815 * file.
5816 * STYLE_BT: NL separated
5817 * If expanding `cmd` execute it directly.
5818 * STYLE_GLOB: NUL separated
5819 * If we use *csh, "glob" will work better than "echo".
5820 * STYLE_PRINT: NL or NUL separated
5821 * If we use *zsh, "print -N" will work better than "glob".
5822 * STYLE_VIMGLOB: NL separated
5823 * If we use *sh*, we define "vimglob()".
5824 * STYLE_ECHO: space separated.
5825 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826 */
5827 if (num_pat == 1 && *pat[0] == '`'
5828 && (len = STRLEN(pat[0])) > 2
5829 && *(pat[0] + len - 1) == '`')
5830 shell_style = STYLE_BT;
5831 else if ((len = STRLEN(p_sh)) >= 3)
5832 {
5833 if (STRCMP(p_sh + len - 3, "csh") == 0)
5834 shell_style = STYLE_GLOB;
5835 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5836 shell_style = STYLE_PRINT;
5837 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005838 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5839 "sh") != NULL)
5840 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841
Bram Moolenaarc7247912008-01-13 12:54:11 +00005842 /* Compute the length of the command. We need 2 extra bytes: for the
5843 * optional '&' and for the NUL.
5844 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005846 if (shell_style == STYLE_VIMGLOB)
5847 len += STRLEN(sh_vimglob_func);
5848
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005849 for (i = 0; i < num_pat; ++i)
5850 {
5851 /* Count the length of the patterns in the same way as they are put in
5852 * "command" below. */
5853#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005855#else
5856 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005857 for (j = 0; pat[i][j] != NUL; ++j)
5858 {
5859 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5860 ++len; /* may add a backslash */
5861 ++len;
5862 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005863#endif
5864 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865 command = alloc(len);
5866 if (command == NULL)
5867 {
5868 /* out of memory */
5869 vim_free(tempname);
5870 return FAIL;
5871 }
5872
5873 /*
5874 * Build the shell command:
5875 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5876 * recognizes this).
5877 * - Add the shell command to print the expanded names.
5878 * - Add the temp file name.
5879 * - Add the file name patterns.
5880 */
5881 if (shell_style == STYLE_BT)
5882 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005883 /* change `command; command& ` to (command; command ) */
5884 STRCPY(command, "(");
5885 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005886 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005887 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888 while (p > command && vim_iswhite(*p))
5889 --p;
5890 if (*p == '&') /* remove trailing '&' */
5891 {
5892 ampersent = TRUE;
5893 *p = ' ';
5894 }
5895 STRCAT(command, ">");
5896 }
5897 else
5898 {
5899 if (flags & EW_NOTFOUND)
5900 STRCPY(command, "set nonomatch; ");
5901 else
5902 STRCPY(command, "unset nonomatch; ");
5903 if (shell_style == STYLE_GLOB)
5904 STRCAT(command, "glob >");
5905 else if (shell_style == STYLE_PRINT)
5906 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005907 else if (shell_style == STYLE_VIMGLOB)
5908 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 else
5910 STRCAT(command, "echo >");
5911 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005912
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005914
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 if (shell_style != STYLE_BT)
5916 for (i = 0; i < num_pat; ++i)
5917 {
5918 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005919 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005920 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921#ifdef USE_SYSTEM
5922 STRCAT(command, " \"");
5923 STRCAT(command, pat[i]);
5924 STRCAT(command, "\"");
5925#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005926 int intick = FALSE;
5927
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 p = command + STRLEN(command);
5929 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005930 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005931 {
5932 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005933 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005934 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5935 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005936 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005937 * backslash inside backticks, before a special character
5938 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005939 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005940 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5941 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005942 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005943 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005944 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02005945 else if (!intick
5946 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
5947 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005948 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02005949 * when inside ``. And not for $var when EW_KEEPDOLLAR is
5950 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005951 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005952
5953 /* Copy one character. */
5954 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 *p = NUL;
5957#endif
5958 }
5959 if (flags & EW_SILENT)
5960 show_shell_mess = FALSE;
5961 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005962 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963
5964 /*
5965 * Using zsh -G: If a pattern has no matches, it is just deleted from
5966 * the argument list, otherwise zsh gives an error message and doesn't
5967 * expand any other pattern.
5968 */
5969 if (shell_style == STYLE_PRINT)
5970 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5971
5972 /*
5973 * If we use -f then shell variables set in .cshrc won't get expanded.
5974 * vi can do it, so we will too, but it is only necessary if there is a "$"
5975 * in one of the patterns, otherwise we can still use the fast option.
5976 */
5977 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5978 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5979
5980 /*
5981 * execute the shell command
5982 */
5983 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5984
5985 /* When running in the background, give it some time to create the temp
5986 * file, but don't wait for it to finish. */
5987 if (ampersent)
5988 mch_delay(10L, TRUE);
5989
5990 extra_shell_arg = NULL; /* cleanup */
5991 show_shell_mess = TRUE;
5992 vim_free(command);
5993
Bram Moolenaarc7247912008-01-13 12:54:11 +00005994 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995 {
5996 mch_remove(tempname);
5997 vim_free(tempname);
5998 /*
5999 * With interactive completion, the error message is not printed.
6000 * However with USE_SYSTEM, I don't know how to turn off error messages
6001 * from the shell, so screen may still get messed up -- webb.
6002 */
6003#ifndef USE_SYSTEM
6004 if (!(flags & EW_SILENT))
6005#endif
6006 {
6007 redraw_later_clear(); /* probably messed up screen */
6008 msg_putchar('\n'); /* clear bottom line quickly */
6009 cmdline_row = Rows - 1; /* continue on last line */
6010#ifdef USE_SYSTEM
6011 if (!(flags & EW_SILENT))
6012#endif
6013 {
6014 MSG(_(e_wildexpand));
6015 msg_start(); /* don't overwrite this message */
6016 }
6017 }
6018 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6019 * EW_NOTFOUND is given */
6020 if (shell_style == STYLE_BT)
6021 return FAIL;
6022 goto notfound;
6023 }
6024
6025 /*
6026 * read the names from the file into memory
6027 */
6028 fd = fopen((char *)tempname, READBIN);
6029 if (fd == NULL)
6030 {
6031 /* Something went wrong, perhaps a file name with a special char. */
6032 if (!(flags & EW_SILENT))
6033 {
6034 MSG(_(e_wildexpand));
6035 msg_start(); /* don't overwrite this message */
6036 }
6037 vim_free(tempname);
6038 goto notfound;
6039 }
6040 fseek(fd, 0L, SEEK_END);
6041 len = ftell(fd); /* get size of temp file */
6042 fseek(fd, 0L, SEEK_SET);
6043 buffer = alloc(len + 1);
6044 if (buffer == NULL)
6045 {
6046 /* out of memory */
6047 mch_remove(tempname);
6048 vim_free(tempname);
6049 fclose(fd);
6050 return FAIL;
6051 }
6052 i = fread((char *)buffer, 1, len, fd);
6053 fclose(fd);
6054 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006055 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006056 {
6057 /* unexpected read error */
6058 EMSG2(_(e_notread), tempname);
6059 vim_free(tempname);
6060 vim_free(buffer);
6061 return FAIL;
6062 }
6063 vim_free(tempname);
6064
Bram Moolenaarc7247912008-01-13 12:54:11 +00006065# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6067 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006068 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6070 *p++ = buffer[i];
6071 len = p - buffer;
6072# endif
6073
6074
6075 /* file names are separated with Space */
6076 if (shell_style == STYLE_ECHO)
6077 {
6078 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6079 p = buffer;
6080 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6081 {
6082 while (*p != ' ' && *p != '\n')
6083 ++p;
6084 p = skipwhite(p); /* skip to next entry */
6085 }
6086 }
6087 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006088 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089 {
6090 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6091 p = buffer;
6092 for (i = 0; *p != NUL; ++i) /* count number of entries */
6093 {
6094 while (*p != '\n' && *p != NUL)
6095 ++p;
6096 if (*p != NUL)
6097 ++p;
6098 p = skipwhite(p); /* skip leading white space */
6099 }
6100 }
6101 /* file names are separated with NUL */
6102 else
6103 {
6104 /*
6105 * Some versions of zsh use spaces instead of NULs to separate
6106 * results. Only do this when there is no NUL before the end of the
6107 * buffer, otherwise we would never be able to use file names with
6108 * embedded spaces when zsh does use NULs.
6109 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6110 * don't check for spaces again.
6111 */
6112 check_spaces = FALSE;
6113 if (shell_style == STYLE_PRINT && !did_find_nul)
6114 {
6115 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006116 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006117 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 did_find_nul = TRUE;
6119 else
6120 check_spaces = TRUE;
6121 }
6122
6123 /*
6124 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6125 * already is one, for STYLE_GLOB it needs to be added.
6126 */
6127 if (len && buffer[len - 1] == NUL)
6128 --len;
6129 else
6130 buffer[len] = NUL;
6131 i = 0;
6132 for (p = buffer; p < buffer + len; ++p)
6133 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6134 {
6135 ++i;
6136 *p = NUL;
6137 }
6138 if (len)
6139 ++i; /* count last entry */
6140 }
6141 if (i == 0)
6142 {
6143 /*
6144 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6145 * /bin/sh will happily expand it to nothing rather than returning an
6146 * error; and hey, it's good to check anyway -- webb.
6147 */
6148 vim_free(buffer);
6149 goto notfound;
6150 }
6151 *num_file = i;
6152 *file = (char_u **)alloc(sizeof(char_u *) * i);
6153 if (*file == NULL)
6154 {
6155 /* out of memory */
6156 vim_free(buffer);
6157 return FAIL;
6158 }
6159
6160 /*
6161 * Isolate the individual file names.
6162 */
6163 p = buffer;
6164 for (i = 0; i < *num_file; ++i)
6165 {
6166 (*file)[i] = p;
6167 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006168 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6169 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006171 while (!(shell_style == STYLE_ECHO && *p == ' ')
6172 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 ++p;
6174 if (p == buffer + len) /* last entry */
6175 *p = NUL;
6176 else
6177 {
6178 *p++ = NUL;
6179 p = skipwhite(p); /* skip to next entry */
6180 }
6181 }
6182 else /* NUL separates */
6183 {
6184 while (*p && p < buffer + len) /* skip entry */
6185 ++p;
6186 ++p; /* skip NUL */
6187 }
6188 }
6189
6190 /*
6191 * Move the file names to allocated memory.
6192 */
6193 for (j = 0, i = 0; i < *num_file; ++i)
6194 {
6195 /* Require the files to exist. Helps when using /bin/sh */
6196 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6197 continue;
6198
6199 /* check if this entry should be included */
6200 dir = (mch_isdir((*file)[i]));
6201 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6202 continue;
6203
Bram Moolenaara2031822006-03-07 22:29:51 +00006204 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006205 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i], NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00006206 continue;
6207
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6209 if (p)
6210 {
6211 STRCPY(p, (*file)[i]);
6212 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006213 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 (*file)[j++] = p;
6215 }
6216 }
6217 vim_free(buffer);
6218 *num_file = j;
6219
6220 if (*num_file == 0) /* rejected all entries */
6221 {
6222 vim_free(*file);
6223 *file = NULL;
6224 goto notfound;
6225 }
6226
6227 return OK;
6228
6229notfound:
6230 if (flags & EW_NOTFOUND)
6231 return save_patterns(num_pat, pat, num_file, file);
6232 return FAIL;
6233
6234#endif /* __EMX__ */
6235}
6236
6237#endif /* VMS */
6238
6239#ifndef __EMX__
6240 static int
6241save_patterns(num_pat, pat, num_file, file)
6242 int num_pat;
6243 char_u **pat;
6244 int *num_file;
6245 char_u ***file;
6246{
6247 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006248 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249
6250 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6251 if (*file == NULL)
6252 return FAIL;
6253 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006254 {
6255 s = vim_strsave(pat[i]);
6256 if (s != NULL)
6257 /* Be compatible with expand_filename(): halve the number of
6258 * backslashes. */
6259 backslash_halve(s);
6260 (*file)[i] = s;
6261 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 *num_file = num_pat;
6263 return OK;
6264}
6265#endif
6266
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267/*
6268 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6269 * expand.
6270 */
6271 int
6272mch_has_exp_wildcard(p)
6273 char_u *p;
6274{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006275 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 {
6277#ifndef OS2
6278 if (*p == '\\' && p[1] != NUL)
6279 ++p;
6280 else
6281#endif
6282 if (vim_strchr((char_u *)
6283#ifdef VMS
6284 "*?%"
6285#else
6286# ifdef OS2
6287 "*?"
6288# else
6289 "*?[{'"
6290# endif
6291#endif
6292 , *p) != NULL)
6293 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 }
6295 return FALSE;
6296}
6297
6298/*
6299 * Return TRUE if the string "p" contains a wildcard.
6300 * Don't recognize '~' at the end as a wildcard.
6301 */
6302 int
6303mch_has_wildcard(p)
6304 char_u *p;
6305{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006306 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 {
6308#ifndef OS2
6309 if (*p == '\\' && p[1] != NUL)
6310 ++p;
6311 else
6312#endif
6313 if (vim_strchr((char_u *)
6314#ifdef VMS
6315 "*?%$"
6316#else
6317# ifdef OS2
6318# ifdef VIM_BACKTICK
6319 "*?$`"
6320# else
6321 "*?$"
6322# endif
6323# else
6324 "*?[{`'$"
6325# endif
6326#endif
6327 , *p) != NULL
6328 || (*p == '~' && p[1] != NUL))
6329 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 }
6331 return FALSE;
6332}
6333
6334#ifndef __EMX__
6335 static int
6336have_wildcard(num, file)
6337 int num;
6338 char_u **file;
6339{
6340 int i;
6341
6342 for (i = 0; i < num; i++)
6343 if (mch_has_wildcard(file[i]))
6344 return 1;
6345 return 0;
6346}
6347
6348 static int
6349have_dollars(num, file)
6350 int num;
6351 char_u **file;
6352{
6353 int i;
6354
6355 for (i = 0; i < num; i++)
6356 if (vim_strchr(file[i], '$') != NULL)
6357 return TRUE;
6358 return FALSE;
6359}
6360#endif /* ifndef __EMX__ */
6361
6362#ifndef HAVE_RENAME
6363/*
6364 * Scaled-down version of rename(), which is missing in Xenix.
6365 * This version can only move regular files and will fail if the
6366 * destination exists.
6367 */
6368 int
6369mch_rename(src, dest)
6370 const char *src, *dest;
6371{
6372 struct stat st;
6373
6374 if (stat(dest, &st) >= 0) /* fail if destination exists */
6375 return -1;
6376 if (link(src, dest) != 0) /* link file to new name */
6377 return -1;
6378 if (mch_remove(src) == 0) /* delete link to old name */
6379 return 0;
6380 return -1;
6381}
6382#endif /* !HAVE_RENAME */
6383
6384#ifdef FEAT_MOUSE_GPM
6385/*
6386 * Initializes connection with gpm (if it isn't already opened)
6387 * Return 1 if succeeded (or connection already opened), 0 if failed
6388 */
6389 static int
6390gpm_open()
6391{
6392 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6393
6394 if (!gpm_flag)
6395 {
6396 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6397 gpm_connect.defaultMask = ~GPM_HARD;
6398 /* Default handling for mouse move*/
6399 gpm_connect.minMod = 0; /* Handle any modifier keys */
6400 gpm_connect.maxMod = 0xffff;
6401 if (Gpm_Open(&gpm_connect, 0) > 0)
6402 {
6403 /* gpm library tries to handling TSTP causes
6404 * problems. Anyways, we close connection to Gpm whenever
6405 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006406 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006408# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 return 1; /* succeed */
6412 }
6413 if (gpm_fd == -2)
6414 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6415 return 0;
6416 }
6417 return 1; /* already open */
6418}
6419
6420/*
6421 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422 */
6423 static void
6424gpm_close()
6425{
6426 if (gpm_flag && gpm_fd >= 0) /* if Open */
6427 Gpm_Close();
6428}
6429
6430/* Reads gpm event and adds special keys to input buf. Returns length of
6431 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006432 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433 */
6434 static int
6435mch_gpm_process()
6436{
6437 int button;
6438 static Gpm_Event gpm_event;
6439 char_u string[6];
6440 int_u vim_modifiers;
6441 int row,col;
6442 unsigned char buttons_mask;
6443 unsigned char gpm_modifiers;
6444 static unsigned char old_buttons = 0;
6445
6446 Gpm_GetEvent(&gpm_event);
6447
6448#ifdef FEAT_GUI
6449 /* Don't put events in the input queue now. */
6450 if (hold_gui_events)
6451 return 0;
6452#endif
6453
6454 row = gpm_event.y - 1;
6455 col = gpm_event.x - 1;
6456
6457 string[0] = ESC; /* Our termcode */
6458 string[1] = 'M';
6459 string[2] = 'G';
6460 switch (GPM_BARE_EVENTS(gpm_event.type))
6461 {
6462 case GPM_DRAG:
6463 string[3] = MOUSE_DRAG;
6464 break;
6465 case GPM_DOWN:
6466 buttons_mask = gpm_event.buttons & ~old_buttons;
6467 old_buttons = gpm_event.buttons;
6468 switch (buttons_mask)
6469 {
6470 case GPM_B_LEFT:
6471 button = MOUSE_LEFT;
6472 break;
6473 case GPM_B_MIDDLE:
6474 button = MOUSE_MIDDLE;
6475 break;
6476 case GPM_B_RIGHT:
6477 button = MOUSE_RIGHT;
6478 break;
6479 default:
6480 return 0;
6481 /*Don't know what to do. Can more than one button be
6482 * reported in one event? */
6483 }
6484 string[3] = (char_u)(button | 0x20);
6485 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6486 break;
6487 case GPM_UP:
6488 string[3] = MOUSE_RELEASE;
6489 old_buttons &= ~gpm_event.buttons;
6490 break;
6491 default:
6492 return 0;
6493 }
6494 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6495 gpm_modifiers = gpm_event.modifiers;
6496 vim_modifiers = 0x0;
6497 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6498 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6499 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6500 */
6501 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6502 vim_modifiers |= MOUSE_SHIFT;
6503
6504 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6505 vim_modifiers |= MOUSE_CTRL;
6506 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6507 vim_modifiers |= MOUSE_ALT;
6508 string[3] |= vim_modifiers;
6509 string[4] = (char_u)(col + ' ' + 1);
6510 string[5] = (char_u)(row + ' ' + 1);
6511 add_to_input_buf(string, 6);
6512 return 6;
6513}
6514#endif /* FEAT_MOUSE_GPM */
6515
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006516#ifdef FEAT_SYSMOUSE
6517/*
6518 * Initialize connection with sysmouse.
6519 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6520 * output, any sysmouse output than will be processed via sig_sysmouse().
6521 * Return OK if succeeded, FAIL if failed.
6522 */
6523 static int
6524sysmouse_open()
6525{
6526 struct mouse_info mouse;
6527
6528 mouse.operation = MOUSE_MODE;
6529 mouse.u.mode.mode = 0;
6530 mouse.u.mode.signal = SIGUSR2;
6531 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6532 {
6533 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6534 mouse.operation = MOUSE_SHOW;
6535 ioctl(1, CONS_MOUSECTL, &mouse);
6536 return OK;
6537 }
6538 return FAIL;
6539}
6540
6541/*
6542 * Stop processing SIGUSR2 signals, and also make sure that
6543 * virtual console do not send us any sysmouse related signal.
6544 */
6545 static void
6546sysmouse_close()
6547{
6548 struct mouse_info mouse;
6549
6550 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6551 mouse.operation = MOUSE_MODE;
6552 mouse.u.mode.mode = 0;
6553 mouse.u.mode.signal = 0;
6554 ioctl(1, CONS_MOUSECTL, &mouse);
6555}
6556
6557/*
6558 * Gets info from sysmouse and adds special keys to input buf.
6559 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006560 static RETSIGTYPE
6561sig_sysmouse SIGDEFARG(sigarg)
6562{
6563 struct mouse_info mouse;
6564 struct video_info video;
6565 char_u string[6];
6566 int row, col;
6567 int button;
6568 int buttons;
6569 static int oldbuttons = 0;
6570
6571#ifdef FEAT_GUI
6572 /* Don't put events in the input queue now. */
6573 if (hold_gui_events)
6574 return;
6575#endif
6576
6577 mouse.operation = MOUSE_GETINFO;
6578 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6579 && ioctl(1, FBIO_MODEINFO, &video) != -1
6580 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6581 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6582 {
6583 row = mouse.u.data.y / video.vi_cheight;
6584 col = mouse.u.data.x / video.vi_cwidth;
6585 buttons = mouse.u.data.buttons;
6586 string[0] = ESC; /* Our termcode */
6587 string[1] = 'M';
6588 string[2] = 'S';
6589 if (oldbuttons == buttons && buttons != 0)
6590 {
6591 button = MOUSE_DRAG;
6592 }
6593 else
6594 {
6595 switch (buttons)
6596 {
6597 case 0:
6598 button = MOUSE_RELEASE;
6599 break;
6600 case 1:
6601 button = MOUSE_LEFT;
6602 break;
6603 case 2:
6604 button = MOUSE_MIDDLE;
6605 break;
6606 case 4:
6607 button = MOUSE_RIGHT;
6608 break;
6609 default:
6610 return;
6611 }
6612 oldbuttons = buttons;
6613 }
6614 string[3] = (char_u)(button);
6615 string[4] = (char_u)(col + ' ' + 1);
6616 string[5] = (char_u)(row + ' ' + 1);
6617 add_to_input_buf(string, 6);
6618 }
6619 return;
6620}
6621#endif /* FEAT_SYSMOUSE */
6622
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623#if defined(FEAT_LIBCALL) || defined(PROTO)
6624typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6625typedef char_u * (*INTPROCSTR)__ARGS((int));
6626typedef int (*STRPROCINT)__ARGS((char_u *));
6627typedef int (*INTPROCINT)__ARGS((int));
6628
6629/*
6630 * Call a DLL routine which takes either a string or int param
6631 * and returns an allocated string.
6632 */
6633 int
6634mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6635 char_u *libname;
6636 char_u *funcname;
6637 char_u *argstring; /* NULL when using a argint */
6638 int argint;
6639 char_u **string_result;/* NULL when using number_result */
6640 int *number_result;
6641{
6642# if defined(USE_DLOPEN)
6643 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006644 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645# else
6646 shl_t hinstLib;
6647# endif
6648 STRPROCSTR ProcAdd;
6649 INTPROCSTR ProcAddI;
6650 char_u *retval_str = NULL;
6651 int retval_int = 0;
6652 int success = FALSE;
6653
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006654 /*
6655 * Get a handle to the DLL module.
6656 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006658 /* First clear any error, it's not cleared by the dlopen() call. */
6659 (void)dlerror();
6660
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 hinstLib = dlopen((char *)libname, RTLD_LAZY
6662# ifdef RTLD_LOCAL
6663 | RTLD_LOCAL
6664# endif
6665 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006666 if (hinstLib == NULL)
6667 {
6668 /* "dlerr" must be used before dlclose() */
6669 dlerr = (char *)dlerror();
6670 if (dlerr != NULL)
6671 EMSG2(_("dlerror = \"%s\""), dlerr);
6672 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673# else
6674 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6675# endif
6676
6677 /* If the handle is valid, try to get the function address. */
6678 if (hinstLib != NULL)
6679 {
6680# ifdef HAVE_SETJMP_H
6681 /*
6682 * Catch a crash when calling the library function. For example when
6683 * using a number where a string pointer is expected.
6684 */
6685 mch_startjmp();
6686 if (SETJMP(lc_jump_env) != 0)
6687 {
6688 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006689# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006690 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006691# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 mch_didjmp();
6693 }
6694 else
6695# endif
6696 {
6697 retval_str = NULL;
6698 retval_int = 0;
6699
6700 if (argstring != NULL)
6701 {
6702# if defined(USE_DLOPEN)
6703 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006704 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705# else
6706 if (shl_findsym(&hinstLib, (const char *)funcname,
6707 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6708 ProcAdd = NULL;
6709# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006710 if ((success = (ProcAdd != NULL
6711# if defined(USE_DLOPEN)
6712 && dlerr == NULL
6713# endif
6714 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 {
6716 if (string_result == NULL)
6717 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6718 else
6719 retval_str = (ProcAdd)(argstring);
6720 }
6721 }
6722 else
6723 {
6724# if defined(USE_DLOPEN)
6725 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006726 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727# else
6728 if (shl_findsym(&hinstLib, (const char *)funcname,
6729 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6730 ProcAddI = NULL;
6731# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006732 if ((success = (ProcAddI != NULL
6733# if defined(USE_DLOPEN)
6734 && dlerr == NULL
6735# endif
6736 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006737 {
6738 if (string_result == NULL)
6739 retval_int = ((INTPROCINT)ProcAddI)(argint);
6740 else
6741 retval_str = (ProcAddI)(argint);
6742 }
6743 }
6744
6745 /* Save the string before we free the library. */
6746 /* Assume that a "1" or "-1" result is an illegal pointer. */
6747 if (string_result == NULL)
6748 *number_result = retval_int;
6749 else if (retval_str != NULL
6750 && retval_str != (char_u *)1
6751 && retval_str != (char_u *)-1)
6752 *string_result = vim_strsave(retval_str);
6753 }
6754
6755# ifdef HAVE_SETJMP_H
6756 mch_endjmp();
6757# ifdef SIGHASARG
6758 if (lc_signal != 0)
6759 {
6760 int i;
6761
6762 /* try to find the name of this signal */
6763 for (i = 0; signal_info[i].sig != -1; i++)
6764 if (lc_signal == signal_info[i].sig)
6765 break;
6766 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6767 }
6768# endif
6769# endif
6770
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006772 /* "dlerr" must be used before dlclose() */
6773 if (dlerr != NULL)
6774 EMSG2(_("dlerror = \"%s\""), dlerr);
6775
6776 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 (void)dlclose(hinstLib);
6778# else
6779 (void)shl_unload(hinstLib);
6780# endif
6781 }
6782
6783 if (!success)
6784 {
6785 EMSG2(_(e_libcall), funcname);
6786 return FAIL;
6787 }
6788
6789 return OK;
6790}
6791#endif
6792
6793#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6794static int xterm_trace = -1; /* default: disabled */
6795static int xterm_button;
6796
6797/*
6798 * Setup a dummy window for X selections in a terminal.
6799 */
6800 void
6801setup_term_clip()
6802{
6803 int z = 0;
6804 char *strp = "";
6805 Widget AppShell;
6806
6807 if (!x_connect_to_server())
6808 return;
6809
6810 open_app_context();
6811 if (app_context != NULL && xterm_Shell == (Widget)0)
6812 {
6813 int (*oldhandler)();
6814#if defined(HAVE_SETJMP_H)
6815 int (*oldIOhandler)();
6816#endif
6817# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6818 struct timeval start_tv;
6819
6820 if (p_verbose > 0)
6821 gettimeofday(&start_tv, NULL);
6822# endif
6823
6824 /* Ignore X errors while opening the display */
6825 oldhandler = XSetErrorHandler(x_error_check);
6826
6827#if defined(HAVE_SETJMP_H)
6828 /* Ignore X IO errors while opening the display */
6829 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6830 mch_startjmp();
6831 if (SETJMP(lc_jump_env) != 0)
6832 {
6833 mch_didjmp();
6834 xterm_dpy = NULL;
6835 }
6836 else
6837#endif
6838 {
6839 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6840 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6841#if defined(HAVE_SETJMP_H)
6842 mch_endjmp();
6843#endif
6844 }
6845
6846#if defined(HAVE_SETJMP_H)
6847 /* Now handle X IO errors normally. */
6848 (void)XSetIOErrorHandler(oldIOhandler);
6849#endif
6850 /* Now handle X errors normally. */
6851 (void)XSetErrorHandler(oldhandler);
6852
6853 if (xterm_dpy == NULL)
6854 {
6855 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006856 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 return;
6858 }
6859
6860 /* Catch terminating error of the X server connection. */
6861 (void)XSetIOErrorHandler(x_IOerror_handler);
6862
6863# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6864 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006865 {
6866 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006868 verbose_leave();
6869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870# endif
6871
6872 /* Create a Shell to make converters work. */
6873 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6874 applicationShellWidgetClass, xterm_dpy,
6875 NULL);
6876 if (AppShell == (Widget)0)
6877 return;
6878 xterm_Shell = XtVaCreatePopupShell("VIM",
6879 topLevelShellWidgetClass, AppShell,
6880 XtNmappedWhenManaged, 0,
6881 XtNwidth, 1,
6882 XtNheight, 1,
6883 NULL);
6884 if (xterm_Shell == (Widget)0)
6885 return;
6886
6887 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006888 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 if (x11_display == NULL)
6890 x11_display = xterm_dpy;
6891
6892 XtRealizeWidget(xterm_Shell);
6893 XSync(xterm_dpy, False);
6894 xterm_update();
6895 }
6896 if (xterm_Shell != (Widget)0)
6897 {
6898 clip_init(TRUE);
6899 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6900 x11_window = (Window)atol(strp);
6901 /* Check if $WINDOWID is valid. */
6902 if (test_x11_window(xterm_dpy) == FAIL)
6903 x11_window = 0;
6904 if (x11_window != 0)
6905 xterm_trace = 0;
6906 }
6907}
6908
6909 void
6910start_xterm_trace(button)
6911 int button;
6912{
6913 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6914 return;
6915 xterm_trace = 1;
6916 xterm_button = button;
6917 do_xterm_trace();
6918}
6919
6920
6921 void
6922stop_xterm_trace()
6923{
6924 if (xterm_trace < 0)
6925 return;
6926 xterm_trace = 0;
6927}
6928
6929/*
6930 * Query the xterm pointer and generate mouse termcodes if necessary
6931 * return TRUE if dragging is active, else FALSE
6932 */
6933 static int
6934do_xterm_trace()
6935{
6936 Window root, child;
6937 int root_x, root_y;
6938 int win_x, win_y;
6939 int row, col;
6940 int_u mask_return;
6941 char_u buf[50];
6942 char_u *strp;
6943 long got_hints;
6944 static char_u *mouse_code;
6945 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6946 static int prev_row = 0, prev_col = 0;
6947 static XSizeHints xterm_hints;
6948
6949 if (xterm_trace <= 0)
6950 return FALSE;
6951
6952 if (xterm_trace == 1)
6953 {
6954 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006955 * have changed recently. */
6956 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6957 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958 || xterm_hints.width_inc <= 1
6959 || xterm_hints.height_inc <= 1)
6960 {
6961 xterm_trace = -1; /* Not enough data -- disable tracing */
6962 return FALSE;
6963 }
6964
6965 /* Rely on the same mouse code for the duration of this */
6966 mouse_code = find_termcode(mouse_name);
6967 prev_row = mouse_row;
6968 prev_row = mouse_col;
6969 xterm_trace = 2;
6970
6971 /* Find the offset of the chars, there might be a scrollbar on the
6972 * left of the window and/or a menu on the top (eterm etc.) */
6973 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6974 &win_x, &win_y, &mask_return);
6975 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6976 - (xterm_hints.height_inc / 2);
6977 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6978 xterm_hints.y = 2;
6979 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6980 - (xterm_hints.width_inc / 2);
6981 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6982 xterm_hints.x = 2;
6983 return TRUE;
6984 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006985 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 {
6987 xterm_trace = 0;
6988 return FALSE;
6989 }
6990
6991 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6992 &win_x, &win_y, &mask_return);
6993
6994 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6995 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6996 if (row == prev_row && col == prev_col)
6997 return TRUE;
6998
6999 STRCPY(buf, mouse_code);
7000 strp = buf + STRLEN(buf);
7001 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7002 *strp++ = (char_u)(col + ' ' + 1);
7003 *strp++ = (char_u)(row + ' ' + 1);
7004 *strp = 0;
7005 add_to_input_buf(buf, STRLEN(buf));
7006
7007 prev_row = row;
7008 prev_col = col;
7009 return TRUE;
7010}
7011
7012# if defined(FEAT_GUI) || defined(PROTO)
7013/*
7014 * Destroy the display, window and app_context. Required for GTK.
7015 */
7016 void
7017clear_xterm_clip()
7018{
7019 if (xterm_Shell != (Widget)0)
7020 {
7021 XtDestroyWidget(xterm_Shell);
7022 xterm_Shell = (Widget)0;
7023 }
7024 if (xterm_dpy != NULL)
7025 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007026# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 /* Lesstif and Solaris crash here, lose some memory */
7028 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007029# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030 if (x11_display == xterm_dpy)
7031 x11_display = NULL;
7032 xterm_dpy = NULL;
7033 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007034# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 if (app_context != (XtAppContext)NULL)
7036 {
7037 /* Lesstif and Solaris crash here, lose some memory */
7038 XtDestroyApplicationContext(app_context);
7039 app_context = (XtAppContext)NULL;
7040 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007041# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042}
7043# endif
7044
7045/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007046 * Catch up with GUI or X events.
7047 */
7048 static void
7049clip_update()
7050{
7051# ifdef FEAT_GUI
7052 if (gui.in_use)
7053 gui_mch_update();
7054 else
7055# endif
7056 if (xterm_Shell != (Widget)0)
7057 xterm_update();
7058}
7059
7060/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 * Catch up with any queued X events. This may put keyboard input into the
7062 * input buffer, call resize call-backs, trigger timers etc. If there is
7063 * nothing in the X event queue (& no timers pending), then we return
7064 * immediately.
7065 */
7066 static void
7067xterm_update()
7068{
7069 XEvent event;
7070
7071 while (XtAppPending(app_context) && !vim_is_input_buf_full())
7072 {
7073 XtAppNextEvent(app_context, &event);
7074#ifdef FEAT_CLIENTSERVER
7075 {
7076 XPropertyEvent *e = (XPropertyEvent *)&event;
7077
7078 if (e->type == PropertyNotify && e->window == commWindow
7079 && e->atom == commProperty && e->state == PropertyNewValue)
7080 serverEventProc(xterm_dpy, &event);
7081 }
7082#endif
7083 XtDispatchEvent(&event);
7084 }
7085}
7086
7087 int
7088clip_xterm_own_selection(cbd)
7089 VimClipboard *cbd;
7090{
7091 if (xterm_Shell != (Widget)0)
7092 return clip_x11_own_selection(xterm_Shell, cbd);
7093 return FAIL;
7094}
7095
7096 void
7097clip_xterm_lose_selection(cbd)
7098 VimClipboard *cbd;
7099{
7100 if (xterm_Shell != (Widget)0)
7101 clip_x11_lose_selection(xterm_Shell, cbd);
7102}
7103
7104 void
7105clip_xterm_request_selection(cbd)
7106 VimClipboard *cbd;
7107{
7108 if (xterm_Shell != (Widget)0)
7109 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7110}
7111
7112 void
7113clip_xterm_set_selection(cbd)
7114 VimClipboard *cbd;
7115{
7116 clip_x11_set_selection(cbd);
7117}
7118#endif
7119
7120
7121#if defined(USE_XSMP) || defined(PROTO)
7122/*
7123 * Code for X Session Management Protocol.
7124 */
7125static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
7126static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
7127static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
7128static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
7129static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
7130
7131
7132# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7133static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7134
7135/*
7136 * This is our chance to ask the user if they want to save,
7137 * or abort the logout
7138 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 static void
7140xsmp_handle_interaction(smc_conn, client_data)
7141 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007142 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143{
7144 cmdmod_T save_cmdmod;
7145 int cancel_shutdown = False;
7146
7147 save_cmdmod = cmdmod;
7148 cmdmod.confirm = TRUE;
7149 if (check_changed_any(FALSE))
7150 /* Mustn't logout */
7151 cancel_shutdown = True;
7152 cmdmod = save_cmdmod;
7153 setcursor(); /* position cursor */
7154 out_flush();
7155
7156 /* Done interaction */
7157 SmcInteractDone(smc_conn, cancel_shutdown);
7158
7159 /* Finish off
7160 * Only end save-yourself here if we're not cancelling shutdown;
7161 * we'll get a cancelled callback later in which we'll end it.
7162 * Hopefully get around glitchy SMs (like GNOME-1)
7163 */
7164 if (!cancel_shutdown)
7165 {
7166 xsmp.save_yourself = False;
7167 SmcSaveYourselfDone(smc_conn, True);
7168 }
7169}
7170# endif
7171
7172/*
7173 * Callback that starts save-yourself.
7174 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007175 static void
7176xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7177 shutdown, interact_style, fast)
7178 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007179 SmPointer client_data UNUSED;
7180 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007182 int interact_style UNUSED;
7183 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184{
7185 /* Handle already being in saveyourself */
7186 if (xsmp.save_yourself)
7187 SmcSaveYourselfDone(smc_conn, True);
7188 xsmp.save_yourself = True;
7189 xsmp.shutdown = shutdown;
7190
7191 /* First up, preserve all files */
7192 out_flush();
7193 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7194
7195 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007196 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197
7198# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7199 /* Now see if we can ask about unsaved files */
7200 if (shutdown && !fast && gui.in_use)
7201 /* Need to interact with user, but need SM's permission */
7202 SmcInteractRequest(smc_conn, SmDialogError,
7203 xsmp_handle_interaction, client_data);
7204 else
7205# endif
7206 {
7207 /* Can stop the cycle here */
7208 SmcSaveYourselfDone(smc_conn, True);
7209 xsmp.save_yourself = False;
7210 }
7211}
7212
7213
7214/*
7215 * Callback to warn us of imminent death.
7216 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 static void
7218xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007219 SmcConn smc_conn UNUSED;
7220 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221{
7222 xsmp_close();
7223
7224 /* quit quickly leaving swapfiles for modified buffers behind */
7225 getout_preserve_modified(0);
7226}
7227
7228
7229/*
7230 * Callback to tell us that save-yourself has completed.
7231 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 static void
7233xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007234 SmcConn smc_conn UNUSED;
7235 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236{
7237 xsmp.save_yourself = False;
7238}
7239
7240
7241/*
7242 * Callback to tell us that an instigated shutdown was cancelled
7243 * (maybe even by us)
7244 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 static void
7246xsmp_shutdown_cancelled(smc_conn, client_data)
7247 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007248 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249{
7250 if (xsmp.save_yourself)
7251 SmcSaveYourselfDone(smc_conn, True);
7252 xsmp.save_yourself = False;
7253 xsmp.shutdown = False;
7254}
7255
7256
7257/*
7258 * Callback to tell us that a new ICE connection has been established.
7259 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 static void
7261xsmp_ice_connection(iceConn, clientData, opening, watchData)
7262 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007263 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007264 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007265 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266{
7267 /* Intercept creation of ICE connection fd */
7268 if (opening)
7269 {
7270 xsmp_icefd = IceConnectionNumber(iceConn);
7271 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7272 }
7273}
7274
7275
7276/* Handle any ICE processing that's required; return FAIL if SM lost */
7277 int
7278xsmp_handle_requests()
7279{
7280 Bool rep;
7281
7282 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7283 == IceProcessMessagesIOError)
7284 {
7285 /* Lost ICE */
7286 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007287 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 xsmp_close();
7289 return FAIL;
7290 }
7291 else
7292 return OK;
7293}
7294
7295static int dummy;
7296
7297/* Set up X Session Management Protocol */
7298 void
7299xsmp_init(void)
7300{
7301 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 SmcCallbacks smcallbacks;
7303#if 0
7304 SmPropValue smname;
7305 SmProp smnameprop;
7306 SmProp *smprops[1];
7307#endif
7308
7309 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007310 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311
7312 xsmp.save_yourself = xsmp.shutdown = False;
7313
7314 /* Set up SM callbacks - must have all, even if they're not used */
7315 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7316 smcallbacks.save_yourself.client_data = NULL;
7317 smcallbacks.die.callback = xsmp_die;
7318 smcallbacks.die.client_data = NULL;
7319 smcallbacks.save_complete.callback = xsmp_save_complete;
7320 smcallbacks.save_complete.client_data = NULL;
7321 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7322 smcallbacks.shutdown_cancelled.client_data = NULL;
7323
7324 /* Set up a watch on ICE connection creations. The "dummy" argument is
7325 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7326 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7327 {
7328 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007329 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330 return;
7331 }
7332
7333 /* Create an SM connection */
7334 xsmp.smcconn = SmcOpenConnection(
7335 NULL,
7336 NULL,
7337 SmProtoMajor,
7338 SmProtoMinor,
7339 SmcSaveYourselfProcMask | SmcDieProcMask
7340 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7341 &smcallbacks,
7342 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007343 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 sizeof(errorstring),
7345 errorstring);
7346 if (xsmp.smcconn == NULL)
7347 {
7348 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007349
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007351 {
7352 vim_snprintf(errorreport, sizeof(errorreport),
7353 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7354 verb_msg((char_u *)errorreport);
7355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356 return;
7357 }
7358 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7359
7360#if 0
7361 /* ID ourselves */
7362 smname.value = "vim";
7363 smname.length = 3;
7364 smnameprop.name = "SmProgram";
7365 smnameprop.type = "SmARRAY8";
7366 smnameprop.num_vals = 1;
7367 smnameprop.vals = &smname;
7368
7369 smprops[0] = &smnameprop;
7370 SmcSetProperties(xsmp.smcconn, 1, smprops);
7371#endif
7372}
7373
7374
7375/* Shut down XSMP comms. */
7376 void
7377xsmp_close()
7378{
7379 if (xsmp_icefd != -1)
7380 {
7381 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007382 if (xsmp.clientid != NULL)
7383 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007384 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 xsmp_icefd = -1;
7386 }
7387}
7388#endif /* USE_XSMP */
7389
7390
7391#ifdef EBCDIC
7392/* Translate character to its CTRL- value */
7393char CtrlTable[] =
7394{
7395/* 00 - 5E */
7396 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7397 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7398 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7399 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7400 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7401 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7402/* ^ */ 0x1E,
7403/* - */ 0x1F,
7404/* 61 - 6C */
7405 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7406/* _ */ 0x1F,
7407/* 6E - 80 */
7408 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7409/* a */ 0x01,
7410/* b */ 0x02,
7411/* c */ 0x03,
7412/* d */ 0x37,
7413/* e */ 0x2D,
7414/* f */ 0x2E,
7415/* g */ 0x2F,
7416/* h */ 0x16,
7417/* i */ 0x05,
7418/* 8A - 90 */
7419 0, 0, 0, 0, 0, 0, 0,
7420/* j */ 0x15,
7421/* k */ 0x0B,
7422/* l */ 0x0C,
7423/* m */ 0x0D,
7424/* n */ 0x0E,
7425/* o */ 0x0F,
7426/* p */ 0x10,
7427/* q */ 0x11,
7428/* r */ 0x12,
7429/* 9A - A1 */
7430 0, 0, 0, 0, 0, 0, 0, 0,
7431/* s */ 0x13,
7432/* t */ 0x3C,
7433/* u */ 0x3D,
7434/* v */ 0x32,
7435/* w */ 0x26,
7436/* x */ 0x18,
7437/* y */ 0x19,
7438/* z */ 0x3F,
7439/* AA - AC */
7440 0, 0, 0,
7441/* [ */ 0x27,
7442/* AE - BC */
7443 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7444/* ] */ 0x1D,
7445/* BE - C0 */ 0, 0, 0,
7446/* A */ 0x01,
7447/* B */ 0x02,
7448/* C */ 0x03,
7449/* D */ 0x37,
7450/* E */ 0x2D,
7451/* F */ 0x2E,
7452/* G */ 0x2F,
7453/* H */ 0x16,
7454/* I */ 0x05,
7455/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7456/* J */ 0x15,
7457/* K */ 0x0B,
7458/* L */ 0x0C,
7459/* M */ 0x0D,
7460/* N */ 0x0E,
7461/* O */ 0x0F,
7462/* P */ 0x10,
7463/* Q */ 0x11,
7464/* R */ 0x12,
7465/* DA - DF */ 0, 0, 0, 0, 0, 0,
7466/* \ */ 0x1C,
7467/* E1 */ 0,
7468/* S */ 0x13,
7469/* T */ 0x3C,
7470/* U */ 0x3D,
7471/* V */ 0x32,
7472/* W */ 0x26,
7473/* X */ 0x18,
7474/* Y */ 0x19,
7475/* Z */ 0x3F,
7476/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7477 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7478};
7479
7480char MetaCharTable[]=
7481{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7482 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7483 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7484 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7485 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7486};
7487
7488
7489/* TODO: Use characters NOT numbers!!! */
7490char CtrlCharTable[]=
7491{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7492 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7493 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7494 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7495 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7496};
7497
7498
7499#endif