blob: 491d41a2e0640e5def9f372576bae1c5bcdbd2f0 [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 */
28#ifndef __APPLE__
29# 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#ifdef HAVE_FCNTL_H
39# include <fcntl.h>
40#endif
41
42#include "os_unixx.h" /* unix includes for os_unix.c only */
43
44#ifdef USE_XSMP
45# include <X11/SM/SMlib.h>
46#endif
47
48/*
49 * Use this prototype for select, some include files have a wrong prototype
50 */
51#undef select
52#ifdef __BEOS__
53# define select beos_select
54#endif
55
56#if defined(HAVE_SELECT)
57extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
58#endif
59
60#ifdef FEAT_MOUSE_GPM
61# include <gpm.h>
62/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
63 * I just copied relevant defines here. A cleaner solution would be to put gpm
64 * code into separate file and include there linux/keyboard.h
65 */
66/* #include <linux/keyboard.h> */
67# define KG_SHIFT 0
68# define KG_CTRL 2
69# define KG_ALT 3
70# define KG_ALTGR 1
71# define KG_SHIFTL 4
72# define KG_SHIFTR 5
73# define KG_CTRLL 6
74# define KG_CTRLR 7
75# define KG_CAPSSHIFT 8
76
77static void gpm_close __ARGS((void));
78static int gpm_open __ARGS((void));
79static int mch_gpm_process __ARGS((void));
80#endif
81
82/*
83 * end of autoconf section. To be extended...
84 */
85
86/* Are the following #ifdefs still required? And why? Is that for X11? */
87
88#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
89# ifdef SIGWINCH
90# undef SIGWINCH
91# endif
92# ifdef TIOCGWINSZ
93# undef TIOCGWINSZ
94# endif
95#endif
96
97#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
98# define SIGWINCH SIGWINDOW
99#endif
100
101#ifdef FEAT_X11
102# include <X11/Xlib.h>
103# include <X11/Xutil.h>
104# include <X11/Xatom.h>
105# ifdef FEAT_XCLIPBOARD
106# include <X11/Intrinsic.h>
107# include <X11/Shell.h>
108# include <X11/StringDefs.h>
109static Widget xterm_Shell = (Widget)0;
110static void xterm_update __ARGS((void));
111# endif
112
113# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
114Window x11_window = 0;
115# endif
116Display *x11_display = NULL;
117
118# ifdef FEAT_TITLE
119static int get_x11_windis __ARGS((void));
120static void set_x11_title __ARGS((char_u *));
121static void set_x11_icon __ARGS((char_u *));
122# endif
123#endif
124
125#ifdef FEAT_TITLE
126static int get_x11_title __ARGS((int));
127static int get_x11_icon __ARGS((int));
128
129static char_u *oldtitle = NULL;
130static int did_set_title = FALSE;
131static char_u *oldicon = NULL;
132static int did_set_icon = FALSE;
133#endif
134
135static void may_core_dump __ARGS((void));
136
137static int WaitForChar __ARGS((long));
138#if defined(__BEOS__)
139int RealWaitForChar __ARGS((int, long, int *));
140#else
141static int RealWaitForChar __ARGS((int, long, int *));
142#endif
143
144#ifdef FEAT_XCLIPBOARD
145static int do_xterm_trace __ARGS((void));
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000146# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
149static void handle_resize __ARGS((void));
150
151#if defined(SIGWINCH)
152static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
153#endif
154#if defined(SIGINT)
155static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
156#endif
157#if defined(SIGPWR)
158static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
159#endif
160#if defined(SIGALRM) && defined(FEAT_X11) \
161 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
162# define SET_SIG_ALARM
163static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
164static int sig_alarm_called;
165#endif
166static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
167
Bram Moolenaardf177f62005-02-22 08:39:57 +0000168static void catch_int_signal __ARGS((void));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169static void set_signals __ARGS((void));
170static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
171#ifndef __EMX__
172static int have_wildcard __ARGS((int, char_u **));
173static int have_dollars __ARGS((int, char_u **));
174#endif
175
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176#ifndef __EMX__
177static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
178#endif
179
180#ifndef SIG_ERR
181# define SIG_ERR ((RETSIGTYPE (*)())-1)
182#endif
183
184static int do_resize = FALSE;
185#ifndef __EMX__
186static char_u *extra_shell_arg = NULL;
187static int show_shell_mess = TRUE;
188#endif
189static int deadly_signal = 0; /* The signal we caught */
190
191static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
192
193#ifdef USE_XSMP
194typedef struct
195{
196 SmcConn smcconn; /* The SM connection ID */
197 IceConn iceconn; /* The ICE connection ID */
198 Bool save_yourself; /* If we're in the middle of a save_yourself */
199 Bool shutdown; /* If we're in shutdown mode */
200} xsmp_config_T;
201
202static xsmp_config_T xsmp;
203#endif
204
205#ifdef SYS_SIGLIST_DECLARED
206/*
207 * I have seen
208 * extern char *_sys_siglist[NSIG];
209 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
210 * that describe the signals. That is nearly what we want here. But
211 * autoconf does only check for sys_siglist (without the underscore), I
212 * do not want to change everything today.... jw.
213 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
214 */
215#endif
216
217static struct signalinfo
218{
219 int sig; /* Signal number, eg. SIGSEGV etc */
220 char *name; /* Signal name (not char_u!). */
221 char deadly; /* Catch as a deadly signal? */
222} signal_info[] =
223{
224#ifdef SIGHUP
225 {SIGHUP, "HUP", TRUE},
226#endif
227#ifdef SIGQUIT
228 {SIGQUIT, "QUIT", TRUE},
229#endif
230#ifdef SIGILL
231 {SIGILL, "ILL", TRUE},
232#endif
233#ifdef SIGTRAP
234 {SIGTRAP, "TRAP", TRUE},
235#endif
236#ifdef SIGABRT
237 {SIGABRT, "ABRT", TRUE},
238#endif
239#ifdef SIGEMT
240 {SIGEMT, "EMT", TRUE},
241#endif
242#ifdef SIGFPE
243 {SIGFPE, "FPE", TRUE},
244#endif
245#ifdef SIGBUS
246 {SIGBUS, "BUS", TRUE},
247#endif
248#ifdef SIGSEGV
249 {SIGSEGV, "SEGV", TRUE},
250#endif
251#ifdef SIGSYS
252 {SIGSYS, "SYS", TRUE},
253#endif
254#ifdef SIGALRM
255 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
256#endif
257#ifdef SIGTERM
258 {SIGTERM, "TERM", TRUE},
259#endif
260#ifdef SIGVTALRM
261 {SIGVTALRM, "VTALRM", TRUE},
262#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000263#if defined(SIGPROF) && !defined(FEAT_MZSCHEME)
264 /* MzScheme uses SIGPROF for its own needs */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265 {SIGPROF, "PROF", TRUE},
266#endif
267#ifdef SIGXCPU
268 {SIGXCPU, "XCPU", TRUE},
269#endif
270#ifdef SIGXFSZ
271 {SIGXFSZ, "XFSZ", TRUE},
272#endif
273#ifdef SIGUSR1
274 {SIGUSR1, "USR1", TRUE},
275#endif
276#ifdef SIGUSR2
277 {SIGUSR2, "USR2", TRUE},
278#endif
279#ifdef SIGINT
280 {SIGINT, "INT", FALSE},
281#endif
282#ifdef SIGWINCH
283 {SIGWINCH, "WINCH", FALSE},
284#endif
285#ifdef SIGTSTP
286 {SIGTSTP, "TSTP", FALSE},
287#endif
288#ifdef SIGPIPE
289 {SIGPIPE, "PIPE", FALSE},
290#endif
291 {-1, "Unknown!", FALSE}
292};
293
294 void
295mch_write(s, len)
296 char_u *s;
297 int len;
298{
299 write(1, (char *)s, len);
300 if (p_wd) /* Unix is too fast, slow down a bit more */
301 RealWaitForChar(read_cmd_fd, p_wd, NULL);
302}
303
304/*
305 * mch_inchar(): low level input funcion.
306 * Get a characters from the keyboard.
307 * Return the number of characters that are available.
308 * If wtime == 0 do not wait for characters.
309 * If wtime == n wait a short time for characters.
310 * If wtime == -1 wait forever for characters.
311 */
312 int
313mch_inchar(buf, maxlen, wtime, tb_change_cnt)
314 char_u *buf;
315 int maxlen;
316 long wtime; /* don't use "time", MIPS cannot handle it */
317 int tb_change_cnt;
318{
319 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000320
321 /* Check if window changed size while we were busy, perhaps the ":set
322 * columns=99" command was used. */
323 while (do_resize)
324 handle_resize();
325
326 if (wtime >= 0)
327 {
328 while (WaitForChar(wtime) == 0) /* no character available */
329 {
330 if (!do_resize) /* return if not interrupted by resize */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 handle_resize();
333 }
334 }
335 else /* wtime == -1 */
336 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000337 /*
338 * If there is no character available within 'updatetime' seconds
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000339 * flush all the swap files to disk.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 * Also done when interrupted by SIGWINCH.
341 */
342 if (WaitForChar(p_ut) == 0)
343 {
344#ifdef FEAT_AUTOCMD
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000345 if (!did_cursorhold
346 && has_cursorhold()
347 && get_real_state() == NORMAL_BUSY
348 && maxlen >= 3
349 && !typebuf_changed(tb_change_cnt))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 {
Bram Moolenaar4317d9b2005-03-18 20:25:31 +0000351 buf[0] = K_SPECIAL;
352 buf[1] = KS_EXTRA;
353 buf[2] = (int)KE_CURSORHOLD;
354 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356#endif
Bram Moolenaard4098f52005-06-27 22:37:13 +0000357 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 }
359 }
360
361 for (;;) /* repeat until we got a character */
362 {
363 while (do_resize) /* window changed size */
364 handle_resize();
365 /*
366 * we want to be interrupted by the winch signal
367 */
368 WaitForChar(-1L);
369 if (do_resize) /* interrupted by SIGWINCH signal */
370 continue;
371
372 /* If input was put directly in typeahead buffer bail out here. */
373 if (typebuf_changed(tb_change_cnt))
374 return 0;
375
376 /*
377 * For some terminals we only get one character at a time.
378 * We want the get all available characters, so we could keep on
379 * trying until none is available
380 * For some other terminals this is quite slow, that's why we don't do
381 * it.
382 */
383 len = read_from_input_buf(buf, (long)maxlen);
384 if (len > 0)
385 {
386#ifdef OS2
387 int i;
388
389 for (i = 0; i < len; i++)
390 if (buf[i] == 0)
391 buf[i] = K_NUL;
392#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 return len;
394 }
395 }
396}
397
398 static void
399handle_resize()
400{
401 do_resize = FALSE;
402 shell_resized();
403}
404
405/*
406 * return non-zero if a character is available
407 */
408 int
409mch_char_avail()
410{
411 return WaitForChar(0L);
412}
413
414#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
415# ifdef HAVE_SYS_RESOURCE_H
416# include <sys/resource.h>
417# endif
418# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
419# include <sys/sysctl.h>
420# endif
421# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
422# include <sys/sysinfo.h>
423# endif
424
425/*
426 * Return total amount of memory available. Doesn't change when memory has
427 * been allocated.
428 */
429/* ARGSUSED */
430 long_u
431mch_total_mem(special)
432 int special;
433{
434# ifdef __EMX__
435 return ulimit(3, 0L); /* always 32MB? */
436# else
437 long_u mem = 0;
438
439# ifdef HAVE_SYSCTL
440 int mib[2], physmem;
441 size_t len;
442
443 /* BSD way of getting the amount of RAM available. */
444 mib[0] = CTL_HW;
445 mib[1] = HW_USERMEM;
446 len = sizeof(physmem);
447 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
448 mem = (long_u)physmem;
449# endif
450
451# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
452 if (mem == 0)
453 {
454 struct sysinfo sinfo;
455
456 /* Linux way of getting amount of RAM available */
457 if (sysinfo(&sinfo) == 0)
458 mem = sinfo.totalram;
459 }
460# endif
461
462# ifdef HAVE_SYSCONF
463 if (mem == 0)
464 {
465 long pagesize, pagecount;
466
467 /* Solaris way of getting amount of RAM available */
468 pagesize = sysconf(_SC_PAGESIZE);
469 pagecount = sysconf(_SC_PHYS_PAGES);
470 if (pagesize > 0 && pagecount > 0)
471 mem = (long_u)pagesize * pagecount;
472 }
473# endif
474
475 /* Return the minimum of the physical memory and the user limit, because
476 * using more than the user limit may cause Vim to be terminated. */
477# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
478 {
479 struct rlimit rlp;
480
481 if (getrlimit(RLIMIT_DATA, &rlp) == 0
482 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
483# ifdef RLIM_INFINITY
484 && rlp.rlim_cur != RLIM_INFINITY
485# endif
486 && (long_u)rlp.rlim_cur < mem
487 )
488 return (long_u)rlp.rlim_cur;
489 }
490# endif
491
492 if (mem > 0)
493 return mem;
494 return (long_u)0x7fffffff;
495# endif
496}
497#endif
498
499 void
500mch_delay(msec, ignoreinput)
501 long msec;
502 int ignoreinput;
503{
504 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000505#ifdef FEAT_MZSCHEME
506 long total = msec; /* remember original value */
507#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508
509 if (ignoreinput)
510 {
511 /* Go to cooked mode without echo, to allow SIGINT interrupting us
512 * here */
513 old_tmode = curr_tmode;
514 if (curr_tmode == TMODE_RAW)
515 settmode(TMODE_SLEEP);
516
517 /*
518 * Everybody sleeps in a different way...
519 * Prefer nanosleep(), some versions of usleep() can only sleep up to
520 * one second.
521 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000522#ifdef FEAT_MZSCHEME
523 do
524 {
525 /* if total is large enough, wait by portions in p_mzq */
526 if (total > p_mzq)
527 msec = p_mzq;
528 else
529 msec = total;
530 total -= msec;
531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532#ifdef HAVE_NANOSLEEP
533 {
534 struct timespec ts;
535
536 ts.tv_sec = msec / 1000;
537 ts.tv_nsec = (msec % 1000) * 1000000;
538 (void)nanosleep(&ts, NULL);
539 }
540#else
541# ifdef HAVE_USLEEP
542 while (msec >= 1000)
543 {
544 usleep((unsigned int)(999 * 1000));
545 msec -= 999;
546 }
547 usleep((unsigned int)(msec * 1000));
548# else
549# ifndef HAVE_SELECT
550 poll(NULL, 0, (int)msec);
551# else
552# ifdef __EMX__
553 _sleep2(msec);
554# else
555 {
556 struct timeval tv;
557
558 tv.tv_sec = msec / 1000;
559 tv.tv_usec = (msec % 1000) * 1000;
560 /*
561 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
562 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
563 */
564 select(0, NULL, NULL, NULL, &tv);
565 }
566# endif /* __EMX__ */
567# endif /* HAVE_SELECT */
568# endif /* HAVE_NANOSLEEP */
569#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000570#ifdef FEAT_MZSCHEME
571 }
572 while (total > 0);
573#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574
575 settmode(old_tmode);
576 }
577 else
578 WaitForChar(msec);
579}
580
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000581#if 0 /* disabled, no longer needed now that regmatch() is not recursive */
582# if defined(HAVE_GETRLIMIT)
583# define HAVE_STACK_LIMIT
584# endif
585#endif
586
587#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
589# define HAVE_CHECK_STACK_GROWTH
590/*
591 * Support for checking for an almost-out-of-stack-space situation.
592 */
593
594/*
595 * Return a pointer to an item on the stack. Used to find out if the stack
596 * grows up or down.
597 */
598static void check_stack_growth __ARGS((char *p));
599static int stack_grows_downwards;
600
601/*
602 * Find out if the stack grows upwards or downwards.
603 * "p" points to a variable on the stack of the caller.
604 */
605 static void
606check_stack_growth(p)
607 char *p;
608{
609 int i;
610
611 stack_grows_downwards = (p > (char *)&i);
612}
613#endif
614
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000615#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616static char *stack_limit = NULL;
617
618#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
619# include <pthread.h>
620# include <pthread_np.h>
621#endif
622
623/*
624 * Find out until how var the stack can grow without getting into trouble.
625 * Called when starting up and when switching to the signal stack in
626 * deathtrap().
627 */
628 static void
629get_stack_limit()
630{
631 struct rlimit rlp;
632 int i;
633 long lim;
634
635 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
636 * limit doesn't fit in a long (rlim_cur might be "long long"). */
637 if (getrlimit(RLIMIT_STACK, &rlp) == 0
638 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
639# ifdef RLIM_INFINITY
640 && rlp.rlim_cur != RLIM_INFINITY
641# endif
642 )
643 {
644 lim = (long)rlp.rlim_cur;
645#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
646 {
647 pthread_attr_t attr;
648 size_t size;
649
650 /* On FreeBSD the initial thread always has a fixed stack size, no
651 * matter what the limits are set to. Normally it's 1 Mbyte. */
652 pthread_attr_init(&attr);
653 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
654 {
655 pthread_attr_getstacksize(&attr, &size);
656 if (lim > (long)size)
657 lim = (long)size;
658 }
659 pthread_attr_destroy(&attr);
660 }
661#endif
662 if (stack_grows_downwards)
663 {
664 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
665 if (stack_limit >= (char *)&i)
666 /* overflow, set to 1/16 of current stack position */
667 stack_limit = (char *)((long)&i / 16L);
668 }
669 else
670 {
671 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
672 if (stack_limit <= (char *)&i)
673 stack_limit = NULL; /* overflow */
674 }
675 }
676}
677
678/*
679 * Return FAIL when running out of stack space.
680 * "p" must point to any variable local to the caller that's on the stack.
681 */
682 int
683mch_stackcheck(p)
684 char *p;
685{
686 if (stack_limit != NULL)
687 {
688 if (stack_grows_downwards)
689 {
690 if (p < stack_limit)
691 return FAIL;
692 }
693 else if (p > stack_limit)
694 return FAIL;
695 }
696 return OK;
697}
698#endif
699
700#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
701/*
702 * Support for using the signal stack.
703 * This helps when we run out of stack space, which causes a SIGSEGV. The
704 * signal handler then must run on another stack, since the normal stack is
705 * completely full.
706 */
707
708#ifndef SIGSTKSZ
709# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
710#endif
711
712# ifdef HAVE_SIGALTSTACK
713static stack_t sigstk; /* for sigaltstack() */
714# else
715static struct sigstack sigstk; /* for sigstack() */
716# endif
717
718static void init_signal_stack __ARGS((void));
719static char *signal_stack;
720
721 static void
722init_signal_stack()
723{
724 if (signal_stack != NULL)
725 {
726# ifdef HAVE_SIGALTSTACK
727# ifdef __APPLE__
728 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
729 * "struct sigaltstack" needs to be declared. */
730 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
731# endif
732
733# ifdef HAVE_SS_BASE
734 sigstk.ss_base = signal_stack;
735# else
736 sigstk.ss_sp = signal_stack;
737# endif
738 sigstk.ss_size = SIGSTKSZ;
739 sigstk.ss_flags = 0;
740 (void)sigaltstack(&sigstk, NULL);
741# else
742 sigstk.ss_sp = signal_stack;
743 if (stack_grows_downwards)
744 sigstk.ss_sp += SIGSTKSZ - 1;
745 sigstk.ss_onstack = 0;
746 (void)sigstack(&sigstk, NULL);
747# endif
748 }
749}
750#endif
751
752/*
753 * We need correct potatotypes for a signal function, otherwise mean compilers
754 * will barf when the second argument to signal() is ``wrong''.
755 * Let me try it with a few tricky defines from my own osdef.h (jw).
756 */
757#if defined(SIGWINCH)
758/* ARGSUSED */
759 static RETSIGTYPE
760sig_winch SIGDEFARG(sigarg)
761{
762 /* this is not required on all systems, but it doesn't hurt anybody */
763 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
764 do_resize = TRUE;
765 SIGRETURN;
766}
767#endif
768
769#if defined(SIGINT)
770/* ARGSUSED */
771 static RETSIGTYPE
772catch_sigint SIGDEFARG(sigarg)
773{
774 /* this is not required on all systems, but it doesn't hurt anybody */
775 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
776 got_int = TRUE;
777 SIGRETURN;
778}
779#endif
780
781#if defined(SIGPWR)
782/* ARGSUSED */
783 static RETSIGTYPE
784catch_sigpwr SIGDEFARG(sigarg)
785{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000786 /* this is not required on all systems, but it doesn't hurt anybody */
787 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000788 /*
789 * I'm not sure we get the SIGPWR signal when the system is really going
790 * down or when the batteries are almost empty. Just preserve the swap
791 * files and don't exit, that can't do any harm.
792 */
793 ml_sync_all(FALSE, FALSE);
794 SIGRETURN;
795}
796#endif
797
798#ifdef SET_SIG_ALARM
799/*
800 * signal function for alarm().
801 */
802/* ARGSUSED */
803 static RETSIGTYPE
804sig_alarm SIGDEFARG(sigarg)
805{
806 /* doesn't do anything, just to break a system call */
807 sig_alarm_called = TRUE;
808 SIGRETURN;
809}
810#endif
811
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000812#if (defined(HAVE_SETJMP_H) \
813 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
814 || defined(FEAT_LIBCALL))) \
815 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816/*
817 * A simplistic version of setjmp() that only allows one level of using.
818 * Don't call twice before calling mch_endjmp()!.
819 * Usage:
820 * mch_startjmp();
821 * if (SETJMP(lc_jump_env) != 0)
822 * {
823 * mch_didjmp();
824 * EMSG("crash!");
825 * }
826 * else
827 * {
828 * do_the_work;
829 * mch_endjmp();
830 * }
831 * Note: Can't move SETJMP() here, because a function calling setjmp() must
832 * not return before the saved environment is used.
833 * Returns OK for normal return, FAIL when the protected code caused a
834 * problem and LONGJMP() was used.
835 */
836 void
837mch_startjmp()
838{
839#ifdef SIGHASARG
840 lc_signal = 0;
841#endif
842 lc_active = TRUE;
843}
844
845 void
846mch_endjmp()
847{
848 lc_active = FALSE;
849}
850
851 void
852mch_didjmp()
853{
854# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
855 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
856 * otherwise catching the signal only works once. */
857 init_signal_stack();
858# endif
859}
860#endif
861
862/*
863 * This function handles deadly signals.
864 * It tries to preserve any swap file and exit properly.
865 * (partly from Elvis).
866 */
867 static RETSIGTYPE
868deathtrap SIGDEFARG(sigarg)
869{
870 static int entered = 0; /* count the number of times we got here.
871 Note: when memory has been corrupted
872 this may get an arbitrary value! */
873#ifdef SIGHASARG
874 int i;
875#endif
876
877#if defined(HAVE_SETJMP_H)
878 /*
879 * Catch a crash in protected code.
880 * Restores the environment saved in lc_jump_env, which looks like
881 * SETJMP() returns 1.
882 */
883 if (lc_active)
884 {
885# if defined(SIGHASARG)
886 lc_signal = sigarg;
887# endif
888 lc_active = FALSE; /* don't jump again */
889 LONGJMP(lc_jump_env, 1);
890 /* NOTREACHED */
891 }
892#endif
893
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000894#ifdef SIGHASARG
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000895 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
896 * here. This avoids that a non-reentrant function is interrupted, e.g.,
897 * free(). Calling free() again may then cause a crash. */
898 if (entered == 0
899 && (0
900# ifdef SIGHUP
901 || sigarg == SIGHUP
902# endif
903# ifdef SIGQUIT
904 || sigarg == SIGQUIT
905# endif
906# ifdef SIGTERM
907 || sigarg == SIGTERM
908# endif
909# ifdef SIGPWR
910 || sigarg == SIGPWR
911# endif
912# ifdef SIGUSR1
913 || sigarg == SIGUSR1
914# endif
915# ifdef SIGUSR2
916 || sigarg == SIGUSR2
917# endif
918 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +0000919 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000920 SIGRETURN;
921#endif
922
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 /* Remember how often we have been called. */
924 ++entered;
925
926#ifdef FEAT_EVAL
927 /* Set the v:dying variable. */
928 set_vim_var_nr(VV_DYING, (long)entered);
929#endif
930
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000931#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932 /* Since we are now using the signal stack, need to reset the stack
933 * limit. Otherwise using a regexp will fail. */
934 get_stack_limit();
935#endif
936
937#ifdef SIGHASARG
938 /* try to find the name of this signal */
939 for (i = 0; signal_info[i].sig != -1; i++)
940 if (sigarg == signal_info[i].sig)
941 break;
942 deadly_signal = sigarg;
943#endif
944
945 full_screen = FALSE; /* don't write message to the GUI, it might be
946 * part of the problem... */
947 /*
948 * If something goes wrong after entering here, we may get here again.
949 * When this happens, give a message and try to exit nicely (resetting the
950 * terminal mode, etc.)
951 * When this happens twice, just exit, don't even try to give a message,
952 * stack may be corrupt or something weird.
953 * When this still happens again (or memory was corrupted in such a way
954 * that "entered" was clobbered) use _exit(), don't try freeing resources.
955 */
956 if (entered >= 3)
957 {
958 reset_signals(); /* don't catch any signals anymore */
959 may_core_dump();
960 if (entered >= 4)
961 _exit(8);
962 exit(7);
963 }
964 if (entered == 2)
965 {
966 OUT_STR(_("Vim: Double signal, exiting\n"));
967 out_flush();
968 getout(1);
969 }
970
971#ifdef SIGHASARG
972 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
973 signal_info[i].name);
974#else
975 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
976#endif
977 preserve_exit(); /* preserve files and exit */
978
Bram Moolenaar009b2592004-10-24 19:18:58 +0000979#ifdef NBDEBUG
980 reset_signals();
981 may_core_dump();
982 abort();
983#endif
984
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 SIGRETURN;
986}
987
988#ifdef _REENTRANT
989/*
990 * On Solaris with multi-threading, suspending might not work immediately.
991 * Catch the SIGCONT signal, which will be used as an indication whether the
992 * suspending has been done or not.
993 */
994static int sigcont_received;
995static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
996
997/*
998 * signal handler for SIGCONT
999 */
1000/* ARGSUSED */
1001 static RETSIGTYPE
1002sigcont_handler SIGDEFARG(sigarg)
1003{
1004 sigcont_received = TRUE;
1005 SIGRETURN;
1006}
1007#endif
1008
1009/*
1010 * If the machine has job control, use it to suspend the program,
1011 * otherwise fake it by starting a new shell.
1012 */
1013 void
1014mch_suspend()
1015{
1016 /* BeOS does have SIGTSTP, but it doesn't work. */
1017#if defined(SIGTSTP) && !defined(__BEOS__)
1018 out_flush(); /* needed to make cursor visible on some systems */
1019 settmode(TMODE_COOK);
1020 out_flush(); /* needed to disable mouse on some systems */
1021
1022# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1023 /* Since we are going to sleep, we can't respond to requests for the X
1024 * selections. Lose them, otherwise other applications will hang. But
1025 * first copy the text to cut buffer 0. */
1026 if (clip_star.owned || clip_plus.owned)
1027 {
1028 x11_export_final_selection();
1029 if (clip_star.owned)
1030 clip_lose_selection(&clip_star);
1031 if (clip_plus.owned)
1032 clip_lose_selection(&clip_plus);
1033 if (x11_display != NULL)
1034 XFlush(x11_display);
1035 }
1036# endif
1037
1038# ifdef _REENTRANT
1039 sigcont_received = FALSE;
1040# endif
1041 kill(0, SIGTSTP); /* send ourselves a STOP signal */
1042# ifdef _REENTRANT
1043 /* When we didn't suspend immediately in the kill(), do it now. Happens
1044 * on multi-threaded Solaris. */
1045 if (!sigcont_received)
1046 pause();
1047# endif
1048
1049# ifdef FEAT_TITLE
1050 /*
1051 * Set oldtitle to NULL, so the current title is obtained again.
1052 */
1053 vim_free(oldtitle);
1054 oldtitle = NULL;
1055# endif
1056 settmode(TMODE_RAW);
1057 need_check_timestamps = TRUE;
1058 did_check_timestamps = FALSE;
1059#else
1060 suspend_shell();
1061#endif
1062}
1063
1064 void
1065mch_init()
1066{
1067 Columns = 80;
1068 Rows = 24;
1069
1070 out_flush();
1071 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001072
1073#if defined(MACOS_X) && defined(FEAT_MBYTE)
1074 mac_conv_init();
1075#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076}
1077
1078 static void
1079set_signals()
1080{
1081#if defined(SIGWINCH)
1082 /*
1083 * WINDOW CHANGE signal is handled with sig_winch().
1084 */
1085 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1086#endif
1087
1088 /*
1089 * We want the STOP signal to work, to make mch_suspend() work.
1090 * For "rvim" the STOP signal is ignored.
1091 */
1092#ifdef SIGTSTP
1093 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1094#endif
1095#ifdef _REENTRANT
1096 signal(SIGCONT, sigcont_handler);
1097#endif
1098
1099 /*
1100 * We want to ignore breaking of PIPEs.
1101 */
1102#ifdef SIGPIPE
1103 signal(SIGPIPE, SIG_IGN);
1104#endif
1105
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001107 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108#endif
1109
1110 /*
1111 * Ignore alarm signals (Perl's alarm() generates it).
1112 */
1113#ifdef SIGALRM
1114 signal(SIGALRM, SIG_IGN);
1115#endif
1116
1117 /*
1118 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1119 * work will be lost.
1120 */
1121#ifdef SIGPWR
1122 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1123#endif
1124
1125 /*
1126 * Arrange for other signals to gracefully shutdown Vim.
1127 */
1128 catch_signals(deathtrap, SIG_ERR);
1129
1130#if defined(FEAT_GUI) && defined(SIGHUP)
1131 /*
1132 * When the GUI is running, ignore the hangup signal.
1133 */
1134 if (gui.in_use)
1135 signal(SIGHUP, SIG_IGN);
1136#endif
1137}
1138
Bram Moolenaardf177f62005-02-22 08:39:57 +00001139#if defined(SIGINT) || defined(PROTO)
1140/*
1141 * Catch CTRL-C (only works while in Cooked mode).
1142 */
1143 static void
1144catch_int_signal()
1145{
1146 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1147}
1148#endif
1149
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 void
1151reset_signals()
1152{
1153 catch_signals(SIG_DFL, SIG_DFL);
1154#ifdef _REENTRANT
1155 /* SIGCONT isn't in the list, because its default action is ignore */
1156 signal(SIGCONT, SIG_DFL);
1157#endif
1158}
1159
1160 static void
1161catch_signals(func_deadly, func_other)
1162 RETSIGTYPE (*func_deadly)();
1163 RETSIGTYPE (*func_other)();
1164{
1165 int i;
1166
1167 for (i = 0; signal_info[i].sig != -1; i++)
1168 if (signal_info[i].deadly)
1169 {
1170#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1171 struct sigaction sa;
1172
1173 /* Setup to use the alternate stack for the signal function. */
1174 sa.sa_handler = func_deadly;
1175 sigemptyset(&sa.sa_mask);
1176# if defined(__linux__) && defined(_REENTRANT)
1177 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1178 * thread handling in combination with using the alternate stack:
1179 * pthread library functions try to use the stack pointer to
1180 * identify the current thread, causing a SEGV signal, which
1181 * recursively calls deathtrap() and hangs. */
1182 sa.sa_flags = 0;
1183# else
1184 sa.sa_flags = SA_ONSTACK;
1185# endif
1186 sigaction(signal_info[i].sig, &sa, NULL);
1187#else
1188# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1189 struct sigvec sv;
1190
1191 /* Setup to use the alternate stack for the signal function. */
1192 sv.sv_handler = func_deadly;
1193 sv.sv_mask = 0;
1194 sv.sv_flags = SV_ONSTACK;
1195 sigvec(signal_info[i].sig, &sv, NULL);
1196# else
1197 signal(signal_info[i].sig, func_deadly);
1198# endif
1199#endif
1200 }
1201 else if (func_other != SIG_ERR)
1202 signal(signal_info[i].sig, func_other);
1203}
1204
1205/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001206 * Handling of SIGHUP, SIGQUIT and SIGTERM:
1207 * "when" == a signal: when busy, postpone, otherwise return TRUE
1208 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1209 * "when" == SIGNAL_UNBLOCK: Going wait, unblock signals
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001210 * Returns TRUE when Vim should exit.
1211 */
1212 int
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001213vim_handle_signal(sig)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001214 int sig;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001215{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001216 static int got_signal = 0;
1217 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001218
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001219 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001220 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001221 case SIGNAL_BLOCK: blocked = TRUE;
1222 break;
1223
1224 case SIGNAL_UNBLOCK: blocked = FALSE;
1225 if (got_signal != 0)
1226 {
1227 kill(getpid(), got_signal);
1228 got_signal = 0;
1229 }
1230 break;
1231
1232 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001233 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001234 got_signal = sig;
1235#ifdef SIGPWR
1236 if (sig != SIGPWR)
1237#endif
1238 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001239 break;
1240 }
1241 return FALSE;
1242}
1243
1244/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 * Check_win checks whether we have an interactive stdout.
1246 */
1247/* ARGSUSED */
1248 int
1249mch_check_win(argc, argv)
1250 int argc;
1251 char **argv;
1252{
1253#ifdef OS2
1254 /*
1255 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1256 * name, mostly it's just "vim" and found in the path, which is unusable.
1257 */
1258 if (mch_isFullName(argv[0]))
1259 exe_name = vim_strsave((char_u *)argv[0]);
1260#endif
1261 if (isatty(1))
1262 return OK;
1263 return FAIL;
1264}
1265
1266/*
1267 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1268 */
1269 int
1270mch_input_isatty()
1271{
1272 if (isatty(read_cmd_fd))
1273 return TRUE;
1274 return FALSE;
1275}
1276
1277#ifdef FEAT_X11
1278
1279# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1280 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1281
1282static void xopen_message __ARGS((struct timeval *tvp));
1283
1284/*
1285 * Give a message about the elapsed time for opening the X window.
1286 */
1287 static void
1288xopen_message(tvp)
1289 struct timeval *tvp; /* must contain start time */
1290{
1291 struct timeval end_tv;
1292
1293 /* Compute elapsed time. */
1294 gettimeofday(&end_tv, NULL);
1295 smsg((char_u *)_("Opening the X display took %ld msec"),
1296 (end_tv.tv_sec - tvp->tv_sec) * 1000L
Bram Moolenaar051b7822005-05-19 21:00:46 +00001297 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298}
1299# endif
1300#endif
1301
1302#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1303/*
1304 * A few functions shared by X11 title and clipboard code.
1305 */
1306static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1307static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1308static int x_connect_to_server __ARGS((void));
1309static int test_x11_window __ARGS((Display *dpy));
1310
1311static int got_x_error = FALSE;
1312
1313/*
1314 * X Error handler, otherwise X just exits! (very rude) -- webb
1315 */
1316 static int
1317x_error_handler(dpy, error_event)
1318 Display *dpy;
1319 XErrorEvent *error_event;
1320{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001321 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar81695252004-12-29 20:58:21 +00001322#if defined(FEAT_GUI_KDE)
1323 /* KDE sometimes produces X error that we want to ignore */
1324 STRCAT(IObuff, _("\nVim: Got X error but we continue...\n"));
1325 mch_errmsg((char *)IObuff);
Bram Moolenaar843ee412004-06-30 16:16:41 +00001326 return 0;
1327#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 STRCAT(IObuff, _("\nVim: Got X error\n"));
1329
1330 /* We cannot print a message and continue, because no X calls are allowed
1331 * here (causes my system to hang). Silently continuing might be an
1332 * alternative... */
1333 preserve_exit(); /* preserve files and exit */
1334
1335 return 0; /* NOTREACHED */
Bram Moolenaar843ee412004-06-30 16:16:41 +00001336#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337}
1338
1339/*
1340 * Another X Error handler, just used to check for errors.
1341 */
1342/* ARGSUSED */
1343 static int
1344x_error_check(dpy, error_event)
1345 Display *dpy;
1346 XErrorEvent *error_event;
1347{
1348 got_x_error = TRUE;
1349 return 0;
1350}
1351
1352#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1353# if defined(HAVE_SETJMP_H)
1354/*
1355 * An X IO Error handler, used to catch error while opening the display.
1356 */
1357static int x_IOerror_check __ARGS((Display *dpy));
1358
1359/* ARGSUSED */
1360 static int
1361x_IOerror_check(dpy)
1362 Display *dpy;
1363{
1364 /* This function should not return, it causes exit(). Longjump instead. */
1365 LONGJMP(lc_jump_env, 1);
1366 /*NOTREACHED*/
1367 return 0;
1368}
1369# endif
1370
1371/*
1372 * An X IO Error handler, used to catch terminal errors.
1373 */
1374static int x_IOerror_handler __ARGS((Display *dpy));
1375
1376/* ARGSUSED */
1377 static int
1378x_IOerror_handler(dpy)
1379 Display *dpy;
1380{
1381 xterm_dpy = NULL;
1382 x11_window = 0;
1383 x11_display = NULL;
1384 xterm_Shell = (Widget)0;
1385
1386 /* This function should not return, it causes exit(). Longjump instead. */
1387 LONGJMP(x_jump_env, 1);
1388 /*NOTREACHED*/
1389 return 0;
1390}
1391#endif
1392
1393/*
1394 * Return TRUE when connection to the X server is desired.
1395 */
1396 static int
1397x_connect_to_server()
1398{
1399 regmatch_T regmatch;
1400
1401#if defined(FEAT_CLIENTSERVER)
1402 if (x_force_connect)
1403 return TRUE;
1404#endif
1405 if (x_no_connect)
1406 return FALSE;
1407
1408 /* Check for a match with "exclude:" from 'clipboard'. */
1409 if (clip_exclude_prog != NULL)
1410 {
1411 regmatch.rm_ic = FALSE; /* Don't ignore case */
1412 regmatch.regprog = clip_exclude_prog;
1413 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1414 return FALSE;
1415 }
1416 return TRUE;
1417}
1418
1419/*
1420 * Test if "dpy" and x11_window are valid by getting the window title.
1421 * I don't actually want it yet, so there may be a simpler call to use, but
1422 * this will cause the error handler x_error_check() to be called if anything
1423 * is wrong, such as the window pointer being invalid (as can happen when the
1424 * user changes his DISPLAY, but not his WINDOWID) -- webb
1425 */
1426 static int
1427test_x11_window(dpy)
1428 Display *dpy;
1429{
1430 int (*old_handler)();
1431 XTextProperty text_prop;
1432
1433 old_handler = XSetErrorHandler(x_error_check);
1434 got_x_error = FALSE;
1435 if (XGetWMName(dpy, x11_window, &text_prop))
1436 XFree((void *)text_prop.value);
1437 XSync(dpy, False);
1438 (void)XSetErrorHandler(old_handler);
1439
1440 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001441 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442
1443 return (got_x_error ? FAIL : OK);
1444}
1445#endif
1446
1447#ifdef FEAT_TITLE
1448
1449#ifdef FEAT_X11
1450
1451static int get_x11_thing __ARGS((int get_title, int test_only));
1452
1453/*
1454 * try to get x11 window and display
1455 *
1456 * return FAIL for failure, OK otherwise
1457 */
1458 static int
1459get_x11_windis()
1460{
1461 char *winid;
1462 static int result = -1;
1463#define XD_NONE 0 /* x11_display not set here */
1464#define XD_HERE 1 /* x11_display opened here */
1465#define XD_GUI 2 /* x11_display used from gui.dpy */
1466#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1467 static int x11_display_from = XD_NONE;
1468 static int did_set_error_handler = FALSE;
1469
1470 if (!did_set_error_handler)
1471 {
1472 /* X just exits if it finds an error otherwise! */
1473 (void)XSetErrorHandler(x_error_handler);
1474 did_set_error_handler = TRUE;
1475 }
1476
Bram Moolenaar843ee412004-06-30 16:16:41 +00001477#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001478 if (gui.in_use)
1479 {
1480 /*
1481 * If the X11 display was opened here before, for the window where Vim
1482 * was started, close that one now to avoid a memory leak.
1483 */
1484 if (x11_display_from == XD_HERE && x11_display != NULL)
1485 {
1486 XCloseDisplay(x11_display);
1487 x11_display_from = XD_NONE;
1488 }
1489 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1490 {
1491 x11_display_from = XD_GUI;
1492 return OK;
1493 }
1494 x11_display = NULL;
1495 return FAIL;
1496 }
1497 else if (x11_display_from == XD_GUI)
1498 {
1499 /* GUI must have stopped somehow, clear x11_display */
1500 x11_window = 0;
1501 x11_display = NULL;
1502 x11_display_from = XD_NONE;
1503 }
1504#endif
1505
1506 /* When started with the "-X" argument, don't try connecting. */
1507 if (!x_connect_to_server())
1508 return FAIL;
1509
1510 /*
1511 * If WINDOWID not set, should try another method to find out
1512 * what the current window number is. The only code I know for
1513 * this is very complicated.
1514 * We assume that zero is invalid for WINDOWID.
1515 */
1516 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1517 x11_window = (Window)atol(winid);
1518
1519#ifdef FEAT_XCLIPBOARD
1520 if (xterm_dpy != NULL && x11_window != 0)
1521 {
1522 /* Checked it already. */
1523 if (x11_display_from == XD_XTERM)
1524 return OK;
1525
1526 /*
1527 * If the X11 display was opened here before, for the window where Vim
1528 * was started, close that one now to avoid a memory leak.
1529 */
1530 if (x11_display_from == XD_HERE && x11_display != NULL)
1531 XCloseDisplay(x11_display);
1532 x11_display = xterm_dpy;
1533 x11_display_from = XD_XTERM;
1534 if (test_x11_window(x11_display) == FAIL)
1535 {
1536 /* probably bad $WINDOWID */
1537 x11_window = 0;
1538 x11_display = NULL;
1539 x11_display_from = XD_NONE;
1540 return FAIL;
1541 }
1542 return OK;
1543 }
1544#endif
1545
1546 if (x11_window == 0 || x11_display == NULL)
1547 result = -1;
1548
1549 if (result != -1) /* Have already been here and set this */
1550 return result; /* Don't do all these X calls again */
1551
1552 if (x11_window != 0 && x11_display == NULL)
1553 {
1554#ifdef SET_SIG_ALARM
1555 RETSIGTYPE (*sig_save)();
1556#endif
1557#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1558 struct timeval start_tv;
1559
1560 if (p_verbose > 0)
1561 gettimeofday(&start_tv, NULL);
1562#endif
1563
1564#ifdef SET_SIG_ALARM
1565 /*
1566 * Opening the Display may hang if the DISPLAY setting is wrong, or
1567 * the network connection is bad. Set an alarm timer to get out.
1568 */
1569 sig_alarm_called = FALSE;
1570 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1571 (RETSIGTYPE (*)())sig_alarm);
1572 alarm(2);
1573#endif
1574 x11_display = XOpenDisplay(NULL);
1575
1576#ifdef SET_SIG_ALARM
1577 alarm(0);
1578 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1579 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001580 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581#endif
1582 if (x11_display != NULL)
1583 {
1584# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1585 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001586 {
1587 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001589 verbose_leave();
1590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591# endif
1592 if (test_x11_window(x11_display) == FAIL)
1593 {
1594 /* Maybe window id is bad */
1595 x11_window = 0;
1596 XCloseDisplay(x11_display);
1597 x11_display = NULL;
1598 }
1599 else
1600 x11_display_from = XD_HERE;
1601 }
1602 }
1603 if (x11_window == 0 || x11_display == NULL)
1604 return (result = FAIL);
1605 return (result = OK);
1606}
1607
1608/*
1609 * Determine original x11 Window Title
1610 */
1611 static int
1612get_x11_title(test_only)
1613 int test_only;
1614{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001615 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616}
1617
1618/*
1619 * Determine original x11 Window icon
1620 */
1621 static int
1622get_x11_icon(test_only)
1623 int test_only;
1624{
1625 int retval = FALSE;
1626
1627 retval = get_x11_thing(FALSE, test_only);
1628
1629 /* could not get old icon, use terminal name */
1630 if (oldicon == NULL && !test_only)
1631 {
1632 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1633 oldicon = T_NAME + 8;
1634 else
1635 oldicon = T_NAME;
1636 }
1637
1638 return retval;
1639}
1640
1641 static int
1642get_x11_thing(get_title, test_only)
1643 int get_title; /* get title string */
1644 int test_only;
1645{
1646 XTextProperty text_prop;
1647 int retval = FALSE;
1648 Status status;
1649
1650 if (get_x11_windis() == OK)
1651 {
1652 /* Get window/icon name if any */
1653 if (get_title)
1654 status = XGetWMName(x11_display, x11_window, &text_prop);
1655 else
1656 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1657
1658 /*
1659 * If terminal is xterm, then x11_window may be a child window of the
1660 * outer xterm window that actually contains the window/icon name, so
1661 * keep traversing up the tree until a window with a title/icon is
1662 * found.
1663 */
1664 /* Previously this was only done for xterm and alikes. I don't see a
1665 * reason why it would fail for other terminal emulators.
1666 * if (term_is_xterm) */
1667 {
1668 Window root;
1669 Window parent;
1670 Window win = x11_window;
1671 Window *children;
1672 unsigned int num_children;
1673
1674 while (!status || text_prop.value == NULL)
1675 {
1676 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1677 &num_children))
1678 break;
1679 if (children)
1680 XFree((void *)children);
1681 if (parent == root || parent == 0)
1682 break;
1683
1684 win = parent;
1685 if (get_title)
1686 status = XGetWMName(x11_display, win, &text_prop);
1687 else
1688 status = XGetWMIconName(x11_display, win, &text_prop);
1689 }
1690 }
1691 if (status && text_prop.value != NULL)
1692 {
1693 retval = TRUE;
1694 if (!test_only)
1695 {
1696#ifdef FEAT_XFONTSET
1697 if (text_prop.encoding == XA_STRING)
1698 {
1699#endif
1700 if (get_title)
1701 oldtitle = vim_strsave((char_u *)text_prop.value);
1702 else
1703 oldicon = vim_strsave((char_u *)text_prop.value);
1704#ifdef FEAT_XFONTSET
1705 }
1706 else
1707 {
1708 char **cl;
1709 Status transform_status;
1710 int n = 0;
1711
1712 transform_status = XmbTextPropertyToTextList(x11_display,
1713 &text_prop,
1714 &cl, &n);
1715 if (transform_status >= Success && n > 0 && cl[0])
1716 {
1717 if (get_title)
1718 oldtitle = vim_strsave((char_u *) cl[0]);
1719 else
1720 oldicon = vim_strsave((char_u *) cl[0]);
1721 XFreeStringList(cl);
1722 }
1723 else
1724 {
1725 if (get_title)
1726 oldtitle = vim_strsave((char_u *)text_prop.value);
1727 else
1728 oldicon = vim_strsave((char_u *)text_prop.value);
1729 }
1730 }
1731#endif
1732 }
1733 XFree((void *)text_prop.value);
1734 }
1735 }
1736 return retval;
1737}
1738
1739/* Are Xutf8 functions available? Avoid error from old compilers. */
1740#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1741# if X_HAVE_UTF8_STRING
1742# define USE_UTF8_STRING
1743# endif
1744#endif
1745
1746/*
1747 * Set x11 Window Title
1748 *
1749 * get_x11_windis() must be called before this and have returned OK
1750 */
1751 static void
1752set_x11_title(title)
1753 char_u *title;
1754{
1755 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1756 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1757 * supported everywhere and STRING doesn't work for multi-byte titles.
1758 */
1759#ifdef USE_UTF8_STRING
1760 if (enc_utf8)
1761 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1762 NULL, NULL, 0, NULL, NULL, NULL);
1763 else
1764#endif
1765 {
1766#if XtSpecificationRelease >= 4
1767# ifdef FEAT_XFONTSET
1768 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1769 NULL, NULL, 0, NULL, NULL, NULL);
1770# else
1771 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001772 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773
1774 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001775 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 XSetWMProperties(x11_display, x11_window, &text_prop,
1777 NULL, NULL, 0, NULL, NULL, NULL);
1778# endif
1779#else
1780 XStoreName(x11_display, x11_window, (char *)title);
1781#endif
1782 }
1783 XFlush(x11_display);
1784}
1785
1786/*
1787 * Set x11 Window icon
1788 *
1789 * get_x11_windis() must be called before this and have returned OK
1790 */
1791 static void
1792set_x11_icon(icon)
1793 char_u *icon;
1794{
1795 /* See above for comments about using X*SetWMProperties(). */
1796#ifdef USE_UTF8_STRING
1797 if (enc_utf8)
1798 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1799 NULL, 0, NULL, NULL, NULL);
1800 else
1801#endif
1802 {
1803#if XtSpecificationRelease >= 4
1804# ifdef FEAT_XFONTSET
1805 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1806 NULL, 0, NULL, NULL, NULL);
1807# else
1808 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001809 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810
Bram Moolenaar9d75c832005-01-25 21:57:23 +00001811 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1813 NULL, 0, NULL, NULL, NULL);
1814# endif
1815#else
1816 XSetIconName(x11_display, x11_window, (char *)icon);
1817#endif
1818 }
1819 XFlush(x11_display);
1820}
1821
1822#else /* FEAT_X11 */
1823
1824/*ARGSUSED*/
1825 static int
1826get_x11_title(test_only)
1827 int test_only;
1828{
1829 return FALSE;
1830}
1831
1832 static int
1833get_x11_icon(test_only)
1834 int test_only;
1835{
1836 if (!test_only)
1837 {
1838 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1839 oldicon = T_NAME + 8;
1840 else
1841 oldicon = T_NAME;
1842 }
1843 return FALSE;
1844}
1845
1846#endif /* FEAT_X11 */
1847
1848 int
1849mch_can_restore_title()
1850{
1851 return get_x11_title(TRUE);
1852}
1853
1854 int
1855mch_can_restore_icon()
1856{
1857 return get_x11_icon(TRUE);
1858}
1859
1860/*
1861 * Set the window title and icon.
1862 */
1863 void
1864mch_settitle(title, icon)
1865 char_u *title;
1866 char_u *icon;
1867{
1868 int type = 0;
1869 static int recursive = 0;
1870
1871 if (T_NAME == NULL) /* no terminal name (yet) */
1872 return;
1873 if (title == NULL && icon == NULL) /* nothing to do */
1874 return;
1875
1876 /* When one of the X11 functions causes a deadly signal, we get here again
1877 * recursively. Avoid hanging then (something is probably locked). */
1878 if (recursive)
1879 return;
1880 ++recursive;
1881
1882 /*
1883 * if the window ID and the display is known, we may use X11 calls
1884 */
1885#ifdef FEAT_X11
1886 if (get_x11_windis() == OK)
1887 type = 1;
1888#else
1889# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
1890 if (gui.in_use)
1891 type = 1;
1892# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893#endif
1894
1895 /*
1896 * Note: if "t_TS" is set, title is set with escape sequence rather
1897 * than x11 calls, because the x11 calls don't always work
1898 */
Bram Moolenaar843ee412004-06-30 16:16:41 +00001899#ifdef FEAT_GUI_KDE
Bram Moolenaar47136d72004-10-12 20:02:24 +00001900 /* dont know why but KDE needs this one as we don't go through the next
1901 * function... */
Bram Moolenaar843ee412004-06-30 16:16:41 +00001902 gui_mch_settitle(title, icon);
1903#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 if ((type || *T_TS != NUL) && title != NULL)
1905 {
1906 if (oldtitle == NULL
1907#ifdef FEAT_GUI
1908 && !gui.in_use
1909#endif
1910 ) /* first call but not in GUI, save title */
1911 (void)get_x11_title(FALSE);
1912
1913 if (*T_TS != NUL) /* it's OK if t_fs is empty */
1914 term_settitle(title);
1915#ifdef FEAT_X11
1916 else
1917# ifdef FEAT_GUI_GTK
1918 if (!gui.in_use) /* don't do this if GTK+ is running */
1919# endif
1920 set_x11_title(title); /* x11 */
1921#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00001922#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
1924 else
1925 gui_mch_settitle(title, icon);
1926#endif
1927 did_set_title = TRUE;
1928 }
1929
1930 if ((type || *T_CIS != NUL) && icon != NULL)
1931 {
1932 if (oldicon == NULL
1933#ifdef FEAT_GUI
1934 && !gui.in_use
1935#endif
1936 ) /* first call, save icon */
1937 get_x11_icon(FALSE);
1938
1939 if (*T_CIS != NUL)
1940 {
1941 out_str(T_CIS); /* set icon start */
1942 out_str_nf(icon);
1943 out_str(T_CIE); /* set icon end */
1944 out_flush();
1945 }
1946#ifdef FEAT_X11
1947 else
1948# ifdef FEAT_GUI_GTK
1949 if (!gui.in_use) /* don't do this if GTK+ is running */
1950# endif
1951 set_x11_icon(icon); /* x11 */
1952#endif
1953 did_set_icon = TRUE;
1954 }
1955 --recursive;
1956}
1957
1958/*
1959 * Restore the window/icon title.
1960 * "which" is one of:
1961 * 1 only restore title
1962 * 2 only restore icon
1963 * 3 restore title and icon
1964 */
1965 void
1966mch_restore_title(which)
1967 int which;
1968{
1969 /* only restore the title or icon when it has been set */
1970 mch_settitle(((which & 1) && did_set_title) ?
1971 (oldtitle ? oldtitle : p_titleold) : NULL,
1972 ((which & 2) && did_set_icon) ? oldicon : NULL);
1973}
1974
1975#endif /* FEAT_TITLE */
1976
1977/*
1978 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001979 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 */
1981 int
1982vim_is_xterm(name)
1983 char_u *name;
1984{
1985 if (name == NULL)
1986 return FALSE;
1987 return (STRNICMP(name, "xterm", 5) == 0
1988 || STRNICMP(name, "nxterm", 6) == 0
1989 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001990 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 || STRNICMP(name, "rxvt", 4) == 0
1992 || STRCMP(name, "builtin_xterm") == 0);
1993}
1994
1995#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
1996/*
1997 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
1998 * Return 1 for "xterm".
1999 * Return 2 for "xterm2".
2000 */
2001 int
2002use_xterm_mouse()
2003{
2004 if (ttym_flags == TTYM_XTERM2)
2005 return 2;
2006 if (ttym_flags == TTYM_XTERM)
2007 return 1;
2008 return 0;
2009}
2010#endif
2011
2012 int
2013vim_is_iris(name)
2014 char_u *name;
2015{
2016 if (name == NULL)
2017 return FALSE;
2018 return (STRNICMP(name, "iris-ansi", 9) == 0
2019 || STRCMP(name, "builtin_iris-ansi") == 0);
2020}
2021
2022 int
2023vim_is_vt300(name)
2024 char_u *name;
2025{
2026 if (name == NULL)
2027 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002028 /* catch VT100 - VT5xx */
2029 return ((STRNICMP(name, "vt", 2) == 0
2030 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 || STRCMP(name, "builtin_vt320") == 0);
2032}
2033
2034/*
2035 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2036 * This should include all windowed terminal emulators.
2037 */
2038 int
2039vim_is_fastterm(name)
2040 char_u *name;
2041{
2042 if (name == NULL)
2043 return FALSE;
2044 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2045 return TRUE;
2046 return ( STRNICMP(name, "hpterm", 6) == 0
2047 || STRNICMP(name, "sun-cmd", 7) == 0
2048 || STRNICMP(name, "screen", 6) == 0
2049 || STRNICMP(name, "dtterm", 6) == 0);
2050}
2051
2052/*
2053 * Insert user name in s[len].
2054 * Return OK if a name found.
2055 */
2056 int
2057mch_get_user_name(s, len)
2058 char_u *s;
2059 int len;
2060{
2061#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002062 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 return OK;
2064#else
2065 return mch_get_uname(getuid(), s, len);
2066#endif
2067}
2068
2069/*
2070 * Insert user name for "uid" in s[len].
2071 * Return OK if a name found.
2072 */
2073 int
2074mch_get_uname(uid, s, len)
2075 uid_t uid;
2076 char_u *s;
2077 int len;
2078{
2079#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2080 struct passwd *pw;
2081
2082 if ((pw = getpwuid(uid)) != NULL
2083 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2084 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002085 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 return OK;
2087 }
2088#endif
2089 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2090 return FAIL; /* a number is not a name */
2091}
2092
2093/*
2094 * Insert host name is s[len].
2095 */
2096
2097#ifdef HAVE_SYS_UTSNAME_H
2098 void
2099mch_get_host_name(s, len)
2100 char_u *s;
2101 int len;
2102{
2103 struct utsname vutsname;
2104
2105 if (uname(&vutsname) < 0)
2106 *s = NUL;
2107 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002108 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109}
2110#else /* HAVE_SYS_UTSNAME_H */
2111
2112# ifdef HAVE_SYS_SYSTEMINFO_H
2113# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2114# endif
2115
2116 void
2117mch_get_host_name(s, len)
2118 char_u *s;
2119 int len;
2120{
2121# ifdef VAXC
2122 vaxc$gethostname((char *)s, len);
2123# else
2124 gethostname((char *)s, len);
2125# endif
2126 s[len - 1] = NUL; /* make sure it's terminated */
2127}
2128#endif /* HAVE_SYS_UTSNAME_H */
2129
2130/*
2131 * return process ID
2132 */
2133 long
2134mch_get_pid()
2135{
2136 return (long)getpid();
2137}
2138
2139#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2140static char *strerror __ARGS((int));
2141
2142 static char *
2143strerror(err)
2144 int err;
2145{
2146 extern int sys_nerr;
2147 extern char *sys_errlist[];
2148 static char er[20];
2149
2150 if (err > 0 && err < sys_nerr)
2151 return (sys_errlist[err]);
2152 sprintf(er, "Error %d", err);
2153 return er;
2154}
2155#endif
2156
2157/*
2158 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2159 * Return OK for success, FAIL for failure.
2160 */
2161 int
2162mch_dirname(buf, len)
2163 char_u *buf;
2164 int len;
2165{
2166#if defined(USE_GETCWD)
2167 if (getcwd((char *)buf, len) == NULL)
2168 {
2169 STRCPY(buf, strerror(errno));
2170 return FAIL;
2171 }
2172 return OK;
2173#else
2174 return (getwd((char *)buf) != NULL ? OK : FAIL);
2175#endif
2176}
2177
2178#if defined(OS2) || defined(PROTO)
2179/*
2180 * Replace all slashes by backslashes.
2181 * When 'shellslash' set do it the other way around.
2182 */
2183 void
2184slash_adjust(p)
2185 char_u *p;
2186{
2187 while (*p)
2188 {
2189 if (*p == psepcN)
2190 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002191 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 }
2193}
2194#endif
2195
2196/*
2197 * Get absolute file name into buffer 'buf' of length 'len' bytes.
2198 *
2199 * return FAIL for failure, OK for success
2200 */
2201 int
2202mch_FullName(fname, buf, len, force)
2203 char_u *fname, *buf;
2204 int len;
2205 int force; /* also expand when already absolute path */
2206{
2207 int l;
2208#ifdef OS2
2209 int only_drive; /* file name is only a drive letter */
2210#endif
2211#ifdef HAVE_FCHDIR
2212 int fd = -1;
2213 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
2214#endif
2215 char_u olddir[MAXPATHL];
2216 char_u *p;
2217 int retval = OK;
2218
2219#ifdef VMS
2220 fname = vms_fixfilename(fname);
2221#endif
2222
2223 /* expand it if forced or not an absolute path */
2224 if (force || !mch_isFullName(fname))
2225 {
2226 /*
2227 * If the file name has a path, change to that directory for a moment,
2228 * and then do the getwd() (and get back to where we were).
2229 * This will get the correct path name with "../" things.
2230 */
2231#ifdef OS2
2232 only_drive = 0;
2233 if (((p = vim_strrchr(fname, '/')) != NULL)
2234 || ((p = vim_strrchr(fname, '\\')) != NULL)
2235 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
2236#else
2237 if ((p = vim_strrchr(fname, '/')) != NULL)
2238#endif
2239 {
2240#ifdef HAVE_FCHDIR
2241 /*
2242 * Use fchdir() if possible, it's said to be faster and more
2243 * reliable. But on SunOS 4 it might not work. Check this by
2244 * doing a fchdir() right now.
2245 */
2246 if (!dont_fchdir)
2247 {
2248 fd = open(".", O_RDONLY | O_EXTRA, 0);
2249 if (fd >= 0 && fchdir(fd) < 0)
2250 {
2251 close(fd);
2252 fd = -1;
2253 dont_fchdir = TRUE; /* don't try again */
2254 }
2255 }
2256#endif
2257
2258 /* Only change directory when we are sure we can return to where
2259 * we are now. After doing "su" chdir(".") might not work. */
2260 if (
2261#ifdef HAVE_FCHDIR
2262 fd < 0 &&
2263#endif
2264 (mch_dirname(olddir, MAXPATHL) == FAIL
2265 || mch_chdir((char *)olddir) != 0))
2266 {
2267 p = NULL; /* can't get current dir: don't chdir */
2268 retval = FAIL;
2269 }
2270 else
2271 {
2272#ifdef OS2
2273 /*
2274 * compensate for case where ':' from "D:" was the only
2275 * path separator detected in the file name; the _next_
2276 * character has to be removed, and then restored later.
2277 */
2278 if (only_drive)
2279 p++;
2280#endif
2281 /* The directory is copied into buf[], to be able to remove
2282 * the file name without changing it (could be a string in
2283 * read-only memory) */
2284 if (p - fname >= len)
2285 retval = FAIL;
2286 else
2287 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002288 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 if (mch_chdir((char *)buf))
2290 retval = FAIL;
2291 else
2292 fname = p + 1;
2293 *buf = NUL;
2294 }
2295#ifdef OS2
2296 if (only_drive)
2297 {
2298 p--;
2299 if (retval != FAIL)
2300 fname--;
2301 }
2302#endif
2303 }
2304 }
2305 if (mch_dirname(buf, len) == FAIL)
2306 {
2307 retval = FAIL;
2308 *buf = NUL;
2309 }
2310 if (p != NULL)
2311 {
2312#ifdef HAVE_FCHDIR
2313 if (fd >= 0)
2314 {
2315 l = fchdir(fd);
2316 close(fd);
2317 }
2318 else
2319#endif
2320 l = mch_chdir((char *)olddir);
2321 if (l != 0)
2322 EMSG(_(e_prev_dir));
2323 }
2324
2325 l = STRLEN(buf);
2326 if (l >= len)
2327 retval = FAIL;
2328#ifndef VMS
2329 else
2330 {
2331 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2332 && STRCMP(fname, ".") != 0)
2333 STRCAT(buf, "/");
2334 }
2335#endif
2336 }
2337 /* Catch file names which are too long. */
2338 if (retval == FAIL || STRLEN(buf) + STRLEN(fname) >= len)
2339 return FAIL;
2340
2341 /* Do not append ".", "/dir/." is equal to "/dir". */
2342 if (STRCMP(fname, ".") != 0)
2343 STRCAT(buf, fname);
2344
2345 return OK;
2346}
2347
2348/*
2349 * Return TRUE if "fname" does not depend on the current directory.
2350 */
2351 int
2352mch_isFullName(fname)
2353 char_u *fname;
2354{
2355#ifdef __EMX__
2356 return _fnisabs(fname);
2357#else
2358# ifdef VMS
2359 return ( fname[0] == '/' || fname[0] == '.' ||
2360 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2361 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2362 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2363# else
2364 return (*fname == '/' || *fname == '~');
2365# endif
2366#endif
2367}
2368
2369/*
2370 * Get file permissions for 'name'.
2371 * Returns -1 when it doesn't exist.
2372 */
2373 long
2374mch_getperm(name)
2375 char_u *name;
2376{
2377 struct stat statb;
2378
2379 /* Keep the #ifdef outside of stat(), it may be a macro. */
2380#ifdef VMS
2381 if (stat((char *)vms_fixfilename(name), &statb))
2382#else
2383 if (stat((char *)name, &statb))
2384#endif
2385 return -1;
2386 return statb.st_mode;
2387}
2388
2389/*
2390 * set file permission for 'name' to 'perm'
2391 *
2392 * return FAIL for failure, OK otherwise
2393 */
2394 int
2395mch_setperm(name, perm)
2396 char_u *name;
2397 long perm;
2398{
2399 return (chmod((char *)
2400#ifdef VMS
2401 vms_fixfilename(name),
2402#else
2403 name,
2404#endif
2405 (mode_t)perm) == 0 ? OK : FAIL);
2406}
2407
2408#if defined(HAVE_ACL) || defined(PROTO)
2409# ifdef HAVE_SYS_ACL_H
2410# include <sys/acl.h>
2411# endif
2412# ifdef HAVE_SYS_ACCESS_H
2413# include <sys/access.h>
2414# endif
2415
2416# ifdef HAVE_SOLARIS_ACL
2417typedef struct vim_acl_solaris_T {
2418 int acl_cnt;
2419 aclent_t *acl_entry;
2420} vim_acl_solaris_T;
2421# endif
2422
2423/*
2424 * Return a pointer to the ACL of file "fname" in allocated memory.
2425 * Return NULL if the ACL is not available for whatever reason.
2426 */
2427 vim_acl_T
2428mch_get_acl(fname)
2429 char_u *fname;
2430{
2431 vim_acl_T ret = NULL;
2432#ifdef HAVE_POSIX_ACL
2433 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2434#else
2435#ifdef HAVE_SOLARIS_ACL
2436 vim_acl_solaris_T *aclent;
2437
2438 aclent = malloc(sizeof(vim_acl_solaris_T));
2439 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2440 {
2441 free(aclent);
2442 return NULL;
2443 }
2444 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2445 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2446 {
2447 free(aclent->acl_entry);
2448 free(aclent);
2449 return NULL;
2450 }
2451 ret = (vim_acl_T)aclent;
2452#else
2453#if defined(HAVE_AIX_ACL)
2454 int aclsize;
2455 struct acl *aclent;
2456
2457 aclsize = sizeof(struct acl);
2458 aclent = malloc(aclsize);
2459 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2460 {
2461 if (errno == ENOSPC)
2462 {
2463 aclsize = aclent->acl_len;
2464 aclent = realloc(aclent, aclsize);
2465 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2466 {
2467 free(aclent);
2468 return NULL;
2469 }
2470 }
2471 else
2472 {
2473 free(aclent);
2474 return NULL;
2475 }
2476 }
2477 ret = (vim_acl_T)aclent;
2478#endif /* HAVE_AIX_ACL */
2479#endif /* HAVE_SOLARIS_ACL */
2480#endif /* HAVE_POSIX_ACL */
2481 return ret;
2482}
2483
2484/*
2485 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2486 */
2487 void
2488mch_set_acl(fname, aclent)
2489 char_u *fname;
2490 vim_acl_T aclent;
2491{
2492 if (aclent == NULL)
2493 return;
2494#ifdef HAVE_POSIX_ACL
2495 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2496#else
2497#ifdef HAVE_SOLARIS_ACL
2498 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2499 ((vim_acl_solaris_T *)aclent)->acl_entry);
2500#else
2501#ifdef HAVE_AIX_ACL
2502 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2503#endif /* HAVE_AIX_ACL */
2504#endif /* HAVE_SOLARIS_ACL */
2505#endif /* HAVE_POSIX_ACL */
2506}
2507
2508 void
2509mch_free_acl(aclent)
2510 vim_acl_T aclent;
2511{
2512 if (aclent == NULL)
2513 return;
2514#ifdef HAVE_POSIX_ACL
2515 acl_free((acl_t)aclent);
2516#else
2517#ifdef HAVE_SOLARIS_ACL
2518 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2519 free(aclent);
2520#else
2521#ifdef HAVE_AIX_ACL
2522 free(aclent);
2523#endif /* HAVE_AIX_ACL */
2524#endif /* HAVE_SOLARIS_ACL */
2525#endif /* HAVE_POSIX_ACL */
2526}
2527#endif
2528
2529/*
2530 * Set hidden flag for "name".
2531 */
2532/* ARGSUSED */
2533 void
2534mch_hide(name)
2535 char_u *name;
2536{
2537 /* can't hide a file */
2538}
2539
2540/*
2541 * return TRUE if "name" is a directory
2542 * return FALSE if "name" is not a directory
2543 * return FALSE for error
2544 */
2545 int
2546mch_isdir(name)
2547 char_u *name;
2548{
2549 struct stat statb;
2550
2551 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2552 return FALSE;
2553 if (stat((char *)name, &statb))
2554 return FALSE;
2555#ifdef _POSIX_SOURCE
2556 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2557#else
2558 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2559#endif
2560}
2561
2562#if defined(FEAT_EVAL) || defined(PROTO)
2563
2564static int executable_file __ARGS((char_u *name));
2565
2566/*
2567 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2568 */
2569 static int
2570executable_file(name)
2571 char_u *name;
2572{
2573 struct stat st;
2574
2575 if (stat((char *)name, &st))
2576 return 0;
2577 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2578}
2579
2580/*
2581 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2582 * Return -1 if unknown.
2583 */
2584 int
2585mch_can_exe(name)
2586 char_u *name;
2587{
2588 char_u *buf;
2589 char_u *p, *e;
2590 int retval;
2591
2592 /* If it's an absolute or relative path don't need to use $PATH. */
2593 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2594 || (name[1] == '.' && name[2] == '/'))))
2595 return executable_file(name);
2596
2597 p = (char_u *)getenv("PATH");
2598 if (p == NULL || *p == NUL)
2599 return -1;
2600 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2601 if (buf == NULL)
2602 return -1;
2603
2604 /*
2605 * Walk through all entries in $PATH to check if "name" exists there and
2606 * is an executable file.
2607 */
2608 for (;;)
2609 {
2610 e = (char_u *)strchr((char *)p, ':');
2611 if (e == NULL)
2612 e = p + STRLEN(p);
2613 if (e - p <= 1) /* empty entry means current dir */
2614 STRCPY(buf, "./");
2615 else
2616 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002617 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 add_pathsep(buf);
2619 }
2620 STRCAT(buf, name);
2621 retval = executable_file(buf);
2622 if (retval == 1)
2623 break;
2624
2625 if (*e != ':')
2626 break;
2627 p = e + 1;
2628 }
2629
2630 vim_free(buf);
2631 return retval;
2632}
2633#endif
2634
2635/*
2636 * Check what "name" is:
2637 * NODE_NORMAL: file or directory (or doesn't exist)
2638 * NODE_WRITABLE: writable device, socket, fifo, etc.
2639 * NODE_OTHER: non-writable things
2640 */
2641 int
2642mch_nodetype(name)
2643 char_u *name;
2644{
2645 struct stat st;
2646
2647 if (stat((char *)name, &st))
2648 return NODE_NORMAL;
2649 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2650 return NODE_NORMAL;
2651#ifndef OS2
2652 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2653 return NODE_OTHER;
2654#endif
2655 /* Everything else is writable? */
2656 return NODE_WRITABLE;
2657}
2658
2659 void
2660mch_early_init()
2661{
2662#ifdef HAVE_CHECK_STACK_GROWTH
2663 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 check_stack_growth((char *)&i);
2666
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002667# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 get_stack_limit();
2669# endif
2670
2671#endif
2672
2673 /*
2674 * Setup an alternative stack for signals. Helps to catch signals when
2675 * running out of stack space.
2676 * Use of sigaltstack() is preferred, it's more portable.
2677 * Ignore any errors.
2678 */
2679#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2680 signal_stack = malloc(SIGSTKSZ);
2681 init_signal_stack();
2682#endif
2683}
2684
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002685#if defined(EXITFREE) || defined(PROTO)
2686 void
2687mch_free_mem()
2688{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00002689# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2690 if (clip_star.owned)
2691 clip_lose_selection(&clip_star);
2692 if (clip_plus.owned)
2693 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002694# endif
2695# if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
2696 if (xterm_Shell != (Widget)0)
2697 XtDestroyWidget(xterm_Shell);
2698 if (xterm_dpy != NULL)
2699 XtCloseDisplay(xterm_dpy);
2700 if (app_context != (XtAppContext)NULL)
2701 XtDestroyApplicationContext(app_context);
2702# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00002703# ifdef FEAT_X11
2704 if (x11_display != NULL && x11_display != xterm_dpy)
2705 XCloseDisplay(x11_display);
2706# endif
2707# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2708 vim_free(signal_stack);
2709 signal_stack = NULL;
2710# endif
2711# ifdef FEAT_TITLE
2712 vim_free(oldtitle);
2713 vim_free(oldicon);
2714# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002715}
2716#endif
2717
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718static void exit_scroll __ARGS((void));
2719
2720/*
2721 * Output a newline when exiting.
2722 * Make sure the newline goes to the same stream as the text.
2723 */
2724 static void
2725exit_scroll()
2726{
Bram Moolenaardf177f62005-02-22 08:39:57 +00002727 if (silent_mode)
2728 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 if (newline_on_exit || msg_didout)
2730 {
2731 if (msg_use_printf())
2732 {
2733 if (info_message)
2734 mch_msg("\n");
2735 else
2736 mch_errmsg("\r\n");
2737 }
2738 else
2739 out_char('\n');
2740 }
2741 else
2742 {
2743 restore_cterm_colors(); /* get original colors back */
2744 msg_clr_eos_force(); /* clear the rest of the display */
2745 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
2746 }
2747}
2748
2749 void
2750mch_exit(r)
2751 int r;
2752{
2753 exiting = TRUE;
2754
2755#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
2756 x11_export_final_selection();
2757#endif
2758
2759#ifdef FEAT_GUI
2760 if (!gui.in_use)
2761#endif
2762 {
2763 settmode(TMODE_COOK);
2764#ifdef FEAT_TITLE
2765 mch_restore_title(3); /* restore xterm title and icon name */
2766#endif
2767 /*
2768 * When t_ti is not empty but it doesn't cause swapping terminal
2769 * pages, need to output a newline when msg_didout is set. But when
2770 * t_ti does swap pages it should not go to the shell page. Do this
2771 * before stoptermcap().
2772 */
2773 if (swapping_screen() && !newline_on_exit)
2774 exit_scroll();
2775
2776 /* Stop termcap: May need to check for T_CRV response, which
2777 * requires RAW mode. */
2778 stoptermcap();
2779
2780 /*
2781 * A newline is only required after a message in the alternate screen.
2782 * This is set to TRUE by wait_return().
2783 */
2784 if (!swapping_screen() || newline_on_exit)
2785 exit_scroll();
2786
2787 /* Cursor may have been switched off without calling starttermcap()
2788 * when doing "vim -u vimrc" and vimrc contains ":q". */
2789 if (full_screen)
2790 cursor_on();
2791 }
2792 out_flush();
2793 ml_close_all(TRUE); /* remove all memfiles */
2794 may_core_dump();
2795#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 gui_exit(r);
2798#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00002799
2800#if defined(MACOS_X) && defined(FEAT_MBYTE)
2801 mac_conv_cleanup();
2802#endif
2803
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804#ifdef __QNX__
2805 /* A core dump won't be created if the signal handler
2806 * doesn't return, so we can't call exit() */
2807 if (deadly_signal != 0)
2808 return;
2809#endif
2810
Bram Moolenaar009b2592004-10-24 19:18:58 +00002811#ifdef FEAT_NETBEANS_INTG
2812 if (usingNetbeans)
2813 netbeans_send_disconnect();
2814#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00002815
2816#ifdef EXITFREE
2817 free_all_mem();
2818#endif
2819
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 exit(r);
2821}
2822
2823 static void
2824may_core_dump()
2825{
2826 if (deadly_signal != 0)
2827 {
2828 signal(deadly_signal, SIG_DFL);
2829 kill(getpid(), deadly_signal); /* Die using the signal we caught */
2830 }
2831}
2832
2833#ifndef VMS
2834
2835 void
2836mch_settmode(tmode)
2837 int tmode;
2838{
2839 static int first = TRUE;
2840
2841 /* Why is NeXT excluded here (and not in os_unixx.h)? */
2842#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
2843 /*
2844 * for "new" tty systems
2845 */
2846# ifdef HAVE_TERMIOS_H
2847 static struct termios told;
2848 struct termios tnew;
2849# else
2850 static struct termio told;
2851 struct termio tnew;
2852# endif
2853
2854 if (first)
2855 {
2856 first = FALSE;
2857# if defined(HAVE_TERMIOS_H)
2858 tcgetattr(read_cmd_fd, &told);
2859# else
2860 ioctl(read_cmd_fd, TCGETA, &told);
2861# endif
2862 }
2863
2864 tnew = told;
2865 if (tmode == TMODE_RAW)
2866 {
2867 /*
2868 * ~ICRNL enables typing ^V^M
2869 */
2870 tnew.c_iflag &= ~ICRNL;
2871 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
2872# if defined(IEXTEN) && !defined(__MINT__)
2873 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
2874 /* but it breaks function keys on MINT */
2875# endif
2876 );
2877# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
2878 tnew.c_oflag &= ~ONLCR;
2879# endif
2880 tnew.c_cc[VMIN] = 1; /* return after 1 char */
2881 tnew.c_cc[VTIME] = 0; /* don't wait */
2882 }
2883 else if (tmode == TMODE_SLEEP)
2884 tnew.c_lflag &= ~(ECHO);
2885
2886# if defined(HAVE_TERMIOS_H)
2887 {
2888 int n = 10;
2889
2890 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
2891 * few times. */
2892 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
2893 && errno == EINTR && n > 0)
2894 --n;
2895 }
2896# else
2897 ioctl(read_cmd_fd, TCSETA, &tnew);
2898# endif
2899
2900#else
2901
2902 /*
2903 * for "old" tty systems
2904 */
2905# ifndef TIOCSETN
2906# define TIOCSETN TIOCSETP /* for hpux 9.0 */
2907# endif
2908 static struct sgttyb ttybold;
2909 struct sgttyb ttybnew;
2910
2911 if (first)
2912 {
2913 first = FALSE;
2914 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
2915 }
2916
2917 ttybnew = ttybold;
2918 if (tmode == TMODE_RAW)
2919 {
2920 ttybnew.sg_flags &= ~(CRMOD | ECHO);
2921 ttybnew.sg_flags |= RAW;
2922 }
2923 else if (tmode == TMODE_SLEEP)
2924 ttybnew.sg_flags &= ~(ECHO);
2925 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
2926#endif
2927 curr_tmode = tmode;
2928}
2929
2930/*
2931 * Try to get the code for "t_kb" from the stty setting
2932 *
2933 * Even if termcap claims a backspace key, the user's setting *should*
2934 * prevail. stty knows more about reality than termcap does, and if
2935 * somebody's usual erase key is DEL (which, for most BSD users, it will
2936 * be), they're going to get really annoyed if their erase key starts
2937 * doing forward deletes for no reason. (Eric Fischer)
2938 */
2939 void
2940get_stty()
2941{
2942 char_u buf[2];
2943 char_u *p;
2944
2945 /* Why is NeXT excluded here (and not in os_unixx.h)? */
2946#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
2947 /* for "new" tty systems */
2948# ifdef HAVE_TERMIOS_H
2949 struct termios keys;
2950# else
2951 struct termio keys;
2952# endif
2953
2954# if defined(HAVE_TERMIOS_H)
2955 if (tcgetattr(read_cmd_fd, &keys) != -1)
2956# else
2957 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
2958# endif
2959 {
2960 buf[0] = keys.c_cc[VERASE];
2961 intr_char = keys.c_cc[VINTR];
2962#else
2963 /* for "old" tty systems */
2964 struct sgttyb keys;
2965
2966 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
2967 {
2968 buf[0] = keys.sg_erase;
2969 intr_char = keys.sg_kill;
2970#endif
2971 buf[1] = NUL;
2972 add_termcode((char_u *)"kb", buf, FALSE);
2973
2974 /*
2975 * If <BS> and <DEL> are now the same, redefine <DEL>.
2976 */
2977 p = find_termcode((char_u *)"kD");
2978 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
2979 do_fixdel(NULL);
2980 }
2981#if 0
2982 } /* to keep cindent happy */
2983#endif
2984}
2985
2986#endif /* VMS */
2987
2988#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2989/*
2990 * Set mouse clicks on or off.
2991 */
2992 void
2993mch_setmouse(on)
2994 int on;
2995{
2996 static int ison = FALSE;
2997 int xterm_mouse_vers;
2998
2999 if (on == ison) /* return quickly if nothing to do */
3000 return;
3001
3002 xterm_mouse_vers = use_xterm_mouse();
3003 if (xterm_mouse_vers > 0)
3004 {
3005 if (on) /* enable mouse events, use mouse tracking if available */
3006 out_str_nf((char_u *)
3007 (xterm_mouse_vers > 1
3008 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3009 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3010 else /* disable mouse events, could probably always send the same */
3011 out_str_nf((char_u *)
3012 (xterm_mouse_vers > 1
3013 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3014 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3015 ison = on;
3016 }
3017
3018# ifdef FEAT_MOUSE_DEC
3019 else if (ttym_flags == TTYM_DEC)
3020 {
3021 if (on) /* enable mouse events */
3022 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3023 else /* disable mouse events */
3024 out_str_nf((char_u *)"\033['z");
3025 ison = on;
3026 }
3027# endif
3028
3029# ifdef FEAT_MOUSE_GPM
3030 else
3031 {
3032 if (on)
3033 {
3034 if (gpm_open())
3035 ison = TRUE;
3036 }
3037 else
3038 {
3039 gpm_close();
3040 ison = FALSE;
3041 }
3042 }
3043# endif
3044
3045# ifdef FEAT_MOUSE_JSB
3046 else
3047 {
3048 if (on)
3049 {
3050 /* D - Enable Mouse up/down messages
3051 * L - Enable Left Button Reporting
3052 * M - Enable Middle Button Reporting
3053 * R - Enable Right Button Reporting
3054 * K - Enable SHIFT and CTRL key Reporting
3055 * + - Enable Advanced messaging of mouse moves and up/down messages
3056 * Q - Quiet No Ack
3057 * # - Numeric value of mouse pointer required
3058 * 0 = Multiview 2000 cursor, used as standard
3059 * 1 = Windows Arrow
3060 * 2 = Windows I Beam
3061 * 3 = Windows Hour Glass
3062 * 4 = Windows Cross Hair
3063 * 5 = Windows UP Arrow
3064 */
3065#ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3066 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3067 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3068#else
3069 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3070 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3071#endif
3072 ison = TRUE;
3073 }
3074 else
3075 {
3076 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3077 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3078 ison = FALSE;
3079 }
3080 }
3081# endif
3082# ifdef FEAT_MOUSE_PTERM
3083 else
3084 {
3085 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3086 if (on)
3087 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3088 else
3089 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3090 ison = on;
3091 }
3092# endif
3093}
3094
3095/*
3096 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3097 */
3098 void
3099check_mouse_termcode()
3100{
3101# ifdef FEAT_MOUSE_XTERM
3102 if (use_xterm_mouse()
3103# ifdef FEAT_GUI
3104 && !gui.in_use
3105# endif
3106 )
3107 {
3108 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003109 ? IF_EB("\233M", CSI_STR "M")
3110 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 if (*p_mouse != NUL)
3112 {
3113 /* force mouse off and maybe on to send possibly new mouse
3114 * activation sequence to the xterm, with(out) drag tracing. */
3115 mch_setmouse(FALSE);
3116 setmouse();
3117 }
3118 }
3119 else
3120 del_mouse_termcode(KS_MOUSE);
3121# endif
3122
3123# ifdef FEAT_MOUSE_GPM
3124 if (!use_xterm_mouse()
3125# ifdef FEAT_GUI
3126 && !gui.in_use
3127# endif
3128 )
3129 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3130# endif
3131
3132# ifdef FEAT_MOUSE_JSB
3133 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3134 if (!use_xterm_mouse()
3135# ifdef FEAT_GUI
3136 && !gui.in_use
3137# endif
3138 )
3139 set_mouse_termcode(KS_JSBTERM_MOUSE,
3140 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3141 else
3142 del_mouse_termcode(KS_JSBTERM_MOUSE);
3143# endif
3144
3145# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003146 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 * define it in the GUI or when using an xterm. */
3148 if (!use_xterm_mouse()
3149# ifdef FEAT_GUI
3150 && !gui.in_use
3151# endif
3152 )
3153 set_mouse_termcode(KS_NETTERM_MOUSE,
3154 (char_u *)IF_EB("\033}", ESC_STR "}"));
3155 else
3156 del_mouse_termcode(KS_NETTERM_MOUSE);
3157# endif
3158
3159# ifdef FEAT_MOUSE_DEC
3160 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3161 if (!use_xterm_mouse()
3162# ifdef FEAT_GUI
3163 && !gui.in_use
3164# endif
3165 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003166 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3167 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 else
3169 del_mouse_termcode(KS_DEC_MOUSE);
3170# endif
3171# ifdef FEAT_MOUSE_PTERM
3172 /* same as the dec mouse */
3173 if (!use_xterm_mouse()
3174# ifdef FEAT_GUI
3175 && !gui.in_use
3176# endif
3177 )
3178 set_mouse_termcode(KS_PTERM_MOUSE,
3179 (char_u *) IF_EB("\033[", ESC_STR "["));
3180 else
3181 del_mouse_termcode(KS_PTERM_MOUSE);
3182# endif
3183}
3184#endif
3185
3186/*
3187 * set screen mode, always fails.
3188 */
3189/* ARGSUSED */
3190 int
3191mch_screenmode(arg)
3192 char_u *arg;
3193{
3194 EMSG(_(e_screenmode));
3195 return FAIL;
3196}
3197
3198#ifndef VMS
3199
3200/*
3201 * Try to get the current window size:
3202 * 1. with an ioctl(), most accurate method
3203 * 2. from the environment variables LINES and COLUMNS
3204 * 3. from the termcap
3205 * 4. keep using the old values
3206 * Return OK when size could be determined, FAIL otherwise.
3207 */
3208 int
3209mch_get_shellsize()
3210{
3211 long rows = 0;
3212 long columns = 0;
3213 char_u *p;
3214
3215 /*
3216 * For OS/2 use _scrsize().
3217 */
3218# ifdef __EMX__
3219 {
3220 int s[2];
3221
3222 _scrsize(s);
3223 columns = s[0];
3224 rows = s[1];
3225 }
3226# endif
3227
3228 /*
3229 * 1. try using an ioctl. It is the most accurate method.
3230 *
3231 * Try using TIOCGWINSZ first, some systems that have it also define
3232 * TIOCGSIZE but don't have a struct ttysize.
3233 */
3234# ifdef TIOCGWINSZ
3235 {
3236 struct winsize ws;
3237 int fd = 1;
3238
3239 /* When stdout is not a tty, use stdin for the ioctl(). */
3240 if (!isatty(fd) && isatty(read_cmd_fd))
3241 fd = read_cmd_fd;
3242 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3243 {
3244 columns = ws.ws_col;
3245 rows = ws.ws_row;
3246 }
3247 }
3248# else /* TIOCGWINSZ */
3249# ifdef TIOCGSIZE
3250 {
3251 struct ttysize ts;
3252 int fd = 1;
3253
3254 /* When stdout is not a tty, use stdin for the ioctl(). */
3255 if (!isatty(fd) && isatty(read_cmd_fd))
3256 fd = read_cmd_fd;
3257 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3258 {
3259 columns = ts.ts_cols;
3260 rows = ts.ts_lines;
3261 }
3262 }
3263# endif /* TIOCGSIZE */
3264# endif /* TIOCGWINSZ */
3265
3266 /*
3267 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003268 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3269 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003270 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003271 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272 {
3273 if ((p = (char_u *)getenv("LINES")))
3274 rows = atoi((char *)p);
3275 if ((p = (char_u *)getenv("COLUMNS")))
3276 columns = atoi((char *)p);
3277 }
3278
3279#ifdef HAVE_TGETENT
3280 /*
3281 * 3. try reading "co" and "li" entries from termcap
3282 */
3283 if (columns == 0 || rows == 0)
3284 getlinecol(&columns, &rows);
3285#endif
3286
3287 /*
3288 * 4. If everything fails, use the old values
3289 */
3290 if (columns <= 0 || rows <= 0)
3291 return FAIL;
3292
3293 Rows = rows;
3294 Columns = columns;
3295 return OK;
3296}
3297
3298/*
3299 * Try to set the window size to Rows and Columns.
3300 */
3301 void
3302mch_set_shellsize()
3303{
3304 if (*T_CWS)
3305 {
3306 /*
3307 * NOTE: if you get an error here that term_set_winsize() is
3308 * undefined, check the output of configure. It could probably not
3309 * find a ncurses, termcap or termlib library.
3310 */
3311 term_set_winsize((int)Rows, (int)Columns);
3312 out_flush();
3313 screen_start(); /* don't know where cursor is now */
3314 }
3315}
3316
3317#endif /* VMS */
3318
3319/*
3320 * Rows and/or Columns has changed.
3321 */
3322 void
3323mch_new_shellsize()
3324{
3325 /* Nothing to do. */
3326}
3327
Bram Moolenaardf177f62005-02-22 08:39:57 +00003328#ifndef USE_SYSTEM
3329static void append_ga_line __ARGS((garray_T *gap));
3330
3331/*
3332 * Append the text in "gap" below the cursor line and clear "gap".
3333 */
3334 static void
3335append_ga_line(gap)
3336 garray_T *gap;
3337{
3338 /* Remove trailing CR. */
3339 if (gap->ga_len > 0
3340 && !curbuf->b_p_bin
3341 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
3342 --gap->ga_len;
3343 ga_append(gap, NUL);
3344 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
3345 gap->ga_len = 0;
3346}
3347#endif
3348
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 int
3350mch_call_shell(cmd, options)
3351 char_u *cmd;
3352 int options; /* SHELL_*, see vim.h */
3353{
3354#ifdef VMS
3355 char *ifn = NULL;
3356 char *ofn = NULL;
3357#endif
3358 int tmode = cur_tmode;
3359#ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3360 int x;
3361# ifndef __EMX__
3362 char_u *newcmd; /* only needed for unix */
3363# else
3364 /*
3365 * Set the preferred shell in the EMXSHELL environment variable (but
3366 * only if it is different from what is already in the environment).
3367 * Emx then takes care of whether to use "/c" or "-c" in an
3368 * intelligent way. Simply pass the whole thing to emx's system() call.
3369 * Emx also starts an interactive shell if system() is passed an empty
3370 * string.
3371 */
3372 char_u *p, *old;
3373
3374 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3375 {
3376 /* should check HAVE_SETENV, but I know we don't have it. */
3377 p = alloc(10 + strlen(p_sh));
3378 if (p)
3379 {
3380 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3381 putenv((char *)p); /* don't free the pointer! */
3382 }
3383 }
3384# endif
3385
3386 out_flush();
3387
3388 if (options & SHELL_COOKED)
3389 settmode(TMODE_COOK); /* set to normal mode */
3390
3391# ifdef __EMX__
3392 if (cmd == NULL)
3393 x = system(""); /* this starts an interactive shell in emx */
3394 else
3395 x = system((char *)cmd);
3396 /* system() returns -1 when error occurs in starting shell */
3397 if (x == -1 && !emsg_silent)
3398 {
3399 MSG_PUTS(_("\nCannot execute shell "));
3400 msg_outtrans(p_sh);
3401 msg_putchar('\n');
3402 }
3403# else /* not __EMX__ */
3404 if (cmd == NULL)
3405 x = system((char *)p_sh);
3406 else
3407 {
3408# ifdef VMS
3409 if (ofn = strchr((char *)cmd, '>'))
3410 *ofn++ = '\0';
3411 if (ifn = strchr((char *)cmd, '<'))
3412 {
3413 char *p;
3414
3415 *ifn++ = '\0';
3416 p = strchr(ifn,' '); /* chop off any trailing spaces */
3417 if (p)
3418 *p = '\0';
3419 }
3420 if (ofn)
3421 x = vms_sys((char *)cmd, ofn, ifn);
3422 else
3423 x = system((char *)cmd);
3424# else
3425 newcmd = lalloc(STRLEN(p_sh)
3426 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3427 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3428 if (newcmd == NULL)
3429 x = 0;
3430 else
3431 {
3432 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3433 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3434 (char *)p_shcf,
3435 (char *)cmd);
3436 x = system((char *)newcmd);
3437 vim_free(newcmd);
3438 }
3439# endif
3440 }
3441# ifdef VMS
3442 x = vms_sys_status(x);
3443# endif
3444 if (emsg_silent)
3445 ;
3446 else if (x == 127)
3447 MSG_PUTS(_("\nCannot execute shell sh\n"));
3448# endif /* __EMX__ */
3449 else if (x && !(options & SHELL_SILENT))
3450 {
3451 MSG_PUTS(_("\nshell returned "));
3452 msg_outnum((long)x);
3453 msg_putchar('\n');
3454 }
3455
3456 if (tmode == TMODE_RAW)
3457 settmode(TMODE_RAW); /* set to raw mode */
3458# ifdef FEAT_TITLE
3459 resettitle();
3460# endif
3461 return x;
3462
3463#else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3464
Bram Moolenaardf177f62005-02-22 08:39:57 +00003465# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3466 127, some shells use that already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467
3468 char_u *newcmd = NULL;
3469 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003470 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 pid_t wait_pid = 0;
3472# ifdef HAVE_UNION_WAIT
3473 union wait status;
3474# else
3475 int status = -1;
3476# endif
3477 int retval = -1;
3478 char **argv = NULL;
3479 int argc;
3480 int i;
3481 char_u *p;
3482 int inquote;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003484# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 int pty_slave_fd = -1;
3486 char *tty_name;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003487# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 int fd_toshell[2]; /* for pipes */
3489 int fd_fromshell[2];
3490 int pipe_error = FALSE;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003491# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492 char envbuf[50];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003493# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 static char envbuf_Rows[20];
3495 static char envbuf_Columns[20];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496# endif
3497 int did_settmode = FALSE; /* TRUE when settmode(TMODE_RAW) called */
3498
3499 out_flush();
3500 if (options & SHELL_COOKED)
3501 settmode(TMODE_COOK); /* set to normal mode */
3502
3503 /*
3504 * 1: find number of arguments
3505 * 2: separate them and built argv[]
3506 */
3507 newcmd = vim_strsave(p_sh);
3508 if (newcmd == NULL) /* out of memory */
3509 goto error;
3510 for (i = 0; i < 2; ++i)
3511 {
3512 p = newcmd;
3513 inquote = FALSE;
3514 argc = 0;
3515 for (;;)
3516 {
3517 if (i == 1)
3518 argv[argc] = (char *)p;
3519 ++argc;
3520 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3521 {
3522 if (*p == '"')
3523 inquote = !inquote;
3524 ++p;
3525 }
3526 if (*p == NUL)
3527 break;
3528 if (i == 1)
3529 *p++ = NUL;
3530 p = skipwhite(p);
3531 }
3532 if (i == 0)
3533 {
3534 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3535 if (argv == NULL) /* out of memory */
3536 goto error;
3537 }
3538 }
3539 if (cmd != NULL)
3540 {
3541 if (extra_shell_arg != NULL)
3542 argv[argc++] = (char *)extra_shell_arg;
3543 argv[argc++] = (char *)p_shcf;
3544 argv[argc++] = (char *)cmd;
3545 }
3546 argv[argc] = NULL;
3547
Bram Moolenaar071d4272004-06-13 20:20:40 +00003548 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00003549 * For the GUI, when writing the output into the buffer and when reading
3550 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3551 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003553 if ((options & (SHELL_READ|SHELL_WRITE))
3554# ifdef FEAT_GUI
3555 || (gui.in_use && show_shell_mess)
3556# endif
3557 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003558 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003559# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560 /*
3561 * Try to open a master pty.
3562 * If this works, open the slave pty.
3563 * If the slave can't be opened, close the master pty.
3564 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003565 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 {
3567 pty_master_fd = OpenPTY(&tty_name); /* open pty */
3568 if (pty_master_fd >= 0 && ((pty_slave_fd =
3569 open(tty_name, O_RDWR | O_EXTRA, 0)) < 0))
3570 {
3571 close(pty_master_fd);
3572 pty_master_fd = -1;
3573 }
3574 }
3575 /*
3576 * If not opening a pty or it didn't work, try using pipes.
3577 */
3578 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003579# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 {
3581 pipe_error = (pipe(fd_toshell) < 0);
3582 if (!pipe_error) /* pipe create OK */
3583 {
3584 pipe_error = (pipe(fd_fromshell) < 0);
3585 if (pipe_error) /* pipe create failed */
3586 {
3587 close(fd_toshell[0]);
3588 close(fd_toshell[1]);
3589 }
3590 }
3591 if (pipe_error)
3592 {
3593 MSG_PUTS(_("\nCannot create pipes\n"));
3594 out_flush();
3595 }
3596 }
3597 }
3598
3599 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600 {
3601# ifdef __BEOS__
3602 beos_cleanup_read_thread();
3603# endif
3604 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3605 {
3606 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00003607 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003609 || (gui.in_use && show_shell_mess)
3610# endif
3611 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003613# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 if (pty_master_fd >= 0) /* close the pseudo tty */
3615 {
3616 close(pty_master_fd);
3617 close(pty_slave_fd);
3618 }
3619 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 {
3622 close(fd_toshell[0]);
3623 close(fd_toshell[1]);
3624 close(fd_fromshell[0]);
3625 close(fd_fromshell[1]);
3626 }
3627 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 }
3629 else if (pid == 0) /* child */
3630 {
3631 reset_signals(); /* handle signals normally */
3632
3633 if (!show_shell_mess || (options & SHELL_EXPAND))
3634 {
3635 int fd;
3636
3637 /*
3638 * Don't want to show any message from the shell. Can't just
3639 * close stdout and stderr though, because some systems will
3640 * break if you try to write to them after that, so we must
3641 * use dup() to replace them with something else -- webb
3642 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3643 * waiting for input.
3644 */
3645 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3646 fclose(stdin);
3647 fclose(stdout);
3648 fclose(stderr);
3649
3650 /*
3651 * If any of these open()'s and dup()'s fail, we just continue
3652 * anyway. It's not fatal, and on most systems it will make
3653 * no difference at all. On a few it will cause the execvp()
3654 * to exit with a non-zero status even when the completion
3655 * could be done, which is nothing too serious. If the open()
3656 * or dup() failed we'd just do the same thing ourselves
3657 * anyway -- webb
3658 */
3659 if (fd >= 0)
3660 {
3661 dup(fd); /* To replace stdin (file descriptor 0) */
3662 dup(fd); /* To replace stdout (file descriptor 1) */
3663 dup(fd); /* To replace stderr (file descriptor 2) */
3664
3665 /* Don't need this now that we've duplicated it */
3666 close(fd);
3667 }
3668 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00003669 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00003671 || gui.in_use
3672# endif
3673 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 {
3675
Bram Moolenaardf177f62005-02-22 08:39:57 +00003676# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 (void)setsid();
Bram Moolenaardf177f62005-02-22 08:39:57 +00003678# endif
3679# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680 /* push stream discipline modules */
3681 if (options & SHELL_COOKED)
3682 SetupSlavePTY(pty_slave_fd);
3683# ifdef TIOCSCTTY
3684 /* try to become controlling tty (probably doesn't work,
3685 * unless run by root) */
3686 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
3687# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689 /* Simulate to have a dumb terminal (for now) */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003690# ifdef HAVE_SETENV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 setenv("TERM", "dumb", 1);
3692 sprintf((char *)envbuf, "%ld", Rows);
3693 setenv("ROWS", (char *)envbuf, 1);
3694 sprintf((char *)envbuf, "%ld", Rows);
3695 setenv("LINES", (char *)envbuf, 1);
3696 sprintf((char *)envbuf, "%ld", Columns);
3697 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003698# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 /*
3700 * Putenv does not copy the string, it has to remain valid.
3701 * Use a static array to avoid loosing allocated memory.
3702 */
3703 putenv("TERM=dumb");
3704 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
3705 putenv(envbuf_Rows);
3706 sprintf(envbuf_Rows, "LINES=%ld", Rows);
3707 putenv(envbuf_Rows);
3708 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
3709 putenv(envbuf_Columns);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711
Bram Moolenaardf177f62005-02-22 08:39:57 +00003712# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 if (pty_master_fd >= 0)
3714 {
3715 close(pty_master_fd); /* close master side of pty */
3716
3717 /* set up stdin/stdout/stderr for the child */
3718 close(0);
3719 dup(pty_slave_fd);
3720 close(1);
3721 dup(pty_slave_fd);
3722 close(2);
3723 dup(pty_slave_fd);
3724
3725 close(pty_slave_fd); /* has been dupped, close it now */
3726 }
3727 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00003728# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 {
3730 /* set up stdin for the child */
3731 close(fd_toshell[1]);
3732 close(0);
3733 dup(fd_toshell[0]);
3734 close(fd_toshell[0]);
3735
3736 /* set up stdout for the child */
3737 close(fd_fromshell[0]);
3738 close(1);
3739 dup(fd_fromshell[1]);
3740 close(fd_fromshell[1]);
3741
3742 /* set up stderr for the child */
3743 close(2);
3744 dup(1);
3745 }
3746 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00003747
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 /*
3749 * There is no type cast for the argv, because the type may be
3750 * different on different machines. This may cause a warning
3751 * message with strict compilers, don't worry about it.
3752 * Call _exit() instead of exit() to avoid closing the connection
3753 * to the X server (esp. with GTK, which uses atexit()).
3754 */
3755 execvp(argv[0], argv);
3756 _exit(EXEC_FAILED); /* exec failed, return failure code */
3757 }
3758 else /* parent */
3759 {
3760 /*
3761 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00003762 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763 */
3764 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003765 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766
3767 /*
3768 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00003769 * This is also used to pipe stdin/stdout to/from the external
3770 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003772 if ((options & (SHELL_READ|SHELL_WRITE))
3773# ifdef FEAT_GUI
3774 || (gui.in_use && show_shell_mess)
3775# endif
3776 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003778# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00003780# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00003782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3784 int ta_len = 0; /* valid bytes in ta_buf[] */
3785 int len;
3786 int p_more_save;
3787 int old_State;
3788 int c;
3789 int toshell_fd;
3790 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003791 garray_T ga;
3792 int noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793
Bram Moolenaardf177f62005-02-22 08:39:57 +00003794# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 if (pty_master_fd >= 0)
3796 {
3797 close(pty_slave_fd); /* close slave side of pty */
3798 fromshell_fd = pty_master_fd;
3799 toshell_fd = dup(pty_master_fd);
3800 }
3801 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00003802# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 {
3804 close(fd_toshell[0]);
3805 close(fd_fromshell[1]);
3806 toshell_fd = fd_toshell[1];
3807 fromshell_fd = fd_fromshell[0];
3808 }
3809
3810 /*
3811 * Write to the child if there are typed characters.
3812 * Read from the child if there are characters available.
3813 * Repeat the reading a few times if more characters are
3814 * available. Need to check for typed keys now and then, but
3815 * not too often (delays when no chars are available).
3816 * This loop is quit if no characters can be read from the pty
3817 * (WaitForChar detected special condition), or there are no
3818 * characters available and the child has exited.
3819 * Only check if the child has exited when there is no more
3820 * output. The child may exit before all the output has
3821 * been printed.
3822 *
3823 * Currently this busy loops!
3824 * This can probably dead-lock when the write blocks!
3825 */
3826 p_more_save = p_more;
3827 p_more = FALSE;
3828 old_State = State;
3829 State = EXTERNCMD; /* don't redraw at window resize */
3830
Bram Moolenaardf177f62005-02-22 08:39:57 +00003831 if (options & SHELL_WRITE && toshell_fd >= 0)
3832 {
3833 /* Fork a process that will write the lines to the
3834 * external program. */
3835 if ((wpid = fork()) == -1)
3836 {
3837 MSG_PUTS(_("\nCannot fork\n"));
3838 }
3839 else if (wpid == 0)
3840 {
3841 linenr_T lnum = curbuf->b_op_start.lnum;
3842 int written = 0;
3843 char_u *p = ml_get(lnum);
3844 char_u *s;
3845 size_t l;
3846
3847 /* child */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00003848 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003849 for (;;)
3850 {
3851 l = STRLEN(p + written);
3852 if (l == 0)
3853 len = 0;
3854 else if (p[written] == NL)
3855 /* NL -> NUL translation */
3856 len = write(toshell_fd, "", (size_t)1);
3857 else
3858 {
3859 s = vim_strchr(p + written, NL);
3860 len = write(toshell_fd, (char *)p + written,
3861 s == NULL ? l : s - (p + written));
3862 }
3863 if (len == l)
3864 {
3865 /* Finished a line, add a NL, unless this line
3866 * should not have one. */
3867 if (lnum != curbuf->b_op_end.lnum
3868 || !curbuf->b_p_bin
3869 || (lnum != write_no_eol_lnum
3870 && (lnum !=
3871 curbuf->b_ml.ml_line_count
3872 || curbuf->b_p_eol)))
3873 write(toshell_fd, "\n", (size_t)1);
3874 ++lnum;
3875 if (lnum > curbuf->b_op_end.lnum)
3876 {
3877 /* finished all the lines, close pipe */
3878 close(toshell_fd);
3879 toshell_fd = -1;
3880 break;
3881 }
3882 p = ml_get(lnum);
3883 written = 0;
3884 }
3885 else if (len > 0)
3886 written += len;
3887 }
3888 _exit(0);
3889 }
3890 else
3891 {
3892 close(toshell_fd);
3893 toshell_fd = -1;
3894 }
3895 }
3896
3897 if (options & SHELL_READ)
3898 ga_init2(&ga, 1, BUFLEN);
3899
3900 noread_cnt = 0;
3901
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 for (;;)
3903 {
3904 /*
3905 * Check if keys have been typed, write them to the child
3906 * if there are any. Don't do this if we are expanding
3907 * wild cards (would eat typeahead). Don't get extra
3908 * characters when we already have one.
Bram Moolenaardf177f62005-02-22 08:39:57 +00003909 * Don't read characters unless we didn't get output for a
3910 * while, avoids that ":r !ls" eats typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 */
3912 len = 0;
3913 if (!(options & SHELL_EXPAND)
3914 && (ta_len > 0
Bram Moolenaardf177f62005-02-22 08:39:57 +00003915 || (noread_cnt > 4
3916 && (len = ui_inchar(ta_buf,
3917 BUFLEN, 10L, 0)) > 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 {
3919 /*
3920 * For pipes:
3921 * Check for CTRL-C: send interrupt signal to child.
3922 * Check for CTRL-D: EOF, close pipe to child.
3923 */
3924 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
3925 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00003926# ifdef SIGINT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 /*
3928 * Send SIGINT to the child's group or all
3929 * processes in our group.
3930 */
3931 if (ta_buf[ta_len] == Ctrl_C
3932 || ta_buf[ta_len] == intr_char)
Bram Moolenaardf177f62005-02-22 08:39:57 +00003933 {
3934# ifdef HAVE_SETSID
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 kill(-pid, SIGINT);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003936# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 kill(0, SIGINT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938# endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003939 if (wpid > 0)
3940 kill(wpid, SIGINT);
3941 }
3942# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 if (pty_master_fd < 0 && toshell_fd >= 0
3944 && ta_buf[ta_len] == Ctrl_D)
3945 {
3946 close(toshell_fd);
3947 toshell_fd = -1;
3948 }
3949 }
3950
3951 /* replace K_BS by <BS> and K_DEL by <DEL> */
3952 for (i = ta_len; i < ta_len + len; ++i)
3953 {
3954 if (ta_buf[i] == CSI && len - i > 2)
3955 {
3956 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3957 if (c == K_DEL || c == K_KDEL || c == K_BS)
3958 {
3959 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3960 (size_t)(len - i - 2));
3961 if (c == K_DEL || c == K_KDEL)
3962 ta_buf[i] = DEL;
3963 else
3964 ta_buf[i] = Ctrl_H;
3965 len -= 2;
3966 }
3967 }
3968 else if (ta_buf[i] == '\r')
3969 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00003970# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 if (has_mbyte)
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00003972 i += (*mb_ptr2len)(ta_buf + i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00003973# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 }
3975
3976 /*
3977 * For pipes: echo the typed characters.
3978 * For a pty this does not seem to work.
3979 */
3980 if (pty_master_fd < 0)
3981 {
3982 for (i = ta_len; i < ta_len + len; ++i)
3983 {
3984 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3985 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00003986# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 else if (has_mbyte)
3988 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00003989 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003990
3991 msg_outtrans_len(ta_buf + i, l);
3992 i += l - 1;
3993 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00003994# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 else
3996 msg_outtrans_len(ta_buf + i, 1);
3997 }
3998 windgoto(msg_row, msg_col);
3999 out_flush();
4000 }
4001
4002 ta_len += len;
4003
4004 /*
4005 * Write the characters to the child, unless EOF has
4006 * been typed for pipes. Write one character at a
4007 * time, to avoid loosing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004008 * When writing buffer lines, drop the typed
4009 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004011 if (options & SHELL_WRITE)
4012 ta_len = 0;
4013 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014 {
4015 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4016 if (len > 0)
4017 {
4018 ta_len -= len;
4019 mch_memmove(ta_buf, ta_buf + len, ta_len);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004020 noread_cnt = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021 }
4022 }
4023 }
4024
Bram Moolenaardf177f62005-02-22 08:39:57 +00004025 if (got_int)
4026 {
4027 /* CTRL-C sends a signal to the child, we ignore it
4028 * ourselves */
4029# ifdef HAVE_SETSID
4030 kill(-pid, SIGINT);
4031# else
4032 kill(0, SIGINT);
4033# endif
4034 if (wpid > 0)
4035 kill(wpid, SIGINT);
4036 got_int = FALSE;
4037 }
4038
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039 /*
4040 * Check if the child has any characters to be printed.
4041 * Read them and write them to our window. Repeat this as
4042 * long as there is something to do, avoid the 10ms wait
4043 * for mch_inchar(), or sending typeahead characters to
4044 * the external process.
4045 * TODO: This should handle escape sequences, compatible
4046 * to some terminal (vt52?).
4047 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004048 ++noread_cnt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4050 {
4051 len = read(fromshell_fd, (char *)buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00004052# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004054# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00004056# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 );
4058 if (len <= 0) /* end of file or error */
4059 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004060
4061 noread_cnt = 0;
4062 if (options & SHELL_READ)
4063 {
4064 /* Do NUL -> NL translation, append NL separated
4065 * lines to the current buffer. */
4066 for (i = 0; i < len; ++i)
4067 {
4068 if (buffer[i] == NL)
4069 append_ga_line(&ga);
4070 else if (buffer[i] == NUL)
4071 ga_append(&ga, NL);
4072 else
4073 ga_append(&ga, buffer[i]);
4074 }
4075 }
4076# ifdef FEAT_MBYTE
4077 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078 {
4079 int l;
4080
Bram Moolenaardf177f62005-02-22 08:39:57 +00004081 len += buffer_off;
4082 buffer[len] = NUL;
4083
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 /* Check if the last character in buffer[] is
4085 * incomplete, keep these bytes for the next
4086 * round. */
4087 for (p = buffer; p < buffer + len; p += l)
4088 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004089 l = mb_cptr2len(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 if (l == 0)
4091 l = 1; /* NUL byte? */
4092 else if (MB_BYTE2LEN(*p) != l)
4093 break;
4094 }
4095 if (p == buffer) /* no complete character */
4096 {
4097 /* avoid getting stuck at an illegal byte */
4098 if (len >= 12)
4099 ++p;
4100 else
4101 {
4102 buffer_off = len;
4103 continue;
4104 }
4105 }
4106 c = *p;
4107 *p = NUL;
4108 msg_puts(buffer);
4109 if (p < buffer + len)
4110 {
4111 *p = c;
4112 buffer_off = (buffer + len) - p;
4113 mch_memmove(buffer, p, buffer_off);
4114 continue;
4115 }
4116 buffer_off = 0;
4117 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004118# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 {
4121 buffer[len] = NUL;
4122 msg_puts(buffer);
4123 }
4124
4125 windgoto(msg_row, msg_col);
4126 cursor_on();
4127 out_flush();
4128 if (got_int)
4129 break;
4130 }
4131
4132 /*
4133 * Check if the child still exists, before checking for
4134 * typed characters (otherwise we would loose typeahead).
4135 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004136# ifdef __NeXT__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004138# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004140# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4142 || (wait_pid == pid && WIFEXITED(status)))
4143 {
4144 wait_pid = pid;
4145 break;
4146 }
4147 wait_pid = 0;
4148 }
4149finished:
4150 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004151 if (options & SHELL_READ)
4152 {
4153 if (ga.ga_len > 0)
4154 {
4155 append_ga_line(&ga);
4156 /* remember that the NL was missing */
4157 write_no_eol_lnum = curwin->w_cursor.lnum;
4158 }
4159 else
4160 write_no_eol_lnum = 0;
4161 ga_clear(&ga);
4162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 /*
4165 * Give all typeahead that wasn't used back to ui_inchar().
4166 */
4167 if (ta_len)
4168 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 State = old_State;
4170 if (toshell_fd >= 0)
4171 close(toshell_fd);
4172 close(fromshell_fd);
4173 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174
4175 /*
4176 * Wait until our child has exited.
4177 * Ignore wait() returning pids of other children and returning
4178 * because of some signal like SIGWINCH.
4179 * Don't wait if wait_pid was already set above, indicating the
4180 * child already exited.
4181 */
4182 while (wait_pid != pid)
4183 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004184# ifdef _THREAD_SAFE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 /* Ugly hack: when compiled with Python threads are probably
4186 * used, in which case wait() sometimes hangs for no obvious
4187 * reason. Use waitpid() instead and loop (like the GUI). */
4188# ifdef __NeXT__
4189 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4190# else
4191 wait_pid = waitpid(pid, &status, WNOHANG);
4192# endif
4193 if (wait_pid == 0)
4194 {
4195 /* Wait for 1/100 sec before trying again. */
4196 mch_delay(10L, TRUE);
4197 continue;
4198 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004199# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200 wait_pid = wait(&status);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004201# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 if (wait_pid <= 0
4203# ifdef ECHILD
4204 && errno == ECHILD
4205# endif
4206 )
4207 break;
4208 }
4209
Bram Moolenaardf177f62005-02-22 08:39:57 +00004210 /* Make sure the child that writes to the external program is
4211 * dead. */
4212 if (wpid > 0)
4213 kill(wpid, SIGKILL);
4214
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 /*
4216 * Set to raw mode right now, otherwise a CTRL-C after
4217 * catch_signals() will kill Vim.
4218 */
4219 if (tmode == TMODE_RAW)
4220 settmode(TMODE_RAW);
4221 did_settmode = TRUE;
4222 set_signals();
4223
4224 if (WIFEXITED(status))
4225 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00004226 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 retval = WEXITSTATUS(status);
4228 if (retval && !emsg_silent)
4229 {
4230 if (retval == EXEC_FAILED)
4231 {
4232 MSG_PUTS(_("\nCannot execute shell "));
4233 msg_outtrans(p_sh);
4234 msg_putchar('\n');
4235 }
4236 else if (!(options & SHELL_SILENT))
4237 {
4238 MSG_PUTS(_("\nshell returned "));
4239 msg_outnum((long)retval);
4240 msg_putchar('\n');
4241 }
4242 }
4243 }
4244 else
4245 MSG_PUTS(_("\nCommand terminated\n"));
4246 }
4247 }
4248 vim_free(argv);
4249
4250error:
4251 if (!did_settmode)
4252 if (tmode == TMODE_RAW)
4253 settmode(TMODE_RAW); /* set to raw mode */
4254# ifdef FEAT_TITLE
4255 resettitle();
4256# endif
4257 vim_free(newcmd);
4258
4259 return retval;
4260
4261#endif /* USE_SYSTEM */
4262}
4263
4264/*
4265 * Check for CTRL-C typed by reading all available characters.
4266 * In cooked mode we should get SIGINT, no need to check.
4267 */
4268 void
4269mch_breakcheck()
4270{
4271 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4272 fill_input_buf(FALSE);
4273}
4274
4275/*
4276 * Wait "msec" msec until a character is available from the keyboard or from
4277 * inbuf[]. msec == -1 will block forever.
4278 * When a GUI is being used, this will never get called -- webb
4279 */
4280 static int
4281WaitForChar(msec)
4282 long msec;
4283{
4284#ifdef FEAT_MOUSE_GPM
4285 int gpm_process_wanted;
4286#endif
4287#ifdef FEAT_XCLIPBOARD
4288 int rest;
4289#endif
4290 int avail;
4291
4292 if (input_available()) /* something in inbuf[] */
4293 return 1;
4294
4295#if defined(FEAT_MOUSE_DEC)
4296 /* May need to query the mouse position. */
4297 if (WantQueryMouse)
4298 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00004299 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4301 }
4302#endif
4303
4304 /*
4305 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4306 * events. This is a bit complicated, because they might both be defined.
4307 */
4308#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4309# ifdef FEAT_XCLIPBOARD
4310 rest = 0;
4311 if (do_xterm_trace())
4312 rest = msec;
4313# endif
4314 do
4315 {
4316# ifdef FEAT_XCLIPBOARD
4317 if (rest != 0)
4318 {
4319 msec = XT_TRACE_DELAY;
4320 if (rest >= 0 && rest < XT_TRACE_DELAY)
4321 msec = rest;
4322 if (rest >= 0)
4323 rest -= msec;
4324 }
4325# endif
4326# ifdef FEAT_MOUSE_GPM
4327 gpm_process_wanted = 0;
4328 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4329# else
4330 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4331# endif
4332 if (!avail)
4333 {
4334 if (input_available())
4335 return 1;
4336# ifdef FEAT_XCLIPBOARD
4337 if (rest == 0 || !do_xterm_trace())
4338# endif
4339 break;
4340 }
4341 }
4342 while (FALSE
4343# ifdef FEAT_MOUSE_GPM
4344 || (gpm_process_wanted && mch_gpm_process() == 0)
4345# endif
4346# ifdef FEAT_XCLIPBOARD
4347 || (!avail && rest != 0)
4348# endif
4349 );
4350
4351#else
4352 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4353#endif
4354 return avail;
4355}
4356
4357/*
4358 * Wait "msec" msec until a character is available from file descriptor "fd".
4359 * Time == -1 will block forever.
4360 * When a GUI is being used, this will not be used for input -- webb
4361 * Returns also, when a request from Sniff is waiting -- toni.
4362 * Or when a Linux GPM mouse event is waiting.
4363 */
4364/* ARGSUSED */
4365#if defined(__BEOS__)
4366 int
4367#else
4368 static int
4369#endif
4370RealWaitForChar(fd, msec, check_for_gpm)
4371 int fd;
4372 long msec;
4373 int *check_for_gpm;
4374{
4375 int ret;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004376#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004377 static int busy = FALSE;
4378
4379 /* May retry getting characters after an event was handled. */
4380# define MAY_LOOP
4381
4382# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4383 /* Remember at what time we started, so that we know how much longer we
4384 * should wait after being interrupted. */
4385# define USE_START_TV
4386 struct timeval start_tv;
4387
4388 if (msec > 0 && (
4389# ifdef FEAT_XCLIPBOARD
4390 xterm_Shell != (Widget)0
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004391# if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392 ||
4393# endif
4394# endif
4395# ifdef USE_XSMP
4396 xsmp_icefd != -1
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004397# ifdef FEAT_MZSCHEME
4398 ||
4399# endif
4400# endif
4401# ifdef FEAT_MZSCHEME
4402 (mzthreads_allowed() && p_mzq > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403# endif
4404 ))
4405 gettimeofday(&start_tv, NULL);
4406# endif
4407
4408 /* Handle being called recursively. This may happen for the session
4409 * manager stuff, it may save the file, which does a breakcheck. */
4410 if (busy)
4411 return 0;
4412#endif
4413
4414#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00004415 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416#endif
4417 {
4418#ifdef MAY_LOOP
4419 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004420# ifdef FEAT_MZSCHEME
4421 int mzquantum_used = FALSE;
4422# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423#endif
4424#ifndef HAVE_SELECT
4425 struct pollfd fds[5];
4426 int nfd;
4427# ifdef FEAT_XCLIPBOARD
4428 int xterm_idx = -1;
4429# endif
4430# ifdef FEAT_MOUSE_GPM
4431 int gpm_idx = -1;
4432# endif
4433# ifdef USE_XSMP
4434 int xsmp_idx = -1;
4435# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004436 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004438# ifdef FEAT_MZSCHEME
4439 mzvim_check_threads();
4440 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4441 {
4442 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4443 mzquantum_used = TRUE;
4444 }
4445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 fds[0].fd = fd;
4447 fds[0].events = POLLIN;
4448 nfd = 1;
4449
4450# ifdef FEAT_SNIFF
4451# define SNIFF_IDX 1
4452 if (want_sniff_request)
4453 {
4454 fds[SNIFF_IDX].fd = fd_from_sniff;
4455 fds[SNIFF_IDX].events = POLLIN;
4456 nfd++;
4457 }
4458# endif
4459# ifdef FEAT_XCLIPBOARD
4460 if (xterm_Shell != (Widget)0)
4461 {
4462 xterm_idx = nfd;
4463 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4464 fds[nfd].events = POLLIN;
4465 nfd++;
4466 }
4467# endif
4468# ifdef FEAT_MOUSE_GPM
4469 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4470 {
4471 gpm_idx = nfd;
4472 fds[nfd].fd = gpm_fd;
4473 fds[nfd].events = POLLIN;
4474 nfd++;
4475 }
4476# endif
4477# ifdef USE_XSMP
4478 if (xsmp_icefd != -1)
4479 {
4480 xsmp_idx = nfd;
4481 fds[nfd].fd = xsmp_icefd;
4482 fds[nfd].events = POLLIN;
4483 nfd++;
4484 }
4485# endif
4486
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004487 ret = poll(fds, nfd, towait);
4488# ifdef FEAT_MZSCHEME
4489 if (ret == 0 && mzquantum_used)
4490 /* MzThreads scheduling is required and timeout occured */
4491 finished = FALSE;
4492# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493
4494# ifdef FEAT_SNIFF
4495 if (ret < 0)
4496 sniff_disconnect(1);
4497 else if (want_sniff_request)
4498 {
4499 if (fds[SNIFF_IDX].revents & POLLHUP)
4500 sniff_disconnect(1);
4501 if (fds[SNIFF_IDX].revents & POLLIN)
4502 sniff_request_waiting = 1;
4503 }
4504# endif
4505# ifdef FEAT_XCLIPBOARD
4506 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4507 {
4508 xterm_update(); /* Maybe we should hand out clipboard */
4509 if (--ret == 0 && !input_available())
4510 /* Try again */
4511 finished = FALSE;
4512 }
4513# endif
4514# ifdef FEAT_MOUSE_GPM
4515 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4516 {
4517 *check_for_gpm = 1;
4518 }
4519# endif
4520# ifdef USE_XSMP
4521 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4522 {
4523 if (fds[xsmp_idx].revents & POLLIN)
4524 {
4525 busy = TRUE;
4526 xsmp_handle_requests();
4527 busy = FALSE;
4528 }
4529 else if (fds[xsmp_idx].revents & POLLHUP)
4530 {
4531 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004532 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 xsmp_close();
4534 }
4535 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004536 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 }
4538# endif
4539
4540
4541#else /* HAVE_SELECT */
4542
4543 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004544 struct timeval *tvp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 fd_set rfds, efds;
4546 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004547 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004549# ifdef FEAT_MZSCHEME
4550 mzvim_check_threads();
4551 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4552 {
4553 towait = p_mzq; /* don't wait longer than 'mzquantum' */
4554 mzquantum_used = TRUE;
4555 }
4556# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557# ifdef __EMX__
4558 /* don't check for incoming chars if not in raw mode, because select()
4559 * always returns TRUE then (in some version of emx.dll) */
4560 if (curr_tmode != TMODE_RAW)
4561 return 0;
4562# endif
4563
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004564 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004566 tv.tv_sec = towait / 1000;
4567 tv.tv_usec = (towait % 1000) * (1000000/1000);
4568 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004570 else
4571 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572
4573 /*
4574 * Select on ready for reading and exceptional condition (end of file).
4575 */
4576 FD_ZERO(&rfds); /* calls bzero() on a sun */
4577 FD_ZERO(&efds);
4578 FD_SET(fd, &rfds);
4579# if !defined(__QNX__) && !defined(__CYGWIN32__)
4580 /* For QNX select() always returns 1 if this is set. Why? */
4581 FD_SET(fd, &efds);
4582# endif
4583 maxfd = fd;
4584
4585# ifdef FEAT_SNIFF
4586 if (want_sniff_request)
4587 {
4588 FD_SET(fd_from_sniff, &rfds);
4589 FD_SET(fd_from_sniff, &efds);
4590 if (maxfd < fd_from_sniff)
4591 maxfd = fd_from_sniff;
4592 }
4593# endif
4594# ifdef FEAT_XCLIPBOARD
4595 if (xterm_Shell != (Widget)0)
4596 {
4597 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
4598 if (maxfd < ConnectionNumber(xterm_dpy))
4599 maxfd = ConnectionNumber(xterm_dpy);
4600 }
4601# endif
4602# ifdef FEAT_MOUSE_GPM
4603 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4604 {
4605 FD_SET(gpm_fd, &rfds);
4606 FD_SET(gpm_fd, &efds);
4607 if (maxfd < gpm_fd)
4608 maxfd = gpm_fd;
4609 }
4610# endif
4611# ifdef USE_XSMP
4612 if (xsmp_icefd != -1)
4613 {
4614 FD_SET(xsmp_icefd, &rfds);
4615 FD_SET(xsmp_icefd, &efds);
4616 if (maxfd < xsmp_icefd)
4617 maxfd = xsmp_icefd;
4618 }
4619# endif
4620
4621# ifdef OLD_VMS
4622 /* Old VMS as v6.2 and older have broken select(). It waits more than
4623 * required. Should not be used */
4624 ret = 0;
4625# else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004626 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
4627# endif
4628# ifdef FEAT_MZSCHEME
4629 if (ret == 0 && mzquantum_used)
4630 /* loop if MzThreads must be scheduled and timeout occured */
4631 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632# endif
4633
4634# ifdef FEAT_SNIFF
4635 if (ret < 0 )
4636 sniff_disconnect(1);
4637 else if (ret > 0 && want_sniff_request)
4638 {
4639 if (FD_ISSET(fd_from_sniff, &efds))
4640 sniff_disconnect(1);
4641 if (FD_ISSET(fd_from_sniff, &rfds))
4642 sniff_request_waiting = 1;
4643 }
4644# endif
4645# ifdef FEAT_XCLIPBOARD
4646 if (ret > 0 && xterm_Shell != (Widget)0
4647 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
4648 {
4649 xterm_update(); /* Maybe we should hand out clipboard */
4650 /* continue looping when we only got the X event and the input
4651 * buffer is empty */
4652 if (--ret == 0 && !input_available())
4653 {
4654 /* Try again */
4655 finished = FALSE;
4656 }
4657 }
4658# endif
4659# ifdef FEAT_MOUSE_GPM
4660 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
4661 {
4662 if (FD_ISSET(gpm_fd, &efds))
4663 gpm_close();
4664 else if (FD_ISSET(gpm_fd, &rfds))
4665 *check_for_gpm = 1;
4666 }
4667# endif
4668# ifdef USE_XSMP
4669 if (ret > 0 && xsmp_icefd != -1)
4670 {
4671 if (FD_ISSET(xsmp_icefd, &efds))
4672 {
4673 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00004674 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675 xsmp_close();
4676 if (--ret == 0)
4677 finished = FALSE; /* keep going if event was only one */
4678 }
4679 else if (FD_ISSET(xsmp_icefd, &rfds))
4680 {
4681 busy = TRUE;
4682 xsmp_handle_requests();
4683 busy = FALSE;
4684 if (--ret == 0)
4685 finished = FALSE; /* keep going if event was only one */
4686 }
4687 }
4688# endif
4689
4690#endif /* HAVE_SELECT */
4691
4692#ifdef MAY_LOOP
4693 if (finished || msec == 0)
4694 break;
4695
4696 /* We're going to loop around again, find out for how long */
4697 if (msec > 0)
4698 {
4699# ifdef USE_START_TV
4700 struct timeval mtv;
4701
4702 /* Compute remaining wait time. */
4703 gettimeofday(&mtv, NULL);
4704 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
4705 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
4706# else
4707 /* Guess we got interrupted halfway. */
4708 msec = msec / 2;
4709# endif
4710 if (msec <= 0)
4711 break; /* waited long enough */
4712 }
4713#endif
4714 }
4715
4716 return (ret > 0);
4717}
4718
4719#ifndef VMS
4720
4721#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722/*
Bram Moolenaar02743632005-07-25 20:42:36 +00004723 * Expand a path into all matching files and/or directories. Handles "*",
4724 * "?", "[a-z]", "**", etc.
4725 * "path" has backslashes before chars that are not to be expanded.
4726 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 */
4728 int
4729mch_expandpath(gap, path, flags)
4730 garray_T *gap;
4731 char_u *path;
4732 int flags; /* EW_* flags */
4733{
Bram Moolenaar02743632005-07-25 20:42:36 +00004734 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735}
4736#endif
4737
4738/*
4739 * mch_expand_wildcards() - this code does wild-card pattern matching using
4740 * the shell
4741 *
4742 * return OK for success, FAIL for error (you may lose some memory) and put
4743 * an error message in *file.
4744 *
4745 * num_pat is number of input patterns
4746 * pat is array of pointers to input patterns
4747 * num_file is pointer to number of matched file names
4748 * file is pointer to array of pointers to matched file names
4749 */
4750
4751#ifndef SEEK_SET
4752# define SEEK_SET 0
4753#endif
4754#ifndef SEEK_END
4755# define SEEK_END 2
4756#endif
4757
4758/* ARGSUSED */
4759 int
4760mch_expand_wildcards(num_pat, pat, num_file, file, flags)
4761 int num_pat;
4762 char_u **pat;
4763 int *num_file;
4764 char_u ***file;
4765 int flags; /* EW_* flags */
4766{
4767 int i;
4768 size_t len;
4769 char_u *p;
4770 int dir;
4771#ifdef __EMX__
4772# define EXPL_ALLOC_INC 16
4773 char_u **expl_files;
4774 size_t files_alloced, files_free;
4775 char_u *buf;
4776 int has_wildcard;
4777
4778 *num_file = 0; /* default: no files found */
4779 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
4780 files_free = EXPL_ALLOC_INC; /* how much space is not used */
4781 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
4782 if (*file == NULL)
4783 return FAIL;
4784
4785 for (; num_pat > 0; num_pat--, pat++)
4786 {
4787 expl_files = NULL;
4788 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
4789 /* expand environment var or home dir */
4790 buf = expand_env_save(*pat);
4791 else
4792 buf = vim_strsave(*pat);
4793 expl_files = NULL;
Bram Moolenaard8b02732005-01-14 21:48:43 +00004794 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795 if (has_wildcard) /* yes, so expand them */
4796 expl_files = (char_u **)_fnexplode(buf);
4797
4798 /*
4799 * return value of buf if no wildcards left,
4800 * OR if no match AND EW_NOTFOUND is set.
4801 */
4802 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
4803 || (expl_files == NULL && (flags & EW_NOTFOUND)))
4804 { /* simply save the current contents of *buf */
4805 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
4806 if (expl_files != NULL)
4807 {
4808 expl_files[0] = vim_strsave(buf);
4809 expl_files[1] = NULL;
4810 }
4811 }
4812 vim_free(buf);
4813
4814 /*
4815 * Count number of names resulting from expansion,
4816 * At the same time add a backslash to the end of names that happen to
4817 * be directories, and replace slashes with backslashes.
4818 */
4819 if (expl_files)
4820 {
4821 for (i = 0; (p = expl_files[i]) != NULL; i++)
4822 {
4823 dir = mch_isdir(p);
4824 /* If we don't want dirs and this is one, skip it */
4825 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
4826 continue;
4827
4828 if (--files_free == 0)
4829 {
4830 /* need more room in table of pointers */
4831 files_alloced += EXPL_ALLOC_INC;
4832 *file = (char_u **)vim_realloc(*file,
4833 sizeof(char_u **) * files_alloced);
4834 if (*file == NULL)
4835 {
4836 EMSG(_(e_outofmem));
4837 *num_file = 0;
4838 return FAIL;
4839 }
4840 files_free = EXPL_ALLOC_INC;
4841 }
4842 slash_adjust(p);
4843 if (dir)
4844 {
4845 /* For a directory we add a '/', unless it's already
4846 * there. */
4847 len = STRLEN(p);
4848 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
4849 {
4850 STRCPY((*file)[*num_file], p);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004851 if (!after_pathsep((*file)[*num_file] + len))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 {
4853 (*file)[*num_file][len] = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004854 (*file)[*num_file][len + 1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
4856 }
4857 }
4858 else
4859 {
4860 (*file)[*num_file] = vim_strsave(p);
4861 }
4862
4863 /*
4864 * Error message already given by either alloc or vim_strsave.
4865 * Should return FAIL, but returning OK works also.
4866 */
4867 if ((*file)[*num_file] == NULL)
4868 break;
4869 (*num_file)++;
4870 }
4871 _fnexplodefree((char **)expl_files);
4872 }
4873 }
4874 return OK;
4875
4876#else /* __EMX__ */
4877
4878 int j;
4879 char_u *tempname;
4880 char_u *command;
4881 FILE *fd;
4882 char_u *buffer;
4883#define STYLE_ECHO 0 /* use "echo" to expand */
4884#define STYLE_GLOB 1 /* use "glob" to expand, for csh */
4885#define STYLE_PRINT 2 /* use "print -N" to expand, for zsh */
4886#define STYLE_BT 3 /* `cmd` expansion, execute the pattern directly */
4887 int shell_style = STYLE_ECHO;
4888 int check_spaces;
4889 static int did_find_nul = FALSE;
4890 int ampersent = FALSE;
4891
4892 *num_file = 0; /* default: no files found */
4893 *file = NULL;
4894
4895 /*
4896 * If there are no wildcards, just copy the names to allocated memory.
4897 * Saves a lot of time, because we don't have to start a new shell.
4898 */
4899 if (!have_wildcard(num_pat, pat))
4900 return save_patterns(num_pat, pat, num_file, file);
4901
Bram Moolenaar0e634da2005-07-20 21:57:28 +00004902# ifdef HAVE_SANDBOX
4903 /* Don't allow any shell command in the sandbox. */
4904 if (sandbox != 0 && check_secure())
4905 return FAIL;
4906# endif
4907
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 /*
4909 * Don't allow the use of backticks in secure and restricted mode.
4910 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00004911 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 for (i = 0; i < num_pat; ++i)
4913 if (vim_strchr(pat[i], '`') != NULL
4914 && (check_restricted() || check_secure()))
4915 return FAIL;
4916
4917 /*
4918 * get a name for the temp file
4919 */
4920 if ((tempname = vim_tempname('o')) == NULL)
4921 {
4922 EMSG(_(e_notmp));
4923 return FAIL;
4924 }
4925
4926 /*
4927 * Let the shell expand the patterns and write the result into the temp
4928 * file. if expanding `cmd` execute it directly.
4929 * If we use csh, glob will work better than echo.
4930 * If we use zsh, print -N will work better than glob.
4931 */
4932 if (num_pat == 1 && *pat[0] == '`'
4933 && (len = STRLEN(pat[0])) > 2
4934 && *(pat[0] + len - 1) == '`')
4935 shell_style = STYLE_BT;
4936 else if ((len = STRLEN(p_sh)) >= 3)
4937 {
4938 if (STRCMP(p_sh + len - 3, "csh") == 0)
4939 shell_style = STYLE_GLOB;
4940 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
4941 shell_style = STYLE_PRINT;
4942 }
4943
4944 /* "unset nonomatch; print -N >" plus two is 29 */
4945 len = STRLEN(tempname) + 29;
Bram Moolenaarb23c3382005-01-31 19:09:12 +00004946 for (i = 0; i < num_pat; ++i)
4947 {
4948 /* Count the length of the patterns in the same way as they are put in
4949 * "command" below. */
4950#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00004952#else
4953 ++len; /* add space */
4954 for (j = 0; pat[i][j] != NUL; )
4955 if (vim_strchr((char_u *)" '", pat[i][j]) != NULL)
4956 {
4957 len += 2; /* add two quotes */
4958 while (pat[i][j] != NUL
4959 && vim_strchr((char_u *)" '", pat[i][j]) != NULL)
4960 {
4961 ++len;
4962 ++j;
4963 }
4964 }
4965 else
4966 {
4967 ++len;
4968 ++j;
4969 }
4970#endif
4971 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 command = alloc(len);
4973 if (command == NULL)
4974 {
4975 /* out of memory */
4976 vim_free(tempname);
4977 return FAIL;
4978 }
4979
4980 /*
4981 * Build the shell command:
4982 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
4983 * recognizes this).
4984 * - Add the shell command to print the expanded names.
4985 * - Add the temp file name.
4986 * - Add the file name patterns.
4987 */
4988 if (shell_style == STYLE_BT)
4989 {
4990 STRCPY(command, pat[0] + 1); /* exclude first backtick */
4991 p = command + STRLEN(command) - 1;
4992 *p = ' '; /* remove last backtick */
4993 while (p > command && vim_iswhite(*p))
4994 --p;
4995 if (*p == '&') /* remove trailing '&' */
4996 {
4997 ampersent = TRUE;
4998 *p = ' ';
4999 }
5000 STRCAT(command, ">");
5001 }
5002 else
5003 {
5004 if (flags & EW_NOTFOUND)
5005 STRCPY(command, "set nonomatch; ");
5006 else
5007 STRCPY(command, "unset nonomatch; ");
5008 if (shell_style == STYLE_GLOB)
5009 STRCAT(command, "glob >");
5010 else if (shell_style == STYLE_PRINT)
5011 STRCAT(command, "print -N >");
5012 else
5013 STRCAT(command, "echo >");
5014 }
5015 STRCAT(command, tempname);
5016 if (shell_style != STYLE_BT)
5017 for (i = 0; i < num_pat; ++i)
5018 {
5019 /* When using system() always add extra quotes, because the shell
5020 * is started twice. Otherwise only put quotes around spaces and
5021 * single quotes. */
5022#ifdef USE_SYSTEM
5023 STRCAT(command, " \"");
5024 STRCAT(command, pat[i]);
5025 STRCAT(command, "\"");
5026#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00005027 int intick = FALSE;
5028
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 p = command + STRLEN(command);
5030 *p++ = ' ';
5031 for (j = 0; pat[i][j] != NUL; )
Bram Moolenaar582fd852005-03-28 20:58:01 +00005032 {
5033 if (pat[i][j] == '`')
5034 {
5035 intick = !intick;
5036 *p++ = pat[i][j++];
5037 }
5038 else if (!intick && vim_strchr((char_u *)" '",
5039 pat[i][j]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 {
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00005041 /* Put quotes around special characters, but not when
5042 * inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 *p++ = '"';
5044 while (pat[i][j] != NUL
5045 && vim_strchr((char_u *)" '", pat[i][j]) != NULL)
5046 *p++ = pat[i][j++];
5047 *p++ = '"';
5048 }
5049 else
Bram Moolenaar0cf6f542005-01-16 21:59:36 +00005050 {
5051 /* For a backslash also copy the next character, don't
5052 * want to put quotes around it. */
5053 if ((*p++ = pat[i][j++]) == '\\' && pat[i][j] != NUL)
5054 *p++ = pat[i][j++];
5055 }
Bram Moolenaar582fd852005-03-28 20:58:01 +00005056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057 *p = NUL;
5058#endif
5059 }
5060 if (flags & EW_SILENT)
5061 show_shell_mess = FALSE;
5062 if (ampersent)
5063 STRCAT(command, "&"); /* put the '&' back after the
5064 redirection */
5065
5066 /*
5067 * Using zsh -G: If a pattern has no matches, it is just deleted from
5068 * the argument list, otherwise zsh gives an error message and doesn't
5069 * expand any other pattern.
5070 */
5071 if (shell_style == STYLE_PRINT)
5072 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5073
5074 /*
5075 * If we use -f then shell variables set in .cshrc won't get expanded.
5076 * vi can do it, so we will too, but it is only necessary if there is a "$"
5077 * in one of the patterns, otherwise we can still use the fast option.
5078 */
5079 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5080 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5081
5082 /*
5083 * execute the shell command
5084 */
5085 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5086
5087 /* When running in the background, give it some time to create the temp
5088 * file, but don't wait for it to finish. */
5089 if (ampersent)
5090 mch_delay(10L, TRUE);
5091
5092 extra_shell_arg = NULL; /* cleanup */
5093 show_shell_mess = TRUE;
5094 vim_free(command);
5095
5096 if (i) /* mch_call_shell() failed */
5097 {
5098 mch_remove(tempname);
5099 vim_free(tempname);
5100 /*
5101 * With interactive completion, the error message is not printed.
5102 * However with USE_SYSTEM, I don't know how to turn off error messages
5103 * from the shell, so screen may still get messed up -- webb.
5104 */
5105#ifndef USE_SYSTEM
5106 if (!(flags & EW_SILENT))
5107#endif
5108 {
5109 redraw_later_clear(); /* probably messed up screen */
5110 msg_putchar('\n'); /* clear bottom line quickly */
5111 cmdline_row = Rows - 1; /* continue on last line */
5112#ifdef USE_SYSTEM
5113 if (!(flags & EW_SILENT))
5114#endif
5115 {
5116 MSG(_(e_wildexpand));
5117 msg_start(); /* don't overwrite this message */
5118 }
5119 }
5120 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5121 * EW_NOTFOUND is given */
5122 if (shell_style == STYLE_BT)
5123 return FAIL;
5124 goto notfound;
5125 }
5126
5127 /*
5128 * read the names from the file into memory
5129 */
5130 fd = fopen((char *)tempname, READBIN);
5131 if (fd == NULL)
5132 {
5133 /* Something went wrong, perhaps a file name with a special char. */
5134 if (!(flags & EW_SILENT))
5135 {
5136 MSG(_(e_wildexpand));
5137 msg_start(); /* don't overwrite this message */
5138 }
5139 vim_free(tempname);
5140 goto notfound;
5141 }
5142 fseek(fd, 0L, SEEK_END);
5143 len = ftell(fd); /* get size of temp file */
5144 fseek(fd, 0L, SEEK_SET);
5145 buffer = alloc(len + 1);
5146 if (buffer == NULL)
5147 {
5148 /* out of memory */
5149 mch_remove(tempname);
5150 vim_free(tempname);
5151 fclose(fd);
5152 return FAIL;
5153 }
5154 i = fread((char *)buffer, 1, len, fd);
5155 fclose(fd);
5156 mch_remove(tempname);
5157 if (i != len)
5158 {
5159 /* unexpected read error */
5160 EMSG2(_(e_notread), tempname);
5161 vim_free(tempname);
5162 vim_free(buffer);
5163 return FAIL;
5164 }
5165 vim_free(tempname);
5166
5167#if defined(__CYGWIN__) || defined(__CYGWIN32__)
5168 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5169 p = buffer;
5170 for (i = 0; i < len; ++i)
5171 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5172 *p++ = buffer[i];
5173 len = p - buffer;
5174# endif
5175
5176
5177 /* file names are separated with Space */
5178 if (shell_style == STYLE_ECHO)
5179 {
5180 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5181 p = buffer;
5182 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5183 {
5184 while (*p != ' ' && *p != '\n')
5185 ++p;
5186 p = skipwhite(p); /* skip to next entry */
5187 }
5188 }
5189 /* file names are separated with NL */
5190 else if (shell_style == STYLE_BT)
5191 {
5192 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5193 p = buffer;
5194 for (i = 0; *p != NUL; ++i) /* count number of entries */
5195 {
5196 while (*p != '\n' && *p != NUL)
5197 ++p;
5198 if (*p != NUL)
5199 ++p;
5200 p = skipwhite(p); /* skip leading white space */
5201 }
5202 }
5203 /* file names are separated with NUL */
5204 else
5205 {
5206 /*
5207 * Some versions of zsh use spaces instead of NULs to separate
5208 * results. Only do this when there is no NUL before the end of the
5209 * buffer, otherwise we would never be able to use file names with
5210 * embedded spaces when zsh does use NULs.
5211 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5212 * don't check for spaces again.
5213 */
5214 check_spaces = FALSE;
5215 if (shell_style == STYLE_PRINT && !did_find_nul)
5216 {
5217 /* If there is a NUL, set did_find_nul, else set check_spaces */
5218 if (len && (int)STRLEN(buffer) < len - 1)
5219 did_find_nul = TRUE;
5220 else
5221 check_spaces = TRUE;
5222 }
5223
5224 /*
5225 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5226 * already is one, for STYLE_GLOB it needs to be added.
5227 */
5228 if (len && buffer[len - 1] == NUL)
5229 --len;
5230 else
5231 buffer[len] = NUL;
5232 i = 0;
5233 for (p = buffer; p < buffer + len; ++p)
5234 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5235 {
5236 ++i;
5237 *p = NUL;
5238 }
5239 if (len)
5240 ++i; /* count last entry */
5241 }
5242 if (i == 0)
5243 {
5244 /*
5245 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5246 * /bin/sh will happily expand it to nothing rather than returning an
5247 * error; and hey, it's good to check anyway -- webb.
5248 */
5249 vim_free(buffer);
5250 goto notfound;
5251 }
5252 *num_file = i;
5253 *file = (char_u **)alloc(sizeof(char_u *) * i);
5254 if (*file == NULL)
5255 {
5256 /* out of memory */
5257 vim_free(buffer);
5258 return FAIL;
5259 }
5260
5261 /*
5262 * Isolate the individual file names.
5263 */
5264 p = buffer;
5265 for (i = 0; i < *num_file; ++i)
5266 {
5267 (*file)[i] = p;
5268 /* Space or NL separates */
5269 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT)
5270 {
5271 while (!(shell_style == STYLE_ECHO && *p == ' ') && *p != '\n')
5272 ++p;
5273 if (p == buffer + len) /* last entry */
5274 *p = NUL;
5275 else
5276 {
5277 *p++ = NUL;
5278 p = skipwhite(p); /* skip to next entry */
5279 }
5280 }
5281 else /* NUL separates */
5282 {
5283 while (*p && p < buffer + len) /* skip entry */
5284 ++p;
5285 ++p; /* skip NUL */
5286 }
5287 }
5288
5289 /*
5290 * Move the file names to allocated memory.
5291 */
5292 for (j = 0, i = 0; i < *num_file; ++i)
5293 {
5294 /* Require the files to exist. Helps when using /bin/sh */
5295 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5296 continue;
5297
5298 /* check if this entry should be included */
5299 dir = (mch_isdir((*file)[i]));
5300 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5301 continue;
5302
5303 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5304 if (p)
5305 {
5306 STRCPY(p, (*file)[i]);
5307 if (dir)
5308 STRCAT(p, "/"); /* add '/' to a directory name */
5309 (*file)[j++] = p;
5310 }
5311 }
5312 vim_free(buffer);
5313 *num_file = j;
5314
5315 if (*num_file == 0) /* rejected all entries */
5316 {
5317 vim_free(*file);
5318 *file = NULL;
5319 goto notfound;
5320 }
5321
5322 return OK;
5323
5324notfound:
5325 if (flags & EW_NOTFOUND)
5326 return save_patterns(num_pat, pat, num_file, file);
5327 return FAIL;
5328
5329#endif /* __EMX__ */
5330}
5331
5332#endif /* VMS */
5333
5334#ifndef __EMX__
5335 static int
5336save_patterns(num_pat, pat, num_file, file)
5337 int num_pat;
5338 char_u **pat;
5339 int *num_file;
5340 char_u ***file;
5341{
5342 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00005343 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344
5345 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5346 if (*file == NULL)
5347 return FAIL;
5348 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00005349 {
5350 s = vim_strsave(pat[i]);
5351 if (s != NULL)
5352 /* Be compatible with expand_filename(): halve the number of
5353 * backslashes. */
5354 backslash_halve(s);
5355 (*file)[i] = s;
5356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005357 *num_file = num_pat;
5358 return OK;
5359}
5360#endif
5361
5362
5363/*
5364 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5365 * expand.
5366 */
5367 int
5368mch_has_exp_wildcard(p)
5369 char_u *p;
5370{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005371 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372 {
5373#ifndef OS2
5374 if (*p == '\\' && p[1] != NUL)
5375 ++p;
5376 else
5377#endif
5378 if (vim_strchr((char_u *)
5379#ifdef VMS
5380 "*?%"
5381#else
5382# ifdef OS2
5383 "*?"
5384# else
5385 "*?[{'"
5386# endif
5387#endif
5388 , *p) != NULL)
5389 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 }
5391 return FALSE;
5392}
5393
5394/*
5395 * Return TRUE if the string "p" contains a wildcard.
5396 * Don't recognize '~' at the end as a wildcard.
5397 */
5398 int
5399mch_has_wildcard(p)
5400 char_u *p;
5401{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005402 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005403 {
5404#ifndef OS2
5405 if (*p == '\\' && p[1] != NUL)
5406 ++p;
5407 else
5408#endif
5409 if (vim_strchr((char_u *)
5410#ifdef VMS
5411 "*?%$"
5412#else
5413# ifdef OS2
5414# ifdef VIM_BACKTICK
5415 "*?$`"
5416# else
5417 "*?$"
5418# endif
5419# else
5420 "*?[{`'$"
5421# endif
5422#endif
5423 , *p) != NULL
5424 || (*p == '~' && p[1] != NUL))
5425 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005426 }
5427 return FALSE;
5428}
5429
5430#ifndef __EMX__
5431 static int
5432have_wildcard(num, file)
5433 int num;
5434 char_u **file;
5435{
5436 int i;
5437
5438 for (i = 0; i < num; i++)
5439 if (mch_has_wildcard(file[i]))
5440 return 1;
5441 return 0;
5442}
5443
5444 static int
5445have_dollars(num, file)
5446 int num;
5447 char_u **file;
5448{
5449 int i;
5450
5451 for (i = 0; i < num; i++)
5452 if (vim_strchr(file[i], '$') != NULL)
5453 return TRUE;
5454 return FALSE;
5455}
5456#endif /* ifndef __EMX__ */
5457
5458#ifndef HAVE_RENAME
5459/*
5460 * Scaled-down version of rename(), which is missing in Xenix.
5461 * This version can only move regular files and will fail if the
5462 * destination exists.
5463 */
5464 int
5465mch_rename(src, dest)
5466 const char *src, *dest;
5467{
5468 struct stat st;
5469
5470 if (stat(dest, &st) >= 0) /* fail if destination exists */
5471 return -1;
5472 if (link(src, dest) != 0) /* link file to new name */
5473 return -1;
5474 if (mch_remove(src) == 0) /* delete link to old name */
5475 return 0;
5476 return -1;
5477}
5478#endif /* !HAVE_RENAME */
5479
5480#ifdef FEAT_MOUSE_GPM
5481/*
5482 * Initializes connection with gpm (if it isn't already opened)
5483 * Return 1 if succeeded (or connection already opened), 0 if failed
5484 */
5485 static int
5486gpm_open()
5487{
5488 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
5489
5490 if (!gpm_flag)
5491 {
5492 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
5493 gpm_connect.defaultMask = ~GPM_HARD;
5494 /* Default handling for mouse move*/
5495 gpm_connect.minMod = 0; /* Handle any modifier keys */
5496 gpm_connect.maxMod = 0xffff;
5497 if (Gpm_Open(&gpm_connect, 0) > 0)
5498 {
5499 /* gpm library tries to handling TSTP causes
5500 * problems. Anyways, we close connection to Gpm whenever
5501 * we are going to suspend or starting an external process
5502 * so we should'nt have problem with this
5503 */
5504 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
5505 return 1; /* succeed */
5506 }
5507 if (gpm_fd == -2)
5508 Gpm_Close(); /* We don't want to talk to xterm via gpm */
5509 return 0;
5510 }
5511 return 1; /* already open */
5512}
5513
5514/*
5515 * Closes connection to gpm
5516 * returns non-zero if connection succesfully closed
5517 */
5518 static void
5519gpm_close()
5520{
5521 if (gpm_flag && gpm_fd >= 0) /* if Open */
5522 Gpm_Close();
5523}
5524
5525/* Reads gpm event and adds special keys to input buf. Returns length of
5526 * generated key sequence.
5527 * This function is made after gui_send_mouse_event
5528 */
5529 static int
5530mch_gpm_process()
5531{
5532 int button;
5533 static Gpm_Event gpm_event;
5534 char_u string[6];
5535 int_u vim_modifiers;
5536 int row,col;
5537 unsigned char buttons_mask;
5538 unsigned char gpm_modifiers;
5539 static unsigned char old_buttons = 0;
5540
5541 Gpm_GetEvent(&gpm_event);
5542
5543#ifdef FEAT_GUI
5544 /* Don't put events in the input queue now. */
5545 if (hold_gui_events)
5546 return 0;
5547#endif
5548
5549 row = gpm_event.y - 1;
5550 col = gpm_event.x - 1;
5551
5552 string[0] = ESC; /* Our termcode */
5553 string[1] = 'M';
5554 string[2] = 'G';
5555 switch (GPM_BARE_EVENTS(gpm_event.type))
5556 {
5557 case GPM_DRAG:
5558 string[3] = MOUSE_DRAG;
5559 break;
5560 case GPM_DOWN:
5561 buttons_mask = gpm_event.buttons & ~old_buttons;
5562 old_buttons = gpm_event.buttons;
5563 switch (buttons_mask)
5564 {
5565 case GPM_B_LEFT:
5566 button = MOUSE_LEFT;
5567 break;
5568 case GPM_B_MIDDLE:
5569 button = MOUSE_MIDDLE;
5570 break;
5571 case GPM_B_RIGHT:
5572 button = MOUSE_RIGHT;
5573 break;
5574 default:
5575 return 0;
5576 /*Don't know what to do. Can more than one button be
5577 * reported in one event? */
5578 }
5579 string[3] = (char_u)(button | 0x20);
5580 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
5581 break;
5582 case GPM_UP:
5583 string[3] = MOUSE_RELEASE;
5584 old_buttons &= ~gpm_event.buttons;
5585 break;
5586 default:
5587 return 0;
5588 }
5589 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
5590 gpm_modifiers = gpm_event.modifiers;
5591 vim_modifiers = 0x0;
5592 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
5593 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
5594 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
5595 */
5596 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
5597 vim_modifiers |= MOUSE_SHIFT;
5598
5599 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
5600 vim_modifiers |= MOUSE_CTRL;
5601 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
5602 vim_modifiers |= MOUSE_ALT;
5603 string[3] |= vim_modifiers;
5604 string[4] = (char_u)(col + ' ' + 1);
5605 string[5] = (char_u)(row + ' ' + 1);
5606 add_to_input_buf(string, 6);
5607 return 6;
5608}
5609#endif /* FEAT_MOUSE_GPM */
5610
5611#if defined(FEAT_LIBCALL) || defined(PROTO)
5612typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
5613typedef char_u * (*INTPROCSTR)__ARGS((int));
5614typedef int (*STRPROCINT)__ARGS((char_u *));
5615typedef int (*INTPROCINT)__ARGS((int));
5616
5617/*
5618 * Call a DLL routine which takes either a string or int param
5619 * and returns an allocated string.
5620 */
5621 int
5622mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
5623 char_u *libname;
5624 char_u *funcname;
5625 char_u *argstring; /* NULL when using a argint */
5626 int argint;
5627 char_u **string_result;/* NULL when using number_result */
5628 int *number_result;
5629{
5630# if defined(USE_DLOPEN)
5631 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005632 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633# else
5634 shl_t hinstLib;
5635# endif
5636 STRPROCSTR ProcAdd;
5637 INTPROCSTR ProcAddI;
5638 char_u *retval_str = NULL;
5639 int retval_int = 0;
5640 int success = FALSE;
5641
5642 /* Get a handle to the DLL module. */
5643# if defined(USE_DLOPEN)
5644 hinstLib = dlopen((char *)libname, RTLD_LAZY
5645# ifdef RTLD_LOCAL
5646 | RTLD_LOCAL
5647# endif
5648 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005649 if (hinstLib == NULL)
5650 {
5651 /* "dlerr" must be used before dlclose() */
5652 dlerr = (char *)dlerror();
5653 if (dlerr != NULL)
5654 EMSG2(_("dlerror = \"%s\""), dlerr);
5655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656# else
5657 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
5658# endif
5659
5660 /* If the handle is valid, try to get the function address. */
5661 if (hinstLib != NULL)
5662 {
5663# ifdef HAVE_SETJMP_H
5664 /*
5665 * Catch a crash when calling the library function. For example when
5666 * using a number where a string pointer is expected.
5667 */
5668 mch_startjmp();
5669 if (SETJMP(lc_jump_env) != 0)
5670 {
5671 success = FALSE;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005672 dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 mch_didjmp();
5674 }
5675 else
5676# endif
5677 {
5678 retval_str = NULL;
5679 retval_int = 0;
5680
5681 if (argstring != NULL)
5682 {
5683# if defined(USE_DLOPEN)
5684 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005685 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686# else
5687 if (shl_findsym(&hinstLib, (const char *)funcname,
5688 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
5689 ProcAdd = NULL;
5690# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005691 if ((success = (ProcAdd != NULL
5692# if defined(USE_DLOPEN)
5693 && dlerr == NULL
5694# endif
5695 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 {
5697 if (string_result == NULL)
5698 retval_int = ((STRPROCINT)ProcAdd)(argstring);
5699 else
5700 retval_str = (ProcAdd)(argstring);
5701 }
5702 }
5703 else
5704 {
5705# if defined(USE_DLOPEN)
5706 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005707 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708# else
5709 if (shl_findsym(&hinstLib, (const char *)funcname,
5710 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
5711 ProcAddI = NULL;
5712# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005713 if ((success = (ProcAddI != NULL
5714# if defined(USE_DLOPEN)
5715 && dlerr == NULL
5716# endif
5717 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 {
5719 if (string_result == NULL)
5720 retval_int = ((INTPROCINT)ProcAddI)(argint);
5721 else
5722 retval_str = (ProcAddI)(argint);
5723 }
5724 }
5725
5726 /* Save the string before we free the library. */
5727 /* Assume that a "1" or "-1" result is an illegal pointer. */
5728 if (string_result == NULL)
5729 *number_result = retval_int;
5730 else if (retval_str != NULL
5731 && retval_str != (char_u *)1
5732 && retval_str != (char_u *)-1)
5733 *string_result = vim_strsave(retval_str);
5734 }
5735
5736# ifdef HAVE_SETJMP_H
5737 mch_endjmp();
5738# ifdef SIGHASARG
5739 if (lc_signal != 0)
5740 {
5741 int i;
5742
5743 /* try to find the name of this signal */
5744 for (i = 0; signal_info[i].sig != -1; i++)
5745 if (lc_signal == signal_info[i].sig)
5746 break;
5747 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
5748 }
5749# endif
5750# endif
5751
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00005753 /* "dlerr" must be used before dlclose() */
5754 if (dlerr != NULL)
5755 EMSG2(_("dlerror = \"%s\""), dlerr);
5756
5757 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 (void)dlclose(hinstLib);
5759# else
5760 (void)shl_unload(hinstLib);
5761# endif
5762 }
5763
5764 if (!success)
5765 {
5766 EMSG2(_(e_libcall), funcname);
5767 return FAIL;
5768 }
5769
5770 return OK;
5771}
5772#endif
5773
5774#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
5775static int xterm_trace = -1; /* default: disabled */
5776static int xterm_button;
5777
5778/*
5779 * Setup a dummy window for X selections in a terminal.
5780 */
5781 void
5782setup_term_clip()
5783{
5784 int z = 0;
5785 char *strp = "";
5786 Widget AppShell;
5787
5788 if (!x_connect_to_server())
5789 return;
5790
5791 open_app_context();
5792 if (app_context != NULL && xterm_Shell == (Widget)0)
5793 {
5794 int (*oldhandler)();
5795#if defined(HAVE_SETJMP_H)
5796 int (*oldIOhandler)();
5797#endif
5798# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5799 struct timeval start_tv;
5800
5801 if (p_verbose > 0)
5802 gettimeofday(&start_tv, NULL);
5803# endif
5804
5805 /* Ignore X errors while opening the display */
5806 oldhandler = XSetErrorHandler(x_error_check);
5807
5808#if defined(HAVE_SETJMP_H)
5809 /* Ignore X IO errors while opening the display */
5810 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
5811 mch_startjmp();
5812 if (SETJMP(lc_jump_env) != 0)
5813 {
5814 mch_didjmp();
5815 xterm_dpy = NULL;
5816 }
5817 else
5818#endif
5819 {
5820 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
5821 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
5822#if defined(HAVE_SETJMP_H)
5823 mch_endjmp();
5824#endif
5825 }
5826
5827#if defined(HAVE_SETJMP_H)
5828 /* Now handle X IO errors normally. */
5829 (void)XSetIOErrorHandler(oldIOhandler);
5830#endif
5831 /* Now handle X errors normally. */
5832 (void)XSetErrorHandler(oldhandler);
5833
5834 if (xterm_dpy == NULL)
5835 {
5836 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005837 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838 return;
5839 }
5840
5841 /* Catch terminating error of the X server connection. */
5842 (void)XSetIOErrorHandler(x_IOerror_handler);
5843
5844# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5845 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005846 {
5847 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 xopen_message(&start_tv);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00005849 verbose_leave();
5850 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851# endif
5852
5853 /* Create a Shell to make converters work. */
5854 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
5855 applicationShellWidgetClass, xterm_dpy,
5856 NULL);
5857 if (AppShell == (Widget)0)
5858 return;
5859 xterm_Shell = XtVaCreatePopupShell("VIM",
5860 topLevelShellWidgetClass, AppShell,
5861 XtNmappedWhenManaged, 0,
5862 XtNwidth, 1,
5863 XtNheight, 1,
5864 NULL);
5865 if (xterm_Shell == (Widget)0)
5866 return;
5867
5868 x11_setup_atoms(xterm_dpy);
5869 if (x11_display == NULL)
5870 x11_display = xterm_dpy;
5871
5872 XtRealizeWidget(xterm_Shell);
5873 XSync(xterm_dpy, False);
5874 xterm_update();
5875 }
5876 if (xterm_Shell != (Widget)0)
5877 {
5878 clip_init(TRUE);
5879 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
5880 x11_window = (Window)atol(strp);
5881 /* Check if $WINDOWID is valid. */
5882 if (test_x11_window(xterm_dpy) == FAIL)
5883 x11_window = 0;
5884 if (x11_window != 0)
5885 xterm_trace = 0;
5886 }
5887}
5888
5889 void
5890start_xterm_trace(button)
5891 int button;
5892{
5893 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
5894 return;
5895 xterm_trace = 1;
5896 xterm_button = button;
5897 do_xterm_trace();
5898}
5899
5900
5901 void
5902stop_xterm_trace()
5903{
5904 if (xterm_trace < 0)
5905 return;
5906 xterm_trace = 0;
5907}
5908
5909/*
5910 * Query the xterm pointer and generate mouse termcodes if necessary
5911 * return TRUE if dragging is active, else FALSE
5912 */
5913 static int
5914do_xterm_trace()
5915{
5916 Window root, child;
5917 int root_x, root_y;
5918 int win_x, win_y;
5919 int row, col;
5920 int_u mask_return;
5921 char_u buf[50];
5922 char_u *strp;
5923 long got_hints;
5924 static char_u *mouse_code;
5925 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
5926 static int prev_row = 0, prev_col = 0;
5927 static XSizeHints xterm_hints;
5928
5929 if (xterm_trace <= 0)
5930 return FALSE;
5931
5932 if (xterm_trace == 1)
5933 {
5934 /* Get the hints just before tracking starts. The font size might
5935 * have changed recently */
5936 XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints);
5937 if (!(got_hints & PResizeInc)
5938 || xterm_hints.width_inc <= 1
5939 || xterm_hints.height_inc <= 1)
5940 {
5941 xterm_trace = -1; /* Not enough data -- disable tracing */
5942 return FALSE;
5943 }
5944
5945 /* Rely on the same mouse code for the duration of this */
5946 mouse_code = find_termcode(mouse_name);
5947 prev_row = mouse_row;
5948 prev_row = mouse_col;
5949 xterm_trace = 2;
5950
5951 /* Find the offset of the chars, there might be a scrollbar on the
5952 * left of the window and/or a menu on the top (eterm etc.) */
5953 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
5954 &win_x, &win_y, &mask_return);
5955 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
5956 - (xterm_hints.height_inc / 2);
5957 if (xterm_hints.y <= xterm_hints.height_inc / 2)
5958 xterm_hints.y = 2;
5959 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
5960 - (xterm_hints.width_inc / 2);
5961 if (xterm_hints.x <= xterm_hints.width_inc / 2)
5962 xterm_hints.x = 2;
5963 return TRUE;
5964 }
5965 if (mouse_code == NULL)
5966 {
5967 xterm_trace = 0;
5968 return FALSE;
5969 }
5970
5971 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
5972 &win_x, &win_y, &mask_return);
5973
5974 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
5975 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
5976 if (row == prev_row && col == prev_col)
5977 return TRUE;
5978
5979 STRCPY(buf, mouse_code);
5980 strp = buf + STRLEN(buf);
5981 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
5982 *strp++ = (char_u)(col + ' ' + 1);
5983 *strp++ = (char_u)(row + ' ' + 1);
5984 *strp = 0;
5985 add_to_input_buf(buf, STRLEN(buf));
5986
5987 prev_row = row;
5988 prev_col = col;
5989 return TRUE;
5990}
5991
5992# if defined(FEAT_GUI) || defined(PROTO)
5993/*
5994 * Destroy the display, window and app_context. Required for GTK.
5995 */
5996 void
5997clear_xterm_clip()
5998{
5999 if (xterm_Shell != (Widget)0)
6000 {
6001 XtDestroyWidget(xterm_Shell);
6002 xterm_Shell = (Widget)0;
6003 }
6004 if (xterm_dpy != NULL)
6005 {
6006#if 0
6007 /* Lesstif and Solaris crash here, lose some memory */
6008 XtCloseDisplay(xterm_dpy);
6009#endif
6010 if (x11_display == xterm_dpy)
6011 x11_display = NULL;
6012 xterm_dpy = NULL;
6013 }
6014#if 0
6015 if (app_context != (XtAppContext)NULL)
6016 {
6017 /* Lesstif and Solaris crash here, lose some memory */
6018 XtDestroyApplicationContext(app_context);
6019 app_context = (XtAppContext)NULL;
6020 }
6021#endif
6022}
6023# endif
6024
6025/*
6026 * Catch up with any queued X events. This may put keyboard input into the
6027 * input buffer, call resize call-backs, trigger timers etc. If there is
6028 * nothing in the X event queue (& no timers pending), then we return
6029 * immediately.
6030 */
6031 static void
6032xterm_update()
6033{
6034 XEvent event;
6035
6036 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6037 {
6038 XtAppNextEvent(app_context, &event);
6039#ifdef FEAT_CLIENTSERVER
6040 {
6041 XPropertyEvent *e = (XPropertyEvent *)&event;
6042
6043 if (e->type == PropertyNotify && e->window == commWindow
6044 && e->atom == commProperty && e->state == PropertyNewValue)
6045 serverEventProc(xterm_dpy, &event);
6046 }
6047#endif
6048 XtDispatchEvent(&event);
6049 }
6050}
6051
6052 int
6053clip_xterm_own_selection(cbd)
6054 VimClipboard *cbd;
6055{
6056 if (xterm_Shell != (Widget)0)
6057 return clip_x11_own_selection(xterm_Shell, cbd);
6058 return FAIL;
6059}
6060
6061 void
6062clip_xterm_lose_selection(cbd)
6063 VimClipboard *cbd;
6064{
6065 if (xterm_Shell != (Widget)0)
6066 clip_x11_lose_selection(xterm_Shell, cbd);
6067}
6068
6069 void
6070clip_xterm_request_selection(cbd)
6071 VimClipboard *cbd;
6072{
6073 if (xterm_Shell != (Widget)0)
6074 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6075}
6076
6077 void
6078clip_xterm_set_selection(cbd)
6079 VimClipboard *cbd;
6080{
6081 clip_x11_set_selection(cbd);
6082}
6083#endif
6084
6085
6086#if defined(USE_XSMP) || defined(PROTO)
6087/*
6088 * Code for X Session Management Protocol.
6089 */
6090static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6091static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6092static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6093static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6094static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6095
6096
6097# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6098static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6099
6100/*
6101 * This is our chance to ask the user if they want to save,
6102 * or abort the logout
6103 */
6104/*ARGSUSED*/
6105 static void
6106xsmp_handle_interaction(smc_conn, client_data)
6107 SmcConn smc_conn;
6108 SmPointer client_data;
6109{
6110 cmdmod_T save_cmdmod;
6111 int cancel_shutdown = False;
6112
6113 save_cmdmod = cmdmod;
6114 cmdmod.confirm = TRUE;
6115 if (check_changed_any(FALSE))
6116 /* Mustn't logout */
6117 cancel_shutdown = True;
6118 cmdmod = save_cmdmod;
6119 setcursor(); /* position cursor */
6120 out_flush();
6121
6122 /* Done interaction */
6123 SmcInteractDone(smc_conn, cancel_shutdown);
6124
6125 /* Finish off
6126 * Only end save-yourself here if we're not cancelling shutdown;
6127 * we'll get a cancelled callback later in which we'll end it.
6128 * Hopefully get around glitchy SMs (like GNOME-1)
6129 */
6130 if (!cancel_shutdown)
6131 {
6132 xsmp.save_yourself = False;
6133 SmcSaveYourselfDone(smc_conn, True);
6134 }
6135}
6136# endif
6137
6138/*
6139 * Callback that starts save-yourself.
6140 */
6141/*ARGSUSED*/
6142 static void
6143xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6144 shutdown, interact_style, fast)
6145 SmcConn smc_conn;
6146 SmPointer client_data;
6147 int save_type;
6148 Bool shutdown;
6149 int interact_style;
6150 Bool fast;
6151{
6152 /* Handle already being in saveyourself */
6153 if (xsmp.save_yourself)
6154 SmcSaveYourselfDone(smc_conn, True);
6155 xsmp.save_yourself = True;
6156 xsmp.shutdown = shutdown;
6157
6158 /* First up, preserve all files */
6159 out_flush();
6160 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6161
6162 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006163 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164
6165# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6166 /* Now see if we can ask about unsaved files */
6167 if (shutdown && !fast && gui.in_use)
6168 /* Need to interact with user, but need SM's permission */
6169 SmcInteractRequest(smc_conn, SmDialogError,
6170 xsmp_handle_interaction, client_data);
6171 else
6172# endif
6173 {
6174 /* Can stop the cycle here */
6175 SmcSaveYourselfDone(smc_conn, True);
6176 xsmp.save_yourself = False;
6177 }
6178}
6179
6180
6181/*
6182 * Callback to warn us of imminent death.
6183 */
6184/*ARGSUSED*/
6185 static void
6186xsmp_die(smc_conn, client_data)
6187 SmcConn smc_conn;
6188 SmPointer client_data;
6189{
6190 xsmp_close();
6191
6192 /* quit quickly leaving swapfiles for modified buffers behind */
6193 getout_preserve_modified(0);
6194}
6195
6196
6197/*
6198 * Callback to tell us that save-yourself has completed.
6199 */
6200/*ARGSUSED*/
6201 static void
6202xsmp_save_complete(smc_conn, client_data)
6203 SmcConn smc_conn;
6204 SmPointer client_data;
6205{
6206 xsmp.save_yourself = False;
6207}
6208
6209
6210/*
6211 * Callback to tell us that an instigated shutdown was cancelled
6212 * (maybe even by us)
6213 */
6214/*ARGSUSED*/
6215 static void
6216xsmp_shutdown_cancelled(smc_conn, client_data)
6217 SmcConn smc_conn;
6218 SmPointer client_data;
6219{
6220 if (xsmp.save_yourself)
6221 SmcSaveYourselfDone(smc_conn, True);
6222 xsmp.save_yourself = False;
6223 xsmp.shutdown = False;
6224}
6225
6226
6227/*
6228 * Callback to tell us that a new ICE connection has been established.
6229 */
6230/*ARGSUSED*/
6231 static void
6232xsmp_ice_connection(iceConn, clientData, opening, watchData)
6233 IceConn iceConn;
6234 IcePointer clientData;
6235 Bool opening;
6236 IcePointer *watchData;
6237{
6238 /* Intercept creation of ICE connection fd */
6239 if (opening)
6240 {
6241 xsmp_icefd = IceConnectionNumber(iceConn);
6242 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6243 }
6244}
6245
6246
6247/* Handle any ICE processing that's required; return FAIL if SM lost */
6248 int
6249xsmp_handle_requests()
6250{
6251 Bool rep;
6252
6253 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6254 == IceProcessMessagesIOError)
6255 {
6256 /* Lost ICE */
6257 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006258 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 xsmp_close();
6260 return FAIL;
6261 }
6262 else
6263 return OK;
6264}
6265
6266static int dummy;
6267
6268/* Set up X Session Management Protocol */
6269 void
6270xsmp_init(void)
6271{
6272 char errorstring[80];
6273 char *clientid;
6274 SmcCallbacks smcallbacks;
6275#if 0
6276 SmPropValue smname;
6277 SmProp smnameprop;
6278 SmProp *smprops[1];
6279#endif
6280
6281 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006282 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283
6284 xsmp.save_yourself = xsmp.shutdown = False;
6285
6286 /* Set up SM callbacks - must have all, even if they're not used */
6287 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6288 smcallbacks.save_yourself.client_data = NULL;
6289 smcallbacks.die.callback = xsmp_die;
6290 smcallbacks.die.client_data = NULL;
6291 smcallbacks.save_complete.callback = xsmp_save_complete;
6292 smcallbacks.save_complete.client_data = NULL;
6293 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6294 smcallbacks.shutdown_cancelled.client_data = NULL;
6295
6296 /* Set up a watch on ICE connection creations. The "dummy" argument is
6297 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6298 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6299 {
6300 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006301 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 return;
6303 }
6304
6305 /* Create an SM connection */
6306 xsmp.smcconn = SmcOpenConnection(
6307 NULL,
6308 NULL,
6309 SmProtoMajor,
6310 SmProtoMinor,
6311 SmcSaveYourselfProcMask | SmcDieProcMask
6312 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6313 &smcallbacks,
6314 NULL,
6315 &clientid,
6316 sizeof(errorstring),
6317 errorstring);
6318 if (xsmp.smcconn == NULL)
6319 {
6320 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00006321
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006323 {
6324 vim_snprintf(errorreport, sizeof(errorreport),
6325 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6326 verb_msg((char_u *)errorreport);
6327 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 return;
6329 }
6330 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6331
6332#if 0
6333 /* ID ourselves */
6334 smname.value = "vim";
6335 smname.length = 3;
6336 smnameprop.name = "SmProgram";
6337 smnameprop.type = "SmARRAY8";
6338 smnameprop.num_vals = 1;
6339 smnameprop.vals = &smname;
6340
6341 smprops[0] = &smnameprop;
6342 SmcSetProperties(xsmp.smcconn, 1, smprops);
6343#endif
6344}
6345
6346
6347/* Shut down XSMP comms. */
6348 void
6349xsmp_close()
6350{
6351 if (xsmp_icefd != -1)
6352 {
6353 SmcCloseConnection(xsmp.smcconn, 0, NULL);
6354 xsmp_icefd = -1;
6355 }
6356}
6357#endif /* USE_XSMP */
6358
6359
6360#ifdef EBCDIC
6361/* Translate character to its CTRL- value */
6362char CtrlTable[] =
6363{
6364/* 00 - 5E */
6365 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6366 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6367 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6368 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6369 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6370 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6371/* ^ */ 0x1E,
6372/* - */ 0x1F,
6373/* 61 - 6C */
6374 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6375/* _ */ 0x1F,
6376/* 6E - 80 */
6377 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6378/* a */ 0x01,
6379/* b */ 0x02,
6380/* c */ 0x03,
6381/* d */ 0x37,
6382/* e */ 0x2D,
6383/* f */ 0x2E,
6384/* g */ 0x2F,
6385/* h */ 0x16,
6386/* i */ 0x05,
6387/* 8A - 90 */
6388 0, 0, 0, 0, 0, 0, 0,
6389/* j */ 0x15,
6390/* k */ 0x0B,
6391/* l */ 0x0C,
6392/* m */ 0x0D,
6393/* n */ 0x0E,
6394/* o */ 0x0F,
6395/* p */ 0x10,
6396/* q */ 0x11,
6397/* r */ 0x12,
6398/* 9A - A1 */
6399 0, 0, 0, 0, 0, 0, 0, 0,
6400/* s */ 0x13,
6401/* t */ 0x3C,
6402/* u */ 0x3D,
6403/* v */ 0x32,
6404/* w */ 0x26,
6405/* x */ 0x18,
6406/* y */ 0x19,
6407/* z */ 0x3F,
6408/* AA - AC */
6409 0, 0, 0,
6410/* [ */ 0x27,
6411/* AE - BC */
6412 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6413/* ] */ 0x1D,
6414/* BE - C0 */ 0, 0, 0,
6415/* A */ 0x01,
6416/* B */ 0x02,
6417/* C */ 0x03,
6418/* D */ 0x37,
6419/* E */ 0x2D,
6420/* F */ 0x2E,
6421/* G */ 0x2F,
6422/* H */ 0x16,
6423/* I */ 0x05,
6424/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
6425/* J */ 0x15,
6426/* K */ 0x0B,
6427/* L */ 0x0C,
6428/* M */ 0x0D,
6429/* N */ 0x0E,
6430/* O */ 0x0F,
6431/* P */ 0x10,
6432/* Q */ 0x11,
6433/* R */ 0x12,
6434/* DA - DF */ 0, 0, 0, 0, 0, 0,
6435/* \ */ 0x1C,
6436/* E1 */ 0,
6437/* S */ 0x13,
6438/* T */ 0x3C,
6439/* U */ 0x3D,
6440/* V */ 0x32,
6441/* W */ 0x26,
6442/* X */ 0x18,
6443/* Y */ 0x19,
6444/* Z */ 0x3F,
6445/* EA - FF*/ 0, 0, 0, 0, 0, 0,
6446 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6447};
6448
6449char MetaCharTable[]=
6450{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6451 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
6452 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
6453 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
6454 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
6455};
6456
6457
6458/* TODO: Use characters NOT numbers!!! */
6459char CtrlCharTable[]=
6460{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6461 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
6462 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
6463 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
6464 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
6465};
6466
6467
6468#endif