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