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