blob: 8cd6b14eb75ae2703b3ad6afcd84c9326c9edd22 [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{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613#if defined(FEAT_CLIENTSERVER)
1614 if (x_force_connect)
1615 return TRUE;
1616#endif
1617 if (x_no_connect)
1618 return FALSE;
1619
1620 /* Check for a match with "exclude:" from 'clipboard'. */
1621 if (clip_exclude_prog != NULL)
1622 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001623 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 return FALSE;
1625 }
1626 return TRUE;
1627}
1628
1629/*
1630 * Test if "dpy" and x11_window are valid by getting the window title.
1631 * I don't actually want it yet, so there may be a simpler call to use, but
1632 * this will cause the error handler x_error_check() to be called if anything
1633 * is wrong, such as the window pointer being invalid (as can happen when the
1634 * user changes his DISPLAY, but not his WINDOWID) -- webb
1635 */
1636 static int
1637test_x11_window(dpy)
1638 Display *dpy;
1639{
1640 int (*old_handler)();
1641 XTextProperty text_prop;
1642
1643 old_handler = XSetErrorHandler(x_error_check);
1644 got_x_error = FALSE;
1645 if (XGetWMName(dpy, x11_window, &text_prop))
1646 XFree((void *)text_prop.value);
1647 XSync(dpy, False);
1648 (void)XSetErrorHandler(old_handler);
1649
1650 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001651 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 return (got_x_error ? FAIL : OK);
1654}
1655#endif
1656
1657#ifdef FEAT_TITLE
1658
1659#ifdef FEAT_X11
1660
1661static int get_x11_thing __ARGS((int get_title, int test_only));
1662
1663/*
1664 * try to get x11 window and display
1665 *
1666 * return FAIL for failure, OK otherwise
1667 */
1668 static int
1669get_x11_windis()
1670{
1671 char *winid;
1672 static int result = -1;
1673#define XD_NONE 0 /* x11_display not set here */
1674#define XD_HERE 1 /* x11_display opened here */
1675#define XD_GUI 2 /* x11_display used from gui.dpy */
1676#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1677 static int x11_display_from = XD_NONE;
1678 static int did_set_error_handler = FALSE;
1679
1680 if (!did_set_error_handler)
1681 {
1682 /* X just exits if it finds an error otherwise! */
1683 (void)XSetErrorHandler(x_error_handler);
1684 did_set_error_handler = TRUE;
1685 }
1686
Bram Moolenaar9372a112005-12-06 19:59:18 +00001687#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 if (gui.in_use)
1689 {
1690 /*
1691 * If the X11 display was opened here before, for the window where Vim
1692 * was started, close that one now to avoid a memory leak.
1693 */
1694 if (x11_display_from == XD_HERE && x11_display != NULL)
1695 {
1696 XCloseDisplay(x11_display);
1697 x11_display_from = XD_NONE;
1698 }
1699 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1700 {
1701 x11_display_from = XD_GUI;
1702 return OK;
1703 }
1704 x11_display = NULL;
1705 return FAIL;
1706 }
1707 else if (x11_display_from == XD_GUI)
1708 {
1709 /* GUI must have stopped somehow, clear x11_display */
1710 x11_window = 0;
1711 x11_display = NULL;
1712 x11_display_from = XD_NONE;
1713 }
1714#endif
1715
1716 /* When started with the "-X" argument, don't try connecting. */
1717 if (!x_connect_to_server())
1718 return FAIL;
1719
1720 /*
1721 * If WINDOWID not set, should try another method to find out
1722 * what the current window number is. The only code I know for
1723 * this is very complicated.
1724 * We assume that zero is invalid for WINDOWID.
1725 */
1726 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1727 x11_window = (Window)atol(winid);
1728
1729#ifdef FEAT_XCLIPBOARD
1730 if (xterm_dpy != NULL && x11_window != 0)
1731 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001732 /* We may have checked it already, but Gnome terminal can move us to
1733 * another window, so we need to check every time. */
1734 if (x11_display_from != XD_XTERM)
1735 {
1736 /*
1737 * If the X11 display was opened here before, for the window where
1738 * Vim was started, close that one now to avoid a memory leak.
1739 */
1740 if (x11_display_from == XD_HERE && x11_display != NULL)
1741 XCloseDisplay(x11_display);
1742 x11_display = xterm_dpy;
1743 x11_display_from = XD_XTERM;
1744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 if (test_x11_window(x11_display) == FAIL)
1746 {
1747 /* probably bad $WINDOWID */
1748 x11_window = 0;
1749 x11_display = NULL;
1750 x11_display_from = XD_NONE;
1751 return FAIL;
1752 }
1753 return OK;
1754 }
1755#endif
1756
1757 if (x11_window == 0 || x11_display == NULL)
1758 result = -1;
1759
1760 if (result != -1) /* Have already been here and set this */
1761 return result; /* Don't do all these X calls again */
1762
1763 if (x11_window != 0 && x11_display == NULL)
1764 {
1765#ifdef SET_SIG_ALARM
1766 RETSIGTYPE (*sig_save)();
1767#endif
1768#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1769 struct timeval start_tv;
1770
1771 if (p_verbose > 0)
1772 gettimeofday(&start_tv, NULL);
1773#endif
1774
1775#ifdef SET_SIG_ALARM
1776 /*
1777 * Opening the Display may hang if the DISPLAY setting is wrong, or
1778 * the network connection is bad. Set an alarm timer to get out.
1779 */
1780 sig_alarm_called = FALSE;
1781 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1782 (RETSIGTYPE (*)())sig_alarm);
1783 alarm(2);
1784#endif
1785 x11_display = XOpenDisplay(NULL);
1786
1787#ifdef SET_SIG_ALARM
1788 alarm(0);
1789 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1790 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001791 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792#endif
1793 if (x11_display != NULL)
1794 {
1795# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1796 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001797 {
1798 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001800 verbose_leave();
1801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802# endif
1803 if (test_x11_window(x11_display) == FAIL)
1804 {
1805 /* Maybe window id is bad */
1806 x11_window = 0;
1807 XCloseDisplay(x11_display);
1808 x11_display = NULL;
1809 }
1810 else
1811 x11_display_from = XD_HERE;
1812 }
1813 }
1814 if (x11_window == 0 || x11_display == NULL)
1815 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001816
1817# ifdef FEAT_EVAL
1818 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1819# endif
1820
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 return (result = OK);
1822}
1823
1824/*
1825 * Determine original x11 Window Title
1826 */
1827 static int
1828get_x11_title(test_only)
1829 int test_only;
1830{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001831 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832}
1833
1834/*
1835 * Determine original x11 Window icon
1836 */
1837 static int
1838get_x11_icon(test_only)
1839 int test_only;
1840{
1841 int retval = FALSE;
1842
1843 retval = get_x11_thing(FALSE, test_only);
1844
1845 /* could not get old icon, use terminal name */
1846 if (oldicon == NULL && !test_only)
1847 {
1848 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001849 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001851 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 }
1853
1854 return retval;
1855}
1856
1857 static int
1858get_x11_thing(get_title, test_only)
1859 int get_title; /* get title string */
1860 int test_only;
1861{
1862 XTextProperty text_prop;
1863 int retval = FALSE;
1864 Status status;
1865
1866 if (get_x11_windis() == OK)
1867 {
1868 /* Get window/icon name if any */
1869 if (get_title)
1870 status = XGetWMName(x11_display, x11_window, &text_prop);
1871 else
1872 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1873
1874 /*
1875 * If terminal is xterm, then x11_window may be a child window of the
1876 * outer xterm window that actually contains the window/icon name, so
1877 * keep traversing up the tree until a window with a title/icon is
1878 * found.
1879 */
1880 /* Previously this was only done for xterm and alikes. I don't see a
1881 * reason why it would fail for other terminal emulators.
1882 * if (term_is_xterm) */
1883 {
1884 Window root;
1885 Window parent;
1886 Window win = x11_window;
1887 Window *children;
1888 unsigned int num_children;
1889
1890 while (!status || text_prop.value == NULL)
1891 {
1892 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1893 &num_children))
1894 break;
1895 if (children)
1896 XFree((void *)children);
1897 if (parent == root || parent == 0)
1898 break;
1899
1900 win = parent;
1901 if (get_title)
1902 status = XGetWMName(x11_display, win, &text_prop);
1903 else
1904 status = XGetWMIconName(x11_display, win, &text_prop);
1905 }
1906 }
1907 if (status && text_prop.value != NULL)
1908 {
1909 retval = TRUE;
1910 if (!test_only)
1911 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001912#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
1913 if (text_prop.encoding == XA_STRING
1914# ifdef FEAT_MBYTE
1915 && !has_mbyte
1916# endif
1917 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 {
1919#endif
1920 if (get_title)
1921 oldtitle = vim_strsave((char_u *)text_prop.value);
1922 else
1923 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02001924#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 }
1926 else
1927 {
1928 char **cl;
1929 Status transform_status;
1930 int n = 0;
1931
1932 transform_status = XmbTextPropertyToTextList(x11_display,
1933 &text_prop,
1934 &cl, &n);
1935 if (transform_status >= Success && n > 0 && cl[0])
1936 {
1937 if (get_title)
1938 oldtitle = vim_strsave((char_u *) cl[0]);
1939 else
1940 oldicon = vim_strsave((char_u *) cl[0]);
1941 XFreeStringList(cl);
1942 }
1943 else
1944 {
1945 if (get_title)
1946 oldtitle = vim_strsave((char_u *)text_prop.value);
1947 else
1948 oldicon = vim_strsave((char_u *)text_prop.value);
1949 }
1950 }
1951#endif
1952 }
1953 XFree((void *)text_prop.value);
1954 }
1955 }
1956 return retval;
1957}
1958
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001959/* Xutf8 functions are not avaialble on older systems. Note that on some
1960 * systems X_HAVE_UTF8_STRING may be defined in a header file but
1961 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
1962 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02001964# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965# define USE_UTF8_STRING
1966# endif
1967#endif
1968
1969/*
1970 * Set x11 Window Title
1971 *
1972 * get_x11_windis() must be called before this and have returned OK
1973 */
1974 static void
1975set_x11_title(title)
1976 char_u *title;
1977{
1978 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1979 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1980 * supported everywhere and STRING doesn't work for multi-byte titles.
1981 */
1982#ifdef USE_UTF8_STRING
1983 if (enc_utf8)
1984 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1985 NULL, NULL, 0, NULL, NULL, NULL);
1986 else
1987#endif
1988 {
1989#if XtSpecificationRelease >= 4
1990# ifdef FEAT_XFONTSET
1991 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1992 NULL, NULL, 0, NULL, NULL, NULL);
1993# else
1994 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001995 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996
1997 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001998 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999 XSetWMProperties(x11_display, x11_window, &text_prop,
2000 NULL, NULL, 0, NULL, NULL, NULL);
2001# endif
2002#else
2003 XStoreName(x11_display, x11_window, (char *)title);
2004#endif
2005 }
2006 XFlush(x11_display);
2007}
2008
2009/*
2010 * Set x11 Window icon
2011 *
2012 * get_x11_windis() must be called before this and have returned OK
2013 */
2014 static void
2015set_x11_icon(icon)
2016 char_u *icon;
2017{
2018 /* See above for comments about using X*SetWMProperties(). */
2019#ifdef USE_UTF8_STRING
2020 if (enc_utf8)
2021 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2022 NULL, 0, NULL, NULL, NULL);
2023 else
2024#endif
2025 {
2026#if XtSpecificationRelease >= 4
2027# ifdef FEAT_XFONTSET
2028 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2029 NULL, 0, NULL, NULL, NULL);
2030# else
2031 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002032 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002034 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2036 NULL, 0, NULL, NULL, NULL);
2037# endif
2038#else
2039 XSetIconName(x11_display, x11_window, (char *)icon);
2040#endif
2041 }
2042 XFlush(x11_display);
2043}
2044
2045#else /* FEAT_X11 */
2046
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 static int
2048get_x11_title(test_only)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002049 int test_only UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050{
2051 return FALSE;
2052}
2053
2054 static int
2055get_x11_icon(test_only)
2056 int test_only;
2057{
2058 if (!test_only)
2059 {
2060 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002061 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002063 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 }
2065 return FALSE;
2066}
2067
2068#endif /* FEAT_X11 */
2069
2070 int
2071mch_can_restore_title()
2072{
2073 return get_x11_title(TRUE);
2074}
2075
2076 int
2077mch_can_restore_icon()
2078{
2079 return get_x11_icon(TRUE);
2080}
2081
2082/*
2083 * Set the window title and icon.
2084 */
2085 void
2086mch_settitle(title, icon)
2087 char_u *title;
2088 char_u *icon;
2089{
2090 int type = 0;
2091 static int recursive = 0;
2092
2093 if (T_NAME == NULL) /* no terminal name (yet) */
2094 return;
2095 if (title == NULL && icon == NULL) /* nothing to do */
2096 return;
2097
2098 /* When one of the X11 functions causes a deadly signal, we get here again
2099 * recursively. Avoid hanging then (something is probably locked). */
2100 if (recursive)
2101 return;
2102 ++recursive;
2103
2104 /*
2105 * if the window ID and the display is known, we may use X11 calls
2106 */
2107#ifdef FEAT_X11
2108 if (get_x11_windis() == OK)
2109 type = 1;
2110#else
2111# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2112 if (gui.in_use)
2113 type = 1;
2114# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115#endif
2116
2117 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002118 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 * than x11 calls, because the x11 calls don't always work
2120 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121 if ((type || *T_TS != NUL) && title != NULL)
2122 {
2123 if (oldtitle == NULL
2124#ifdef FEAT_GUI
2125 && !gui.in_use
2126#endif
2127 ) /* first call but not in GUI, save title */
2128 (void)get_x11_title(FALSE);
2129
2130 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2131 term_settitle(title);
2132#ifdef FEAT_X11
2133 else
2134# ifdef FEAT_GUI_GTK
2135 if (!gui.in_use) /* don't do this if GTK+ is running */
2136# endif
2137 set_x11_title(title); /* x11 */
2138#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002139#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2141 else
2142 gui_mch_settitle(title, icon);
2143#endif
2144 did_set_title = TRUE;
2145 }
2146
2147 if ((type || *T_CIS != NUL) && icon != NULL)
2148 {
2149 if (oldicon == NULL
2150#ifdef FEAT_GUI
2151 && !gui.in_use
2152#endif
2153 ) /* first call, save icon */
2154 get_x11_icon(FALSE);
2155
2156 if (*T_CIS != NUL)
2157 {
2158 out_str(T_CIS); /* set icon start */
2159 out_str_nf(icon);
2160 out_str(T_CIE); /* set icon end */
2161 out_flush();
2162 }
2163#ifdef FEAT_X11
2164 else
2165# ifdef FEAT_GUI_GTK
2166 if (!gui.in_use) /* don't do this if GTK+ is running */
2167# endif
2168 set_x11_icon(icon); /* x11 */
2169#endif
2170 did_set_icon = TRUE;
2171 }
2172 --recursive;
2173}
2174
2175/*
2176 * Restore the window/icon title.
2177 * "which" is one of:
2178 * 1 only restore title
2179 * 2 only restore icon
2180 * 3 restore title and icon
2181 */
2182 void
2183mch_restore_title(which)
2184 int which;
2185{
2186 /* only restore the title or icon when it has been set */
2187 mch_settitle(((which & 1) && did_set_title) ?
2188 (oldtitle ? oldtitle : p_titleold) : NULL,
2189 ((which & 2) && did_set_icon) ? oldicon : NULL);
2190}
2191
2192#endif /* FEAT_TITLE */
2193
2194/*
2195 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002196 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 */
2198 int
2199vim_is_xterm(name)
2200 char_u *name;
2201{
2202 if (name == NULL)
2203 return FALSE;
2204 return (STRNICMP(name, "xterm", 5) == 0
2205 || STRNICMP(name, "nxterm", 6) == 0
2206 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002207 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208 || STRNICMP(name, "rxvt", 4) == 0
2209 || STRCMP(name, "builtin_xterm") == 0);
2210}
2211
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002212#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2213/*
2214 * Return TRUE if "name" appears to be that of a terminal
2215 * known to support the xterm-style mouse protocol.
2216 * Relies on term_is_xterm having been set to its correct value.
2217 */
2218 int
2219use_xterm_like_mouse(name)
2220 char_u *name;
2221{
2222 return (name != NULL
2223 && (term_is_xterm || STRNICMP(name, "screen", 6) == 0));
2224}
2225#endif
2226
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2228/*
2229 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2230 * Return 1 for "xterm".
2231 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002232 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002233 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 */
2235 int
2236use_xterm_mouse()
2237{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002238 if (ttym_flags == TTYM_SGR)
2239 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002240 if (ttym_flags == TTYM_URXVT)
2241 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242 if (ttym_flags == TTYM_XTERM2)
2243 return 2;
2244 if (ttym_flags == TTYM_XTERM)
2245 return 1;
2246 return 0;
2247}
2248#endif
2249
2250 int
2251vim_is_iris(name)
2252 char_u *name;
2253{
2254 if (name == NULL)
2255 return FALSE;
2256 return (STRNICMP(name, "iris-ansi", 9) == 0
2257 || STRCMP(name, "builtin_iris-ansi") == 0);
2258}
2259
2260 int
2261vim_is_vt300(name)
2262 char_u *name;
2263{
2264 if (name == NULL)
2265 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002266 /* catch VT100 - VT5xx */
2267 return ((STRNICMP(name, "vt", 2) == 0
2268 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269 || STRCMP(name, "builtin_vt320") == 0);
2270}
2271
2272/*
2273 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2274 * This should include all windowed terminal emulators.
2275 */
2276 int
2277vim_is_fastterm(name)
2278 char_u *name;
2279{
2280 if (name == NULL)
2281 return FALSE;
2282 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2283 return TRUE;
2284 return ( STRNICMP(name, "hpterm", 6) == 0
2285 || STRNICMP(name, "sun-cmd", 7) == 0
2286 || STRNICMP(name, "screen", 6) == 0
2287 || STRNICMP(name, "dtterm", 6) == 0);
2288}
2289
2290/*
2291 * Insert user name in s[len].
2292 * Return OK if a name found.
2293 */
2294 int
2295mch_get_user_name(s, len)
2296 char_u *s;
2297 int len;
2298{
2299#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002300 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301 return OK;
2302#else
2303 return mch_get_uname(getuid(), s, len);
2304#endif
2305}
2306
2307/*
2308 * Insert user name for "uid" in s[len].
2309 * Return OK if a name found.
2310 */
2311 int
2312mch_get_uname(uid, s, len)
2313 uid_t uid;
2314 char_u *s;
2315 int len;
2316{
2317#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2318 struct passwd *pw;
2319
2320 if ((pw = getpwuid(uid)) != NULL
2321 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2322 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002323 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 return OK;
2325 }
2326#endif
2327 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2328 return FAIL; /* a number is not a name */
2329}
2330
2331/*
2332 * Insert host name is s[len].
2333 */
2334
2335#ifdef HAVE_SYS_UTSNAME_H
2336 void
2337mch_get_host_name(s, len)
2338 char_u *s;
2339 int len;
2340{
2341 struct utsname vutsname;
2342
2343 if (uname(&vutsname) < 0)
2344 *s = NUL;
2345 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002346 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347}
2348#else /* HAVE_SYS_UTSNAME_H */
2349
2350# ifdef HAVE_SYS_SYSTEMINFO_H
2351# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2352# endif
2353
2354 void
2355mch_get_host_name(s, len)
2356 char_u *s;
2357 int len;
2358{
2359# ifdef VAXC
2360 vaxc$gethostname((char *)s, len);
2361# else
2362 gethostname((char *)s, len);
2363# endif
2364 s[len - 1] = NUL; /* make sure it's terminated */
2365}
2366#endif /* HAVE_SYS_UTSNAME_H */
2367
2368/*
2369 * return process ID
2370 */
2371 long
2372mch_get_pid()
2373{
2374 return (long)getpid();
2375}
2376
2377#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2378static char *strerror __ARGS((int));
2379
2380 static char *
2381strerror(err)
2382 int err;
2383{
2384 extern int sys_nerr;
2385 extern char *sys_errlist[];
2386 static char er[20];
2387
2388 if (err > 0 && err < sys_nerr)
2389 return (sys_errlist[err]);
2390 sprintf(er, "Error %d", err);
2391 return er;
2392}
2393#endif
2394
2395/*
2396 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2397 * Return OK for success, FAIL for failure.
2398 */
2399 int
2400mch_dirname(buf, len)
2401 char_u *buf;
2402 int len;
2403{
2404#if defined(USE_GETCWD)
2405 if (getcwd((char *)buf, len) == NULL)
2406 {
2407 STRCPY(buf, strerror(errno));
2408 return FAIL;
2409 }
2410 return OK;
2411#else
2412 return (getwd((char *)buf) != NULL ? OK : FAIL);
2413#endif
2414}
2415
2416#if defined(OS2) || defined(PROTO)
2417/*
2418 * Replace all slashes by backslashes.
2419 * When 'shellslash' set do it the other way around.
2420 */
2421 void
2422slash_adjust(p)
2423 char_u *p;
2424{
2425 while (*p)
2426 {
2427 if (*p == psepcN)
2428 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002429 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 }
2431}
2432#endif
2433
2434/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002435 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 *
2437 * return FAIL for failure, OK for success
2438 */
2439 int
2440mch_FullName(fname, buf, len, force)
2441 char_u *fname, *buf;
2442 int len;
2443 int force; /* also expand when already absolute path */
2444{
2445 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002446#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 int only_drive; /* file name is only a drive letter */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002448#endif
2449#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 int fd = -1;
2451 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002452#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 char_u olddir[MAXPATHL];
2454 char_u *p;
2455 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002456#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002457 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2458 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002459#endif
2460
Bram Moolenaar38323e42007-03-06 19:22:53 +00002461#ifdef VMS
2462 fname = vms_fixfilename(fname);
2463#endif
2464
Bram Moolenaara2442432007-04-26 14:26:37 +00002465#ifdef __CYGWIN__
2466 /*
2467 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2468 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002469# if CYGWIN_VERSION_DLL_MAJOR >= 1007
2470 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL);
2471# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002472 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002473# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002474 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002475#endif
2476
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 /* expand it if forced or not an absolute path */
2478 if (force || !mch_isFullName(fname))
2479 {
2480 /*
2481 * If the file name has a path, change to that directory for a moment,
2482 * and then do the getwd() (and get back to where we were).
2483 * This will get the correct path name with "../" things.
2484 */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002485#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 only_drive = 0;
2487 if (((p = vim_strrchr(fname, '/')) != NULL)
2488 || ((p = vim_strrchr(fname, '\\')) != NULL)
2489 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
Bram Moolenaar38323e42007-03-06 19:22:53 +00002490#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 if ((p = vim_strrchr(fname, '/')) != NULL)
Bram Moolenaar38323e42007-03-06 19:22:53 +00002492#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002494#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 /*
2496 * Use fchdir() if possible, it's said to be faster and more
2497 * reliable. But on SunOS 4 it might not work. Check this by
2498 * doing a fchdir() right now.
2499 */
2500 if (!dont_fchdir)
2501 {
2502 fd = open(".", O_RDONLY | O_EXTRA, 0);
2503 if (fd >= 0 && fchdir(fd) < 0)
2504 {
2505 close(fd);
2506 fd = -1;
2507 dont_fchdir = TRUE; /* don't try again */
2508 }
2509 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511
2512 /* Only change directory when we are sure we can return to where
2513 * we are now. After doing "su" chdir(".") might not work. */
2514 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002515#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002517#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 (mch_dirname(olddir, MAXPATHL) == FAIL
2519 || mch_chdir((char *)olddir) != 0))
2520 {
2521 p = NULL; /* can't get current dir: don't chdir */
2522 retval = FAIL;
2523 }
2524 else
2525 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002526#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 /*
2528 * compensate for case where ':' from "D:" was the only
2529 * path separator detected in the file name; the _next_
2530 * character has to be removed, and then restored later.
2531 */
2532 if (only_drive)
2533 p++;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002534#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 /* The directory is copied into buf[], to be able to remove
2536 * the file name without changing it (could be a string in
2537 * read-only memory) */
2538 if (p - fname >= len)
2539 retval = FAIL;
2540 else
2541 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002542 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 if (mch_chdir((char *)buf))
2544 retval = FAIL;
2545 else
2546 fname = p + 1;
2547 *buf = NUL;
2548 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002549#ifdef OS2
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 if (only_drive)
2551 {
2552 p--;
2553 if (retval != FAIL)
2554 fname--;
2555 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 }
2558 }
2559 if (mch_dirname(buf, len) == FAIL)
2560 {
2561 retval = FAIL;
2562 *buf = NUL;
2563 }
2564 if (p != NULL)
2565 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002566#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 if (fd >= 0)
2568 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002569 if (p_verbose >= 5)
2570 {
2571 verbose_enter();
2572 MSG("fchdir() to previous dir");
2573 verbose_leave();
2574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 l = fchdir(fd);
2576 close(fd);
2577 }
2578 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002579#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 l = mch_chdir((char *)olddir);
2581 if (l != 0)
2582 EMSG(_(e_prev_dir));
2583 }
2584
2585 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002586 if (l >= len - 1)
2587 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002588#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002589 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002591 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002592#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002594
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002596 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 return FAIL;
2598
2599 /* Do not append ".", "/dir/." is equal to "/dir". */
2600 if (STRCMP(fname, ".") != 0)
2601 STRCAT(buf, fname);
2602
2603 return OK;
2604}
2605
2606/*
2607 * Return TRUE if "fname" does not depend on the current directory.
2608 */
2609 int
2610mch_isFullName(fname)
2611 char_u *fname;
2612{
2613#ifdef __EMX__
2614 return _fnisabs(fname);
2615#else
2616# ifdef VMS
2617 return ( fname[0] == '/' || fname[0] == '.' ||
2618 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2619 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2620 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2621# else
2622 return (*fname == '/' || *fname == '~');
2623# endif
2624#endif
2625}
2626
Bram Moolenaar24552be2005-12-10 20:17:30 +00002627#if defined(USE_FNAME_CASE) || defined(PROTO)
2628/*
2629 * Set the case of the file name, if it already exists. This will cause the
2630 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002631 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002632 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002633 void
2634fname_case(name, len)
2635 char_u *name;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00002636 int len UNUSED; /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002637{
2638 struct stat st;
2639 char_u *slash, *tail;
2640 DIR *dirp;
2641 struct dirent *dp;
2642
2643 if (lstat((char *)name, &st) >= 0)
2644 {
2645 /* Open the directory where the file is located. */
2646 slash = vim_strrchr(name, '/');
2647 if (slash == NULL)
2648 {
2649 dirp = opendir(".");
2650 tail = name;
2651 }
2652 else
2653 {
2654 *slash = NUL;
2655 dirp = opendir((char *)name);
2656 *slash = '/';
2657 tail = slash + 1;
2658 }
2659
2660 if (dirp != NULL)
2661 {
2662 while ((dp = readdir(dirp)) != NULL)
2663 {
2664 /* Only accept names that differ in case and are the same byte
2665 * length. TODO: accept different length name. */
2666 if (STRICMP(tail, dp->d_name) == 0
2667 && STRLEN(tail) == STRLEN(dp->d_name))
2668 {
2669 char_u newname[MAXPATHL + 1];
2670 struct stat st2;
2671
2672 /* Verify the inode is equal. */
2673 vim_strncpy(newname, name, MAXPATHL);
2674 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2675 MAXPATHL - (tail - name));
2676 if (lstat((char *)newname, &st2) >= 0
2677 && st.st_ino == st2.st_ino
2678 && st.st_dev == st2.st_dev)
2679 {
2680 STRCPY(tail, dp->d_name);
2681 break;
2682 }
2683 }
2684 }
2685
2686 closedir(dirp);
2687 }
2688 }
2689}
2690#endif
2691
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692/*
2693 * Get file permissions for 'name'.
2694 * Returns -1 when it doesn't exist.
2695 */
2696 long
2697mch_getperm(name)
2698 char_u *name;
2699{
2700 struct stat statb;
2701
2702 /* Keep the #ifdef outside of stat(), it may be a macro. */
2703#ifdef VMS
2704 if (stat((char *)vms_fixfilename(name), &statb))
2705#else
2706 if (stat((char *)name, &statb))
2707#endif
2708 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002709#ifdef __INTERIX
2710 /* The top bit makes the value negative, which means the file doesn't
2711 * exist. Remove the bit, we don't use it. */
2712 return statb.st_mode & ~S_ADDACE;
2713#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002715#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716}
2717
2718/*
2719 * set file permission for 'name' to 'perm'
2720 *
2721 * return FAIL for failure, OK otherwise
2722 */
2723 int
2724mch_setperm(name, perm)
2725 char_u *name;
2726 long perm;
2727{
2728 return (chmod((char *)
2729#ifdef VMS
2730 vms_fixfilename(name),
2731#else
2732 name,
2733#endif
2734 (mode_t)perm) == 0 ? OK : FAIL);
2735}
2736
2737#if defined(HAVE_ACL) || defined(PROTO)
2738# ifdef HAVE_SYS_ACL_H
2739# include <sys/acl.h>
2740# endif
2741# ifdef HAVE_SYS_ACCESS_H
2742# include <sys/access.h>
2743# endif
2744
2745# ifdef HAVE_SOLARIS_ACL
2746typedef struct vim_acl_solaris_T {
2747 int acl_cnt;
2748 aclent_t *acl_entry;
2749} vim_acl_solaris_T;
2750# endif
2751
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002752#if defined(HAVE_SELINUX) || defined(PROTO)
2753/*
2754 * Copy security info from "from_file" to "to_file".
2755 */
2756 void
2757mch_copy_sec(from_file, to_file)
2758 char_u *from_file;
2759 char_u *to_file;
2760{
2761 if (from_file == NULL)
2762 return;
2763
2764 if (selinux_enabled == -1)
2765 selinux_enabled = is_selinux_enabled();
2766
2767 if (selinux_enabled > 0)
2768 {
2769 security_context_t from_context = NULL;
2770 security_context_t to_context = NULL;
2771
2772 if (getfilecon((char *)from_file, &from_context) < 0)
2773 {
2774 /* If the filesystem doesn't support extended attributes,
2775 the original had no special security context and the
2776 target cannot have one either. */
2777 if (errno == EOPNOTSUPP)
2778 return;
2779
2780 MSG_PUTS(_("\nCould not get security context for "));
2781 msg_outtrans(from_file);
2782 msg_putchar('\n');
2783 return;
2784 }
2785 if (getfilecon((char *)to_file, &to_context) < 0)
2786 {
2787 MSG_PUTS(_("\nCould not get security context for "));
2788 msg_outtrans(to_file);
2789 msg_putchar('\n');
2790 freecon (from_context);
2791 return ;
2792 }
2793 if (strcmp(from_context, to_context) != 0)
2794 {
2795 if (setfilecon((char *)to_file, from_context) < 0)
2796 {
2797 MSG_PUTS(_("\nCould not set security context for "));
2798 msg_outtrans(to_file);
2799 msg_putchar('\n');
2800 }
2801 }
2802 freecon(to_context);
2803 freecon(from_context);
2804 }
2805}
2806#endif /* HAVE_SELINUX */
2807
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002808#if defined(HAVE_SMACK) && !defined(PROTO)
2809/*
2810 * Copy security info from "from_file" to "to_file".
2811 */
2812 void
2813mch_copy_sec(from_file, to_file)
2814 char_u *from_file;
2815 char_u *to_file;
2816{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002817 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002818 {
2819 XATTR_NAME_SMACK,
2820 XATTR_NAME_SMACKEXEC,
2821 XATTR_NAME_SMACKMMAP
2822 };
2823
2824 char buffer[SMACK_LABEL_LEN];
2825 const char *name;
2826 int index;
2827 int ret;
2828 ssize_t size;
2829
2830 if (from_file == NULL)
2831 return;
2832
2833 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2834 / sizeof(smack_copied_attributes)[0]) ; index++)
2835 {
2836 /* get the name of the attribute to copy */
2837 name = smack_copied_attributes[index];
2838
2839 /* get the value of the attribute in buffer */
2840 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2841 if (size >= 0)
2842 {
2843 /* copy the attribute value of buffer */
2844 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2845 if (ret < 0)
2846 {
2847 MSG_PUTS(_("Could not set security context "));
2848 MSG_PUTS(name);
2849 MSG_PUTS(_(" for "));
2850 msg_outtrans(to_file);
2851 msg_putchar('\n');
2852 }
2853 }
2854 else
2855 {
2856 /* what reason of not having the attribute value? */
2857 switch (errno)
2858 {
2859 case ENOTSUP:
2860 /* extended attributes aren't supported or enabled */
2861 /* should a message be echoed? not sure... */
2862 return; /* leave because it isn't usefull to continue */
2863
2864 case ERANGE:
2865 default:
2866 /* no enough size OR unexpected error */
2867 MSG_PUTS(_("Could not get security context "));
2868 MSG_PUTS(name);
2869 MSG_PUTS(_(" for "));
2870 msg_outtrans(from_file);
2871 MSG_PUTS(_(". Removing it!\n"));
2872 /* FALLTHROUGH to remove the attribute */
2873
2874 case ENODATA:
2875 /* no attribute of this name */
2876 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002877 /* Silently ignore errors, apparently this happens when
2878 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002879 break;
2880 }
2881 }
2882 }
2883}
2884#endif /* HAVE_SMACK */
2885
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886/*
2887 * Return a pointer to the ACL of file "fname" in allocated memory.
2888 * Return NULL if the ACL is not available for whatever reason.
2889 */
2890 vim_acl_T
2891mch_get_acl(fname)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002892 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893{
2894 vim_acl_T ret = NULL;
2895#ifdef HAVE_POSIX_ACL
2896 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2897#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002898#ifdef HAVE_SOLARIS_ZFS_ACL
2899 acl_t *aclent;
2900
2901 if (acl_get((char *)fname, 0, &aclent) < 0)
2902 return NULL;
2903 ret = (vim_acl_T)aclent;
2904#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905#ifdef HAVE_SOLARIS_ACL
2906 vim_acl_solaris_T *aclent;
2907
2908 aclent = malloc(sizeof(vim_acl_solaris_T));
2909 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2910 {
2911 free(aclent);
2912 return NULL;
2913 }
2914 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2915 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2916 {
2917 free(aclent->acl_entry);
2918 free(aclent);
2919 return NULL;
2920 }
2921 ret = (vim_acl_T)aclent;
2922#else
2923#if defined(HAVE_AIX_ACL)
2924 int aclsize;
2925 struct acl *aclent;
2926
2927 aclsize = sizeof(struct acl);
2928 aclent = malloc(aclsize);
2929 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2930 {
2931 if (errno == ENOSPC)
2932 {
2933 aclsize = aclent->acl_len;
2934 aclent = realloc(aclent, aclsize);
2935 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2936 {
2937 free(aclent);
2938 return NULL;
2939 }
2940 }
2941 else
2942 {
2943 free(aclent);
2944 return NULL;
2945 }
2946 }
2947 ret = (vim_acl_T)aclent;
2948#endif /* HAVE_AIX_ACL */
2949#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002950#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951#endif /* HAVE_POSIX_ACL */
2952 return ret;
2953}
2954
2955/*
2956 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2957 */
2958 void
2959mch_set_acl(fname, aclent)
Bram Moolenaar78a15312009-05-15 19:33:18 +00002960 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 vim_acl_T aclent;
2962{
2963 if (aclent == NULL)
2964 return;
2965#ifdef HAVE_POSIX_ACL
2966 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2967#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002968#ifdef HAVE_SOLARIS_ZFS_ACL
2969 acl_set((char *)fname, (acl_t *)aclent);
2970#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971#ifdef HAVE_SOLARIS_ACL
2972 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2973 ((vim_acl_solaris_T *)aclent)->acl_entry);
2974#else
2975#ifdef HAVE_AIX_ACL
2976 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2977#endif /* HAVE_AIX_ACL */
2978#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002979#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980#endif /* HAVE_POSIX_ACL */
2981}
2982
2983 void
2984mch_free_acl(aclent)
2985 vim_acl_T aclent;
2986{
2987 if (aclent == NULL)
2988 return;
2989#ifdef HAVE_POSIX_ACL
2990 acl_free((acl_t)aclent);
2991#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002992#ifdef HAVE_SOLARIS_ZFS_ACL
2993 acl_free((acl_t *)aclent);
2994#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995#ifdef HAVE_SOLARIS_ACL
2996 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2997 free(aclent);
2998#else
2999#ifdef HAVE_AIX_ACL
3000 free(aclent);
3001#endif /* HAVE_AIX_ACL */
3002#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003003#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004#endif /* HAVE_POSIX_ACL */
3005}
3006#endif
3007
3008/*
3009 * Set hidden flag for "name".
3010 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 void
3012mch_hide(name)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003013 char_u *name UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014{
3015 /* can't hide a file */
3016}
3017
3018/*
3019 * return TRUE if "name" is a directory
3020 * return FALSE if "name" is not a directory
3021 * return FALSE for error
3022 */
3023 int
3024mch_isdir(name)
3025 char_u *name;
3026{
3027 struct stat statb;
3028
3029 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3030 return FALSE;
3031 if (stat((char *)name, &statb))
3032 return FALSE;
3033#ifdef _POSIX_SOURCE
3034 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
3035#else
3036 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
3037#endif
3038}
3039
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040static int executable_file __ARGS((char_u *name));
3041
3042/*
3043 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3044 */
3045 static int
3046executable_file(name)
3047 char_u *name;
3048{
3049 struct stat st;
3050
3051 if (stat((char *)name, &st))
3052 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003053#ifdef VMS
3054 /* Like on Unix system file can have executable rights but not necessarily
3055 * be an executable, but on Unix is not a default for an ordianry file to
3056 * have an executable flag - on VMS it is in most cases.
3057 * Therefore, this check does not have any sense - let keep us to the
3058 * conventions instead:
3059 * *.COM and *.EXE files are the executables - the rest are not. This is
3060 * not ideal but better then it was.
3061 */
3062 int vms_executable = 0;
3063 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3064 {
3065 if (strstr(vms_tolower((char*)name),".exe") != NULL
3066 || strstr(vms_tolower((char*)name),".com")!= NULL)
3067 vms_executable = 1;
3068 }
3069 return vms_executable;
3070#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003072#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073}
3074
3075/*
3076 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
3077 * Return -1 if unknown.
3078 */
3079 int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003080mch_can_exe(name, path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 char_u *name;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003082 char_u **path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083{
3084 char_u *buf;
3085 char_u *p, *e;
3086 int retval;
3087
3088 /* If it's an absolute or relative path don't need to use $PATH. */
3089 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
3090 || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003091 {
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003092 if (executable_file(name))
3093 {
3094 if (path != NULL)
3095 {
3096 if (name[0] == '.')
3097 *path = FullName_save(name, TRUE);
3098 else
3099 *path = vim_strsave(name);
3100 }
3101 return TRUE;
3102 }
3103 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003104 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105
3106 p = (char_u *)getenv("PATH");
3107 if (p == NULL || *p == NUL)
3108 return -1;
3109 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3110 if (buf == NULL)
3111 return -1;
3112
3113 /*
3114 * Walk through all entries in $PATH to check if "name" exists there and
3115 * is an executable file.
3116 */
3117 for (;;)
3118 {
3119 e = (char_u *)strchr((char *)p, ':');
3120 if (e == NULL)
3121 e = p + STRLEN(p);
3122 if (e - p <= 1) /* empty entry means current dir */
3123 STRCPY(buf, "./");
3124 else
3125 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003126 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 add_pathsep(buf);
3128 }
3129 STRCAT(buf, name);
3130 retval = executable_file(buf);
3131 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003132 {
3133 if (path != NULL)
3134 {
3135 if (buf[0] == '.')
3136 *path = FullName_save(buf, TRUE);
3137 else
3138 *path = vim_strsave(buf);
3139 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003141 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142
3143 if (*e != ':')
3144 break;
3145 p = e + 1;
3146 }
3147
3148 vim_free(buf);
3149 return retval;
3150}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151
3152/*
3153 * Check what "name" is:
3154 * NODE_NORMAL: file or directory (or doesn't exist)
3155 * NODE_WRITABLE: writable device, socket, fifo, etc.
3156 * NODE_OTHER: non-writable things
3157 */
3158 int
3159mch_nodetype(name)
3160 char_u *name;
3161{
3162 struct stat st;
3163
3164 if (stat((char *)name, &st))
3165 return NODE_NORMAL;
3166 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3167 return NODE_NORMAL;
3168#ifndef OS2
3169 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3170 return NODE_OTHER;
3171#endif
3172 /* Everything else is writable? */
3173 return NODE_WRITABLE;
3174}
3175
3176 void
3177mch_early_init()
3178{
3179#ifdef HAVE_CHECK_STACK_GROWTH
3180 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 check_stack_growth((char *)&i);
3183
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003184# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 get_stack_limit();
3186# endif
3187
3188#endif
3189
3190 /*
3191 * Setup an alternative stack for signals. Helps to catch signals when
3192 * running out of stack space.
3193 * Use of sigaltstack() is preferred, it's more portable.
3194 * Ignore any errors.
3195 */
3196#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003197 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 init_signal_stack();
3199#endif
3200}
3201
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003202#if defined(EXITFREE) || defined(PROTO)
3203 void
3204mch_free_mem()
3205{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003206# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3207 if (clip_star.owned)
3208 clip_lose_selection(&clip_star);
3209 if (clip_plus.owned)
3210 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003211# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003212# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003213 if (xterm_Shell != (Widget)0)
3214 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003215# ifndef LESSTIF_VERSION
3216 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003217 if (xterm_dpy != NULL)
3218 XtCloseDisplay(xterm_dpy);
3219 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003220 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003221 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003222# ifdef FEAT_X11
3223 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3224# endif
3225 }
3226# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003227# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003228# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003229 if (x11_display != NULL
3230# ifdef FEAT_XCLIPBOARD
3231 && x11_display != xterm_dpy
3232# endif
3233 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003234 XCloseDisplay(x11_display);
3235# endif
3236# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
3237 vim_free(signal_stack);
3238 signal_stack = NULL;
3239# endif
3240# ifdef FEAT_TITLE
3241 vim_free(oldtitle);
3242 vim_free(oldicon);
3243# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003244}
3245#endif
3246
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247static void exit_scroll __ARGS((void));
3248
3249/*
3250 * Output a newline when exiting.
3251 * Make sure the newline goes to the same stream as the text.
3252 */
3253 static void
3254exit_scroll()
3255{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003256 if (silent_mode)
3257 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 if (newline_on_exit || msg_didout)
3259 {
3260 if (msg_use_printf())
3261 {
3262 if (info_message)
3263 mch_msg("\n");
3264 else
3265 mch_errmsg("\r\n");
3266 }
3267 else
3268 out_char('\n');
3269 }
3270 else
3271 {
3272 restore_cterm_colors(); /* get original colors back */
3273 msg_clr_eos_force(); /* clear the rest of the display */
3274 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3275 }
3276}
3277
3278 void
3279mch_exit(r)
3280 int r;
3281{
3282 exiting = TRUE;
3283
3284#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3285 x11_export_final_selection();
3286#endif
3287
3288#ifdef FEAT_GUI
3289 if (!gui.in_use)
3290#endif
3291 {
3292 settmode(TMODE_COOK);
3293#ifdef FEAT_TITLE
3294 mch_restore_title(3); /* restore xterm title and icon name */
3295#endif
3296 /*
3297 * When t_ti is not empty but it doesn't cause swapping terminal
3298 * pages, need to output a newline when msg_didout is set. But when
3299 * t_ti does swap pages it should not go to the shell page. Do this
3300 * before stoptermcap().
3301 */
3302 if (swapping_screen() && !newline_on_exit)
3303 exit_scroll();
3304
3305 /* Stop termcap: May need to check for T_CRV response, which
3306 * requires RAW mode. */
3307 stoptermcap();
3308
3309 /*
3310 * A newline is only required after a message in the alternate screen.
3311 * This is set to TRUE by wait_return().
3312 */
3313 if (!swapping_screen() || newline_on_exit)
3314 exit_scroll();
3315
3316 /* Cursor may have been switched off without calling starttermcap()
3317 * when doing "vim -u vimrc" and vimrc contains ":q". */
3318 if (full_screen)
3319 cursor_on();
3320 }
3321 out_flush();
3322 ml_close_all(TRUE); /* remove all memfiles */
3323 may_core_dump();
3324#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 gui_exit(r);
3327#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003328
Bram Moolenaar56718732006-03-15 22:53:57 +00003329#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003330 mac_conv_cleanup();
3331#endif
3332
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333#ifdef __QNX__
3334 /* A core dump won't be created if the signal handler
3335 * doesn't return, so we can't call exit() */
3336 if (deadly_signal != 0)
3337 return;
3338#endif
3339
Bram Moolenaar009b2592004-10-24 19:18:58 +00003340#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003341 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003342#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003343
3344#ifdef EXITFREE
3345 free_all_mem();
3346#endif
3347
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 exit(r);
3349}
3350
3351 static void
3352may_core_dump()
3353{
3354 if (deadly_signal != 0)
3355 {
3356 signal(deadly_signal, SIG_DFL);
3357 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3358 }
3359}
3360
3361#ifndef VMS
3362
3363 void
3364mch_settmode(tmode)
3365 int tmode;
3366{
3367 static int first = TRUE;
3368
3369 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3370#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3371 /*
3372 * for "new" tty systems
3373 */
3374# ifdef HAVE_TERMIOS_H
3375 static struct termios told;
3376 struct termios tnew;
3377# else
3378 static struct termio told;
3379 struct termio tnew;
3380# endif
3381
3382 if (first)
3383 {
3384 first = FALSE;
3385# if defined(HAVE_TERMIOS_H)
3386 tcgetattr(read_cmd_fd, &told);
3387# else
3388 ioctl(read_cmd_fd, TCGETA, &told);
3389# endif
3390 }
3391
3392 tnew = told;
3393 if (tmode == TMODE_RAW)
3394 {
3395 /*
3396 * ~ICRNL enables typing ^V^M
3397 */
3398 tnew.c_iflag &= ~ICRNL;
3399 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3400# if defined(IEXTEN) && !defined(__MINT__)
3401 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3402 /* but it breaks function keys on MINT */
3403# endif
3404 );
3405# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3406 tnew.c_oflag &= ~ONLCR;
3407# endif
3408 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3409 tnew.c_cc[VTIME] = 0; /* don't wait */
3410 }
3411 else if (tmode == TMODE_SLEEP)
3412 tnew.c_lflag &= ~(ECHO);
3413
3414# if defined(HAVE_TERMIOS_H)
3415 {
3416 int n = 10;
3417
3418 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3419 * few times. */
3420 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3421 && errno == EINTR && n > 0)
3422 --n;
3423 }
3424# else
3425 ioctl(read_cmd_fd, TCSETA, &tnew);
3426# endif
3427
3428#else
3429
3430 /*
3431 * for "old" tty systems
3432 */
3433# ifndef TIOCSETN
3434# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3435# endif
3436 static struct sgttyb ttybold;
3437 struct sgttyb ttybnew;
3438
3439 if (first)
3440 {
3441 first = FALSE;
3442 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3443 }
3444
3445 ttybnew = ttybold;
3446 if (tmode == TMODE_RAW)
3447 {
3448 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3449 ttybnew.sg_flags |= RAW;
3450 }
3451 else if (tmode == TMODE_SLEEP)
3452 ttybnew.sg_flags &= ~(ECHO);
3453 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3454#endif
3455 curr_tmode = tmode;
3456}
3457
3458/*
3459 * Try to get the code for "t_kb" from the stty setting
3460 *
3461 * Even if termcap claims a backspace key, the user's setting *should*
3462 * prevail. stty knows more about reality than termcap does, and if
3463 * somebody's usual erase key is DEL (which, for most BSD users, it will
3464 * be), they're going to get really annoyed if their erase key starts
3465 * doing forward deletes for no reason. (Eric Fischer)
3466 */
3467 void
3468get_stty()
3469{
3470 char_u buf[2];
3471 char_u *p;
3472
3473 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3474#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3475 /* for "new" tty systems */
3476# ifdef HAVE_TERMIOS_H
3477 struct termios keys;
3478# else
3479 struct termio keys;
3480# endif
3481
3482# if defined(HAVE_TERMIOS_H)
3483 if (tcgetattr(read_cmd_fd, &keys) != -1)
3484# else
3485 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3486# endif
3487 {
3488 buf[0] = keys.c_cc[VERASE];
3489 intr_char = keys.c_cc[VINTR];
3490#else
3491 /* for "old" tty systems */
3492 struct sgttyb keys;
3493
3494 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3495 {
3496 buf[0] = keys.sg_erase;
3497 intr_char = keys.sg_kill;
3498#endif
3499 buf[1] = NUL;
3500 add_termcode((char_u *)"kb", buf, FALSE);
3501
3502 /*
3503 * If <BS> and <DEL> are now the same, redefine <DEL>.
3504 */
3505 p = find_termcode((char_u *)"kD");
3506 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3507 do_fixdel(NULL);
3508 }
3509#if 0
3510 } /* to keep cindent happy */
3511#endif
3512}
3513
3514#endif /* VMS */
3515
3516#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3517/*
3518 * Set mouse clicks on or off.
3519 */
3520 void
3521mch_setmouse(on)
3522 int on;
3523{
3524 static int ison = FALSE;
3525 int xterm_mouse_vers;
3526
3527 if (on == ison) /* return quickly if nothing to do */
3528 return;
3529
3530 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003531
3532# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003533 if (ttym_flags == TTYM_URXVT)
3534 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003535 out_str_nf((char_u *)
3536 (on
3537 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3538 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
3539 ison = on;
3540 }
3541# endif
3542
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003543# ifdef FEAT_MOUSE_SGR
3544 if (ttym_flags == TTYM_SGR)
3545 {
3546 out_str_nf((char_u *)
3547 (on
3548 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3549 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
3550 ison = on;
3551 }
3552# endif
3553
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 if (xterm_mouse_vers > 0)
3555 {
3556 if (on) /* enable mouse events, use mouse tracking if available */
3557 out_str_nf((char_u *)
3558 (xterm_mouse_vers > 1
3559 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3560 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3561 else /* disable mouse events, could probably always send the same */
3562 out_str_nf((char_u *)
3563 (xterm_mouse_vers > 1
3564 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3565 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3566 ison = on;
3567 }
3568
3569# ifdef FEAT_MOUSE_DEC
3570 else if (ttym_flags == TTYM_DEC)
3571 {
3572 if (on) /* enable mouse events */
3573 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3574 else /* disable mouse events */
3575 out_str_nf((char_u *)"\033['z");
3576 ison = on;
3577 }
3578# endif
3579
3580# ifdef FEAT_MOUSE_GPM
3581 else
3582 {
3583 if (on)
3584 {
3585 if (gpm_open())
3586 ison = TRUE;
3587 }
3588 else
3589 {
3590 gpm_close();
3591 ison = FALSE;
3592 }
3593 }
3594# endif
3595
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003596# ifdef FEAT_SYSMOUSE
3597 else
3598 {
3599 if (on)
3600 {
3601 if (sysmouse_open() == OK)
3602 ison = TRUE;
3603 }
3604 else
3605 {
3606 sysmouse_close();
3607 ison = FALSE;
3608 }
3609 }
3610# endif
3611
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612# ifdef FEAT_MOUSE_JSB
3613 else
3614 {
3615 if (on)
3616 {
3617 /* D - Enable Mouse up/down messages
3618 * L - Enable Left Button Reporting
3619 * M - Enable Middle Button Reporting
3620 * R - Enable Right Button Reporting
3621 * K - Enable SHIFT and CTRL key Reporting
3622 * + - Enable Advanced messaging of mouse moves and up/down messages
3623 * Q - Quiet No Ack
3624 * # - Numeric value of mouse pointer required
3625 * 0 = Multiview 2000 cursor, used as standard
3626 * 1 = Windows Arrow
3627 * 2 = Windows I Beam
3628 * 3 = Windows Hour Glass
3629 * 4 = Windows Cross Hair
3630 * 5 = Windows UP Arrow
3631 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003632# ifdef JSBTERM_MOUSE_NONADVANCED
3633 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3635 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003636# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3638 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003639# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 ison = TRUE;
3641 }
3642 else
3643 {
3644 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3645 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3646 ison = FALSE;
3647 }
3648 }
3649# endif
3650# ifdef FEAT_MOUSE_PTERM
3651 else
3652 {
3653 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3654 if (on)
3655 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3656 else
3657 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3658 ison = on;
3659 }
3660# endif
3661}
3662
3663/*
3664 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3665 */
3666 void
3667check_mouse_termcode()
3668{
3669# ifdef FEAT_MOUSE_XTERM
3670 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003671# ifdef FEAT_MOUSE_URXVT
3672 && use_xterm_mouse() != 3
3673# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674# ifdef FEAT_GUI
3675 && !gui.in_use
3676# endif
3677 )
3678 {
3679 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003680 ? IF_EB("\233M", CSI_STR "M")
3681 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 if (*p_mouse != NUL)
3683 {
3684 /* force mouse off and maybe on to send possibly new mouse
3685 * activation sequence to the xterm, with(out) drag tracing. */
3686 mch_setmouse(FALSE);
3687 setmouse();
3688 }
3689 }
3690 else
3691 del_mouse_termcode(KS_MOUSE);
3692# endif
3693
3694# ifdef FEAT_MOUSE_GPM
3695 if (!use_xterm_mouse()
3696# ifdef FEAT_GUI
3697 && !gui.in_use
3698# endif
3699 )
3700 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3701# endif
3702
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003703# ifdef FEAT_SYSMOUSE
3704 if (!use_xterm_mouse()
3705# ifdef FEAT_GUI
3706 && !gui.in_use
3707# endif
3708 )
3709 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3710# endif
3711
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003713 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 if (!use_xterm_mouse()
3715# ifdef FEAT_GUI
3716 && !gui.in_use
3717# endif
3718 )
3719 set_mouse_termcode(KS_JSBTERM_MOUSE,
3720 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3721 else
3722 del_mouse_termcode(KS_JSBTERM_MOUSE);
3723# endif
3724
3725# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003726 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 * define it in the GUI or when using an xterm. */
3728 if (!use_xterm_mouse()
3729# ifdef FEAT_GUI
3730 && !gui.in_use
3731# endif
3732 )
3733 set_mouse_termcode(KS_NETTERM_MOUSE,
3734 (char_u *)IF_EB("\033}", ESC_STR "}"));
3735 else
3736 del_mouse_termcode(KS_NETTERM_MOUSE);
3737# endif
3738
3739# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003740 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003741 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742# ifdef FEAT_GUI
3743 && !gui.in_use
3744# endif
3745 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003746 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3747 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 else
3749 del_mouse_termcode(KS_DEC_MOUSE);
3750# endif
3751# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003752 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003753 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754# ifdef FEAT_GUI
3755 && !gui.in_use
3756# endif
3757 )
3758 set_mouse_termcode(KS_PTERM_MOUSE,
3759 (char_u *) IF_EB("\033[", ESC_STR "["));
3760 else
3761 del_mouse_termcode(KS_PTERM_MOUSE);
3762# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003763# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003764 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003765 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003766# ifdef FEAT_GUI
3767 && !gui.in_use
3768# endif
3769 )
3770 {
3771 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3772 ? IF_EB("\233", CSI_STR)
3773 : IF_EB("\033[", ESC_STR "[")));
3774
3775 if (*p_mouse != NUL)
3776 {
3777 mch_setmouse(FALSE);
3778 setmouse();
3779 }
3780 }
3781 else
3782 del_mouse_termcode(KS_URXVT_MOUSE);
3783# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003784# ifdef FEAT_MOUSE_SGR
Bram Moolenaar24dc2302014-05-13 20:19:58 +02003785 /* There is no conflict with xterm mouse */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003786 if (use_xterm_mouse() == 4
3787# ifdef FEAT_GUI
3788 && !gui.in_use
3789# endif
3790 )
3791 {
3792 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3793 ? IF_EB("\233<", CSI_STR "<")
3794 : IF_EB("\033[<", ESC_STR "[<")));
3795
3796 if (*p_mouse != NUL)
3797 {
3798 mch_setmouse(FALSE);
3799 setmouse();
3800 }
3801 }
3802 else
3803 del_mouse_termcode(KS_SGR_MOUSE);
3804# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003805}
3806#endif
3807
3808/*
3809 * set screen mode, always fails.
3810 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 int
3812mch_screenmode(arg)
Bram Moolenaar78a15312009-05-15 19:33:18 +00003813 char_u *arg UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814{
3815 EMSG(_(e_screenmode));
3816 return FAIL;
3817}
3818
3819#ifndef VMS
3820
3821/*
3822 * Try to get the current window size:
3823 * 1. with an ioctl(), most accurate method
3824 * 2. from the environment variables LINES and COLUMNS
3825 * 3. from the termcap
3826 * 4. keep using the old values
3827 * Return OK when size could be determined, FAIL otherwise.
3828 */
3829 int
3830mch_get_shellsize()
3831{
3832 long rows = 0;
3833 long columns = 0;
3834 char_u *p;
3835
3836 /*
3837 * For OS/2 use _scrsize().
3838 */
3839# ifdef __EMX__
3840 {
3841 int s[2];
3842
3843 _scrsize(s);
3844 columns = s[0];
3845 rows = s[1];
3846 }
3847# endif
3848
3849 /*
3850 * 1. try using an ioctl. It is the most accurate method.
3851 *
3852 * Try using TIOCGWINSZ first, some systems that have it also define
3853 * TIOCGSIZE but don't have a struct ttysize.
3854 */
3855# ifdef TIOCGWINSZ
3856 {
3857 struct winsize ws;
3858 int fd = 1;
3859
3860 /* When stdout is not a tty, use stdin for the ioctl(). */
3861 if (!isatty(fd) && isatty(read_cmd_fd))
3862 fd = read_cmd_fd;
3863 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3864 {
3865 columns = ws.ws_col;
3866 rows = ws.ws_row;
3867 }
3868 }
3869# else /* TIOCGWINSZ */
3870# ifdef TIOCGSIZE
3871 {
3872 struct ttysize ts;
3873 int fd = 1;
3874
3875 /* When stdout is not a tty, use stdin for the ioctl(). */
3876 if (!isatty(fd) && isatty(read_cmd_fd))
3877 fd = read_cmd_fd;
3878 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3879 {
3880 columns = ts.ts_cols;
3881 rows = ts.ts_lines;
3882 }
3883 }
3884# endif /* TIOCGSIZE */
3885# endif /* TIOCGWINSZ */
3886
3887 /*
3888 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003889 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3890 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003892 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 {
3894 if ((p = (char_u *)getenv("LINES")))
3895 rows = atoi((char *)p);
3896 if ((p = (char_u *)getenv("COLUMNS")))
3897 columns = atoi((char *)p);
3898 }
3899
3900#ifdef HAVE_TGETENT
3901 /*
3902 * 3. try reading "co" and "li" entries from termcap
3903 */
3904 if (columns == 0 || rows == 0)
3905 getlinecol(&columns, &rows);
3906#endif
3907
3908 /*
3909 * 4. If everything fails, use the old values
3910 */
3911 if (columns <= 0 || rows <= 0)
3912 return FAIL;
3913
3914 Rows = rows;
3915 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02003916 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917 return OK;
3918}
3919
3920/*
3921 * Try to set the window size to Rows and Columns.
3922 */
3923 void
3924mch_set_shellsize()
3925{
3926 if (*T_CWS)
3927 {
3928 /*
3929 * NOTE: if you get an error here that term_set_winsize() is
3930 * undefined, check the output of configure. It could probably not
3931 * find a ncurses, termcap or termlib library.
3932 */
3933 term_set_winsize((int)Rows, (int)Columns);
3934 out_flush();
3935 screen_start(); /* don't know where cursor is now */
3936 }
3937}
3938
3939#endif /* VMS */
3940
3941/*
3942 * Rows and/or Columns has changed.
3943 */
3944 void
3945mch_new_shellsize()
3946{
3947 /* Nothing to do. */
3948}
3949
Bram Moolenaar205b8862011-09-07 15:04:31 +02003950/*
3951 * Wait for process "child" to end.
3952 * Return "child" if it exited properly, <= 0 on error.
3953 */
3954 static pid_t
3955wait4pid(child, status)
3956 pid_t child;
3957 waitstatus *status;
3958{
3959 pid_t wait_pid = 0;
3960
3961 while (wait_pid != child)
3962 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003963 /* When compiled with Python threads are probably used, in which case
3964 * wait() sometimes hangs for no obvious reason. Use waitpid()
3965 * instead and loop (like the GUI). Also needed for other interfaces,
3966 * they might call system(). */
3967# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02003968 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003969# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02003970 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02003971# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02003972 if (wait_pid == 0)
3973 {
Bram Moolenaar75676462013-01-30 14:55:42 +01003974 /* Wait for 10 msec before trying again. */
Bram Moolenaar205b8862011-09-07 15:04:31 +02003975 mch_delay(10L, TRUE);
3976 continue;
3977 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02003978 if (wait_pid <= 0
3979# ifdef ECHILD
3980 && errno == ECHILD
3981# endif
3982 )
3983 break;
3984 }
3985 return wait_pid;
3986}
3987
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 int
3989mch_call_shell(cmd, options)
3990 char_u *cmd;
3991 int options; /* SHELL_*, see vim.h */
3992{
3993#ifdef VMS
3994 char *ifn = NULL;
3995 char *ofn = NULL;
3996#endif
3997 int tmode = cur_tmode;
3998#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3999 int x;
4000# ifndef __EMX__
4001 char_u *newcmd; /* only needed for unix */
4002# else
4003 /*
4004 * Set the preferred shell in the EMXSHELL environment variable (but
4005 * only if it is different from what is already in the environment).
4006 * Emx then takes care of whether to use "/c" or "-c" in an
4007 * intelligent way. Simply pass the whole thing to emx's system() call.
4008 * Emx also starts an interactive shell if system() is passed an empty
4009 * string.
4010 */
4011 char_u *p, *old;
4012
4013 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
4014 {
4015 /* should check HAVE_SETENV, but I know we don't have it. */
4016 p = alloc(10 + strlen(p_sh));
4017 if (p)
4018 {
4019 sprintf((char *)p, "EMXSHELL=%s", p_sh);
4020 putenv((char *)p); /* don't free the pointer! */
4021 }
4022 }
4023# endif
4024
4025 out_flush();
4026
4027 if (options & SHELL_COOKED)
4028 settmode(TMODE_COOK); /* set to normal mode */
4029
Bram Moolenaar62b42182010-09-21 22:09:37 +02004030# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004031 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004032 loose_clipboard();
4033# endif
4034
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035# ifdef __EMX__
4036 if (cmd == NULL)
4037 x = system(""); /* this starts an interactive shell in emx */
4038 else
4039 x = system((char *)cmd);
4040 /* system() returns -1 when error occurs in starting shell */
4041 if (x == -1 && !emsg_silent)
4042 {
4043 MSG_PUTS(_("\nCannot execute shell "));
4044 msg_outtrans(p_sh);
4045 msg_putchar('\n');
4046 }
4047# else /* not __EMX__ */
4048 if (cmd == NULL)
4049 x = system((char *)p_sh);
4050 else
4051 {
4052# ifdef VMS
4053 if (ofn = strchr((char *)cmd, '>'))
4054 *ofn++ = '\0';
4055 if (ifn = strchr((char *)cmd, '<'))
4056 {
4057 char *p;
4058
4059 *ifn++ = '\0';
4060 p = strchr(ifn,' '); /* chop off any trailing spaces */
4061 if (p)
4062 *p = '\0';
4063 }
4064 if (ofn)
4065 x = vms_sys((char *)cmd, ofn, ifn);
4066 else
4067 x = system((char *)cmd);
4068# else
4069 newcmd = lalloc(STRLEN(p_sh)
4070 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4071 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4072 if (newcmd == NULL)
4073 x = 0;
4074 else
4075 {
4076 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4077 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4078 (char *)p_shcf,
4079 (char *)cmd);
4080 x = system((char *)newcmd);
4081 vim_free(newcmd);
4082 }
4083# endif
4084 }
4085# ifdef VMS
4086 x = vms_sys_status(x);
4087# endif
4088 if (emsg_silent)
4089 ;
4090 else if (x == 127)
4091 MSG_PUTS(_("\nCannot execute shell sh\n"));
4092# endif /* __EMX__ */
4093 else if (x && !(options & SHELL_SILENT))
4094 {
4095 MSG_PUTS(_("\nshell returned "));
4096 msg_outnum((long)x);
4097 msg_putchar('\n');
4098 }
4099
4100 if (tmode == TMODE_RAW)
4101 settmode(TMODE_RAW); /* set to raw mode */
4102# ifdef FEAT_TITLE
4103 resettitle();
4104# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004105# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4106 restore_clipboard();
4107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 return x;
4109
4110#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
4111
Bram Moolenaardf177f62005-02-22 08:39:57 +00004112# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4113 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114
4115 char_u *newcmd = NULL;
4116 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004117 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 pid_t wait_pid = 0;
4119# ifdef HAVE_UNION_WAIT
4120 union wait status;
4121# else
4122 int status = -1;
4123# endif
4124 int retval = -1;
4125 char **argv = NULL;
4126 int argc;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004127 char_u *p_shcf_copy = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 int i;
4129 char_u *p;
4130 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004132# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 int pty_slave_fd = -1;
4134 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004135# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004136 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 int fd_fromshell[2];
4138 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004139# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004141# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 static char envbuf_Rows[20];
4143 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004145 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146
Bram Moolenaar62b42182010-09-21 22:09:37 +02004147 newcmd = vim_strsave(p_sh);
4148 if (newcmd == NULL) /* out of memory */
4149 goto error;
4150
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 out_flush();
4152 if (options & SHELL_COOKED)
4153 settmode(TMODE_COOK); /* set to normal mode */
4154
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004155 /*
4156 * Do this loop twice:
4157 * 1: find number of arguments
4158 * 2: separate them and build argv[]
4159 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 for (i = 0; i < 2; ++i)
4161 {
4162 p = newcmd;
4163 inquote = FALSE;
4164 argc = 0;
4165 for (;;)
4166 {
4167 if (i == 1)
4168 argv[argc] = (char *)p;
4169 ++argc;
4170 while (*p && (inquote || (*p != ' ' && *p != TAB)))
4171 {
4172 if (*p == '"')
4173 inquote = !inquote;
4174 ++p;
4175 }
4176 if (*p == NUL)
4177 break;
4178 if (i == 1)
4179 *p++ = NUL;
4180 p = skipwhite(p);
4181 }
Bram Moolenaareb3593b2006-04-22 22:33:57 +00004182 if (argv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 {
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004184 /*
4185 * Account for possible multiple args in p_shcf.
4186 */
4187 p = p_shcf;
4188 for (;;)
4189 {
4190 p = skiptowhite(p);
4191 if (*p == NUL)
4192 break;
4193 ++argc;
4194 p = skipwhite(p);
4195 }
4196
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
4198 if (argv == NULL) /* out of memory */
4199 goto error;
4200 }
4201 }
4202 if (cmd != NULL)
4203 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004204 char_u *s;
4205
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 if (extra_shell_arg != NULL)
4207 argv[argc++] = (char *)extra_shell_arg;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004208
4209 /* Break 'shellcmdflag' into white separated parts. This doesn't
4210 * handle quoted strings, they are very unlikely to appear. */
4211 p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1);
4212 if (p_shcf_copy == NULL) /* out of memory */
4213 goto error;
4214 s = p_shcf_copy;
4215 p = p_shcf;
4216 while (*p != NUL)
4217 {
4218 argv[argc++] = (char *)s;
4219 while (*p && *p != ' ' && *p != TAB)
4220 *s++ = *p++;
4221 *s++ = NUL;
4222 p = skipwhite(p);
4223 }
4224
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225 argv[argc++] = (char *)cmd;
4226 }
4227 argv[argc] = NULL;
4228
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004230 * For the GUI, when writing the output into the buffer and when reading
4231 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4232 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004234 if ((options & (SHELL_READ|SHELL_WRITE))
4235# ifdef FEAT_GUI
4236 || (gui.in_use && show_shell_mess)
4237# endif
4238 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004240# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 /*
4242 * Try to open a master pty.
4243 * If this works, open the slave pty.
4244 * If the slave can't be opened, close the master pty.
4245 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004246 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 {
4248 pty_master_fd = OpenPTY(&tty_name); /* open pty */
Bram Moolenaare70172e2011-08-04 19:36:52 +02004249 if (pty_master_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004250 {
Bram Moolenaare70172e2011-08-04 19:36:52 +02004251 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4252 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4253 * adding O_NOCTTY always works when defined. */
4254#ifdef O_NOCTTY
4255 pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4256#else
4257 pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4258#endif
4259 if (pty_slave_fd < 0)
4260 {
4261 close(pty_master_fd);
4262 pty_master_fd = -1;
4263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264 }
4265 }
4266 /*
4267 * If not opening a pty or it didn't work, try using pipes.
4268 */
4269 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004270# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 {
4272 pipe_error = (pipe(fd_toshell) < 0);
4273 if (!pipe_error) /* pipe create OK */
4274 {
4275 pipe_error = (pipe(fd_fromshell) < 0);
4276 if (pipe_error) /* pipe create failed */
4277 {
4278 close(fd_toshell[0]);
4279 close(fd_toshell[1]);
4280 }
4281 }
4282 if (pipe_error)
4283 {
4284 MSG_PUTS(_("\nCannot create pipes\n"));
4285 out_flush();
4286 }
4287 }
4288 }
4289
4290 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 {
4292# ifdef __BEOS__
4293 beos_cleanup_read_thread();
4294# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004295
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296 if ((pid = fork()) == -1) /* maybe we should use vfork() */
4297 {
4298 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004299 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004301 || (gui.in_use && show_shell_mess)
4302# endif
4303 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004305# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 if (pty_master_fd >= 0) /* close the pseudo tty */
4307 {
4308 close(pty_master_fd);
4309 close(pty_slave_fd);
4310 }
4311 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004312# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 {
4314 close(fd_toshell[0]);
4315 close(fd_toshell[1]);
4316 close(fd_fromshell[0]);
4317 close(fd_fromshell[1]);
4318 }
4319 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 }
4321 else if (pid == 0) /* child */
4322 {
4323 reset_signals(); /* handle signals normally */
4324
4325 if (!show_shell_mess || (options & SHELL_EXPAND))
4326 {
4327 int fd;
4328
4329 /*
4330 * Don't want to show any message from the shell. Can't just
4331 * close stdout and stderr though, because some systems will
4332 * break if you try to write to them after that, so we must
4333 * use dup() to replace them with something else -- webb
4334 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4335 * waiting for input.
4336 */
4337 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4338 fclose(stdin);
4339 fclose(stdout);
4340 fclose(stderr);
4341
4342 /*
4343 * If any of these open()'s and dup()'s fail, we just continue
4344 * anyway. It's not fatal, and on most systems it will make
4345 * no difference at all. On a few it will cause the execvp()
4346 * to exit with a non-zero status even when the completion
4347 * could be done, which is nothing too serious. If the open()
4348 * or dup() failed we'd just do the same thing ourselves
4349 * anyway -- webb
4350 */
4351 if (fd >= 0)
4352 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004353 ignored = dup(fd); /* To replace stdin (fd 0) */
4354 ignored = dup(fd); /* To replace stdout (fd 1) */
4355 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356
4357 /* Don't need this now that we've duplicated it */
4358 close(fd);
4359 }
4360 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004361 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004363 || gui.in_use
4364# endif
4365 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 {
4367
Bram Moolenaardf177f62005-02-22 08:39:57 +00004368# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004369 /* Create our own process group, so that the child and all its
4370 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004371 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004372 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004373 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004374 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004375# if defined(SIGHUP)
4376 /* When doing "!xterm&" and 'shell' is bash: the shell
4377 * will exit and send SIGHUP to all processes in its
4378 * group, killing the just started process. Ignore SIGHUP
4379 * to avoid that. (suggested by Simon Schubert)
4380 */
4381 signal(SIGHUP, SIG_IGN);
4382# endif
4383 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004384# endif
4385# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004386 if (pty_slave_fd >= 0)
4387 {
4388 /* push stream discipline modules */
4389 if (options & SHELL_COOKED)
4390 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004392 /* Try to become controlling tty (probably doesn't work,
4393 * unless run by root) */
4394 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004396 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004397# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004399# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 setenv("TERM", "dumb", 1);
4401 sprintf((char *)envbuf, "%ld", Rows);
4402 setenv("ROWS", (char *)envbuf, 1);
4403 sprintf((char *)envbuf, "%ld", Rows);
4404 setenv("LINES", (char *)envbuf, 1);
4405 sprintf((char *)envbuf, "%ld", Columns);
4406 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004407# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 /*
4409 * Putenv does not copy the string, it has to remain valid.
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004410 * Use a static array to avoid losing allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 */
4412 putenv("TERM=dumb");
4413 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
4414 putenv(envbuf_Rows);
4415 sprintf(envbuf_Rows, "LINES=%ld", Rows);
4416 putenv(envbuf_Rows);
4417 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
4418 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004419# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420
Bram Moolenaara5792f52005-11-23 21:25:05 +00004421 /*
4422 * stderr is only redirected when using the GUI, so that a
4423 * program like gpg can still access the terminal to get a
4424 * passphrase using stderr.
4425 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004426# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427 if (pty_master_fd >= 0)
4428 {
4429 close(pty_master_fd); /* close master side of pty */
4430
4431 /* set up stdin/stdout/stderr for the child */
4432 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004433 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004435 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004436 if (gui.in_use)
4437 {
4438 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004439 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441
4442 close(pty_slave_fd); /* has been dupped, close it now */
4443 }
4444 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 {
4447 /* set up stdin for the child */
4448 close(fd_toshell[1]);
4449 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004450 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 close(fd_toshell[0]);
4452
4453 /* set up stdout for the child */
4454 close(fd_fromshell[0]);
4455 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004456 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 close(fd_fromshell[1]);
4458
Bram Moolenaara5792f52005-11-23 21:25:05 +00004459# ifdef FEAT_GUI
4460 if (gui.in_use)
4461 {
4462 /* set up stderr for the child */
4463 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004464 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004465 }
4466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 }
4468 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004469
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 /*
4471 * There is no type cast for the argv, because the type may be
4472 * different on different machines. This may cause a warning
4473 * message with strict compilers, don't worry about it.
4474 * Call _exit() instead of exit() to avoid closing the connection
4475 * to the X server (esp. with GTK, which uses atexit()).
4476 */
4477 execvp(argv[0], argv);
4478 _exit(EXEC_FAILED); /* exec failed, return failure code */
4479 }
4480 else /* parent */
4481 {
4482 /*
4483 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004484 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485 */
4486 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004487 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488
4489 /*
4490 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004491 * This is also used to pipe stdin/stdout to/from the external
4492 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004494 if ((options & (SHELL_READ|SHELL_WRITE))
4495# ifdef FEAT_GUI
4496 || (gui.in_use && show_shell_mess)
4497# endif
4498 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004500# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004502# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004504# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4506 int ta_len = 0; /* valid bytes in ta_buf[] */
4507 int len;
4508 int p_more_save;
4509 int old_State;
4510 int c;
4511 int toshell_fd;
4512 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004513 garray_T ga;
4514 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004515# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4516 struct timeval start_tv;
4517# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518
Bram Moolenaardf177f62005-02-22 08:39:57 +00004519# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 if (pty_master_fd >= 0)
4521 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 fromshell_fd = pty_master_fd;
4523 toshell_fd = dup(pty_master_fd);
4524 }
4525 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004526# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 {
4528 close(fd_toshell[0]);
4529 close(fd_fromshell[1]);
4530 toshell_fd = fd_toshell[1];
4531 fromshell_fd = fd_fromshell[0];
4532 }
4533
4534 /*
4535 * Write to the child if there are typed characters.
4536 * Read from the child if there are characters available.
4537 * Repeat the reading a few times if more characters are
4538 * available. Need to check for typed keys now and then, but
4539 * not too often (delays when no chars are available).
4540 * This loop is quit if no characters can be read from the pty
4541 * (WaitForChar detected special condition), or there are no
4542 * characters available and the child has exited.
4543 * Only check if the child has exited when there is no more
4544 * output. The child may exit before all the output has
4545 * been printed.
4546 *
4547 * Currently this busy loops!
4548 * This can probably dead-lock when the write blocks!
4549 */
4550 p_more_save = p_more;
4551 p_more = FALSE;
4552 old_State = State;
4553 State = EXTERNCMD; /* don't redraw at window resize */
4554
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004555 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004556 {
4557 /* Fork a process that will write the lines to the
4558 * external program. */
4559 if ((wpid = fork()) == -1)
4560 {
4561 MSG_PUTS(_("\nCannot fork\n"));
4562 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004563 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004564 {
4565 linenr_T lnum = curbuf->b_op_start.lnum;
4566 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004567 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004568 size_t l;
4569
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004570 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004571 for (;;)
4572 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004573 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004574 if (l == 0)
4575 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004576 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004577 /* NL -> NUL translation */
4578 len = write(toshell_fd, "", (size_t)1);
4579 else
4580 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004581 char_u *s = vim_strchr(lp + written, NL);
4582
Bram Moolenaar89d40322006-08-29 15:30:07 +00004583 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004584 s == NULL ? l
4585 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004586 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004587 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004588 {
4589 /* Finished a line, add a NL, unless this line
4590 * should not have one. */
4591 if (lnum != curbuf->b_op_end.lnum
4592 || !curbuf->b_p_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004593 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004594 && (lnum !=
4595 curbuf->b_ml.ml_line_count
4596 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004597 ignored = write(toshell_fd, "\n",
4598 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004599 ++lnum;
4600 if (lnum > curbuf->b_op_end.lnum)
4601 {
4602 /* finished all the lines, close pipe */
4603 close(toshell_fd);
4604 toshell_fd = -1;
4605 break;
4606 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004607 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004608 written = 0;
4609 }
4610 else if (len > 0)
4611 written += len;
4612 }
4613 _exit(0);
4614 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004615 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004616 {
4617 close(toshell_fd);
4618 toshell_fd = -1;
4619 }
4620 }
4621
4622 if (options & SHELL_READ)
4623 ga_init2(&ga, 1, BUFLEN);
4624
4625 noread_cnt = 0;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004626# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4627 gettimeofday(&start_tv, NULL);
4628# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 for (;;)
4630 {
4631 /*
4632 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004633 * if there are any.
4634 * Don't do this if we are expanding wild cards (would eat
4635 * typeahead).
4636 * Don't do this when filtering and terminal is in cooked
4637 * mode, the shell command will handle the I/O. Avoids
4638 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004639 * Don't get characters when the child has already
4640 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004641 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004642 * while (noread_cnt > 4), avoids that ":r !ls" eats
4643 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004644 */
4645 len = 0;
4646 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004647 && ((options &
4648 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4649 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004650# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004651 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004652# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004653 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004654 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004655 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004657 if (ta_len == 0)
4658 {
4659 /* Get extra characters when we don't have any.
4660 * Reset the counter and timer. */
4661 noread_cnt = 0;
4662# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4663 gettimeofday(&start_tv, NULL);
4664# endif
4665 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4666 }
4667 if (ta_len > 0 || len > 0)
4668 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669 /*
4670 * For pipes:
4671 * Check for CTRL-C: send interrupt signal to child.
4672 * Check for CTRL-D: EOF, close pipe to child.
4673 */
4674 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4675 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004676# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 /*
4678 * Send SIGINT to the child's group or all
4679 * processes in our group.
4680 */
4681 if (ta_buf[ta_len] == Ctrl_C
4682 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004683 {
4684# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004686# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00004689 if (wpid > 0)
4690 kill(wpid, SIGINT);
4691 }
4692# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693 if (pty_master_fd < 0 && toshell_fd >= 0
4694 && ta_buf[ta_len] == Ctrl_D)
4695 {
4696 close(toshell_fd);
4697 toshell_fd = -1;
4698 }
4699 }
4700
4701 /* replace K_BS by <BS> and K_DEL by <DEL> */
4702 for (i = ta_len; i < ta_len + len; ++i)
4703 {
4704 if (ta_buf[i] == CSI && len - i > 2)
4705 {
4706 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4707 if (c == K_DEL || c == K_KDEL || c == K_BS)
4708 {
4709 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4710 (size_t)(len - i - 2));
4711 if (c == K_DEL || c == K_KDEL)
4712 ta_buf[i] = DEL;
4713 else
4714 ta_buf[i] = Ctrl_H;
4715 len -= 2;
4716 }
4717 }
4718 else if (ta_buf[i] == '\r')
4719 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00004720# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00004722 i += (*mb_ptr2len_len)(ta_buf + i,
4723 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725 }
4726
4727 /*
4728 * For pipes: echo the typed characters.
4729 * For a pty this does not seem to work.
4730 */
4731 if (pty_master_fd < 0)
4732 {
4733 for (i = ta_len; i < ta_len + len; ++i)
4734 {
4735 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4736 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004737# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738 else if (has_mbyte)
4739 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004740 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741
4742 msg_outtrans_len(ta_buf + i, l);
4743 i += l - 1;
4744 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746 else
4747 msg_outtrans_len(ta_buf + i, 1);
4748 }
4749 windgoto(msg_row, msg_col);
4750 out_flush();
4751 }
4752
4753 ta_len += len;
4754
4755 /*
4756 * Write the characters to the child, unless EOF has
4757 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004758 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004759 * When writing buffer lines, drop the typed
4760 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004762 if (options & SHELL_WRITE)
4763 ta_len = 0;
4764 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 {
4766 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4767 if (len > 0)
4768 {
4769 ta_len -= len;
4770 mch_memmove(ta_buf, ta_buf + len, ta_len);
4771 }
4772 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 }
4775
Bram Moolenaardf177f62005-02-22 08:39:57 +00004776 if (got_int)
4777 {
4778 /* CTRL-C sends a signal to the child, we ignore it
4779 * ourselves */
4780# ifdef HAVE_SETSID
4781 kill(-pid, SIGINT);
4782# else
4783 kill(0, SIGINT);
4784# endif
4785 if (wpid > 0)
4786 kill(wpid, SIGINT);
4787 got_int = FALSE;
4788 }
4789
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 /*
4791 * Check if the child has any characters to be printed.
4792 * Read them and write them to our window. Repeat this as
4793 * long as there is something to do, avoid the 10ms wait
4794 * for mch_inchar(), or sending typeahead characters to
4795 * the external process.
4796 * TODO: This should handle escape sequences, compatible
4797 * to some terminal (vt52?).
4798 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004799 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4801 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004802 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004803# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004805# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004807# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 );
4809 if (len <= 0) /* end of file or error */
4810 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004811
4812 noread_cnt = 0;
4813 if (options & SHELL_READ)
4814 {
4815 /* Do NUL -> NL translation, append NL separated
4816 * lines to the current buffer. */
4817 for (i = 0; i < len; ++i)
4818 {
4819 if (buffer[i] == NL)
4820 append_ga_line(&ga);
4821 else if (buffer[i] == NUL)
4822 ga_append(&ga, NL);
4823 else
4824 ga_append(&ga, buffer[i]);
4825 }
4826 }
4827# ifdef FEAT_MBYTE
4828 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829 {
4830 int l;
4831
Bram Moolenaardf177f62005-02-22 08:39:57 +00004832 len += buffer_off;
4833 buffer[len] = NUL;
4834
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 /* Check if the last character in buffer[] is
4836 * incomplete, keep these bytes for the next
4837 * round. */
4838 for (p = buffer; p < buffer + len; p += l)
4839 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004840 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 if (l == 0)
4842 l = 1; /* NUL byte? */
4843 else if (MB_BYTE2LEN(*p) != l)
4844 break;
4845 }
4846 if (p == buffer) /* no complete character */
4847 {
4848 /* avoid getting stuck at an illegal byte */
4849 if (len >= 12)
4850 ++p;
4851 else
4852 {
4853 buffer_off = len;
4854 continue;
4855 }
4856 }
4857 c = *p;
4858 *p = NUL;
4859 msg_puts(buffer);
4860 if (p < buffer + len)
4861 {
4862 *p = c;
4863 buffer_off = (buffer + len) - p;
4864 mch_memmove(buffer, p, buffer_off);
4865 continue;
4866 }
4867 buffer_off = 0;
4868 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004869# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004871 {
4872 buffer[len] = NUL;
4873 msg_puts(buffer);
4874 }
4875
4876 windgoto(msg_row, msg_col);
4877 cursor_on();
4878 out_flush();
4879 if (got_int)
4880 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004881
4882# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4883 {
4884 struct timeval now_tv;
4885 long msec;
4886
4887 /* Avoid that we keep looping here without
4888 * checking for a CTRL-C for a long time. Don't
4889 * break out too often to avoid losing typeahead. */
4890 gettimeofday(&now_tv, NULL);
4891 msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L
4892 + (now_tv.tv_usec - start_tv.tv_usec) / 1000L;
4893 if (msec > 2000)
4894 {
4895 noread_cnt = 5;
4896 break;
4897 }
4898 }
4899# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 }
4901
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004902 /* If we already detected the child has finished break the
4903 * loop now. */
4904 if (wait_pid == pid)
4905 break;
4906
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 /*
4908 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004909 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004911# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004912 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004913# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004915# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4917 || (wait_pid == pid && WIFEXITED(status)))
4918 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004919 /* Don't break the loop yet, try reading more
4920 * characters from "fromshell_fd" first. When using
4921 * pipes there might still be something to read and
4922 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004925 else
4926 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004927
Bram Moolenaar95a51352013-03-21 22:53:50 +01004928# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004929 /* Handle any X events, e.g. serving the clipboard. */
4930 clip_update();
4931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 }
4933finished:
4934 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004935 if (options & SHELL_READ)
4936 {
4937 if (ga.ga_len > 0)
4938 {
4939 append_ga_line(&ga);
4940 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004941 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004942 }
4943 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004944 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004945 ga_clear(&ga);
4946 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947
Bram Moolenaar071d4272004-06-13 20:20:40 +00004948 /*
4949 * Give all typeahead that wasn't used back to ui_inchar().
4950 */
4951 if (ta_len)
4952 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 State = old_State;
4954 if (toshell_fd >= 0)
4955 close(toshell_fd);
4956 close(fromshell_fd);
4957 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01004958# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01004959 else
4960 {
4961 /*
4962 * Similar to the loop above, but only handle X events, no
4963 * I/O.
4964 */
4965 for (;;)
4966 {
4967 if (got_int)
4968 {
4969 /* CTRL-C sends a signal to the child, we ignore it
4970 * ourselves */
4971# ifdef HAVE_SETSID
4972 kill(-pid, SIGINT);
4973# else
4974 kill(0, SIGINT);
4975# endif
4976 got_int = FALSE;
4977 }
4978# ifdef __NeXT__
4979 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4980# else
4981 wait_pid = waitpid(pid, &status, WNOHANG);
4982# endif
4983 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4984 || (wait_pid == pid && WIFEXITED(status)))
4985 {
4986 wait_pid = pid;
4987 break;
4988 }
4989
4990 /* Handle any X events, e.g. serving the clipboard. */
4991 clip_update();
4992
4993 mch_delay(10L, TRUE);
4994 }
4995 }
4996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997
4998 /*
4999 * Wait until our child has exited.
5000 * Ignore wait() returning pids of other children and returning
5001 * because of some signal like SIGWINCH.
5002 * Don't wait if wait_pid was already set above, indicating the
5003 * child already exited.
5004 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005005 if (wait_pid != pid)
5006 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007
Bram Moolenaar624891f2010-10-13 16:22:09 +02005008# ifdef FEAT_GUI
5009 /* Close slave side of pty. Only do this after the child has
5010 * exited, otherwise the child may hang when it tries to write on
5011 * the pty. */
5012 if (pty_master_fd >= 0)
5013 close(pty_slave_fd);
5014# endif
5015
Bram Moolenaardf177f62005-02-22 08:39:57 +00005016 /* Make sure the child that writes to the external program is
5017 * dead. */
5018 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005019 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005020 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005021 wait4pid(wpid, NULL);
5022 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005023
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024 /*
5025 * Set to raw mode right now, otherwise a CTRL-C after
5026 * catch_signals() will kill Vim.
5027 */
5028 if (tmode == TMODE_RAW)
5029 settmode(TMODE_RAW);
5030 did_settmode = TRUE;
5031 set_signals();
5032
5033 if (WIFEXITED(status))
5034 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005035 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005037 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 {
5039 if (retval == EXEC_FAILED)
5040 {
5041 MSG_PUTS(_("\nCannot execute shell "));
5042 msg_outtrans(p_sh);
5043 msg_putchar('\n');
5044 }
5045 else if (!(options & SHELL_SILENT))
5046 {
5047 MSG_PUTS(_("\nshell returned "));
5048 msg_outnum((long)retval);
5049 msg_putchar('\n');
5050 }
5051 }
5052 }
5053 else
5054 MSG_PUTS(_("\nCommand terminated\n"));
5055 }
5056 }
5057 vim_free(argv);
Bram Moolenaarea35ef62011-08-04 22:59:28 +02005058 vim_free(p_shcf_copy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059
5060error:
5061 if (!did_settmode)
5062 if (tmode == TMODE_RAW)
5063 settmode(TMODE_RAW); /* set to raw mode */
5064# ifdef FEAT_TITLE
5065 resettitle();
5066# endif
5067 vim_free(newcmd);
5068
5069 return retval;
5070
5071#endif /* USE_SYSTEM */
5072}
5073
5074/*
5075 * Check for CTRL-C typed by reading all available characters.
5076 * In cooked mode we should get SIGINT, no need to check.
5077 */
5078 void
5079mch_breakcheck()
5080{
5081 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
5082 fill_input_buf(FALSE);
5083}
5084
5085/*
5086 * Wait "msec" msec until a character is available from the keyboard or from
5087 * inbuf[]. msec == -1 will block forever.
5088 * When a GUI is being used, this will never get called -- webb
5089 */
5090 static int
5091WaitForChar(msec)
5092 long msec;
5093{
5094#ifdef FEAT_MOUSE_GPM
5095 int gpm_process_wanted;
5096#endif
5097#ifdef FEAT_XCLIPBOARD
5098 int rest;
5099#endif
5100 int avail;
5101
5102 if (input_available()) /* something in inbuf[] */
5103 return 1;
5104
5105#if defined(FEAT_MOUSE_DEC)
5106 /* May need to query the mouse position. */
5107 if (WantQueryMouse)
5108 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005109 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005110 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5111 }
5112#endif
5113
5114 /*
5115 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
5116 * events. This is a bit complicated, because they might both be defined.
5117 */
5118#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
5119# ifdef FEAT_XCLIPBOARD
5120 rest = 0;
5121 if (do_xterm_trace())
5122 rest = msec;
5123# endif
5124 do
5125 {
5126# ifdef FEAT_XCLIPBOARD
5127 if (rest != 0)
5128 {
5129 msec = XT_TRACE_DELAY;
5130 if (rest >= 0 && rest < XT_TRACE_DELAY)
5131 msec = rest;
5132 if (rest >= 0)
5133 rest -= msec;
5134 }
5135# endif
5136# ifdef FEAT_MOUSE_GPM
5137 gpm_process_wanted = 0;
5138 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
5139# else
5140 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5141# endif
5142 if (!avail)
5143 {
5144 if (input_available())
5145 return 1;
5146# ifdef FEAT_XCLIPBOARD
5147 if (rest == 0 || !do_xterm_trace())
5148# endif
5149 break;
5150 }
5151 }
5152 while (FALSE
5153# ifdef FEAT_MOUSE_GPM
5154 || (gpm_process_wanted && mch_gpm_process() == 0)
5155# endif
5156# ifdef FEAT_XCLIPBOARD
5157 || (!avail && rest != 0)
5158# endif
5159 );
5160
5161#else
5162 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
5163#endif
5164 return avail;
5165}
5166
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01005167#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168/*
5169 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005170 * "msec" == 0 will check for characters once.
5171 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 * When a GUI is being used, this will not be used for input -- webb
5173 * Returns also, when a request from Sniff is waiting -- toni.
5174 * Or when a Linux GPM mouse event is waiting.
5175 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176#if defined(__BEOS__)
5177 int
5178#else
5179 static int
5180#endif
5181RealWaitForChar(fd, msec, check_for_gpm)
5182 int fd;
5183 long msec;
Bram Moolenaar78a15312009-05-15 19:33:18 +00005184 int *check_for_gpm UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185{
5186 int ret;
Bram Moolenaar67c53842010-05-22 18:28:27 +02005187#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02005188 int nb_fd = netbeans_filedesc();
Bram Moolenaar67c53842010-05-22 18:28:27 +02005189#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005190#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 static int busy = FALSE;
5192
5193 /* May retry getting characters after an event was handled. */
5194# define MAY_LOOP
5195
5196# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5197 /* Remember at what time we started, so that we know how much longer we
5198 * should wait after being interrupted. */
5199# define USE_START_TV
5200 struct timeval start_tv;
5201
5202 if (msec > 0 && (
5203# ifdef FEAT_XCLIPBOARD
5204 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005205# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 ||
5207# endif
5208# endif
5209# ifdef USE_XSMP
5210 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005211# ifdef FEAT_MZSCHEME
5212 ||
5213# endif
5214# endif
5215# ifdef FEAT_MZSCHEME
5216 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217# endif
5218 ))
5219 gettimeofday(&start_tv, NULL);
5220# endif
5221
5222 /* Handle being called recursively. This may happen for the session
5223 * manager stuff, it may save the file, which does a breakcheck. */
5224 if (busy)
5225 return 0;
5226#endif
5227
5228#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00005229 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005230#endif
5231 {
5232#ifdef MAY_LOOP
5233 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005234# ifdef FEAT_MZSCHEME
5235 int mzquantum_used = FALSE;
5236# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237#endif
5238#ifndef HAVE_SELECT
Bram Moolenaar67c53842010-05-22 18:28:27 +02005239 struct pollfd fds[6];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240 int nfd;
5241# ifdef FEAT_XCLIPBOARD
5242 int xterm_idx = -1;
5243# endif
5244# ifdef FEAT_MOUSE_GPM
5245 int gpm_idx = -1;
5246# endif
5247# ifdef USE_XSMP
5248 int xsmp_idx = -1;
5249# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005250# ifdef FEAT_NETBEANS_INTG
5251 int nb_idx = -1;
5252# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005253 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005255# ifdef FEAT_MZSCHEME
5256 mzvim_check_threads();
5257 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5258 {
5259 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
5260 mzquantum_used = TRUE;
5261 }
5262# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263 fds[0].fd = fd;
5264 fds[0].events = POLLIN;
5265 nfd = 1;
5266
5267# ifdef FEAT_SNIFF
5268# define SNIFF_IDX 1
5269 if (want_sniff_request)
5270 {
5271 fds[SNIFF_IDX].fd = fd_from_sniff;
5272 fds[SNIFF_IDX].events = POLLIN;
5273 nfd++;
5274 }
5275# endif
5276# ifdef FEAT_XCLIPBOARD
5277 if (xterm_Shell != (Widget)0)
5278 {
5279 xterm_idx = nfd;
5280 fds[nfd].fd = ConnectionNumber(xterm_dpy);
5281 fds[nfd].events = POLLIN;
5282 nfd++;
5283 }
5284# endif
5285# ifdef FEAT_MOUSE_GPM
5286 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5287 {
5288 gpm_idx = nfd;
5289 fds[nfd].fd = gpm_fd;
5290 fds[nfd].events = POLLIN;
5291 nfd++;
5292 }
5293# endif
5294# ifdef USE_XSMP
5295 if (xsmp_icefd != -1)
5296 {
5297 xsmp_idx = nfd;
5298 fds[nfd].fd = xsmp_icefd;
5299 fds[nfd].events = POLLIN;
5300 nfd++;
5301 }
5302# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005303#ifdef FEAT_NETBEANS_INTG
5304 if (nb_fd != -1)
5305 {
5306 nb_idx = nfd;
5307 fds[nfd].fd = nb_fd;
5308 fds[nfd].events = POLLIN;
5309 nfd++;
5310 }
5311#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005313 ret = poll(fds, nfd, towait);
5314# ifdef FEAT_MZSCHEME
5315 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005316 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005317 finished = FALSE;
5318# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319
5320# ifdef FEAT_SNIFF
5321 if (ret < 0)
5322 sniff_disconnect(1);
5323 else if (want_sniff_request)
5324 {
5325 if (fds[SNIFF_IDX].revents & POLLHUP)
5326 sniff_disconnect(1);
5327 if (fds[SNIFF_IDX].revents & POLLIN)
5328 sniff_request_waiting = 1;
5329 }
5330# endif
5331# ifdef FEAT_XCLIPBOARD
5332 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
5333 {
5334 xterm_update(); /* Maybe we should hand out clipboard */
5335 if (--ret == 0 && !input_available())
5336 /* Try again */
5337 finished = FALSE;
5338 }
5339# endif
5340# ifdef FEAT_MOUSE_GPM
5341 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
5342 {
5343 *check_for_gpm = 1;
5344 }
5345# endif
5346# ifdef USE_XSMP
5347 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
5348 {
5349 if (fds[xsmp_idx].revents & POLLIN)
5350 {
5351 busy = TRUE;
5352 xsmp_handle_requests();
5353 busy = FALSE;
5354 }
5355 else if (fds[xsmp_idx].revents & POLLHUP)
5356 {
5357 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005358 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359 xsmp_close();
5360 }
5361 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005362 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 }
5364# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005365#ifdef FEAT_NETBEANS_INTG
5366 if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN)
5367 {
5368 netbeans_read();
5369 --ret;
5370 }
5371#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372
5373
5374#else /* HAVE_SELECT */
5375
5376 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005377 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378 fd_set rfds, efds;
5379 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005380 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005382# ifdef FEAT_MZSCHEME
5383 mzvim_check_threads();
5384 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
5385 {
5386 towait = p_mzq; /* don't wait longer than 'mzquantum' */
5387 mzquantum_used = TRUE;
5388 }
5389# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390# ifdef __EMX__
5391 /* don't check for incoming chars if not in raw mode, because select()
5392 * always returns TRUE then (in some version of emx.dll) */
5393 if (curr_tmode != TMODE_RAW)
5394 return 0;
5395# endif
5396
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005397 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005399 tv.tv_sec = towait / 1000;
5400 tv.tv_usec = (towait % 1000) * (1000000/1000);
5401 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005403 else
5404 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405
5406 /*
5407 * Select on ready for reading and exceptional condition (end of file).
5408 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005409select_eintr:
5410 FD_ZERO(&rfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 FD_ZERO(&efds);
5412 FD_SET(fd, &rfds);
5413# if !defined(__QNX__) && !defined(__CYGWIN32__)
5414 /* For QNX select() always returns 1 if this is set. Why? */
5415 FD_SET(fd, &efds);
5416# endif
5417 maxfd = fd;
5418
5419# ifdef FEAT_SNIFF
5420 if (want_sniff_request)
5421 {
5422 FD_SET(fd_from_sniff, &rfds);
5423 FD_SET(fd_from_sniff, &efds);
5424 if (maxfd < fd_from_sniff)
5425 maxfd = fd_from_sniff;
5426 }
5427# endif
5428# ifdef FEAT_XCLIPBOARD
5429 if (xterm_Shell != (Widget)0)
5430 {
5431 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
5432 if (maxfd < ConnectionNumber(xterm_dpy))
5433 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02005434
5435 /* An event may have already been read but not handled. In
5436 * particulary, XFlush may cause this. */
5437 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 }
5439# endif
5440# ifdef FEAT_MOUSE_GPM
5441 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
5442 {
5443 FD_SET(gpm_fd, &rfds);
5444 FD_SET(gpm_fd, &efds);
5445 if (maxfd < gpm_fd)
5446 maxfd = gpm_fd;
5447 }
5448# endif
5449# ifdef USE_XSMP
5450 if (xsmp_icefd != -1)
5451 {
5452 FD_SET(xsmp_icefd, &rfds);
5453 FD_SET(xsmp_icefd, &efds);
5454 if (maxfd < xsmp_icefd)
5455 maxfd = xsmp_icefd;
5456 }
5457# endif
Bram Moolenaardd82d692012-08-15 17:26:57 +02005458# ifdef FEAT_NETBEANS_INTG
Bram Moolenaar67c53842010-05-22 18:28:27 +02005459 if (nb_fd != -1)
5460 {
5461 FD_SET(nb_fd, &rfds);
5462 if (maxfd < nb_fd)
5463 maxfd = nb_fd;
5464 }
Bram Moolenaardd82d692012-08-15 17:26:57 +02005465# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005467 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005468# ifdef EINTR
5469 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005470 {
5471 /* Check whether window has been resized, EINTR may be caused by
5472 * SIGWINCH. */
5473 if (do_resize)
5474 handle_resize();
5475
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005476 /* Interrupted by a signal, need to try again. We ignore msec
5477 * here, because we do want to check even after a timeout if
5478 * characters are available. Needed for reading output of an
5479 * external command after the process has finished. */
5480 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02005481 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005482# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00005483# ifdef __TANDEM
5484 if (ret == -1 && errno == ENOTSUP)
5485 {
5486 FD_ZERO(&rfds);
5487 FD_ZERO(&efds);
5488 ret = 0;
5489 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02005490# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005491# ifdef FEAT_MZSCHEME
5492 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005493 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005494 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495# endif
5496
5497# ifdef FEAT_SNIFF
5498 if (ret < 0 )
5499 sniff_disconnect(1);
5500 else if (ret > 0 && want_sniff_request)
5501 {
5502 if (FD_ISSET(fd_from_sniff, &efds))
5503 sniff_disconnect(1);
5504 if (FD_ISSET(fd_from_sniff, &rfds))
5505 sniff_request_waiting = 1;
5506 }
5507# endif
5508# ifdef FEAT_XCLIPBOARD
5509 if (ret > 0 && xterm_Shell != (Widget)0
5510 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
5511 {
5512 xterm_update(); /* Maybe we should hand out clipboard */
5513 /* continue looping when we only got the X event and the input
5514 * buffer is empty */
5515 if (--ret == 0 && !input_available())
5516 {
5517 /* Try again */
5518 finished = FALSE;
5519 }
5520 }
5521# endif
5522# ifdef FEAT_MOUSE_GPM
5523 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
5524 {
5525 if (FD_ISSET(gpm_fd, &efds))
5526 gpm_close();
5527 else if (FD_ISSET(gpm_fd, &rfds))
5528 *check_for_gpm = 1;
5529 }
5530# endif
5531# ifdef USE_XSMP
5532 if (ret > 0 && xsmp_icefd != -1)
5533 {
5534 if (FD_ISSET(xsmp_icefd, &efds))
5535 {
5536 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005537 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 xsmp_close();
5539 if (--ret == 0)
5540 finished = FALSE; /* keep going if event was only one */
5541 }
5542 else if (FD_ISSET(xsmp_icefd, &rfds))
5543 {
5544 busy = TRUE;
5545 xsmp_handle_requests();
5546 busy = FALSE;
5547 if (--ret == 0)
5548 finished = FALSE; /* keep going if event was only one */
5549 }
5550 }
5551# endif
Bram Moolenaar67c53842010-05-22 18:28:27 +02005552#ifdef FEAT_NETBEANS_INTG
5553 if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds))
5554 {
5555 netbeans_read();
5556 --ret;
5557 }
5558#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559
5560#endif /* HAVE_SELECT */
5561
5562#ifdef MAY_LOOP
5563 if (finished || msec == 0)
5564 break;
5565
5566 /* We're going to loop around again, find out for how long */
5567 if (msec > 0)
5568 {
5569# ifdef USE_START_TV
5570 struct timeval mtv;
5571
5572 /* Compute remaining wait time. */
5573 gettimeofday(&mtv, NULL);
5574 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
5575 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
5576# else
5577 /* Guess we got interrupted halfway. */
5578 msec = msec / 2;
5579# endif
5580 if (msec <= 0)
5581 break; /* waited long enough */
5582 }
5583#endif
5584 }
5585
5586 return (ret > 0);
5587}
5588
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590/*
Bram Moolenaar02743632005-07-25 20:42:36 +00005591 * Expand a path into all matching files and/or directories. Handles "*",
5592 * "?", "[a-z]", "**", etc.
5593 * "path" has backslashes before chars that are not to be expanded.
5594 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 */
5596 int
5597mch_expandpath(gap, path, flags)
5598 garray_T *gap;
5599 char_u *path;
5600 int flags; /* EW_* flags */
5601{
Bram Moolenaar02743632005-07-25 20:42:36 +00005602 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603}
5604#endif
5605
5606/*
5607 * mch_expand_wildcards() - this code does wild-card pattern matching using
5608 * the shell
5609 *
5610 * return OK for success, FAIL for error (you may lose some memory) and put
5611 * an error message in *file.
5612 *
5613 * num_pat is number of input patterns
5614 * pat is array of pointers to input patterns
5615 * num_file is pointer to number of matched file names
5616 * file is pointer to array of pointers to matched file names
5617 */
5618
5619#ifndef SEEK_SET
5620# define SEEK_SET 0
5621#endif
5622#ifndef SEEK_END
5623# define SEEK_END 2
5624#endif
5625
Bram Moolenaar5555acc2006-04-07 21:33:12 +00005626#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00005627
Bram Moolenaar071d4272004-06-13 20:20:40 +00005628 int
5629mch_expand_wildcards(num_pat, pat, num_file, file, flags)
5630 int num_pat;
5631 char_u **pat;
5632 int *num_file;
5633 char_u ***file;
5634 int flags; /* EW_* flags */
5635{
5636 int i;
5637 size_t len;
5638 char_u *p;
5639 int dir;
5640#ifdef __EMX__
Bram Moolenaarc7247912008-01-13 12:54:11 +00005641 /*
5642 * This is the OS/2 implementation.
5643 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644# define EXPL_ALLOC_INC 16
5645 char_u **expl_files;
5646 size_t files_alloced, files_free;
5647 char_u *buf;
5648 int has_wildcard;
5649
5650 *num_file = 0; /* default: no files found */
5651 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
5652 files_free = EXPL_ALLOC_INC; /* how much space is not used */
5653 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
5654 if (*file == NULL)
5655 return FAIL;
5656
5657 for (; num_pat > 0; num_pat--, pat++)
5658 {
5659 expl_files = NULL;
5660 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
5661 /* expand environment var or home dir */
5662 buf = expand_env_save(*pat);
5663 else
5664 buf = vim_strsave(*pat);
5665 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005666 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 if (has_wildcard) /* yes, so expand them */
5668 expl_files = (char_u **)_fnexplode(buf);
5669
5670 /*
5671 * return value of buf if no wildcards left,
5672 * OR if no match AND EW_NOTFOUND is set.
5673 */
5674 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
5675 || (expl_files == NULL && (flags & EW_NOTFOUND)))
5676 { /* simply save the current contents of *buf */
5677 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
5678 if (expl_files != NULL)
5679 {
5680 expl_files[0] = vim_strsave(buf);
5681 expl_files[1] = NULL;
5682 }
5683 }
5684 vim_free(buf);
5685
5686 /*
5687 * Count number of names resulting from expansion,
5688 * At the same time add a backslash to the end of names that happen to
5689 * be directories, and replace slashes with backslashes.
5690 */
5691 if (expl_files)
5692 {
5693 for (i = 0; (p = expl_files[i]) != NULL; i++)
5694 {
5695 dir = mch_isdir(p);
5696 /* If we don't want dirs and this is one, skip it */
5697 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5698 continue;
5699
Bram Moolenaara2031822006-03-07 22:29:51 +00005700 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02005701 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p, NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00005702 continue;
5703
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 if (--files_free == 0)
5705 {
5706 /* need more room in table of pointers */
5707 files_alloced += EXPL_ALLOC_INC;
5708 *file = (char_u **)vim_realloc(*file,
5709 sizeof(char_u **) * files_alloced);
5710 if (*file == NULL)
5711 {
5712 EMSG(_(e_outofmem));
5713 *num_file = 0;
5714 return FAIL;
5715 }
5716 files_free = EXPL_ALLOC_INC;
5717 }
5718 slash_adjust(p);
5719 if (dir)
5720 {
5721 /* For a directory we add a '/', unless it's already
5722 * there. */
5723 len = STRLEN(p);
5724 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5725 {
5726 STRCPY((*file)[*num_file], p);
Bram Moolenaar654b5b52006-06-22 17:47:10 +00005727 if (!after_pathsep((*file)[*num_file],
5728 (*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 {
5730 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005731 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 }
5733 }
5734 }
5735 else
5736 {
5737 (*file)[*num_file] = vim_strsave(p);
5738 }
5739
5740 /*
5741 * Error message already given by either alloc or vim_strsave.
5742 * Should return FAIL, but returning OK works also.
5743 */
5744 if ((*file)[*num_file] == NULL)
5745 break;
5746 (*num_file)++;
5747 }
5748 _fnexplodefree((char **)expl_files);
5749 }
5750 }
5751 return OK;
5752
5753#else /* __EMX__ */
Bram Moolenaarc7247912008-01-13 12:54:11 +00005754 /*
5755 * This is the non-OS/2 implementation (really Unix).
5756 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757 int j;
5758 char_u *tempname;
5759 char_u *command;
5760 FILE *fd;
5761 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005762#define STYLE_ECHO 0 /* use "echo", the default */
5763#define STYLE_GLOB 1 /* use "glob", for csh */
5764#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5765#define STYLE_PRINT 3 /* use "print -N", for zsh */
5766#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5767 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 int shell_style = STYLE_ECHO;
5769 int check_spaces;
5770 static int did_find_nul = FALSE;
5771 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005772 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005773 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774
5775 *num_file = 0; /* default: no files found */
5776 *file = NULL;
5777
5778 /*
5779 * If there are no wildcards, just copy the names to allocated memory.
5780 * Saves a lot of time, because we don't have to start a new shell.
5781 */
5782 if (!have_wildcard(num_pat, pat))
5783 return save_patterns(num_pat, pat, num_file, file);
5784
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005785# ifdef HAVE_SANDBOX
5786 /* Don't allow any shell command in the sandbox. */
5787 if (sandbox != 0 && check_secure())
5788 return FAIL;
5789# endif
5790
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 /*
5792 * Don't allow the use of backticks in secure and restricted mode.
5793 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00005794 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 for (i = 0; i < num_pat; ++i)
5796 if (vim_strchr(pat[i], '`') != NULL
5797 && (check_restricted() || check_secure()))
5798 return FAIL;
5799
5800 /*
5801 * get a name for the temp file
5802 */
5803 if ((tempname = vim_tempname('o')) == NULL)
5804 {
5805 EMSG(_(e_notmp));
5806 return FAIL;
5807 }
5808
5809 /*
5810 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00005811 * file.
5812 * STYLE_BT: NL separated
5813 * If expanding `cmd` execute it directly.
5814 * STYLE_GLOB: NUL separated
5815 * If we use *csh, "glob" will work better than "echo".
5816 * STYLE_PRINT: NL or NUL separated
5817 * If we use *zsh, "print -N" will work better than "glob".
5818 * STYLE_VIMGLOB: NL separated
5819 * If we use *sh*, we define "vimglob()".
5820 * STYLE_ECHO: space separated.
5821 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822 */
5823 if (num_pat == 1 && *pat[0] == '`'
5824 && (len = STRLEN(pat[0])) > 2
5825 && *(pat[0] + len - 1) == '`')
5826 shell_style = STYLE_BT;
5827 else if ((len = STRLEN(p_sh)) >= 3)
5828 {
5829 if (STRCMP(p_sh + len - 3, "csh") == 0)
5830 shell_style = STYLE_GLOB;
5831 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5832 shell_style = STYLE_PRINT;
5833 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005834 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5835 "sh") != NULL)
5836 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837
Bram Moolenaarc7247912008-01-13 12:54:11 +00005838 /* Compute the length of the command. We need 2 extra bytes: for the
5839 * optional '&' and for the NUL.
5840 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00005842 if (shell_style == STYLE_VIMGLOB)
5843 len += STRLEN(sh_vimglob_func);
5844
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005845 for (i = 0; i < num_pat; ++i)
5846 {
5847 /* Count the length of the patterns in the same way as they are put in
5848 * "command" below. */
5849#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005851#else
5852 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005853 for (j = 0; pat[i][j] != NUL; ++j)
5854 {
5855 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5856 ++len; /* may add a backslash */
5857 ++len;
5858 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00005859#endif
5860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861 command = alloc(len);
5862 if (command == NULL)
5863 {
5864 /* out of memory */
5865 vim_free(tempname);
5866 return FAIL;
5867 }
5868
5869 /*
5870 * Build the shell command:
5871 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5872 * recognizes this).
5873 * - Add the shell command to print the expanded names.
5874 * - Add the temp file name.
5875 * - Add the file name patterns.
5876 */
5877 if (shell_style == STYLE_BT)
5878 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00005879 /* change `command; command& ` to (command; command ) */
5880 STRCPY(command, "(");
5881 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005883 *p-- = ')'; /* remove last backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 while (p > command && vim_iswhite(*p))
5885 --p;
5886 if (*p == '&') /* remove trailing '&' */
5887 {
5888 ampersent = TRUE;
5889 *p = ' ';
5890 }
5891 STRCAT(command, ">");
5892 }
5893 else
5894 {
5895 if (flags & EW_NOTFOUND)
5896 STRCPY(command, "set nonomatch; ");
5897 else
5898 STRCPY(command, "unset nonomatch; ");
5899 if (shell_style == STYLE_GLOB)
5900 STRCAT(command, "glob >");
5901 else if (shell_style == STYLE_PRINT)
5902 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00005903 else if (shell_style == STYLE_VIMGLOB)
5904 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905 else
5906 STRCAT(command, "echo >");
5907 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00005908
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00005910
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 if (shell_style != STYLE_BT)
5912 for (i = 0; i < num_pat; ++i)
5913 {
5914 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00005915 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00005916 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917#ifdef USE_SYSTEM
5918 STRCAT(command, " \"");
5919 STRCAT(command, pat[i]);
5920 STRCAT(command, "\"");
5921#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005922 int intick = FALSE;
5923
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924 p = command + STRLEN(command);
5925 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00005926 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00005927 {
5928 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00005929 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005930 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5931 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005932 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00005933 * backslash inside backticks, before a special character
5934 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005935 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00005936 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5937 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00005938 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005939 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00005940 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02005941 else if (!intick
5942 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
5943 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00005944 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02005945 * when inside ``. And not for $var when EW_KEEPDOLLAR is
5946 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00005947 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00005948
5949 /* Copy one character. */
5950 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00005951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 *p = NUL;
5953#endif
5954 }
5955 if (flags & EW_SILENT)
5956 show_shell_mess = FALSE;
5957 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00005958 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959
5960 /*
5961 * Using zsh -G: If a pattern has no matches, it is just deleted from
5962 * the argument list, otherwise zsh gives an error message and doesn't
5963 * expand any other pattern.
5964 */
5965 if (shell_style == STYLE_PRINT)
5966 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5967
5968 /*
5969 * If we use -f then shell variables set in .cshrc won't get expanded.
5970 * vi can do it, so we will too, but it is only necessary if there is a "$"
5971 * in one of the patterns, otherwise we can still use the fast option.
5972 */
5973 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5974 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5975
5976 /*
5977 * execute the shell command
5978 */
5979 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5980
5981 /* When running in the background, give it some time to create the temp
5982 * file, but don't wait for it to finish. */
5983 if (ampersent)
5984 mch_delay(10L, TRUE);
5985
5986 extra_shell_arg = NULL; /* cleanup */
5987 show_shell_mess = TRUE;
5988 vim_free(command);
5989
Bram Moolenaarc7247912008-01-13 12:54:11 +00005990 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991 {
5992 mch_remove(tempname);
5993 vim_free(tempname);
5994 /*
5995 * With interactive completion, the error message is not printed.
5996 * However with USE_SYSTEM, I don't know how to turn off error messages
5997 * from the shell, so screen may still get messed up -- webb.
5998 */
5999#ifndef USE_SYSTEM
6000 if (!(flags & EW_SILENT))
6001#endif
6002 {
6003 redraw_later_clear(); /* probably messed up screen */
6004 msg_putchar('\n'); /* clear bottom line quickly */
6005 cmdline_row = Rows - 1; /* continue on last line */
6006#ifdef USE_SYSTEM
6007 if (!(flags & EW_SILENT))
6008#endif
6009 {
6010 MSG(_(e_wildexpand));
6011 msg_start(); /* don't overwrite this message */
6012 }
6013 }
6014 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6015 * EW_NOTFOUND is given */
6016 if (shell_style == STYLE_BT)
6017 return FAIL;
6018 goto notfound;
6019 }
6020
6021 /*
6022 * read the names from the file into memory
6023 */
6024 fd = fopen((char *)tempname, READBIN);
6025 if (fd == NULL)
6026 {
6027 /* Something went wrong, perhaps a file name with a special char. */
6028 if (!(flags & EW_SILENT))
6029 {
6030 MSG(_(e_wildexpand));
6031 msg_start(); /* don't overwrite this message */
6032 }
6033 vim_free(tempname);
6034 goto notfound;
6035 }
6036 fseek(fd, 0L, SEEK_END);
6037 len = ftell(fd); /* get size of temp file */
6038 fseek(fd, 0L, SEEK_SET);
6039 buffer = alloc(len + 1);
6040 if (buffer == NULL)
6041 {
6042 /* out of memory */
6043 mch_remove(tempname);
6044 vim_free(tempname);
6045 fclose(fd);
6046 return FAIL;
6047 }
6048 i = fread((char *)buffer, 1, len, fd);
6049 fclose(fd);
6050 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006051 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052 {
6053 /* unexpected read error */
6054 EMSG2(_(e_notread), tempname);
6055 vim_free(tempname);
6056 vim_free(buffer);
6057 return FAIL;
6058 }
6059 vim_free(tempname);
6060
Bram Moolenaarc7247912008-01-13 12:54:11 +00006061# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6063 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006064 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006065 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6066 *p++ = buffer[i];
6067 len = p - buffer;
6068# endif
6069
6070
6071 /* file names are separated with Space */
6072 if (shell_style == STYLE_ECHO)
6073 {
6074 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6075 p = buffer;
6076 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6077 {
6078 while (*p != ' ' && *p != '\n')
6079 ++p;
6080 p = skipwhite(p); /* skip to next entry */
6081 }
6082 }
6083 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006084 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085 {
6086 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6087 p = buffer;
6088 for (i = 0; *p != NUL; ++i) /* count number of entries */
6089 {
6090 while (*p != '\n' && *p != NUL)
6091 ++p;
6092 if (*p != NUL)
6093 ++p;
6094 p = skipwhite(p); /* skip leading white space */
6095 }
6096 }
6097 /* file names are separated with NUL */
6098 else
6099 {
6100 /*
6101 * Some versions of zsh use spaces instead of NULs to separate
6102 * results. Only do this when there is no NUL before the end of the
6103 * buffer, otherwise we would never be able to use file names with
6104 * embedded spaces when zsh does use NULs.
6105 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6106 * don't check for spaces again.
6107 */
6108 check_spaces = FALSE;
6109 if (shell_style == STYLE_PRINT && !did_find_nul)
6110 {
6111 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006112 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006113 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 did_find_nul = TRUE;
6115 else
6116 check_spaces = TRUE;
6117 }
6118
6119 /*
6120 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6121 * already is one, for STYLE_GLOB it needs to be added.
6122 */
6123 if (len && buffer[len - 1] == NUL)
6124 --len;
6125 else
6126 buffer[len] = NUL;
6127 i = 0;
6128 for (p = buffer; p < buffer + len; ++p)
6129 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6130 {
6131 ++i;
6132 *p = NUL;
6133 }
6134 if (len)
6135 ++i; /* count last entry */
6136 }
6137 if (i == 0)
6138 {
6139 /*
6140 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6141 * /bin/sh will happily expand it to nothing rather than returning an
6142 * error; and hey, it's good to check anyway -- webb.
6143 */
6144 vim_free(buffer);
6145 goto notfound;
6146 }
6147 *num_file = i;
6148 *file = (char_u **)alloc(sizeof(char_u *) * i);
6149 if (*file == NULL)
6150 {
6151 /* out of memory */
6152 vim_free(buffer);
6153 return FAIL;
6154 }
6155
6156 /*
6157 * Isolate the individual file names.
6158 */
6159 p = buffer;
6160 for (i = 0; i < *num_file; ++i)
6161 {
6162 (*file)[i] = p;
6163 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006164 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6165 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006167 while (!(shell_style == STYLE_ECHO && *p == ' ')
6168 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 ++p;
6170 if (p == buffer + len) /* last entry */
6171 *p = NUL;
6172 else
6173 {
6174 *p++ = NUL;
6175 p = skipwhite(p); /* skip to next entry */
6176 }
6177 }
6178 else /* NUL separates */
6179 {
6180 while (*p && p < buffer + len) /* skip entry */
6181 ++p;
6182 ++p; /* skip NUL */
6183 }
6184 }
6185
6186 /*
6187 * Move the file names to allocated memory.
6188 */
6189 for (j = 0, i = 0; i < *num_file; ++i)
6190 {
6191 /* Require the files to exist. Helps when using /bin/sh */
6192 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6193 continue;
6194
6195 /* check if this entry should be included */
6196 dir = (mch_isdir((*file)[i]));
6197 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6198 continue;
6199
Bram Moolenaara2031822006-03-07 22:29:51 +00006200 /* Skip files that are not executable if we check for that. */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006201 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i], NULL))
Bram Moolenaara2031822006-03-07 22:29:51 +00006202 continue;
6203
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6205 if (p)
6206 {
6207 STRCPY(p, (*file)[i]);
6208 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006209 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 (*file)[j++] = p;
6211 }
6212 }
6213 vim_free(buffer);
6214 *num_file = j;
6215
6216 if (*num_file == 0) /* rejected all entries */
6217 {
6218 vim_free(*file);
6219 *file = NULL;
6220 goto notfound;
6221 }
6222
6223 return OK;
6224
6225notfound:
6226 if (flags & EW_NOTFOUND)
6227 return save_patterns(num_pat, pat, num_file, file);
6228 return FAIL;
6229
6230#endif /* __EMX__ */
6231}
6232
6233#endif /* VMS */
6234
6235#ifndef __EMX__
6236 static int
6237save_patterns(num_pat, pat, num_file, file)
6238 int num_pat;
6239 char_u **pat;
6240 int *num_file;
6241 char_u ***file;
6242{
6243 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006244 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245
6246 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6247 if (*file == NULL)
6248 return FAIL;
6249 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006250 {
6251 s = vim_strsave(pat[i]);
6252 if (s != NULL)
6253 /* Be compatible with expand_filename(): halve the number of
6254 * backslashes. */
6255 backslash_halve(s);
6256 (*file)[i] = s;
6257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258 *num_file = num_pat;
6259 return OK;
6260}
6261#endif
6262
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263/*
6264 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6265 * expand.
6266 */
6267 int
6268mch_has_exp_wildcard(p)
6269 char_u *p;
6270{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006271 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 {
6273#ifndef OS2
6274 if (*p == '\\' && p[1] != NUL)
6275 ++p;
6276 else
6277#endif
6278 if (vim_strchr((char_u *)
6279#ifdef VMS
6280 "*?%"
6281#else
6282# ifdef OS2
6283 "*?"
6284# else
6285 "*?[{'"
6286# endif
6287#endif
6288 , *p) != NULL)
6289 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 }
6291 return FALSE;
6292}
6293
6294/*
6295 * Return TRUE if the string "p" contains a wildcard.
6296 * Don't recognize '~' at the end as a wildcard.
6297 */
6298 int
6299mch_has_wildcard(p)
6300 char_u *p;
6301{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006302 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 {
6304#ifndef OS2
6305 if (*p == '\\' && p[1] != NUL)
6306 ++p;
6307 else
6308#endif
6309 if (vim_strchr((char_u *)
6310#ifdef VMS
6311 "*?%$"
6312#else
6313# ifdef OS2
6314# ifdef VIM_BACKTICK
6315 "*?$`"
6316# else
6317 "*?$"
6318# endif
6319# else
6320 "*?[{`'$"
6321# endif
6322#endif
6323 , *p) != NULL
6324 || (*p == '~' && p[1] != NUL))
6325 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 }
6327 return FALSE;
6328}
6329
6330#ifndef __EMX__
6331 static int
6332have_wildcard(num, file)
6333 int num;
6334 char_u **file;
6335{
6336 int i;
6337
6338 for (i = 0; i < num; i++)
6339 if (mch_has_wildcard(file[i]))
6340 return 1;
6341 return 0;
6342}
6343
6344 static int
6345have_dollars(num, file)
6346 int num;
6347 char_u **file;
6348{
6349 int i;
6350
6351 for (i = 0; i < num; i++)
6352 if (vim_strchr(file[i], '$') != NULL)
6353 return TRUE;
6354 return FALSE;
6355}
6356#endif /* ifndef __EMX__ */
6357
6358#ifndef HAVE_RENAME
6359/*
6360 * Scaled-down version of rename(), which is missing in Xenix.
6361 * This version can only move regular files and will fail if the
6362 * destination exists.
6363 */
6364 int
6365mch_rename(src, dest)
6366 const char *src, *dest;
6367{
6368 struct stat st;
6369
6370 if (stat(dest, &st) >= 0) /* fail if destination exists */
6371 return -1;
6372 if (link(src, dest) != 0) /* link file to new name */
6373 return -1;
6374 if (mch_remove(src) == 0) /* delete link to old name */
6375 return 0;
6376 return -1;
6377}
6378#endif /* !HAVE_RENAME */
6379
6380#ifdef FEAT_MOUSE_GPM
6381/*
6382 * Initializes connection with gpm (if it isn't already opened)
6383 * Return 1 if succeeded (or connection already opened), 0 if failed
6384 */
6385 static int
6386gpm_open()
6387{
6388 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
6389
6390 if (!gpm_flag)
6391 {
6392 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
6393 gpm_connect.defaultMask = ~GPM_HARD;
6394 /* Default handling for mouse move*/
6395 gpm_connect.minMod = 0; /* Handle any modifier keys */
6396 gpm_connect.maxMod = 0xffff;
6397 if (Gpm_Open(&gpm_connect, 0) > 0)
6398 {
6399 /* gpm library tries to handling TSTP causes
6400 * problems. Anyways, we close connection to Gpm whenever
6401 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006402 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006404# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00006406# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 return 1; /* succeed */
6408 }
6409 if (gpm_fd == -2)
6410 Gpm_Close(); /* We don't want to talk to xterm via gpm */
6411 return 0;
6412 }
6413 return 1; /* already open */
6414}
6415
6416/*
6417 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 */
6419 static void
6420gpm_close()
6421{
6422 if (gpm_flag && gpm_fd >= 0) /* if Open */
6423 Gpm_Close();
6424}
6425
6426/* Reads gpm event and adds special keys to input buf. Returns length of
6427 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02006428 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 */
6430 static int
6431mch_gpm_process()
6432{
6433 int button;
6434 static Gpm_Event gpm_event;
6435 char_u string[6];
6436 int_u vim_modifiers;
6437 int row,col;
6438 unsigned char buttons_mask;
6439 unsigned char gpm_modifiers;
6440 static unsigned char old_buttons = 0;
6441
6442 Gpm_GetEvent(&gpm_event);
6443
6444#ifdef FEAT_GUI
6445 /* Don't put events in the input queue now. */
6446 if (hold_gui_events)
6447 return 0;
6448#endif
6449
6450 row = gpm_event.y - 1;
6451 col = gpm_event.x - 1;
6452
6453 string[0] = ESC; /* Our termcode */
6454 string[1] = 'M';
6455 string[2] = 'G';
6456 switch (GPM_BARE_EVENTS(gpm_event.type))
6457 {
6458 case GPM_DRAG:
6459 string[3] = MOUSE_DRAG;
6460 break;
6461 case GPM_DOWN:
6462 buttons_mask = gpm_event.buttons & ~old_buttons;
6463 old_buttons = gpm_event.buttons;
6464 switch (buttons_mask)
6465 {
6466 case GPM_B_LEFT:
6467 button = MOUSE_LEFT;
6468 break;
6469 case GPM_B_MIDDLE:
6470 button = MOUSE_MIDDLE;
6471 break;
6472 case GPM_B_RIGHT:
6473 button = MOUSE_RIGHT;
6474 break;
6475 default:
6476 return 0;
6477 /*Don't know what to do. Can more than one button be
6478 * reported in one event? */
6479 }
6480 string[3] = (char_u)(button | 0x20);
6481 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
6482 break;
6483 case GPM_UP:
6484 string[3] = MOUSE_RELEASE;
6485 old_buttons &= ~gpm_event.buttons;
6486 break;
6487 default:
6488 return 0;
6489 }
6490 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
6491 gpm_modifiers = gpm_event.modifiers;
6492 vim_modifiers = 0x0;
6493 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
6494 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
6495 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
6496 */
6497 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
6498 vim_modifiers |= MOUSE_SHIFT;
6499
6500 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
6501 vim_modifiers |= MOUSE_CTRL;
6502 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
6503 vim_modifiers |= MOUSE_ALT;
6504 string[3] |= vim_modifiers;
6505 string[4] = (char_u)(col + ' ' + 1);
6506 string[5] = (char_u)(row + ' ' + 1);
6507 add_to_input_buf(string, 6);
6508 return 6;
6509}
6510#endif /* FEAT_MOUSE_GPM */
6511
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006512#ifdef FEAT_SYSMOUSE
6513/*
6514 * Initialize connection with sysmouse.
6515 * Let virtual console inform us with SIGUSR2 for pending sysmouse
6516 * output, any sysmouse output than will be processed via sig_sysmouse().
6517 * Return OK if succeeded, FAIL if failed.
6518 */
6519 static int
6520sysmouse_open()
6521{
6522 struct mouse_info mouse;
6523
6524 mouse.operation = MOUSE_MODE;
6525 mouse.u.mode.mode = 0;
6526 mouse.u.mode.signal = SIGUSR2;
6527 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
6528 {
6529 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
6530 mouse.operation = MOUSE_SHOW;
6531 ioctl(1, CONS_MOUSECTL, &mouse);
6532 return OK;
6533 }
6534 return FAIL;
6535}
6536
6537/*
6538 * Stop processing SIGUSR2 signals, and also make sure that
6539 * virtual console do not send us any sysmouse related signal.
6540 */
6541 static void
6542sysmouse_close()
6543{
6544 struct mouse_info mouse;
6545
6546 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
6547 mouse.operation = MOUSE_MODE;
6548 mouse.u.mode.mode = 0;
6549 mouse.u.mode.signal = 0;
6550 ioctl(1, CONS_MOUSECTL, &mouse);
6551}
6552
6553/*
6554 * Gets info from sysmouse and adds special keys to input buf.
6555 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006556 static RETSIGTYPE
6557sig_sysmouse SIGDEFARG(sigarg)
6558{
6559 struct mouse_info mouse;
6560 struct video_info video;
6561 char_u string[6];
6562 int row, col;
6563 int button;
6564 int buttons;
6565 static int oldbuttons = 0;
6566
6567#ifdef FEAT_GUI
6568 /* Don't put events in the input queue now. */
6569 if (hold_gui_events)
6570 return;
6571#endif
6572
6573 mouse.operation = MOUSE_GETINFO;
6574 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
6575 && ioctl(1, FBIO_MODEINFO, &video) != -1
6576 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
6577 && video.vi_cheight > 0 && video.vi_cwidth > 0)
6578 {
6579 row = mouse.u.data.y / video.vi_cheight;
6580 col = mouse.u.data.x / video.vi_cwidth;
6581 buttons = mouse.u.data.buttons;
6582 string[0] = ESC; /* Our termcode */
6583 string[1] = 'M';
6584 string[2] = 'S';
6585 if (oldbuttons == buttons && buttons != 0)
6586 {
6587 button = MOUSE_DRAG;
6588 }
6589 else
6590 {
6591 switch (buttons)
6592 {
6593 case 0:
6594 button = MOUSE_RELEASE;
6595 break;
6596 case 1:
6597 button = MOUSE_LEFT;
6598 break;
6599 case 2:
6600 button = MOUSE_MIDDLE;
6601 break;
6602 case 4:
6603 button = MOUSE_RIGHT;
6604 break;
6605 default:
6606 return;
6607 }
6608 oldbuttons = buttons;
6609 }
6610 string[3] = (char_u)(button);
6611 string[4] = (char_u)(col + ' ' + 1);
6612 string[5] = (char_u)(row + ' ' + 1);
6613 add_to_input_buf(string, 6);
6614 }
6615 return;
6616}
6617#endif /* FEAT_SYSMOUSE */
6618
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619#if defined(FEAT_LIBCALL) || defined(PROTO)
6620typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
6621typedef char_u * (*INTPROCSTR)__ARGS((int));
6622typedef int (*STRPROCINT)__ARGS((char_u *));
6623typedef int (*INTPROCINT)__ARGS((int));
6624
6625/*
6626 * Call a DLL routine which takes either a string or int param
6627 * and returns an allocated string.
6628 */
6629 int
6630mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
6631 char_u *libname;
6632 char_u *funcname;
6633 char_u *argstring; /* NULL when using a argint */
6634 int argint;
6635 char_u **string_result;/* NULL when using number_result */
6636 int *number_result;
6637{
6638# if defined(USE_DLOPEN)
6639 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006640 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641# else
6642 shl_t hinstLib;
6643# endif
6644 STRPROCSTR ProcAdd;
6645 INTPROCSTR ProcAddI;
6646 char_u *retval_str = NULL;
6647 int retval_int = 0;
6648 int success = FALSE;
6649
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006650 /*
6651 * Get a handle to the DLL module.
6652 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00006654 /* First clear any error, it's not cleared by the dlopen() call. */
6655 (void)dlerror();
6656
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 hinstLib = dlopen((char *)libname, RTLD_LAZY
6658# ifdef RTLD_LOCAL
6659 | RTLD_LOCAL
6660# endif
6661 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006662 if (hinstLib == NULL)
6663 {
6664 /* "dlerr" must be used before dlclose() */
6665 dlerr = (char *)dlerror();
6666 if (dlerr != NULL)
6667 EMSG2(_("dlerror = \"%s\""), dlerr);
6668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669# else
6670 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
6671# endif
6672
6673 /* If the handle is valid, try to get the function address. */
6674 if (hinstLib != NULL)
6675 {
6676# ifdef HAVE_SETJMP_H
6677 /*
6678 * Catch a crash when calling the library function. For example when
6679 * using a number where a string pointer is expected.
6680 */
6681 mch_startjmp();
6682 if (SETJMP(lc_jump_env) != 0)
6683 {
6684 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006685# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006686 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00006687# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 mch_didjmp();
6689 }
6690 else
6691# endif
6692 {
6693 retval_str = NULL;
6694 retval_int = 0;
6695
6696 if (argstring != NULL)
6697 {
6698# if defined(USE_DLOPEN)
6699 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006700 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701# else
6702 if (shl_findsym(&hinstLib, (const char *)funcname,
6703 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
6704 ProcAdd = NULL;
6705# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006706 if ((success = (ProcAdd != NULL
6707# if defined(USE_DLOPEN)
6708 && dlerr == NULL
6709# endif
6710 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 {
6712 if (string_result == NULL)
6713 retval_int = ((STRPROCINT)ProcAdd)(argstring);
6714 else
6715 retval_str = (ProcAdd)(argstring);
6716 }
6717 }
6718 else
6719 {
6720# if defined(USE_DLOPEN)
6721 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006722 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723# else
6724 if (shl_findsym(&hinstLib, (const char *)funcname,
6725 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
6726 ProcAddI = NULL;
6727# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006728 if ((success = (ProcAddI != NULL
6729# if defined(USE_DLOPEN)
6730 && dlerr == NULL
6731# endif
6732 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 {
6734 if (string_result == NULL)
6735 retval_int = ((INTPROCINT)ProcAddI)(argint);
6736 else
6737 retval_str = (ProcAddI)(argint);
6738 }
6739 }
6740
6741 /* Save the string before we free the library. */
6742 /* Assume that a "1" or "-1" result is an illegal pointer. */
6743 if (string_result == NULL)
6744 *number_result = retval_int;
6745 else if (retval_str != NULL
6746 && retval_str != (char_u *)1
6747 && retval_str != (char_u *)-1)
6748 *string_result = vim_strsave(retval_str);
6749 }
6750
6751# ifdef HAVE_SETJMP_H
6752 mch_endjmp();
6753# ifdef SIGHASARG
6754 if (lc_signal != 0)
6755 {
6756 int i;
6757
6758 /* try to find the name of this signal */
6759 for (i = 0; signal_info[i].sig != -1; i++)
6760 if (lc_signal == signal_info[i].sig)
6761 break;
6762 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
6763 }
6764# endif
6765# endif
6766
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006768 /* "dlerr" must be used before dlclose() */
6769 if (dlerr != NULL)
6770 EMSG2(_("dlerror = \"%s\""), dlerr);
6771
6772 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 (void)dlclose(hinstLib);
6774# else
6775 (void)shl_unload(hinstLib);
6776# endif
6777 }
6778
6779 if (!success)
6780 {
6781 EMSG2(_(e_libcall), funcname);
6782 return FAIL;
6783 }
6784
6785 return OK;
6786}
6787#endif
6788
6789#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
6790static int xterm_trace = -1; /* default: disabled */
6791static int xterm_button;
6792
6793/*
6794 * Setup a dummy window for X selections in a terminal.
6795 */
6796 void
6797setup_term_clip()
6798{
6799 int z = 0;
6800 char *strp = "";
6801 Widget AppShell;
6802
6803 if (!x_connect_to_server())
6804 return;
6805
6806 open_app_context();
6807 if (app_context != NULL && xterm_Shell == (Widget)0)
6808 {
6809 int (*oldhandler)();
6810#if defined(HAVE_SETJMP_H)
6811 int (*oldIOhandler)();
6812#endif
6813# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6814 struct timeval start_tv;
6815
6816 if (p_verbose > 0)
6817 gettimeofday(&start_tv, NULL);
6818# endif
6819
6820 /* Ignore X errors while opening the display */
6821 oldhandler = XSetErrorHandler(x_error_check);
6822
6823#if defined(HAVE_SETJMP_H)
6824 /* Ignore X IO errors while opening the display */
6825 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6826 mch_startjmp();
6827 if (SETJMP(lc_jump_env) != 0)
6828 {
6829 mch_didjmp();
6830 xterm_dpy = NULL;
6831 }
6832 else
6833#endif
6834 {
6835 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6836 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6837#if defined(HAVE_SETJMP_H)
6838 mch_endjmp();
6839#endif
6840 }
6841
6842#if defined(HAVE_SETJMP_H)
6843 /* Now handle X IO errors normally. */
6844 (void)XSetIOErrorHandler(oldIOhandler);
6845#endif
6846 /* Now handle X errors normally. */
6847 (void)XSetErrorHandler(oldhandler);
6848
6849 if (xterm_dpy == NULL)
6850 {
6851 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006852 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 return;
6854 }
6855
6856 /* Catch terminating error of the X server connection. */
6857 (void)XSetIOErrorHandler(x_IOerror_handler);
6858
6859# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6860 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006861 {
6862 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006864 verbose_leave();
6865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866# endif
6867
6868 /* Create a Shell to make converters work. */
6869 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6870 applicationShellWidgetClass, xterm_dpy,
6871 NULL);
6872 if (AppShell == (Widget)0)
6873 return;
6874 xterm_Shell = XtVaCreatePopupShell("VIM",
6875 topLevelShellWidgetClass, AppShell,
6876 XtNmappedWhenManaged, 0,
6877 XtNwidth, 1,
6878 XtNheight, 1,
6879 NULL);
6880 if (xterm_Shell == (Widget)0)
6881 return;
6882
6883 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02006884 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 if (x11_display == NULL)
6886 x11_display = xterm_dpy;
6887
6888 XtRealizeWidget(xterm_Shell);
6889 XSync(xterm_dpy, False);
6890 xterm_update();
6891 }
6892 if (xterm_Shell != (Widget)0)
6893 {
6894 clip_init(TRUE);
6895 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6896 x11_window = (Window)atol(strp);
6897 /* Check if $WINDOWID is valid. */
6898 if (test_x11_window(xterm_dpy) == FAIL)
6899 x11_window = 0;
6900 if (x11_window != 0)
6901 xterm_trace = 0;
6902 }
6903}
6904
6905 void
6906start_xterm_trace(button)
6907 int button;
6908{
6909 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6910 return;
6911 xterm_trace = 1;
6912 xterm_button = button;
6913 do_xterm_trace();
6914}
6915
6916
6917 void
6918stop_xterm_trace()
6919{
6920 if (xterm_trace < 0)
6921 return;
6922 xterm_trace = 0;
6923}
6924
6925/*
6926 * Query the xterm pointer and generate mouse termcodes if necessary
6927 * return TRUE if dragging is active, else FALSE
6928 */
6929 static int
6930do_xterm_trace()
6931{
6932 Window root, child;
6933 int root_x, root_y;
6934 int win_x, win_y;
6935 int row, col;
6936 int_u mask_return;
6937 char_u buf[50];
6938 char_u *strp;
6939 long got_hints;
6940 static char_u *mouse_code;
6941 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6942 static int prev_row = 0, prev_col = 0;
6943 static XSizeHints xterm_hints;
6944
6945 if (xterm_trace <= 0)
6946 return FALSE;
6947
6948 if (xterm_trace == 1)
6949 {
6950 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00006951 * have changed recently. */
6952 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6953 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954 || xterm_hints.width_inc <= 1
6955 || xterm_hints.height_inc <= 1)
6956 {
6957 xterm_trace = -1; /* Not enough data -- disable tracing */
6958 return FALSE;
6959 }
6960
6961 /* Rely on the same mouse code for the duration of this */
6962 mouse_code = find_termcode(mouse_name);
6963 prev_row = mouse_row;
6964 prev_row = mouse_col;
6965 xterm_trace = 2;
6966
6967 /* Find the offset of the chars, there might be a scrollbar on the
6968 * left of the window and/or a menu on the top (eterm etc.) */
6969 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6970 &win_x, &win_y, &mask_return);
6971 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6972 - (xterm_hints.height_inc / 2);
6973 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6974 xterm_hints.y = 2;
6975 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6976 - (xterm_hints.width_inc / 2);
6977 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6978 xterm_hints.x = 2;
6979 return TRUE;
6980 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006981 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 {
6983 xterm_trace = 0;
6984 return FALSE;
6985 }
6986
6987 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6988 &win_x, &win_y, &mask_return);
6989
6990 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6991 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6992 if (row == prev_row && col == prev_col)
6993 return TRUE;
6994
6995 STRCPY(buf, mouse_code);
6996 strp = buf + STRLEN(buf);
6997 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6998 *strp++ = (char_u)(col + ' ' + 1);
6999 *strp++ = (char_u)(row + ' ' + 1);
7000 *strp = 0;
7001 add_to_input_buf(buf, STRLEN(buf));
7002
7003 prev_row = row;
7004 prev_col = col;
7005 return TRUE;
7006}
7007
7008# if defined(FEAT_GUI) || defined(PROTO)
7009/*
7010 * Destroy the display, window and app_context. Required for GTK.
7011 */
7012 void
7013clear_xterm_clip()
7014{
7015 if (xterm_Shell != (Widget)0)
7016 {
7017 XtDestroyWidget(xterm_Shell);
7018 xterm_Shell = (Widget)0;
7019 }
7020 if (xterm_dpy != NULL)
7021 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007022# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023 /* Lesstif and Solaris crash here, lose some memory */
7024 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007025# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 if (x11_display == xterm_dpy)
7027 x11_display = NULL;
7028 xterm_dpy = NULL;
7029 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007030# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 if (app_context != (XtAppContext)NULL)
7032 {
7033 /* Lesstif and Solaris crash here, lose some memory */
7034 XtDestroyApplicationContext(app_context);
7035 app_context = (XtAppContext)NULL;
7036 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007037# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038}
7039# endif
7040
7041/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007042 * Catch up with GUI or X events.
7043 */
7044 static void
7045clip_update()
7046{
7047# ifdef FEAT_GUI
7048 if (gui.in_use)
7049 gui_mch_update();
7050 else
7051# endif
7052 if (xterm_Shell != (Widget)0)
7053 xterm_update();
7054}
7055
7056/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 * Catch up with any queued X events. This may put keyboard input into the
7058 * input buffer, call resize call-backs, trigger timers etc. If there is
7059 * nothing in the X event queue (& no timers pending), then we return
7060 * immediately.
7061 */
7062 static void
7063xterm_update()
7064{
7065 XEvent event;
7066
7067 while (XtAppPending(app_context) && !vim_is_input_buf_full())
7068 {
7069 XtAppNextEvent(app_context, &event);
7070#ifdef FEAT_CLIENTSERVER
7071 {
7072 XPropertyEvent *e = (XPropertyEvent *)&event;
7073
7074 if (e->type == PropertyNotify && e->window == commWindow
7075 && e->atom == commProperty && e->state == PropertyNewValue)
7076 serverEventProc(xterm_dpy, &event);
7077 }
7078#endif
7079 XtDispatchEvent(&event);
7080 }
7081}
7082
7083 int
7084clip_xterm_own_selection(cbd)
7085 VimClipboard *cbd;
7086{
7087 if (xterm_Shell != (Widget)0)
7088 return clip_x11_own_selection(xterm_Shell, cbd);
7089 return FAIL;
7090}
7091
7092 void
7093clip_xterm_lose_selection(cbd)
7094 VimClipboard *cbd;
7095{
7096 if (xterm_Shell != (Widget)0)
7097 clip_x11_lose_selection(xterm_Shell, cbd);
7098}
7099
7100 void
7101clip_xterm_request_selection(cbd)
7102 VimClipboard *cbd;
7103{
7104 if (xterm_Shell != (Widget)0)
7105 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7106}
7107
7108 void
7109clip_xterm_set_selection(cbd)
7110 VimClipboard *cbd;
7111{
7112 clip_x11_set_selection(cbd);
7113}
7114#endif
7115
7116
7117#if defined(USE_XSMP) || defined(PROTO)
7118/*
7119 * Code for X Session Management Protocol.
7120 */
7121static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
7122static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
7123static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
7124static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
7125static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
7126
7127
7128# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7129static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
7130
7131/*
7132 * This is our chance to ask the user if they want to save,
7133 * or abort the logout
7134 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 static void
7136xsmp_handle_interaction(smc_conn, client_data)
7137 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007138 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139{
7140 cmdmod_T save_cmdmod;
7141 int cancel_shutdown = False;
7142
7143 save_cmdmod = cmdmod;
7144 cmdmod.confirm = TRUE;
7145 if (check_changed_any(FALSE))
7146 /* Mustn't logout */
7147 cancel_shutdown = True;
7148 cmdmod = save_cmdmod;
7149 setcursor(); /* position cursor */
7150 out_flush();
7151
7152 /* Done interaction */
7153 SmcInteractDone(smc_conn, cancel_shutdown);
7154
7155 /* Finish off
7156 * Only end save-yourself here if we're not cancelling shutdown;
7157 * we'll get a cancelled callback later in which we'll end it.
7158 * Hopefully get around glitchy SMs (like GNOME-1)
7159 */
7160 if (!cancel_shutdown)
7161 {
7162 xsmp.save_yourself = False;
7163 SmcSaveYourselfDone(smc_conn, True);
7164 }
7165}
7166# endif
7167
7168/*
7169 * Callback that starts save-yourself.
7170 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 static void
7172xsmp_handle_save_yourself(smc_conn, client_data, save_type,
7173 shutdown, interact_style, fast)
7174 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007175 SmPointer client_data UNUSED;
7176 int save_type UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177 Bool shutdown;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007178 int interact_style UNUSED;
7179 Bool fast UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180{
7181 /* Handle already being in saveyourself */
7182 if (xsmp.save_yourself)
7183 SmcSaveYourselfDone(smc_conn, True);
7184 xsmp.save_yourself = True;
7185 xsmp.shutdown = shutdown;
7186
7187 /* First up, preserve all files */
7188 out_flush();
7189 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7190
7191 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007192 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007193
7194# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7195 /* Now see if we can ask about unsaved files */
7196 if (shutdown && !fast && gui.in_use)
7197 /* Need to interact with user, but need SM's permission */
7198 SmcInteractRequest(smc_conn, SmDialogError,
7199 xsmp_handle_interaction, client_data);
7200 else
7201# endif
7202 {
7203 /* Can stop the cycle here */
7204 SmcSaveYourselfDone(smc_conn, True);
7205 xsmp.save_yourself = False;
7206 }
7207}
7208
7209
7210/*
7211 * Callback to warn us of imminent death.
7212 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 static void
7214xsmp_die(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007215 SmcConn smc_conn UNUSED;
7216 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217{
7218 xsmp_close();
7219
7220 /* quit quickly leaving swapfiles for modified buffers behind */
7221 getout_preserve_modified(0);
7222}
7223
7224
7225/*
7226 * Callback to tell us that save-yourself has completed.
7227 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 static void
7229xsmp_save_complete(smc_conn, client_data)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007230 SmcConn smc_conn UNUSED;
7231 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232{
7233 xsmp.save_yourself = False;
7234}
7235
7236
7237/*
7238 * Callback to tell us that an instigated shutdown was cancelled
7239 * (maybe even by us)
7240 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241 static void
7242xsmp_shutdown_cancelled(smc_conn, client_data)
7243 SmcConn smc_conn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007244 SmPointer client_data UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245{
7246 if (xsmp.save_yourself)
7247 SmcSaveYourselfDone(smc_conn, True);
7248 xsmp.save_yourself = False;
7249 xsmp.shutdown = False;
7250}
7251
7252
7253/*
7254 * Callback to tell us that a new ICE connection has been established.
7255 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 static void
7257xsmp_ice_connection(iceConn, clientData, opening, watchData)
7258 IceConn iceConn;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007259 IcePointer clientData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 Bool opening;
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00007261 IcePointer *watchData UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262{
7263 /* Intercept creation of ICE connection fd */
7264 if (opening)
7265 {
7266 xsmp_icefd = IceConnectionNumber(iceConn);
7267 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7268 }
7269}
7270
7271
7272/* Handle any ICE processing that's required; return FAIL if SM lost */
7273 int
7274xsmp_handle_requests()
7275{
7276 Bool rep;
7277
7278 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7279 == IceProcessMessagesIOError)
7280 {
7281 /* Lost ICE */
7282 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007283 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007284 xsmp_close();
7285 return FAIL;
7286 }
7287 else
7288 return OK;
7289}
7290
7291static int dummy;
7292
7293/* Set up X Session Management Protocol */
7294 void
7295xsmp_init(void)
7296{
7297 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 SmcCallbacks smcallbacks;
7299#if 0
7300 SmPropValue smname;
7301 SmProp smnameprop;
7302 SmProp *smprops[1];
7303#endif
7304
7305 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007306 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307
7308 xsmp.save_yourself = xsmp.shutdown = False;
7309
7310 /* Set up SM callbacks - must have all, even if they're not used */
7311 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
7312 smcallbacks.save_yourself.client_data = NULL;
7313 smcallbacks.die.callback = xsmp_die;
7314 smcallbacks.die.client_data = NULL;
7315 smcallbacks.save_complete.callback = xsmp_save_complete;
7316 smcallbacks.save_complete.client_data = NULL;
7317 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
7318 smcallbacks.shutdown_cancelled.client_data = NULL;
7319
7320 /* Set up a watch on ICE connection creations. The "dummy" argument is
7321 * apparently required for FreeBSD (we get a BUS error when using NULL). */
7322 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
7323 {
7324 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007325 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 return;
7327 }
7328
7329 /* Create an SM connection */
7330 xsmp.smcconn = SmcOpenConnection(
7331 NULL,
7332 NULL,
7333 SmProtoMajor,
7334 SmProtoMinor,
7335 SmcSaveYourselfProcMask | SmcDieProcMask
7336 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
7337 &smcallbacks,
7338 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00007339 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 sizeof(errorstring),
7341 errorstring);
7342 if (xsmp.smcconn == NULL)
7343 {
7344 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00007345
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007347 {
7348 vim_snprintf(errorreport, sizeof(errorreport),
7349 _("XSMP SmcOpenConnection failed: %s"), errorstring);
7350 verb_msg((char_u *)errorreport);
7351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352 return;
7353 }
7354 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
7355
7356#if 0
7357 /* ID ourselves */
7358 smname.value = "vim";
7359 smname.length = 3;
7360 smnameprop.name = "SmProgram";
7361 smnameprop.type = "SmARRAY8";
7362 smnameprop.num_vals = 1;
7363 smnameprop.vals = &smname;
7364
7365 smprops[0] = &smnameprop;
7366 SmcSetProperties(xsmp.smcconn, 1, smprops);
7367#endif
7368}
7369
7370
7371/* Shut down XSMP comms. */
7372 void
7373xsmp_close()
7374{
7375 if (xsmp_icefd != -1)
7376 {
7377 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00007378 if (xsmp.clientid != NULL)
7379 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00007380 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 xsmp_icefd = -1;
7382 }
7383}
7384#endif /* USE_XSMP */
7385
7386
7387#ifdef EBCDIC
7388/* Translate character to its CTRL- value */
7389char CtrlTable[] =
7390{
7391/* 00 - 5E */
7392 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7393 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7394 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7395 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
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,
7398/* ^ */ 0x1E,
7399/* - */ 0x1F,
7400/* 61 - 6C */
7401 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7402/* _ */ 0x1F,
7403/* 6E - 80 */
7404 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7405/* a */ 0x01,
7406/* b */ 0x02,
7407/* c */ 0x03,
7408/* d */ 0x37,
7409/* e */ 0x2D,
7410/* f */ 0x2E,
7411/* g */ 0x2F,
7412/* h */ 0x16,
7413/* i */ 0x05,
7414/* 8A - 90 */
7415 0, 0, 0, 0, 0, 0, 0,
7416/* j */ 0x15,
7417/* k */ 0x0B,
7418/* l */ 0x0C,
7419/* m */ 0x0D,
7420/* n */ 0x0E,
7421/* o */ 0x0F,
7422/* p */ 0x10,
7423/* q */ 0x11,
7424/* r */ 0x12,
7425/* 9A - A1 */
7426 0, 0, 0, 0, 0, 0, 0, 0,
7427/* s */ 0x13,
7428/* t */ 0x3C,
7429/* u */ 0x3D,
7430/* v */ 0x32,
7431/* w */ 0x26,
7432/* x */ 0x18,
7433/* y */ 0x19,
7434/* z */ 0x3F,
7435/* AA - AC */
7436 0, 0, 0,
7437/* [ */ 0x27,
7438/* AE - BC */
7439 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7440/* ] */ 0x1D,
7441/* BE - C0 */ 0, 0, 0,
7442/* A */ 0x01,
7443/* B */ 0x02,
7444/* C */ 0x03,
7445/* D */ 0x37,
7446/* E */ 0x2D,
7447/* F */ 0x2E,
7448/* G */ 0x2F,
7449/* H */ 0x16,
7450/* I */ 0x05,
7451/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
7452/* J */ 0x15,
7453/* K */ 0x0B,
7454/* L */ 0x0C,
7455/* M */ 0x0D,
7456/* N */ 0x0E,
7457/* O */ 0x0F,
7458/* P */ 0x10,
7459/* Q */ 0x11,
7460/* R */ 0x12,
7461/* DA - DF */ 0, 0, 0, 0, 0, 0,
7462/* \ */ 0x1C,
7463/* E1 */ 0,
7464/* S */ 0x13,
7465/* T */ 0x3C,
7466/* U */ 0x3D,
7467/* V */ 0x32,
7468/* W */ 0x26,
7469/* X */ 0x18,
7470/* Y */ 0x19,
7471/* Z */ 0x3F,
7472/* EA - FF*/ 0, 0, 0, 0, 0, 0,
7473 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7474};
7475
7476char MetaCharTable[]=
7477{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7478 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
7479 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
7480 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
7481 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
7482};
7483
7484
7485/* TODO: Use characters NOT numbers!!! */
7486char CtrlCharTable[]=
7487{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
7488 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
7489 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
7490 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
7491 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
7492};
7493
7494
7495#endif