Merge commit 'svn-vim'
[MacVim.git] / src / os_unix.c
blobb196175212c3bc529859ebfde69b81c995a60574
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
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.
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.
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
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?
28 #if !defined(__APPLE__) && !defined(__TANDEM)
29 # define select select_declared_wrong
30 #endif
32 #include "vim.h"
34 #ifdef FEAT_MZSCHEME
35 # include "if_mzsch.h"
36 #endif
38 #ifdef HAVE_FCNTL_H
39 # include <fcntl.h>
40 #endif
42 #include "os_unixx.h" /* unix includes for os_unix.c only */
44 #ifdef USE_XSMP
45 # include <X11/SM/SMlib.h>
46 #endif
49 * Use this prototype for select, some include files have a wrong prototype
51 #ifndef __TANDEM
52 # undef select
53 # ifdef __BEOS__
54 # define select beos_select
55 # endif
56 #endif
58 #ifdef __CYGWIN__
59 # ifndef WIN32
60 # include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() */
61 # endif
62 #endif
64 #if defined(HAVE_SELECT)
65 extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *));
66 #endif
68 #ifdef FEAT_MOUSE_GPM
69 # include <gpm.h>
70 /* <linux/keyboard.h> contains defines conflicting with "keymap.h",
71 * I just copied relevant defines here. A cleaner solution would be to put gpm
72 * code into separate file and include there linux/keyboard.h
74 /* #include <linux/keyboard.h> */
75 # define KG_SHIFT 0
76 # define KG_CTRL 2
77 # define KG_ALT 3
78 # define KG_ALTGR 1
79 # define KG_SHIFTL 4
80 # define KG_SHIFTR 5
81 # define KG_CTRLL 6
82 # define KG_CTRLR 7
83 # define KG_CAPSSHIFT 8
85 static void gpm_close __ARGS((void));
86 static int gpm_open __ARGS((void));
87 static int mch_gpm_process __ARGS((void));
88 #endif
91 * end of autoconf section. To be extended...
94 /* Are the following #ifdefs still required? And why? Is that for X11? */
96 #if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
97 # ifdef SIGWINCH
98 # undef SIGWINCH
99 # endif
100 # ifdef TIOCGWINSZ
101 # undef TIOCGWINSZ
102 # endif
103 #endif
105 #if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
106 # define SIGWINCH SIGWINDOW
107 #endif
109 #ifdef FEAT_X11
110 # include <X11/Xlib.h>
111 # include <X11/Xutil.h>
112 # include <X11/Xatom.h>
113 # ifdef FEAT_XCLIPBOARD
114 # include <X11/Intrinsic.h>
115 # include <X11/Shell.h>
116 # include <X11/StringDefs.h>
117 static Widget xterm_Shell = (Widget)0;
118 static void xterm_update __ARGS((void));
119 # endif
121 # if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
122 Window x11_window = 0;
123 # endif
124 Display *x11_display = NULL;
126 # ifdef FEAT_TITLE
127 static int get_x11_windis __ARGS((void));
128 static void set_x11_title __ARGS((char_u *));
129 static void set_x11_icon __ARGS((char_u *));
130 # endif
131 #endif
133 #ifdef FEAT_TITLE
134 static int get_x11_title __ARGS((int));
135 static int get_x11_icon __ARGS((int));
137 static char_u *oldtitle = NULL;
138 static int did_set_title = FALSE;
139 static char_u *oldicon = NULL;
140 static int did_set_icon = FALSE;
141 #endif
143 static void may_core_dump __ARGS((void));
145 static int WaitForChar __ARGS((long));
146 #if defined(__BEOS__)
147 int RealWaitForChar __ARGS((int, long, int *));
148 #else
149 static int RealWaitForChar __ARGS((int, long, int *));
150 #endif
152 #ifdef FEAT_XCLIPBOARD
153 static int do_xterm_trace __ARGS((void));
154 # define XT_TRACE_DELAY 50 /* delay for xterm tracing */
155 #endif
157 static void handle_resize __ARGS((void));
159 #if defined(SIGWINCH)
160 static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG);
161 #endif
162 #if defined(SIGINT)
163 static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG);
164 #endif
165 #if defined(SIGPWR)
166 static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG);
167 #endif
168 #if defined(SIGALRM) && defined(FEAT_X11) \
169 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
170 # define SET_SIG_ALARM
171 static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG);
172 static int sig_alarm_called;
173 #endif
174 static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG);
176 static void catch_int_signal __ARGS((void));
177 static void set_signals __ARGS((void));
178 static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)()));
179 #ifndef __EMX__
180 static int have_wildcard __ARGS((int, char_u **));
181 static int have_dollars __ARGS((int, char_u **));
182 #endif
184 #ifndef __EMX__
185 static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file));
186 #endif
188 #ifndef SIG_ERR
189 # define SIG_ERR ((RETSIGTYPE (*)())-1)
190 #endif
192 static int do_resize = FALSE;
193 #ifndef __EMX__
194 static char_u *extra_shell_arg = NULL;
195 static int show_shell_mess = TRUE;
196 #endif
197 static int deadly_signal = 0; /* The signal we caught */
199 static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
201 #ifdef USE_XSMP
202 typedef struct
204 SmcConn smcconn; /* The SM connection ID */
205 IceConn iceconn; /* The ICE connection ID */
206 Bool save_yourself; /* If we're in the middle of a save_yourself */
207 Bool shutdown; /* If we're in shutdown mode */
208 } xsmp_config_T;
210 static xsmp_config_T xsmp;
211 #endif
213 #ifdef SYS_SIGLIST_DECLARED
215 * I have seen
216 * extern char *_sys_siglist[NSIG];
217 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
218 * that describe the signals. That is nearly what we want here. But
219 * autoconf does only check for sys_siglist (without the underscore), I
220 * do not want to change everything today.... jw.
221 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in
223 #endif
225 static struct signalinfo
227 int sig; /* Signal number, eg. SIGSEGV etc */
228 char *name; /* Signal name (not char_u!). */
229 char deadly; /* Catch as a deadly signal? */
230 } signal_info[] =
232 #ifdef SIGHUP
233 {SIGHUP, "HUP", TRUE},
234 #endif
235 #ifdef SIGQUIT
236 {SIGQUIT, "QUIT", TRUE},
237 #endif
238 #ifdef SIGILL
239 {SIGILL, "ILL", TRUE},
240 #endif
241 #ifdef SIGTRAP
242 {SIGTRAP, "TRAP", TRUE},
243 #endif
244 #ifdef SIGABRT
245 {SIGABRT, "ABRT", TRUE},
246 #endif
247 #ifdef SIGEMT
248 {SIGEMT, "EMT", TRUE},
249 #endif
250 #ifdef SIGFPE
251 {SIGFPE, "FPE", TRUE},
252 #endif
253 #ifdef SIGBUS
254 {SIGBUS, "BUS", TRUE},
255 #endif
256 #ifdef SIGSEGV
257 {SIGSEGV, "SEGV", TRUE},
258 #endif
259 #ifdef SIGSYS
260 {SIGSYS, "SYS", TRUE},
261 #endif
262 #ifdef SIGALRM
263 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
264 #endif
265 #ifdef SIGTERM
266 {SIGTERM, "TERM", TRUE},
267 #endif
268 #ifdef SIGVTALRM
269 {SIGVTALRM, "VTALRM", TRUE},
270 #endif
271 #if defined(SIGPROF) && !defined(FEAT_MZSCHEME)
272 /* MzScheme uses SIGPROF for its own needs */
273 {SIGPROF, "PROF", TRUE},
274 #endif
275 #ifdef SIGXCPU
276 {SIGXCPU, "XCPU", TRUE},
277 #endif
278 #ifdef SIGXFSZ
279 {SIGXFSZ, "XFSZ", TRUE},
280 #endif
281 #ifdef SIGUSR1
282 {SIGUSR1, "USR1", TRUE},
283 #endif
284 #ifdef SIGUSR2
285 {SIGUSR2, "USR2", TRUE},
286 #endif
287 #ifdef SIGINT
288 {SIGINT, "INT", FALSE},
289 #endif
290 #ifdef SIGWINCH
291 {SIGWINCH, "WINCH", FALSE},
292 #endif
293 #ifdef SIGTSTP
294 {SIGTSTP, "TSTP", FALSE},
295 #endif
296 #ifdef SIGPIPE
297 {SIGPIPE, "PIPE", FALSE},
298 #endif
299 {-1, "Unknown!", FALSE}
302 void
303 mch_write(s, len)
304 char_u *s;
305 int len;
307 write(1, (char *)s, len);
308 if (p_wd) /* Unix is too fast, slow down a bit more */
309 RealWaitForChar(read_cmd_fd, p_wd, NULL);
313 * mch_inchar(): low level input function.
314 * Get a characters from the keyboard.
315 * Return the number of characters that are available.
316 * If wtime == 0 do not wait for characters.
317 * If wtime == n wait a short time for characters.
318 * If wtime == -1 wait forever for characters.
321 mch_inchar(buf, maxlen, wtime, tb_change_cnt)
322 char_u *buf;
323 int maxlen;
324 long wtime; /* don't use "time", MIPS cannot handle it */
325 int tb_change_cnt;
327 int len;
329 /* Check if window changed size while we were busy, perhaps the ":set
330 * columns=99" command was used. */
331 while (do_resize)
332 handle_resize();
334 if (wtime >= 0)
336 while (WaitForChar(wtime) == 0) /* no character available */
338 if (!do_resize) /* return if not interrupted by resize */
339 return 0;
340 handle_resize();
343 else /* wtime == -1 */
346 * If there is no character available within 'updatetime' seconds
347 * flush all the swap files to disk.
348 * Also done when interrupted by SIGWINCH.
350 if (WaitForChar(p_ut) == 0)
352 #ifdef FEAT_AUTOCMD
353 if (trigger_cursorhold() && maxlen >= 3
354 && !typebuf_changed(tb_change_cnt))
356 buf[0] = K_SPECIAL;
357 buf[1] = KS_EXTRA;
358 buf[2] = (int)KE_CURSORHOLD;
359 return 3;
361 #endif
362 before_blocking();
366 for (;;) /* repeat until we got a character */
368 while (do_resize) /* window changed size */
369 handle_resize();
371 * we want to be interrupted by the winch signal
373 WaitForChar(-1L);
374 if (do_resize) /* interrupted by SIGWINCH signal */
375 continue;
377 /* If input was put directly in typeahead buffer bail out here. */
378 if (typebuf_changed(tb_change_cnt))
379 return 0;
382 * For some terminals we only get one character at a time.
383 * We want the get all available characters, so we could keep on
384 * trying until none is available
385 * For some other terminals this is quite slow, that's why we don't do
386 * it.
388 len = read_from_input_buf(buf, (long)maxlen);
389 if (len > 0)
391 #ifdef OS2
392 int i;
394 for (i = 0; i < len; i++)
395 if (buf[i] == 0)
396 buf[i] = K_NUL;
397 #endif
398 return len;
403 static void
404 handle_resize()
406 do_resize = FALSE;
407 shell_resized();
411 * return non-zero if a character is available
414 mch_char_avail()
416 return WaitForChar(0L);
419 #if defined(HAVE_TOTAL_MEM) || defined(PROTO)
420 # ifdef HAVE_SYS_RESOURCE_H
421 # include <sys/resource.h>
422 # endif
423 # if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
424 # include <sys/sysctl.h>
425 # endif
426 # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
427 # include <sys/sysinfo.h>
428 # endif
431 * Return total amount of memory available in Kbyte.
432 * Doesn't change when memory has been allocated.
434 /* ARGSUSED */
435 long_u
436 mch_total_mem(special)
437 int special;
439 # ifdef __EMX__
440 return ulimit(3, 0L) >> 10; /* always 32MB? */
441 # else
442 long_u mem = 0;
443 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
445 # ifdef HAVE_SYSCTL
446 int mib[2], physmem;
447 size_t len;
449 /* BSD way of getting the amount of RAM available. */
450 mib[0] = CTL_HW;
451 mib[1] = HW_USERMEM;
452 len = sizeof(physmem);
453 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
454 mem = (long_u)physmem;
455 # endif
457 # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
458 if (mem == 0)
460 struct sysinfo sinfo;
462 /* Linux way of getting amount of RAM available */
463 if (sysinfo(&sinfo) == 0)
465 # ifdef HAVE_SYSINFO_MEM_UNIT
466 /* avoid overflow as much as possible */
467 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
469 sinfo.mem_unit = sinfo.mem_unit >> 1;
470 --shiftright;
472 mem = sinfo.totalram * sinfo.mem_unit;
473 # else
474 mem = sinfo.totalram;
475 # endif
478 # endif
480 # ifdef HAVE_SYSCONF
481 if (mem == 0)
483 long pagesize, pagecount;
485 /* Solaris way of getting amount of RAM available */
486 pagesize = sysconf(_SC_PAGESIZE);
487 pagecount = sysconf(_SC_PHYS_PAGES);
488 if (pagesize > 0 && pagecount > 0)
490 /* avoid overflow as much as possible */
491 while (shiftright > 0 && (pagesize & 1) == 0)
493 pagesize = (long_u)pagesize >> 1;
494 --shiftright;
496 mem = (long_u)pagesize * pagecount;
499 # endif
501 /* Return the minimum of the physical memory and the user limit, because
502 * using more than the user limit may cause Vim to be terminated. */
503 # if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
505 struct rlimit rlp;
507 if (getrlimit(RLIMIT_DATA, &rlp) == 0
508 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
509 # ifdef RLIM_INFINITY
510 && rlp.rlim_cur != RLIM_INFINITY
511 # endif
512 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
515 mem = (long_u)rlp.rlim_cur;
516 shiftright = 10;
519 # endif
521 if (mem > 0)
522 return mem >> shiftright;
523 return (long_u)0x1fffff;
524 # endif
526 #endif
528 void
529 mch_delay(msec, ignoreinput)
530 long msec;
531 int ignoreinput;
533 int old_tmode;
534 #ifdef FEAT_MZSCHEME
535 long total = msec; /* remember original value */
536 #endif
538 if (ignoreinput)
540 /* Go to cooked mode without echo, to allow SIGINT interrupting us
541 * here */
542 old_tmode = curr_tmode;
543 if (curr_tmode == TMODE_RAW)
544 settmode(TMODE_SLEEP);
547 * Everybody sleeps in a different way...
548 * Prefer nanosleep(), some versions of usleep() can only sleep up to
549 * one second.
551 #ifdef FEAT_MZSCHEME
554 /* if total is large enough, wait by portions in p_mzq */
555 if (total > p_mzq)
556 msec = p_mzq;
557 else
558 msec = total;
559 total -= msec;
560 #endif
561 #ifdef HAVE_NANOSLEEP
563 struct timespec ts;
565 ts.tv_sec = msec / 1000;
566 ts.tv_nsec = (msec % 1000) * 1000000;
567 (void)nanosleep(&ts, NULL);
569 #else
570 # ifdef HAVE_USLEEP
571 while (msec >= 1000)
573 usleep((unsigned int)(999 * 1000));
574 msec -= 999;
576 usleep((unsigned int)(msec * 1000));
577 # else
578 # ifndef HAVE_SELECT
579 poll(NULL, 0, (int)msec);
580 # else
581 # ifdef __EMX__
582 _sleep2(msec);
583 # else
585 struct timeval tv;
587 tv.tv_sec = msec / 1000;
588 tv.tv_usec = (msec % 1000) * 1000;
590 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
591 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
593 select(0, NULL, NULL, NULL, &tv);
595 # endif /* __EMX__ */
596 # endif /* HAVE_SELECT */
597 # endif /* HAVE_NANOSLEEP */
598 #endif /* HAVE_USLEEP */
599 #ifdef FEAT_MZSCHEME
601 while (total > 0);
602 #endif
604 settmode(old_tmode);
606 else
607 WaitForChar(msec);
610 #if 0 /* disabled, no longer needed now that regmatch() is not recursive */
611 # if defined(HAVE_GETRLIMIT)
612 # define HAVE_STACK_LIMIT
613 # endif
614 #endif
616 #if defined(HAVE_STACK_LIMIT) \
617 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
618 # define HAVE_CHECK_STACK_GROWTH
620 * Support for checking for an almost-out-of-stack-space situation.
624 * Return a pointer to an item on the stack. Used to find out if the stack
625 * grows up or down.
627 static void check_stack_growth __ARGS((char *p));
628 static int stack_grows_downwards;
631 * Find out if the stack grows upwards or downwards.
632 * "p" points to a variable on the stack of the caller.
634 static void
635 check_stack_growth(p)
636 char *p;
638 int i;
640 stack_grows_downwards = (p > (char *)&i);
642 #endif
644 #if defined(HAVE_STACK_LIMIT) || defined(PROTO)
645 static char *stack_limit = NULL;
647 #if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
648 # include <pthread.h>
649 # include <pthread_np.h>
650 #endif
653 * Find out until how var the stack can grow without getting into trouble.
654 * Called when starting up and when switching to the signal stack in
655 * deathtrap().
657 static void
658 get_stack_limit()
660 struct rlimit rlp;
661 int i;
662 long lim;
664 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
665 * limit doesn't fit in a long (rlim_cur might be "long long"). */
666 if (getrlimit(RLIMIT_STACK, &rlp) == 0
667 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
668 # ifdef RLIM_INFINITY
669 && rlp.rlim_cur != RLIM_INFINITY
670 # endif
673 lim = (long)rlp.rlim_cur;
674 #if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
676 pthread_attr_t attr;
677 size_t size;
679 /* On FreeBSD the initial thread always has a fixed stack size, no
680 * matter what the limits are set to. Normally it's 1 Mbyte. */
681 pthread_attr_init(&attr);
682 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
684 pthread_attr_getstacksize(&attr, &size);
685 if (lim > (long)size)
686 lim = (long)size;
688 pthread_attr_destroy(&attr);
690 #endif
691 if (stack_grows_downwards)
693 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
694 if (stack_limit >= (char *)&i)
695 /* overflow, set to 1/16 of current stack position */
696 stack_limit = (char *)((long)&i / 16L);
698 else
700 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
701 if (stack_limit <= (char *)&i)
702 stack_limit = NULL; /* overflow */
708 * Return FAIL when running out of stack space.
709 * "p" must point to any variable local to the caller that's on the stack.
712 mch_stackcheck(p)
713 char *p;
715 if (stack_limit != NULL)
717 if (stack_grows_downwards)
719 if (p < stack_limit)
720 return FAIL;
722 else if (p > stack_limit)
723 return FAIL;
725 return OK;
727 #endif
729 #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
731 * Support for using the signal stack.
732 * This helps when we run out of stack space, which causes a SIGSEGV. The
733 * signal handler then must run on another stack, since the normal stack is
734 * completely full.
737 #ifndef SIGSTKSZ
738 # define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
739 #endif
741 # ifdef HAVE_SIGALTSTACK
742 static stack_t sigstk; /* for sigaltstack() */
743 # else
744 static struct sigstack sigstk; /* for sigstack() */
745 # endif
747 static void init_signal_stack __ARGS((void));
748 static char *signal_stack;
750 static void
751 init_signal_stack()
753 if (signal_stack != NULL)
755 # ifdef HAVE_SIGALTSTACK
756 # if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \
757 || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040)
758 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
759 * "struct sigaltstack" needs to be declared. */
760 extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss));
761 # endif
763 # ifdef HAVE_SS_BASE
764 sigstk.ss_base = signal_stack;
765 # else
766 sigstk.ss_sp = signal_stack;
767 # endif
768 sigstk.ss_size = SIGSTKSZ;
769 sigstk.ss_flags = 0;
770 (void)sigaltstack(&sigstk, NULL);
771 # else
772 sigstk.ss_sp = signal_stack;
773 if (stack_grows_downwards)
774 sigstk.ss_sp += SIGSTKSZ - 1;
775 sigstk.ss_onstack = 0;
776 (void)sigstack(&sigstk, NULL);
777 # endif
780 #endif
783 * We need correct potatotypes for a signal function, otherwise mean compilers
784 * will barf when the second argument to signal() is ``wrong''.
785 * Let me try it with a few tricky defines from my own osdef.h (jw).
787 #if defined(SIGWINCH)
788 /* ARGSUSED */
789 static RETSIGTYPE
790 sig_winch SIGDEFARG(sigarg)
792 /* this is not required on all systems, but it doesn't hurt anybody */
793 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
794 do_resize = TRUE;
795 SIGRETURN;
797 #endif
799 #if defined(SIGINT)
800 /* ARGSUSED */
801 static RETSIGTYPE
802 catch_sigint SIGDEFARG(sigarg)
804 /* this is not required on all systems, but it doesn't hurt anybody */
805 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
806 got_int = TRUE;
807 SIGRETURN;
809 #endif
811 #if defined(SIGPWR)
812 /* ARGSUSED */
813 static RETSIGTYPE
814 catch_sigpwr SIGDEFARG(sigarg)
816 /* this is not required on all systems, but it doesn't hurt anybody */
817 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
819 * I'm not sure we get the SIGPWR signal when the system is really going
820 * down or when the batteries are almost empty. Just preserve the swap
821 * files and don't exit, that can't do any harm.
823 ml_sync_all(FALSE, FALSE);
824 SIGRETURN;
826 #endif
828 #ifdef SET_SIG_ALARM
830 * signal function for alarm().
832 /* ARGSUSED */
833 static RETSIGTYPE
834 sig_alarm SIGDEFARG(sigarg)
836 /* doesn't do anything, just to break a system call */
837 sig_alarm_called = TRUE;
838 SIGRETURN;
840 #endif
842 #if (defined(HAVE_SETJMP_H) \
843 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
844 || defined(FEAT_LIBCALL))) \
845 || defined(PROTO)
847 * A simplistic version of setjmp() that only allows one level of using.
848 * Don't call twice before calling mch_endjmp()!.
849 * Usage:
850 * mch_startjmp();
851 * if (SETJMP(lc_jump_env) != 0)
853 * mch_didjmp();
854 * EMSG("crash!");
856 * else
858 * do_the_work;
859 * mch_endjmp();
861 * Note: Can't move SETJMP() here, because a function calling setjmp() must
862 * not return before the saved environment is used.
863 * Returns OK for normal return, FAIL when the protected code caused a
864 * problem and LONGJMP() was used.
866 void
867 mch_startjmp()
869 #ifdef SIGHASARG
870 lc_signal = 0;
871 #endif
872 lc_active = TRUE;
875 void
876 mch_endjmp()
878 lc_active = FALSE;
881 void
882 mch_didjmp()
884 # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
885 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
886 * otherwise catching the signal only works once. */
887 init_signal_stack();
888 # endif
890 #endif
893 * This function handles deadly signals.
894 * It tries to preserve any swap file and exit properly.
895 * (partly from Elvis).
897 static RETSIGTYPE
898 deathtrap SIGDEFARG(sigarg)
900 static int entered = 0; /* count the number of times we got here.
901 Note: when memory has been corrupted
902 this may get an arbitrary value! */
903 #ifdef SIGHASARG
904 int i;
905 #endif
907 #if defined(HAVE_SETJMP_H)
909 * Catch a crash in protected code.
910 * Restores the environment saved in lc_jump_env, which looks like
911 * SETJMP() returns 1.
913 if (lc_active)
915 # if defined(SIGHASARG)
916 lc_signal = sigarg;
917 # endif
918 lc_active = FALSE; /* don't jump again */
919 LONGJMP(lc_jump_env, 1);
920 /* NOTREACHED */
922 #endif
924 #ifdef SIGHASARG
925 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
926 * here. This avoids that a non-reentrant function is interrupted, e.g.,
927 * free(). Calling free() again may then cause a crash. */
928 if (entered == 0
929 && (0
930 # ifdef SIGHUP
931 || sigarg == SIGHUP
932 # endif
933 # ifdef SIGQUIT
934 || sigarg == SIGQUIT
935 # endif
936 # ifdef SIGTERM
937 || sigarg == SIGTERM
938 # endif
939 # ifdef SIGPWR
940 || sigarg == SIGPWR
941 # endif
942 # ifdef SIGUSR1
943 || sigarg == SIGUSR1
944 # endif
945 # ifdef SIGUSR2
946 || sigarg == SIGUSR2
947 # endif
949 && !vim_handle_signal(sigarg))
950 SIGRETURN;
951 #endif
953 /* Remember how often we have been called. */
954 ++entered;
956 #ifdef FEAT_EVAL
957 /* Set the v:dying variable. */
958 set_vim_var_nr(VV_DYING, (long)entered);
959 #endif
961 #ifdef HAVE_STACK_LIMIT
962 /* Since we are now using the signal stack, need to reset the stack
963 * limit. Otherwise using a regexp will fail. */
964 get_stack_limit();
965 #endif
967 #if 0
968 /* This is for opening gdb the moment Vim crashes.
969 * You need to manually adjust the file name and Vim executable name.
970 * Suggested by SungHyun Nam. */
972 # define VI_GDB_FILE "/tmp/vimgdb"
973 # define VIM_NAME "/usr/bin/vim"
974 FILE *fp = fopen(VI_GDB_FILE, "w");
975 if (fp)
977 fprintf(fp,
978 "file %s\n"
979 "attach %d\n"
980 "set height 1000\n"
981 "bt full\n"
982 , VIM_NAME, getpid());
983 fclose(fp);
984 system("xterm -e gdb -x "VI_GDB_FILE);
985 unlink(VI_GDB_FILE);
988 #endif
990 #ifdef SIGHASARG
991 /* try to find the name of this signal */
992 for (i = 0; signal_info[i].sig != -1; i++)
993 if (sigarg == signal_info[i].sig)
994 break;
995 deadly_signal = sigarg;
996 #endif
998 full_screen = FALSE; /* don't write message to the GUI, it might be
999 * part of the problem... */
1001 * If something goes wrong after entering here, we may get here again.
1002 * When this happens, give a message and try to exit nicely (resetting the
1003 * terminal mode, etc.)
1004 * When this happens twice, just exit, don't even try to give a message,
1005 * stack may be corrupt or something weird.
1006 * When this still happens again (or memory was corrupted in such a way
1007 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1009 if (entered >= 3)
1011 reset_signals(); /* don't catch any signals anymore */
1012 may_core_dump();
1013 if (entered >= 4)
1014 _exit(8);
1015 exit(7);
1017 if (entered == 2)
1019 OUT_STR(_("Vim: Double signal, exiting\n"));
1020 out_flush();
1021 getout(1);
1024 #ifdef SIGHASARG
1025 sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"),
1026 signal_info[i].name);
1027 #else
1028 sprintf((char *)IObuff, _("Vim: Caught deadly signal\n"));
1029 #endif
1030 preserve_exit(); /* preserve files and exit */
1032 #ifdef NBDEBUG
1033 reset_signals();
1034 may_core_dump();
1035 abort();
1036 #endif
1038 SIGRETURN;
1041 #ifdef _REENTRANT
1043 * On Solaris with multi-threading, suspending might not work immediately.
1044 * Catch the SIGCONT signal, which will be used as an indication whether the
1045 * suspending has been done or not.
1047 static int sigcont_received;
1048 static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG);
1051 * signal handler for SIGCONT
1053 /* ARGSUSED */
1054 static RETSIGTYPE
1055 sigcont_handler SIGDEFARG(sigarg)
1057 sigcont_received = TRUE;
1058 SIGRETURN;
1060 #endif
1063 * If the machine has job control, use it to suspend the program,
1064 * otherwise fake it by starting a new shell.
1066 void
1067 mch_suspend()
1069 /* BeOS does have SIGTSTP, but it doesn't work. */
1070 #if defined(SIGTSTP) && !defined(__BEOS__)
1071 out_flush(); /* needed to make cursor visible on some systems */
1072 settmode(TMODE_COOK);
1073 out_flush(); /* needed to disable mouse on some systems */
1075 # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1076 /* Since we are going to sleep, we can't respond to requests for the X
1077 * selections. Lose them, otherwise other applications will hang. But
1078 * first copy the text to cut buffer 0. */
1079 if (clip_star.owned || clip_plus.owned)
1081 x11_export_final_selection();
1082 if (clip_star.owned)
1083 clip_lose_selection(&clip_star);
1084 if (clip_plus.owned)
1085 clip_lose_selection(&clip_plus);
1086 if (x11_display != NULL)
1087 XFlush(x11_display);
1089 # endif
1091 # ifdef _REENTRANT
1092 sigcont_received = FALSE;
1093 # endif
1094 kill(0, SIGTSTP); /* send ourselves a STOP signal */
1095 # ifdef _REENTRANT
1096 /* When we didn't suspend immediately in the kill(), do it now. Happens
1097 * on multi-threaded Solaris. */
1098 if (!sigcont_received)
1099 pause();
1100 # endif
1102 # ifdef FEAT_TITLE
1104 * Set oldtitle to NULL, so the current title is obtained again.
1106 vim_free(oldtitle);
1107 oldtitle = NULL;
1108 # endif
1109 settmode(TMODE_RAW);
1110 need_check_timestamps = TRUE;
1111 did_check_timestamps = FALSE;
1112 #else
1113 suspend_shell();
1114 #endif
1117 void
1118 mch_init()
1120 Columns = 80;
1121 Rows = 24;
1123 out_flush();
1124 set_signals();
1126 #ifdef MACOS_CONVERT
1127 mac_conv_init();
1128 #endif
1131 static void
1132 set_signals()
1134 #if defined(SIGWINCH)
1136 * WINDOW CHANGE signal is handled with sig_winch().
1138 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1139 #endif
1142 * We want the STOP signal to work, to make mch_suspend() work.
1143 * For "rvim" the STOP signal is ignored.
1145 #ifdef SIGTSTP
1146 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1147 #endif
1148 #ifdef _REENTRANT
1149 signal(SIGCONT, sigcont_handler);
1150 #endif
1153 * We want to ignore breaking of PIPEs.
1155 #ifdef SIGPIPE
1156 signal(SIGPIPE, SIG_IGN);
1157 #endif
1159 #ifdef SIGINT
1160 catch_int_signal();
1161 #endif
1164 * Ignore alarm signals (Perl's alarm() generates it).
1166 #ifdef SIGALRM
1167 signal(SIGALRM, SIG_IGN);
1168 #endif
1171 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1172 * work will be lost.
1174 #ifdef SIGPWR
1175 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1176 #endif
1179 * Arrange for other signals to gracefully shutdown Vim.
1181 catch_signals(deathtrap, SIG_ERR);
1183 #if defined(FEAT_GUI) && defined(SIGHUP)
1185 * When the GUI is running, ignore the hangup signal.
1187 if (gui.in_use)
1188 signal(SIGHUP, SIG_IGN);
1189 #endif
1192 #if defined(SIGINT) || defined(PROTO)
1194 * Catch CTRL-C (only works while in Cooked mode).
1196 static void
1197 catch_int_signal()
1199 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1201 #endif
1203 void
1204 reset_signals()
1206 catch_signals(SIG_DFL, SIG_DFL);
1207 #ifdef _REENTRANT
1208 /* SIGCONT isn't in the list, because its default action is ignore */
1209 signal(SIGCONT, SIG_DFL);
1210 #endif
1213 static void
1214 catch_signals(func_deadly, func_other)
1215 RETSIGTYPE (*func_deadly)();
1216 RETSIGTYPE (*func_other)();
1218 int i;
1220 for (i = 0; signal_info[i].sig != -1; i++)
1221 if (signal_info[i].deadly)
1223 #if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1224 struct sigaction sa;
1226 /* Setup to use the alternate stack for the signal function. */
1227 sa.sa_handler = func_deadly;
1228 sigemptyset(&sa.sa_mask);
1229 # if defined(__linux__) && defined(_REENTRANT)
1230 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1231 * thread handling in combination with using the alternate stack:
1232 * pthread library functions try to use the stack pointer to
1233 * identify the current thread, causing a SEGV signal, which
1234 * recursively calls deathtrap() and hangs. */
1235 sa.sa_flags = 0;
1236 # else
1237 sa.sa_flags = SA_ONSTACK;
1238 # endif
1239 sigaction(signal_info[i].sig, &sa, NULL);
1240 #else
1241 # if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1242 struct sigvec sv;
1244 /* Setup to use the alternate stack for the signal function. */
1245 sv.sv_handler = func_deadly;
1246 sv.sv_mask = 0;
1247 sv.sv_flags = SV_ONSTACK;
1248 sigvec(signal_info[i].sig, &sv, NULL);
1249 # else
1250 signal(signal_info[i].sig, func_deadly);
1251 # endif
1252 #endif
1254 else if (func_other != SIG_ERR)
1255 signal(signal_info[i].sig, func_other);
1259 * Handling of SIGHUP, SIGQUIT and SIGTERM:
1260 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1261 * return TRUE
1262 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1263 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
1264 * signal
1265 * Returns TRUE when Vim should exit.
1268 vim_handle_signal(sig)
1269 int sig;
1271 static int got_signal = 0;
1272 static int blocked = TRUE;
1274 switch (sig)
1276 case SIGNAL_BLOCK: blocked = TRUE;
1277 break;
1279 case SIGNAL_UNBLOCK: blocked = FALSE;
1280 if (got_signal != 0)
1282 kill(getpid(), got_signal);
1283 got_signal = 0;
1285 break;
1287 default: if (!blocked)
1288 return TRUE; /* exit! */
1289 got_signal = sig;
1290 #ifdef SIGPWR
1291 if (sig != SIGPWR)
1292 #endif
1293 got_int = TRUE; /* break any loops */
1294 break;
1296 return FALSE;
1300 * Check_win checks whether we have an interactive stdout.
1302 /* ARGSUSED */
1304 mch_check_win(argc, argv)
1305 int argc;
1306 char **argv;
1308 #ifdef OS2
1310 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1311 * name, mostly it's just "vim" and found in the path, which is unusable.
1313 if (mch_isFullName(argv[0]))
1314 exe_name = vim_strsave((char_u *)argv[0]);
1315 #endif
1316 if (isatty(1))
1317 return OK;
1318 return FAIL;
1322 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1325 mch_input_isatty()
1327 if (isatty(read_cmd_fd))
1328 return TRUE;
1329 return FALSE;
1332 #ifdef FEAT_X11
1334 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1335 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1337 static void xopen_message __ARGS((struct timeval *tvp));
1340 * Give a message about the elapsed time for opening the X window.
1342 static void
1343 xopen_message(tvp)
1344 struct timeval *tvp; /* must contain start time */
1346 struct timeval end_tv;
1348 /* Compute elapsed time. */
1349 gettimeofday(&end_tv, NULL);
1350 smsg((char_u *)_("Opening the X display took %ld msec"),
1351 (end_tv.tv_sec - tvp->tv_sec) * 1000L
1352 + (end_tv.tv_usec - tvp->tv_usec) / 1000L);
1354 # endif
1355 #endif
1357 #if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1359 * A few functions shared by X11 title and clipboard code.
1361 static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event));
1362 static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
1363 static int x_connect_to_server __ARGS((void));
1364 static int test_x11_window __ARGS((Display *dpy));
1366 static int got_x_error = FALSE;
1369 * X Error handler, otherwise X just exits! (very rude) -- webb
1371 static int
1372 x_error_handler(dpy, error_event)
1373 Display *dpy;
1374 XErrorEvent *error_event;
1376 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
1377 STRCAT(IObuff, _("\nVim: Got X error\n"));
1379 /* We cannot print a message and continue, because no X calls are allowed
1380 * here (causes my system to hang). Silently continuing might be an
1381 * alternative... */
1382 preserve_exit(); /* preserve files and exit */
1384 return 0; /* NOTREACHED */
1388 * Another X Error handler, just used to check for errors.
1390 /* ARGSUSED */
1391 static int
1392 x_error_check(dpy, error_event)
1393 Display *dpy;
1394 XErrorEvent *error_event;
1396 got_x_error = TRUE;
1397 return 0;
1400 #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1401 # if defined(HAVE_SETJMP_H)
1403 * An X IO Error handler, used to catch error while opening the display.
1405 static int x_IOerror_check __ARGS((Display *dpy));
1407 /* ARGSUSED */
1408 static int
1409 x_IOerror_check(dpy)
1410 Display *dpy;
1412 /* This function should not return, it causes exit(). Longjump instead. */
1413 LONGJMP(lc_jump_env, 1);
1414 /*NOTREACHED*/
1415 return 0;
1417 # endif
1420 * An X IO Error handler, used to catch terminal errors.
1422 static int x_IOerror_handler __ARGS((Display *dpy));
1424 /* ARGSUSED */
1425 static int
1426 x_IOerror_handler(dpy)
1427 Display *dpy;
1429 xterm_dpy = NULL;
1430 x11_window = 0;
1431 x11_display = NULL;
1432 xterm_Shell = (Widget)0;
1434 /* This function should not return, it causes exit(). Longjump instead. */
1435 LONGJMP(x_jump_env, 1);
1436 /*NOTREACHED*/
1437 return 0;
1439 #endif
1442 * Return TRUE when connection to the X server is desired.
1444 static int
1445 x_connect_to_server()
1447 regmatch_T regmatch;
1449 #if defined(FEAT_CLIENTSERVER)
1450 if (x_force_connect)
1451 return TRUE;
1452 #endif
1453 if (x_no_connect)
1454 return FALSE;
1456 /* Check for a match with "exclude:" from 'clipboard'. */
1457 if (clip_exclude_prog != NULL)
1459 regmatch.rm_ic = FALSE; /* Don't ignore case */
1460 regmatch.regprog = clip_exclude_prog;
1461 if (vim_regexec(&regmatch, T_NAME, (colnr_T)0))
1462 return FALSE;
1464 return TRUE;
1468 * Test if "dpy" and x11_window are valid by getting the window title.
1469 * I don't actually want it yet, so there may be a simpler call to use, but
1470 * this will cause the error handler x_error_check() to be called if anything
1471 * is wrong, such as the window pointer being invalid (as can happen when the
1472 * user changes his DISPLAY, but not his WINDOWID) -- webb
1474 static int
1475 test_x11_window(dpy)
1476 Display *dpy;
1478 int (*old_handler)();
1479 XTextProperty text_prop;
1481 old_handler = XSetErrorHandler(x_error_check);
1482 got_x_error = FALSE;
1483 if (XGetWMName(dpy, x11_window, &text_prop))
1484 XFree((void *)text_prop.value);
1485 XSync(dpy, False);
1486 (void)XSetErrorHandler(old_handler);
1488 if (p_verbose > 0 && got_x_error)
1489 verb_msg((char_u *)_("Testing the X display failed"));
1491 return (got_x_error ? FAIL : OK);
1493 #endif
1495 #ifdef FEAT_TITLE
1497 #ifdef FEAT_X11
1499 static int get_x11_thing __ARGS((int get_title, int test_only));
1502 * try to get x11 window and display
1504 * return FAIL for failure, OK otherwise
1506 static int
1507 get_x11_windis()
1509 char *winid;
1510 static int result = -1;
1511 #define XD_NONE 0 /* x11_display not set here */
1512 #define XD_HERE 1 /* x11_display opened here */
1513 #define XD_GUI 2 /* x11_display used from gui.dpy */
1514 #define XD_XTERM 3 /* x11_display used from xterm_dpy */
1515 static int x11_display_from = XD_NONE;
1516 static int did_set_error_handler = FALSE;
1518 if (!did_set_error_handler)
1520 /* X just exits if it finds an error otherwise! */
1521 (void)XSetErrorHandler(x_error_handler);
1522 did_set_error_handler = TRUE;
1525 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
1526 if (gui.in_use)
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.
1532 if (x11_display_from == XD_HERE && x11_display != NULL)
1534 XCloseDisplay(x11_display);
1535 x11_display_from = XD_NONE;
1537 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1539 x11_display_from = XD_GUI;
1540 return OK;
1542 x11_display = NULL;
1543 return FAIL;
1545 else if (x11_display_from == XD_GUI)
1547 /* GUI must have stopped somehow, clear x11_display */
1548 x11_window = 0;
1549 x11_display = NULL;
1550 x11_display_from = XD_NONE;
1552 #endif
1554 /* When started with the "-X" argument, don't try connecting. */
1555 if (!x_connect_to_server())
1556 return FAIL;
1559 * If WINDOWID not set, should try another method to find out
1560 * what the current window number is. The only code I know for
1561 * this is very complicated.
1562 * We assume that zero is invalid for WINDOWID.
1564 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1565 x11_window = (Window)atol(winid);
1567 #ifdef FEAT_XCLIPBOARD
1568 if (xterm_dpy != NULL && x11_window != 0)
1570 /* We may have checked it already, but Gnome terminal can move us to
1571 * another window, so we need to check every time. */
1572 if (x11_display_from != XD_XTERM)
1575 * If the X11 display was opened here before, for the window where
1576 * Vim was started, close that one now to avoid a memory leak.
1578 if (x11_display_from == XD_HERE && x11_display != NULL)
1579 XCloseDisplay(x11_display);
1580 x11_display = xterm_dpy;
1581 x11_display_from = XD_XTERM;
1583 if (test_x11_window(x11_display) == FAIL)
1585 /* probably bad $WINDOWID */
1586 x11_window = 0;
1587 x11_display = NULL;
1588 x11_display_from = XD_NONE;
1589 return FAIL;
1591 return OK;
1593 #endif
1595 if (x11_window == 0 || x11_display == NULL)
1596 result = -1;
1598 if (result != -1) /* Have already been here and set this */
1599 return result; /* Don't do all these X calls again */
1601 if (x11_window != 0 && x11_display == NULL)
1603 #ifdef SET_SIG_ALARM
1604 RETSIGTYPE (*sig_save)();
1605 #endif
1606 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1607 struct timeval start_tv;
1609 if (p_verbose > 0)
1610 gettimeofday(&start_tv, NULL);
1611 #endif
1613 #ifdef SET_SIG_ALARM
1615 * Opening the Display may hang if the DISPLAY setting is wrong, or
1616 * the network connection is bad. Set an alarm timer to get out.
1618 sig_alarm_called = FALSE;
1619 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1620 (RETSIGTYPE (*)())sig_alarm);
1621 alarm(2);
1622 #endif
1623 x11_display = XOpenDisplay(NULL);
1625 #ifdef SET_SIG_ALARM
1626 alarm(0);
1627 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1628 if (p_verbose > 0 && sig_alarm_called)
1629 verb_msg((char_u *)_("Opening the X display timed out"));
1630 #endif
1631 if (x11_display != NULL)
1633 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1634 if (p_verbose > 0)
1636 verbose_enter();
1637 xopen_message(&start_tv);
1638 verbose_leave();
1640 # endif
1641 if (test_x11_window(x11_display) == FAIL)
1643 /* Maybe window id is bad */
1644 x11_window = 0;
1645 XCloseDisplay(x11_display);
1646 x11_display = NULL;
1648 else
1649 x11_display_from = XD_HERE;
1652 if (x11_window == 0 || x11_display == NULL)
1653 return (result = FAIL);
1654 return (result = OK);
1658 * Determine original x11 Window Title
1660 static int
1661 get_x11_title(test_only)
1662 int test_only;
1664 return get_x11_thing(TRUE, test_only);
1668 * Determine original x11 Window icon
1670 static int
1671 get_x11_icon(test_only)
1672 int test_only;
1674 int retval = FALSE;
1676 retval = get_x11_thing(FALSE, test_only);
1678 /* could not get old icon, use terminal name */
1679 if (oldicon == NULL && !test_only)
1681 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1682 oldicon = T_NAME + 8;
1683 else
1684 oldicon = T_NAME;
1687 return retval;
1690 static int
1691 get_x11_thing(get_title, test_only)
1692 int get_title; /* get title string */
1693 int test_only;
1695 XTextProperty text_prop;
1696 int retval = FALSE;
1697 Status status;
1699 if (get_x11_windis() == OK)
1701 /* Get window/icon name if any */
1702 if (get_title)
1703 status = XGetWMName(x11_display, x11_window, &text_prop);
1704 else
1705 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1708 * If terminal is xterm, then x11_window may be a child window of the
1709 * outer xterm window that actually contains the window/icon name, so
1710 * keep traversing up the tree until a window with a title/icon is
1711 * found.
1713 /* Previously this was only done for xterm and alikes. I don't see a
1714 * reason why it would fail for other terminal emulators.
1715 * if (term_is_xterm) */
1717 Window root;
1718 Window parent;
1719 Window win = x11_window;
1720 Window *children;
1721 unsigned int num_children;
1723 while (!status || text_prop.value == NULL)
1725 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1726 &num_children))
1727 break;
1728 if (children)
1729 XFree((void *)children);
1730 if (parent == root || parent == 0)
1731 break;
1733 win = parent;
1734 if (get_title)
1735 status = XGetWMName(x11_display, win, &text_prop);
1736 else
1737 status = XGetWMIconName(x11_display, win, &text_prop);
1740 if (status && text_prop.value != NULL)
1742 retval = TRUE;
1743 if (!test_only)
1745 #ifdef FEAT_XFONTSET
1746 if (text_prop.encoding == XA_STRING)
1748 #endif
1749 if (get_title)
1750 oldtitle = vim_strsave((char_u *)text_prop.value);
1751 else
1752 oldicon = vim_strsave((char_u *)text_prop.value);
1753 #ifdef FEAT_XFONTSET
1755 else
1757 char **cl;
1758 Status transform_status;
1759 int n = 0;
1761 transform_status = XmbTextPropertyToTextList(x11_display,
1762 &text_prop,
1763 &cl, &n);
1764 if (transform_status >= Success && n > 0 && cl[0])
1766 if (get_title)
1767 oldtitle = vim_strsave((char_u *) cl[0]);
1768 else
1769 oldicon = vim_strsave((char_u *) cl[0]);
1770 XFreeStringList(cl);
1772 else
1774 if (get_title)
1775 oldtitle = vim_strsave((char_u *)text_prop.value);
1776 else
1777 oldicon = vim_strsave((char_u *)text_prop.value);
1780 #endif
1782 XFree((void *)text_prop.value);
1785 return retval;
1788 /* Are Xutf8 functions available? Avoid error from old compilers. */
1789 #if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1790 # if X_HAVE_UTF8_STRING
1791 # define USE_UTF8_STRING
1792 # endif
1793 #endif
1796 * Set x11 Window Title
1798 * get_x11_windis() must be called before this and have returned OK
1800 static void
1801 set_x11_title(title)
1802 char_u *title;
1804 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1805 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1806 * supported everywhere and STRING doesn't work for multi-byte titles.
1808 #ifdef USE_UTF8_STRING
1809 if (enc_utf8)
1810 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1811 NULL, NULL, 0, NULL, NULL, NULL);
1812 else
1813 #endif
1815 #if XtSpecificationRelease >= 4
1816 # ifdef FEAT_XFONTSET
1817 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1818 NULL, NULL, 0, NULL, NULL, NULL);
1819 # else
1820 XTextProperty text_prop;
1821 char *c_title = (char *)title;
1823 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
1824 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
1825 XSetWMProperties(x11_display, x11_window, &text_prop,
1826 NULL, NULL, 0, NULL, NULL, NULL);
1827 # endif
1828 #else
1829 XStoreName(x11_display, x11_window, (char *)title);
1830 #endif
1832 XFlush(x11_display);
1836 * Set x11 Window icon
1838 * get_x11_windis() must be called before this and have returned OK
1840 static void
1841 set_x11_icon(icon)
1842 char_u *icon;
1844 /* See above for comments about using X*SetWMProperties(). */
1845 #ifdef USE_UTF8_STRING
1846 if (enc_utf8)
1847 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1848 NULL, 0, NULL, NULL, NULL);
1849 else
1850 #endif
1852 #if XtSpecificationRelease >= 4
1853 # ifdef FEAT_XFONTSET
1854 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1855 NULL, 0, NULL, NULL, NULL);
1856 # else
1857 XTextProperty text_prop;
1858 char *c_icon = (char *)icon;
1860 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
1861 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1862 NULL, 0, NULL, NULL, NULL);
1863 # endif
1864 #else
1865 XSetIconName(x11_display, x11_window, (char *)icon);
1866 #endif
1868 XFlush(x11_display);
1871 #else /* FEAT_X11 */
1873 /*ARGSUSED*/
1874 static int
1875 get_x11_title(test_only)
1876 int test_only;
1878 return FALSE;
1881 static int
1882 get_x11_icon(test_only)
1883 int test_only;
1885 if (!test_only)
1887 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1888 oldicon = T_NAME + 8;
1889 else
1890 oldicon = T_NAME;
1892 return FALSE;
1895 #endif /* FEAT_X11 */
1898 mch_can_restore_title()
1900 return get_x11_title(TRUE);
1904 mch_can_restore_icon()
1906 return get_x11_icon(TRUE);
1910 * Set the window title and icon.
1912 void
1913 mch_settitle(title, icon)
1914 char_u *title;
1915 char_u *icon;
1917 int type = 0;
1918 static int recursive = 0;
1920 if (T_NAME == NULL) /* no terminal name (yet) */
1921 return;
1922 if (title == NULL && icon == NULL) /* nothing to do */
1923 return;
1925 /* When one of the X11 functions causes a deadly signal, we get here again
1926 * recursively. Avoid hanging then (something is probably locked). */
1927 if (recursive)
1928 return;
1929 ++recursive;
1932 * if the window ID and the display is known, we may use X11 calls
1934 #ifdef FEAT_X11
1935 if (get_x11_windis() == OK)
1936 type = 1;
1937 #else
1938 # if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) \
1939 || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM)
1940 if (gui.in_use)
1941 type = 1;
1942 # endif
1943 #endif
1946 * Note: if "t_TS" is set, title is set with escape sequence rather
1947 * than x11 calls, because the x11 calls don't always work
1949 if ((type || *T_TS != NUL) && title != NULL)
1951 if (oldtitle == NULL
1952 #ifdef FEAT_GUI
1953 && !gui.in_use
1954 #endif
1955 ) /* first call but not in GUI, save title */
1956 (void)get_x11_title(FALSE);
1958 if (*T_TS != NUL) /* it's OK if t_fs is empty */
1959 term_settitle(title);
1960 #ifdef FEAT_X11
1961 else
1962 # ifdef FEAT_GUI_GTK
1963 if (!gui.in_use) /* don't do this if GTK+ is running */
1964 # endif
1965 set_x11_title(title); /* x11 */
1966 #endif
1967 #if defined(FEAT_GUI_GTK) \
1968 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) \
1969 || defined(FEAT_GUI_MACVIM)
1970 else
1971 gui_mch_settitle(title, icon);
1972 #endif
1973 did_set_title = TRUE;
1976 if ((type || *T_CIS != NUL) && icon != NULL)
1978 if (oldicon == NULL
1979 #ifdef FEAT_GUI
1980 && !gui.in_use
1981 #endif
1982 ) /* first call, save icon */
1983 get_x11_icon(FALSE);
1985 if (*T_CIS != NUL)
1987 out_str(T_CIS); /* set icon start */
1988 out_str_nf(icon);
1989 out_str(T_CIE); /* set icon end */
1990 out_flush();
1992 #ifdef FEAT_X11
1993 else
1994 # ifdef FEAT_GUI_GTK
1995 if (!gui.in_use) /* don't do this if GTK+ is running */
1996 # endif
1997 set_x11_icon(icon); /* x11 */
1998 #endif
1999 did_set_icon = TRUE;
2001 --recursive;
2005 * Restore the window/icon title.
2006 * "which" is one of:
2007 * 1 only restore title
2008 * 2 only restore icon
2009 * 3 restore title and icon
2011 void
2012 mch_restore_title(which)
2013 int which;
2015 /* only restore the title or icon when it has been set */
2016 mch_settitle(((which & 1) && did_set_title) ?
2017 (oldtitle ? oldtitle : p_titleold) : NULL,
2018 ((which & 2) && did_set_icon) ? oldicon : NULL);
2021 #endif /* FEAT_TITLE */
2024 * Return TRUE if "name" looks like some xterm name.
2025 * Seiichi Sato mentioned that "mlterm" works like xterm.
2028 vim_is_xterm(name)
2029 char_u *name;
2031 if (name == NULL)
2032 return FALSE;
2033 return (STRNICMP(name, "xterm", 5) == 0
2034 || STRNICMP(name, "nxterm", 6) == 0
2035 || STRNICMP(name, "kterm", 5) == 0
2036 || STRNICMP(name, "mlterm", 6) == 0
2037 || STRNICMP(name, "rxvt", 4) == 0
2038 || STRCMP(name, "builtin_xterm") == 0);
2041 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2043 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2044 * Return 1 for "xterm".
2045 * Return 2 for "xterm2".
2048 use_xterm_mouse()
2050 if (ttym_flags == TTYM_XTERM2)
2051 return 2;
2052 if (ttym_flags == TTYM_XTERM)
2053 return 1;
2054 return 0;
2056 #endif
2059 vim_is_iris(name)
2060 char_u *name;
2062 if (name == NULL)
2063 return FALSE;
2064 return (STRNICMP(name, "iris-ansi", 9) == 0
2065 || STRCMP(name, "builtin_iris-ansi") == 0);
2069 vim_is_vt300(name)
2070 char_u *name;
2072 if (name == NULL)
2073 return FALSE; /* actually all ANSI comp. terminals should be here */
2074 /* catch VT100 - VT5xx */
2075 return ((STRNICMP(name, "vt", 2) == 0
2076 && vim_strchr((char_u *)"12345", name[2]) != NULL)
2077 || STRCMP(name, "builtin_vt320") == 0);
2081 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2082 * This should include all windowed terminal emulators.
2085 vim_is_fastterm(name)
2086 char_u *name;
2088 if (name == NULL)
2089 return FALSE;
2090 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2091 return TRUE;
2092 return ( STRNICMP(name, "hpterm", 6) == 0
2093 || STRNICMP(name, "sun-cmd", 7) == 0
2094 || STRNICMP(name, "screen", 6) == 0
2095 || STRNICMP(name, "dtterm", 6) == 0);
2099 * Insert user name in s[len].
2100 * Return OK if a name found.
2103 mch_get_user_name(s, len)
2104 char_u *s;
2105 int len;
2107 #ifdef VMS
2108 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
2109 return OK;
2110 #else
2111 return mch_get_uname(getuid(), s, len);
2112 #endif
2116 * Insert user name for "uid" in s[len].
2117 * Return OK if a name found.
2120 mch_get_uname(uid, s, len)
2121 uid_t uid;
2122 char_u *s;
2123 int len;
2125 #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2126 struct passwd *pw;
2128 if ((pw = getpwuid(uid)) != NULL
2129 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2131 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
2132 return OK;
2134 #endif
2135 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2136 return FAIL; /* a number is not a name */
2140 * Insert host name is s[len].
2143 #ifdef HAVE_SYS_UTSNAME_H
2144 void
2145 mch_get_host_name(s, len)
2146 char_u *s;
2147 int len;
2149 struct utsname vutsname;
2151 if (uname(&vutsname) < 0)
2152 *s = NUL;
2153 else
2154 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
2156 #else /* HAVE_SYS_UTSNAME_H */
2158 # ifdef HAVE_SYS_SYSTEMINFO_H
2159 # define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2160 # endif
2162 void
2163 mch_get_host_name(s, len)
2164 char_u *s;
2165 int len;
2167 # ifdef VAXC
2168 vaxc$gethostname((char *)s, len);
2169 # else
2170 gethostname((char *)s, len);
2171 # endif
2172 s[len - 1] = NUL; /* make sure it's terminated */
2174 #endif /* HAVE_SYS_UTSNAME_H */
2177 * return process ID
2179 long
2180 mch_get_pid()
2182 return (long)getpid();
2185 #if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2186 static char *strerror __ARGS((int));
2188 static char *
2189 strerror(err)
2190 int err;
2192 extern int sys_nerr;
2193 extern char *sys_errlist[];
2194 static char er[20];
2196 if (err > 0 && err < sys_nerr)
2197 return (sys_errlist[err]);
2198 sprintf(er, "Error %d", err);
2199 return er;
2201 #endif
2204 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2205 * Return OK for success, FAIL for failure.
2208 mch_dirname(buf, len)
2209 char_u *buf;
2210 int len;
2212 #if defined(USE_GETCWD)
2213 if (getcwd((char *)buf, len) == NULL)
2215 STRCPY(buf, strerror(errno));
2216 return FAIL;
2218 return OK;
2219 #else
2220 return (getwd((char *)buf) != NULL ? OK : FAIL);
2221 #endif
2224 #if defined(OS2) || defined(PROTO)
2226 * Replace all slashes by backslashes.
2227 * When 'shellslash' set do it the other way around.
2229 void
2230 slash_adjust(p)
2231 char_u *p;
2233 while (*p)
2235 if (*p == psepcN)
2236 *p = psepc;
2237 mb_ptr_adv(p);
2240 #endif
2243 * Get absolute file name into "buf[len]".
2245 * return FAIL for failure, OK for success
2248 mch_FullName(fname, buf, len, force)
2249 char_u *fname, *buf;
2250 int len;
2251 int force; /* also expand when already absolute path */
2253 int l;
2254 #ifdef OS2
2255 int only_drive; /* file name is only a drive letter */
2256 #endif
2257 #ifdef HAVE_FCHDIR
2258 int fd = -1;
2259 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
2260 #endif
2261 char_u olddir[MAXPATHL];
2262 char_u *p;
2263 int retval = OK;
2265 #ifdef VMS
2266 fname = vms_fixfilename(fname);
2267 #endif
2269 #ifdef __CYGWIN__
2271 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2273 cygwin_conv_to_posix_path(fname, fname);
2274 #endif
2276 /* expand it if forced or not an absolute path */
2277 if (force || !mch_isFullName(fname))
2280 * If the file name has a path, change to that directory for a moment,
2281 * and then do the getwd() (and get back to where we were).
2282 * This will get the correct path name with "../" things.
2284 #ifdef OS2
2285 only_drive = 0;
2286 if (((p = vim_strrchr(fname, '/')) != NULL)
2287 || ((p = vim_strrchr(fname, '\\')) != NULL)
2288 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
2289 #else
2290 if ((p = vim_strrchr(fname, '/')) != NULL)
2291 #endif
2293 #ifdef HAVE_FCHDIR
2295 * Use fchdir() if possible, it's said to be faster and more
2296 * reliable. But on SunOS 4 it might not work. Check this by
2297 * doing a fchdir() right now.
2299 if (!dont_fchdir)
2301 fd = open(".", O_RDONLY | O_EXTRA, 0);
2302 if (fd >= 0 && fchdir(fd) < 0)
2304 close(fd);
2305 fd = -1;
2306 dont_fchdir = TRUE; /* don't try again */
2309 #endif
2311 /* Only change directory when we are sure we can return to where
2312 * we are now. After doing "su" chdir(".") might not work. */
2313 if (
2314 #ifdef HAVE_FCHDIR
2315 fd < 0 &&
2316 #endif
2317 (mch_dirname(olddir, MAXPATHL) == FAIL
2318 || mch_chdir((char *)olddir) != 0))
2320 p = NULL; /* can't get current dir: don't chdir */
2321 retval = FAIL;
2323 else
2325 #ifdef OS2
2327 * compensate for case where ':' from "D:" was the only
2328 * path separator detected in the file name; the _next_
2329 * character has to be removed, and then restored later.
2331 if (only_drive)
2332 p++;
2333 #endif
2334 /* The directory is copied into buf[], to be able to remove
2335 * the file name without changing it (could be a string in
2336 * read-only memory) */
2337 if (p - fname >= len)
2338 retval = FAIL;
2339 else
2341 vim_strncpy(buf, fname, p - fname);
2342 if (mch_chdir((char *)buf))
2343 retval = FAIL;
2344 else
2345 fname = p + 1;
2346 *buf = NUL;
2348 #ifdef OS2
2349 if (only_drive)
2351 p--;
2352 if (retval != FAIL)
2353 fname--;
2355 #endif
2358 if (mch_dirname(buf, len) == FAIL)
2360 retval = FAIL;
2361 *buf = NUL;
2363 if (p != NULL)
2365 #ifdef HAVE_FCHDIR
2366 if (fd >= 0)
2368 l = fchdir(fd);
2369 close(fd);
2371 else
2372 #endif
2373 l = mch_chdir((char *)olddir);
2374 if (l != 0)
2375 EMSG(_(e_prev_dir));
2378 l = STRLEN(buf);
2379 if (l >= len)
2380 retval = FAIL;
2381 #ifndef VMS
2382 else
2384 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2385 && STRCMP(fname, ".") != 0)
2386 STRCAT(buf, "/");
2388 #endif
2391 /* Catch file names which are too long. */
2392 if (retval == FAIL || STRLEN(buf) + STRLEN(fname) >= len)
2393 return FAIL;
2395 /* Do not append ".", "/dir/." is equal to "/dir". */
2396 if (STRCMP(fname, ".") != 0)
2397 STRCAT(buf, fname);
2399 return OK;
2403 * Return TRUE if "fname" does not depend on the current directory.
2406 mch_isFullName(fname)
2407 char_u *fname;
2409 #ifdef __EMX__
2410 return _fnisabs(fname);
2411 #else
2412 # ifdef VMS
2413 return ( fname[0] == '/' || fname[0] == '.' ||
2414 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2415 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2416 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2417 # else
2418 return (*fname == '/' || *fname == '~');
2419 # endif
2420 #endif
2423 #if defined(USE_FNAME_CASE) || defined(PROTO)
2425 * Set the case of the file name, if it already exists. This will cause the
2426 * file name to remain exactly the same.
2427 * Only required for file systems where case is ignored and preserved.
2429 /*ARGSUSED*/
2430 void
2431 fname_case(name, len)
2432 char_u *name;
2433 int len; /* buffer size, only used when name gets longer */
2435 struct stat st;
2436 char_u *slash, *tail;
2437 DIR *dirp;
2438 struct dirent *dp;
2440 if (lstat((char *)name, &st) >= 0)
2442 /* Open the directory where the file is located. */
2443 slash = vim_strrchr(name, '/');
2444 if (slash == NULL)
2446 dirp = opendir(".");
2447 tail = name;
2449 else
2451 *slash = NUL;
2452 dirp = opendir((char *)name);
2453 *slash = '/';
2454 tail = slash + 1;
2457 if (dirp != NULL)
2459 while ((dp = readdir(dirp)) != NULL)
2461 /* Only accept names that differ in case and are the same byte
2462 * length. TODO: accept different length name. */
2463 if (STRICMP(tail, dp->d_name) == 0
2464 && STRLEN(tail) == STRLEN(dp->d_name))
2466 char_u newname[MAXPATHL + 1];
2467 struct stat st2;
2469 /* Verify the inode is equal. */
2470 vim_strncpy(newname, name, MAXPATHL);
2471 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2472 MAXPATHL - (tail - name));
2473 if (lstat((char *)newname, &st2) >= 0
2474 && st.st_ino == st2.st_ino
2475 && st.st_dev == st2.st_dev)
2477 STRCPY(tail, dp->d_name);
2478 break;
2483 closedir(dirp);
2487 #endif
2490 * Get file permissions for 'name'.
2491 * Returns -1 when it doesn't exist.
2493 long
2494 mch_getperm(name)
2495 char_u *name;
2497 struct stat statb;
2499 /* Keep the #ifdef outside of stat(), it may be a macro. */
2500 #ifdef VMS
2501 if (stat((char *)vms_fixfilename(name), &statb))
2502 #else
2503 if (stat((char *)name, &statb))
2504 #endif
2505 return -1;
2506 #ifdef __INTERIX
2507 /* The top bit makes the value negative, which means the file doesn't
2508 * exist. Remove the bit, we don't use it. */
2509 return statb.st_mode & ~S_ADDACE;
2510 #else
2511 return statb.st_mode;
2512 #endif
2516 * set file permission for 'name' to 'perm'
2518 * return FAIL for failure, OK otherwise
2521 mch_setperm(name, perm)
2522 char_u *name;
2523 long perm;
2525 return (chmod((char *)
2526 #ifdef VMS
2527 vms_fixfilename(name),
2528 #else
2529 name,
2530 #endif
2531 (mode_t)perm) == 0 ? OK : FAIL);
2534 #if defined(HAVE_ACL) || defined(PROTO)
2535 # ifdef HAVE_SYS_ACL_H
2536 # include <sys/acl.h>
2537 # endif
2538 # ifdef HAVE_SYS_ACCESS_H
2539 # include <sys/access.h>
2540 # endif
2542 # ifdef HAVE_SOLARIS_ACL
2543 typedef struct vim_acl_solaris_T {
2544 int acl_cnt;
2545 aclent_t *acl_entry;
2546 } vim_acl_solaris_T;
2547 # endif
2550 * Return a pointer to the ACL of file "fname" in allocated memory.
2551 * Return NULL if the ACL is not available for whatever reason.
2553 vim_acl_T
2554 mch_get_acl(fname)
2555 char_u *fname;
2557 vim_acl_T ret = NULL;
2558 #ifdef HAVE_POSIX_ACL
2559 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2560 #else
2561 #ifdef HAVE_SOLARIS_ACL
2562 vim_acl_solaris_T *aclent;
2564 aclent = malloc(sizeof(vim_acl_solaris_T));
2565 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2567 free(aclent);
2568 return NULL;
2570 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2571 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2573 free(aclent->acl_entry);
2574 free(aclent);
2575 return NULL;
2577 ret = (vim_acl_T)aclent;
2578 #else
2579 #if defined(HAVE_AIX_ACL)
2580 int aclsize;
2581 struct acl *aclent;
2583 aclsize = sizeof(struct acl);
2584 aclent = malloc(aclsize);
2585 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2587 if (errno == ENOSPC)
2589 aclsize = aclent->acl_len;
2590 aclent = realloc(aclent, aclsize);
2591 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2593 free(aclent);
2594 return NULL;
2597 else
2599 free(aclent);
2600 return NULL;
2603 ret = (vim_acl_T)aclent;
2604 #endif /* HAVE_AIX_ACL */
2605 #endif /* HAVE_SOLARIS_ACL */
2606 #endif /* HAVE_POSIX_ACL */
2607 return ret;
2611 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2613 void
2614 mch_set_acl(fname, aclent)
2615 char_u *fname;
2616 vim_acl_T aclent;
2618 if (aclent == NULL)
2619 return;
2620 #ifdef HAVE_POSIX_ACL
2621 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2622 #else
2623 #ifdef HAVE_SOLARIS_ACL
2624 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2625 ((vim_acl_solaris_T *)aclent)->acl_entry);
2626 #else
2627 #ifdef HAVE_AIX_ACL
2628 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2629 #endif /* HAVE_AIX_ACL */
2630 #endif /* HAVE_SOLARIS_ACL */
2631 #endif /* HAVE_POSIX_ACL */
2634 void
2635 mch_free_acl(aclent)
2636 vim_acl_T aclent;
2638 if (aclent == NULL)
2639 return;
2640 #ifdef HAVE_POSIX_ACL
2641 acl_free((acl_t)aclent);
2642 #else
2643 #ifdef HAVE_SOLARIS_ACL
2644 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2645 free(aclent);
2646 #else
2647 #ifdef HAVE_AIX_ACL
2648 free(aclent);
2649 #endif /* HAVE_AIX_ACL */
2650 #endif /* HAVE_SOLARIS_ACL */
2651 #endif /* HAVE_POSIX_ACL */
2653 #endif
2656 * Set hidden flag for "name".
2658 /* ARGSUSED */
2659 void
2660 mch_hide(name)
2661 char_u *name;
2663 /* can't hide a file */
2667 * return TRUE if "name" is a directory
2668 * return FALSE if "name" is not a directory
2669 * return FALSE for error
2672 mch_isdir(name)
2673 char_u *name;
2675 struct stat statb;
2677 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2678 return FALSE;
2679 if (stat((char *)name, &statb))
2680 return FALSE;
2681 #ifdef _POSIX_SOURCE
2682 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2683 #else
2684 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2685 #endif
2688 static int executable_file __ARGS((char_u *name));
2691 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2693 static int
2694 executable_file(name)
2695 char_u *name;
2697 struct stat st;
2699 if (stat((char *)name, &st))
2700 return 0;
2701 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2705 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2706 * Return -1 if unknown.
2709 mch_can_exe(name)
2710 char_u *name;
2712 char_u *buf;
2713 char_u *p, *e;
2714 int retval;
2716 /* If it's an absolute or relative path don't need to use $PATH. */
2717 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2718 || (name[1] == '.' && name[2] == '/'))))
2719 return executable_file(name);
2721 p = (char_u *)getenv("PATH");
2722 if (p == NULL || *p == NUL)
2723 return -1;
2724 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2725 if (buf == NULL)
2726 return -1;
2729 * Walk through all entries in $PATH to check if "name" exists there and
2730 * is an executable file.
2732 for (;;)
2734 e = (char_u *)strchr((char *)p, ':');
2735 if (e == NULL)
2736 e = p + STRLEN(p);
2737 if (e - p <= 1) /* empty entry means current dir */
2738 STRCPY(buf, "./");
2739 else
2741 vim_strncpy(buf, p, e - p);
2742 add_pathsep(buf);
2744 STRCAT(buf, name);
2745 retval = executable_file(buf);
2746 if (retval == 1)
2747 break;
2749 if (*e != ':')
2750 break;
2751 p = e + 1;
2754 vim_free(buf);
2755 return retval;
2759 * Check what "name" is:
2760 * NODE_NORMAL: file or directory (or doesn't exist)
2761 * NODE_WRITABLE: writable device, socket, fifo, etc.
2762 * NODE_OTHER: non-writable things
2765 mch_nodetype(name)
2766 char_u *name;
2768 struct stat st;
2770 if (stat((char *)name, &st))
2771 return NODE_NORMAL;
2772 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2773 return NODE_NORMAL;
2774 #ifndef OS2
2775 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2776 return NODE_OTHER;
2777 #endif
2778 /* Everything else is writable? */
2779 return NODE_WRITABLE;
2782 void
2783 mch_early_init()
2785 #ifdef HAVE_CHECK_STACK_GROWTH
2786 int i;
2788 check_stack_growth((char *)&i);
2790 # ifdef HAVE_STACK_LIMIT
2791 get_stack_limit();
2792 # endif
2794 #endif
2797 * Setup an alternative stack for signals. Helps to catch signals when
2798 * running out of stack space.
2799 * Use of sigaltstack() is preferred, it's more portable.
2800 * Ignore any errors.
2802 #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2803 signal_stack = malloc(SIGSTKSZ);
2804 init_signal_stack();
2805 #endif
2808 #if defined(EXITFREE) || defined(PROTO)
2809 void
2810 mch_free_mem()
2812 # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2813 if (clip_star.owned)
2814 clip_lose_selection(&clip_star);
2815 if (clip_plus.owned)
2816 clip_lose_selection(&clip_plus);
2817 # endif
2818 # if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
2819 if (xterm_Shell != (Widget)0)
2820 XtDestroyWidget(xterm_Shell);
2821 if (xterm_dpy != NULL)
2822 XtCloseDisplay(xterm_dpy);
2823 if (app_context != (XtAppContext)NULL)
2824 XtDestroyApplicationContext(app_context);
2825 # endif
2826 # ifdef FEAT_X11
2827 if (x11_display != NULL && x11_display != xterm_dpy)
2828 XCloseDisplay(x11_display);
2829 # endif
2830 # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2831 vim_free(signal_stack);
2832 signal_stack = NULL;
2833 # endif
2834 # ifdef FEAT_TITLE
2835 vim_free(oldtitle);
2836 vim_free(oldicon);
2837 # endif
2839 #endif
2841 static void exit_scroll __ARGS((void));
2844 * Output a newline when exiting.
2845 * Make sure the newline goes to the same stream as the text.
2847 static void
2848 exit_scroll()
2850 if (silent_mode)
2851 return;
2852 if (newline_on_exit || msg_didout)
2854 if (msg_use_printf())
2856 if (info_message)
2857 mch_msg("\n");
2858 else
2859 mch_errmsg("\r\n");
2861 else
2862 out_char('\n');
2864 else
2866 restore_cterm_colors(); /* get original colors back */
2867 msg_clr_eos_force(); /* clear the rest of the display */
2868 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
2872 void
2873 mch_exit(r)
2874 int r;
2876 exiting = TRUE;
2878 #if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
2879 x11_export_final_selection();
2880 #endif
2882 #ifdef FEAT_GUI
2883 if (!gui.in_use)
2884 #endif
2886 settmode(TMODE_COOK);
2887 #ifdef FEAT_TITLE
2888 mch_restore_title(3); /* restore xterm title and icon name */
2889 #endif
2891 * When t_ti is not empty but it doesn't cause swapping terminal
2892 * pages, need to output a newline when msg_didout is set. But when
2893 * t_ti does swap pages it should not go to the shell page. Do this
2894 * before stoptermcap().
2896 if (swapping_screen() && !newline_on_exit)
2897 exit_scroll();
2899 /* Stop termcap: May need to check for T_CRV response, which
2900 * requires RAW mode. */
2901 stoptermcap();
2904 * A newline is only required after a message in the alternate screen.
2905 * This is set to TRUE by wait_return().
2907 if (!swapping_screen() || newline_on_exit)
2908 exit_scroll();
2910 /* Cursor may have been switched off without calling starttermcap()
2911 * when doing "vim -u vimrc" and vimrc contains ":q". */
2912 if (full_screen)
2913 cursor_on();
2915 out_flush();
2916 ml_close_all(TRUE); /* remove all memfiles */
2917 may_core_dump();
2918 #ifdef FEAT_GUI
2919 if (gui.in_use)
2920 gui_exit(r);
2921 #endif
2923 #ifdef MACOS_CONVERT
2924 mac_conv_cleanup();
2925 #endif
2927 #ifdef __QNX__
2928 /* A core dump won't be created if the signal handler
2929 * doesn't return, so we can't call exit() */
2930 if (deadly_signal != 0)
2931 return;
2932 #endif
2934 #ifdef FEAT_NETBEANS_INTG
2935 if (usingNetbeans)
2936 netbeans_send_disconnect();
2937 #endif
2939 #ifdef EXITFREE
2940 free_all_mem();
2941 #endif
2943 exit(r);
2946 static void
2947 may_core_dump()
2949 if (deadly_signal != 0)
2951 signal(deadly_signal, SIG_DFL);
2952 kill(getpid(), deadly_signal); /* Die using the signal we caught */
2956 #ifndef VMS
2958 void
2959 mch_settmode(tmode)
2960 int tmode;
2962 static int first = TRUE;
2964 /* Why is NeXT excluded here (and not in os_unixx.h)? */
2965 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
2967 * for "new" tty systems
2969 # ifdef HAVE_TERMIOS_H
2970 static struct termios told;
2971 struct termios tnew;
2972 # else
2973 static struct termio told;
2974 struct termio tnew;
2975 # endif
2977 if (first)
2979 first = FALSE;
2980 # if defined(HAVE_TERMIOS_H)
2981 tcgetattr(read_cmd_fd, &told);
2982 # else
2983 ioctl(read_cmd_fd, TCGETA, &told);
2984 # endif
2987 tnew = told;
2988 if (tmode == TMODE_RAW)
2991 * ~ICRNL enables typing ^V^M
2993 tnew.c_iflag &= ~ICRNL;
2994 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
2995 # if defined(IEXTEN) && !defined(__MINT__)
2996 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
2997 /* but it breaks function keys on MINT */
2998 # endif
3000 # ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3001 tnew.c_oflag &= ~ONLCR;
3002 # endif
3003 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3004 tnew.c_cc[VTIME] = 0; /* don't wait */
3006 else if (tmode == TMODE_SLEEP)
3007 tnew.c_lflag &= ~(ECHO);
3009 # if defined(HAVE_TERMIOS_H)
3011 int n = 10;
3013 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3014 * few times. */
3015 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3016 && errno == EINTR && n > 0)
3017 --n;
3019 # else
3020 ioctl(read_cmd_fd, TCSETA, &tnew);
3021 # endif
3023 #else
3026 * for "old" tty systems
3028 # ifndef TIOCSETN
3029 # define TIOCSETN TIOCSETP /* for hpux 9.0 */
3030 # endif
3031 static struct sgttyb ttybold;
3032 struct sgttyb ttybnew;
3034 if (first)
3036 first = FALSE;
3037 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3040 ttybnew = ttybold;
3041 if (tmode == TMODE_RAW)
3043 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3044 ttybnew.sg_flags |= RAW;
3046 else if (tmode == TMODE_SLEEP)
3047 ttybnew.sg_flags &= ~(ECHO);
3048 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3049 #endif
3050 curr_tmode = tmode;
3054 * Try to get the code for "t_kb" from the stty setting
3056 * Even if termcap claims a backspace key, the user's setting *should*
3057 * prevail. stty knows more about reality than termcap does, and if
3058 * somebody's usual erase key is DEL (which, for most BSD users, it will
3059 * be), they're going to get really annoyed if their erase key starts
3060 * doing forward deletes for no reason. (Eric Fischer)
3062 void
3063 get_stty()
3065 char_u buf[2];
3066 char_u *p;
3068 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3069 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3070 /* for "new" tty systems */
3071 # ifdef HAVE_TERMIOS_H
3072 struct termios keys;
3073 # else
3074 struct termio keys;
3075 # endif
3077 # if defined(HAVE_TERMIOS_H)
3078 if (tcgetattr(read_cmd_fd, &keys) != -1)
3079 # else
3080 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3081 # endif
3083 buf[0] = keys.c_cc[VERASE];
3084 intr_char = keys.c_cc[VINTR];
3085 #else
3086 /* for "old" tty systems */
3087 struct sgttyb keys;
3089 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3091 buf[0] = keys.sg_erase;
3092 intr_char = keys.sg_kill;
3093 #endif
3094 buf[1] = NUL;
3095 add_termcode((char_u *)"kb", buf, FALSE);
3098 * If <BS> and <DEL> are now the same, redefine <DEL>.
3100 p = find_termcode((char_u *)"kD");
3101 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3102 do_fixdel(NULL);
3104 #if 0
3105 } /* to keep cindent happy */
3106 #endif
3109 #endif /* VMS */
3111 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3113 * Set mouse clicks on or off.
3115 void
3116 mch_setmouse(on)
3117 int on;
3119 static int ison = FALSE;
3120 int xterm_mouse_vers;
3122 if (on == ison) /* return quickly if nothing to do */
3123 return;
3125 xterm_mouse_vers = use_xterm_mouse();
3126 if (xterm_mouse_vers > 0)
3128 if (on) /* enable mouse events, use mouse tracking if available */
3129 out_str_nf((char_u *)
3130 (xterm_mouse_vers > 1
3131 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3132 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3133 else /* disable mouse events, could probably always send the same */
3134 out_str_nf((char_u *)
3135 (xterm_mouse_vers > 1
3136 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3137 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3138 ison = on;
3141 # ifdef FEAT_MOUSE_DEC
3142 else if (ttym_flags == TTYM_DEC)
3144 if (on) /* enable mouse events */
3145 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3146 else /* disable mouse events */
3147 out_str_nf((char_u *)"\033['z");
3148 ison = on;
3150 # endif
3152 # ifdef FEAT_MOUSE_GPM
3153 else
3155 if (on)
3157 if (gpm_open())
3158 ison = TRUE;
3160 else
3162 gpm_close();
3163 ison = FALSE;
3166 # endif
3168 # ifdef FEAT_MOUSE_JSB
3169 else
3171 if (on)
3173 /* D - Enable Mouse up/down messages
3174 * L - Enable Left Button Reporting
3175 * M - Enable Middle Button Reporting
3176 * R - Enable Right Button Reporting
3177 * K - Enable SHIFT and CTRL key Reporting
3178 * + - Enable Advanced messaging of mouse moves and up/down messages
3179 * Q - Quiet No Ack
3180 * # - Numeric value of mouse pointer required
3181 * 0 = Multiview 2000 cursor, used as standard
3182 * 1 = Windows Arrow
3183 * 2 = Windows I Beam
3184 * 3 = Windows Hour Glass
3185 * 4 = Windows Cross Hair
3186 * 5 = Windows UP Arrow
3188 #ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3189 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3190 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3191 #else
3192 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3193 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3194 #endif
3195 ison = TRUE;
3197 else
3199 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3200 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3201 ison = FALSE;
3204 # endif
3205 # ifdef FEAT_MOUSE_PTERM
3206 else
3208 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3209 if (on)
3210 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3211 else
3212 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3213 ison = on;
3215 # endif
3219 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3221 void
3222 check_mouse_termcode()
3224 # ifdef FEAT_MOUSE_XTERM
3225 if (use_xterm_mouse()
3226 # ifdef FEAT_GUI
3227 && !gui.in_use
3228 # endif
3231 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3232 ? IF_EB("\233M", CSI_STR "M")
3233 : IF_EB("\033[M", ESC_STR "[M")));
3234 if (*p_mouse != NUL)
3236 /* force mouse off and maybe on to send possibly new mouse
3237 * activation sequence to the xterm, with(out) drag tracing. */
3238 mch_setmouse(FALSE);
3239 setmouse();
3242 else
3243 del_mouse_termcode(KS_MOUSE);
3244 # endif
3246 # ifdef FEAT_MOUSE_GPM
3247 if (!use_xterm_mouse()
3248 # ifdef FEAT_GUI
3249 && !gui.in_use
3250 # endif
3252 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3253 # endif
3255 # ifdef FEAT_MOUSE_JSB
3256 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3257 if (!use_xterm_mouse()
3258 # ifdef FEAT_GUI
3259 && !gui.in_use
3260 # endif
3262 set_mouse_termcode(KS_JSBTERM_MOUSE,
3263 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3264 else
3265 del_mouse_termcode(KS_JSBTERM_MOUSE);
3266 # endif
3268 # ifdef FEAT_MOUSE_NET
3269 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
3270 * define it in the GUI or when using an xterm. */
3271 if (!use_xterm_mouse()
3272 # ifdef FEAT_GUI
3273 && !gui.in_use
3274 # endif
3276 set_mouse_termcode(KS_NETTERM_MOUSE,
3277 (char_u *)IF_EB("\033}", ESC_STR "}"));
3278 else
3279 del_mouse_termcode(KS_NETTERM_MOUSE);
3280 # endif
3282 # ifdef FEAT_MOUSE_DEC
3283 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3284 if (!use_xterm_mouse()
3285 # ifdef FEAT_GUI
3286 && !gui.in_use
3287 # endif
3289 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3290 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
3291 else
3292 del_mouse_termcode(KS_DEC_MOUSE);
3293 # endif
3294 # ifdef FEAT_MOUSE_PTERM
3295 /* same as the dec mouse */
3296 if (!use_xterm_mouse()
3297 # ifdef FEAT_GUI
3298 && !gui.in_use
3299 # endif
3301 set_mouse_termcode(KS_PTERM_MOUSE,
3302 (char_u *) IF_EB("\033[", ESC_STR "["));
3303 else
3304 del_mouse_termcode(KS_PTERM_MOUSE);
3305 # endif
3307 #endif
3310 * set screen mode, always fails.
3312 /* ARGSUSED */
3314 mch_screenmode(arg)
3315 char_u *arg;
3317 EMSG(_(e_screenmode));
3318 return FAIL;
3321 #ifndef VMS
3324 * Try to get the current window size:
3325 * 1. with an ioctl(), most accurate method
3326 * 2. from the environment variables LINES and COLUMNS
3327 * 3. from the termcap
3328 * 4. keep using the old values
3329 * Return OK when size could be determined, FAIL otherwise.
3332 mch_get_shellsize()
3334 long rows = 0;
3335 long columns = 0;
3336 char_u *p;
3339 * For OS/2 use _scrsize().
3341 # ifdef __EMX__
3343 int s[2];
3345 _scrsize(s);
3346 columns = s[0];
3347 rows = s[1];
3349 # endif
3352 * 1. try using an ioctl. It is the most accurate method.
3354 * Try using TIOCGWINSZ first, some systems that have it also define
3355 * TIOCGSIZE but don't have a struct ttysize.
3357 # ifdef TIOCGWINSZ
3359 struct winsize ws;
3360 int fd = 1;
3362 /* When stdout is not a tty, use stdin for the ioctl(). */
3363 if (!isatty(fd) && isatty(read_cmd_fd))
3364 fd = read_cmd_fd;
3365 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3367 columns = ws.ws_col;
3368 rows = ws.ws_row;
3371 # else /* TIOCGWINSZ */
3372 # ifdef TIOCGSIZE
3374 struct ttysize ts;
3375 int fd = 1;
3377 /* When stdout is not a tty, use stdin for the ioctl(). */
3378 if (!isatty(fd) && isatty(read_cmd_fd))
3379 fd = read_cmd_fd;
3380 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3382 columns = ts.ts_cols;
3383 rows = ts.ts_lines;
3386 # endif /* TIOCGSIZE */
3387 # endif /* TIOCGWINSZ */
3390 * 2. get size from environment
3391 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3392 * the ioctl() values!
3394 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
3396 if ((p = (char_u *)getenv("LINES")))
3397 rows = atoi((char *)p);
3398 if ((p = (char_u *)getenv("COLUMNS")))
3399 columns = atoi((char *)p);
3402 #ifdef HAVE_TGETENT
3404 * 3. try reading "co" and "li" entries from termcap
3406 if (columns == 0 || rows == 0)
3407 getlinecol(&columns, &rows);
3408 #endif
3411 * 4. If everything fails, use the old values
3413 if (columns <= 0 || rows <= 0)
3414 return FAIL;
3416 Rows = rows;
3417 Columns = columns;
3418 return OK;
3422 * Try to set the window size to Rows and Columns.
3424 void
3425 mch_set_shellsize()
3427 if (*T_CWS)
3430 * NOTE: if you get an error here that term_set_winsize() is
3431 * undefined, check the output of configure. It could probably not
3432 * find a ncurses, termcap or termlib library.
3434 term_set_winsize((int)Rows, (int)Columns);
3435 out_flush();
3436 screen_start(); /* don't know where cursor is now */
3440 #endif /* VMS */
3443 * Rows and/or Columns has changed.
3445 void
3446 mch_new_shellsize()
3448 /* Nothing to do. */
3451 #ifndef USE_SYSTEM
3452 static void append_ga_line __ARGS((garray_T *gap));
3455 * Append the text in "gap" below the cursor line and clear "gap".
3457 static void
3458 append_ga_line(gap)
3459 garray_T *gap;
3461 /* Remove trailing CR. */
3462 if (gap->ga_len > 0
3463 && !curbuf->b_p_bin
3464 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
3465 --gap->ga_len;
3466 ga_append(gap, NUL);
3467 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
3468 gap->ga_len = 0;
3470 #endif
3473 mch_call_shell(cmd, options)
3474 char_u *cmd;
3475 int options; /* SHELL_*, see vim.h */
3477 #ifdef VMS
3478 char *ifn = NULL;
3479 char *ofn = NULL;
3480 #endif
3481 int tmode = cur_tmode;
3482 #ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3483 int x;
3484 # ifndef __EMX__
3485 char_u *newcmd; /* only needed for unix */
3486 # else
3488 * Set the preferred shell in the EMXSHELL environment variable (but
3489 * only if it is different from what is already in the environment).
3490 * Emx then takes care of whether to use "/c" or "-c" in an
3491 * intelligent way. Simply pass the whole thing to emx's system() call.
3492 * Emx also starts an interactive shell if system() is passed an empty
3493 * string.
3495 char_u *p, *old;
3497 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3499 /* should check HAVE_SETENV, but I know we don't have it. */
3500 p = alloc(10 + strlen(p_sh));
3501 if (p)
3503 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3504 putenv((char *)p); /* don't free the pointer! */
3507 # endif
3509 out_flush();
3511 if (options & SHELL_COOKED)
3512 settmode(TMODE_COOK); /* set to normal mode */
3514 # ifdef __EMX__
3515 if (cmd == NULL)
3516 x = system(""); /* this starts an interactive shell in emx */
3517 else
3518 x = system((char *)cmd);
3519 /* system() returns -1 when error occurs in starting shell */
3520 if (x == -1 && !emsg_silent)
3522 MSG_PUTS(_("\nCannot execute shell "));
3523 msg_outtrans(p_sh);
3524 msg_putchar('\n');
3526 # else /* not __EMX__ */
3527 if (cmd == NULL)
3528 x = system((char *)p_sh);
3529 else
3531 # ifdef VMS
3532 if (ofn = strchr((char *)cmd, '>'))
3533 *ofn++ = '\0';
3534 if (ifn = strchr((char *)cmd, '<'))
3536 char *p;
3538 *ifn++ = '\0';
3539 p = strchr(ifn,' '); /* chop off any trailing spaces */
3540 if (p)
3541 *p = '\0';
3543 if (ofn)
3544 x = vms_sys((char *)cmd, ofn, ifn);
3545 else
3546 x = system((char *)cmd);
3547 # else
3548 newcmd = lalloc(STRLEN(p_sh)
3549 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3550 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3551 if (newcmd == NULL)
3552 x = 0;
3553 else
3555 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3556 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3557 (char *)p_shcf,
3558 (char *)cmd);
3559 x = system((char *)newcmd);
3560 vim_free(newcmd);
3562 # endif
3564 # ifdef VMS
3565 x = vms_sys_status(x);
3566 # endif
3567 if (emsg_silent)
3569 else if (x == 127)
3570 MSG_PUTS(_("\nCannot execute shell sh\n"));
3571 # endif /* __EMX__ */
3572 else if (x && !(options & SHELL_SILENT))
3574 MSG_PUTS(_("\nshell returned "));
3575 msg_outnum((long)x);
3576 msg_putchar('\n');
3579 if (tmode == TMODE_RAW)
3580 settmode(TMODE_RAW); /* set to raw mode */
3581 # ifdef FEAT_TITLE
3582 resettitle();
3583 # endif
3584 return x;
3586 #else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3588 # define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3589 127, some shells use that already */
3591 char_u *newcmd = NULL;
3592 pid_t pid;
3593 pid_t wpid = 0;
3594 pid_t wait_pid = 0;
3595 # ifdef HAVE_UNION_WAIT
3596 union wait status;
3597 # else
3598 int status = -1;
3599 # endif
3600 int retval = -1;
3601 char **argv = NULL;
3602 int argc;
3603 int i;
3604 char_u *p;
3605 int inquote;
3606 int pty_master_fd = -1; /* for pty's */
3607 # ifdef FEAT_GUI
3608 int pty_slave_fd = -1;
3609 char *tty_name;
3610 # endif
3611 int fd_toshell[2]; /* for pipes */
3612 int fd_fromshell[2];
3613 int pipe_error = FALSE;
3614 # ifdef HAVE_SETENV
3615 char envbuf[50];
3616 # else
3617 static char envbuf_Rows[20];
3618 static char envbuf_Columns[20];
3619 # endif
3620 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
3622 out_flush();
3623 if (options & SHELL_COOKED)
3624 settmode(TMODE_COOK); /* set to normal mode */
3626 newcmd = vim_strsave(p_sh);
3627 if (newcmd == NULL) /* out of memory */
3628 goto error;
3631 * Do this loop twice:
3632 * 1: find number of arguments
3633 * 2: separate them and build argv[]
3635 for (i = 0; i < 2; ++i)
3637 p = newcmd;
3638 inquote = FALSE;
3639 argc = 0;
3640 for (;;)
3642 if (i == 1)
3643 argv[argc] = (char *)p;
3644 ++argc;
3645 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3647 if (*p == '"')
3648 inquote = !inquote;
3649 ++p;
3651 if (*p == NUL)
3652 break;
3653 if (i == 1)
3654 *p++ = NUL;
3655 p = skipwhite(p);
3657 if (argv == NULL)
3659 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3660 if (argv == NULL) /* out of memory */
3661 goto error;
3664 if (cmd != NULL)
3666 if (extra_shell_arg != NULL)
3667 argv[argc++] = (char *)extra_shell_arg;
3668 argv[argc++] = (char *)p_shcf;
3669 argv[argc++] = (char *)cmd;
3671 argv[argc] = NULL;
3674 * For the GUI, when writing the output into the buffer and when reading
3675 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3676 * of the executed command into the Vim window. Or use a pipe.
3678 if ((options & (SHELL_READ|SHELL_WRITE))
3679 # ifdef FEAT_GUI
3680 || (gui.in_use && show_shell_mess)
3681 # endif
3684 # ifdef FEAT_GUI
3686 * Try to open a master pty.
3687 * If this works, open the slave pty.
3688 * If the slave can't be opened, close the master pty.
3690 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
3692 pty_master_fd = OpenPTY(&tty_name); /* open pty */
3693 if (pty_master_fd >= 0 && ((pty_slave_fd =
3694 open(tty_name, O_RDWR | O_EXTRA, 0)) < 0))
3696 close(pty_master_fd);
3697 pty_master_fd = -1;
3701 * If not opening a pty or it didn't work, try using pipes.
3703 if (pty_master_fd < 0)
3704 # endif
3706 pipe_error = (pipe(fd_toshell) < 0);
3707 if (!pipe_error) /* pipe create OK */
3709 pipe_error = (pipe(fd_fromshell) < 0);
3710 if (pipe_error) /* pipe create failed */
3712 close(fd_toshell[0]);
3713 close(fd_toshell[1]);
3716 if (pipe_error)
3718 MSG_PUTS(_("\nCannot create pipes\n"));
3719 out_flush();
3724 if (!pipe_error) /* pty or pipe opened or not used */
3726 # ifdef __BEOS__
3727 beos_cleanup_read_thread();
3728 # endif
3730 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3732 MSG_PUTS(_("\nCannot fork\n"));
3733 if ((options & (SHELL_READ|SHELL_WRITE))
3734 # ifdef FEAT_GUI
3735 || (gui.in_use && show_shell_mess)
3736 # endif
3739 # ifdef FEAT_GUI
3740 if (pty_master_fd >= 0) /* close the pseudo tty */
3742 close(pty_master_fd);
3743 close(pty_slave_fd);
3745 else /* close the pipes */
3746 # endif
3748 close(fd_toshell[0]);
3749 close(fd_toshell[1]);
3750 close(fd_fromshell[0]);
3751 close(fd_fromshell[1]);
3755 else if (pid == 0) /* child */
3757 reset_signals(); /* handle signals normally */
3759 if (!show_shell_mess || (options & SHELL_EXPAND))
3761 int fd;
3764 * Don't want to show any message from the shell. Can't just
3765 * close stdout and stderr though, because some systems will
3766 * break if you try to write to them after that, so we must
3767 * use dup() to replace them with something else -- webb
3768 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3769 * waiting for input.
3771 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3772 fclose(stdin);
3773 fclose(stdout);
3774 fclose(stderr);
3777 * If any of these open()'s and dup()'s fail, we just continue
3778 * anyway. It's not fatal, and on most systems it will make
3779 * no difference at all. On a few it will cause the execvp()
3780 * to exit with a non-zero status even when the completion
3781 * could be done, which is nothing too serious. If the open()
3782 * or dup() failed we'd just do the same thing ourselves
3783 * anyway -- webb
3785 if (fd >= 0)
3787 dup(fd); /* To replace stdin (file descriptor 0) */
3788 dup(fd); /* To replace stdout (file descriptor 1) */
3789 dup(fd); /* To replace stderr (file descriptor 2) */
3791 /* Don't need this now that we've duplicated it */
3792 close(fd);
3795 else if ((options & (SHELL_READ|SHELL_WRITE))
3796 # ifdef FEAT_GUI
3797 || gui.in_use
3798 # endif
3802 # ifdef HAVE_SETSID
3803 /* Create our own process group, so that the child and all its
3804 * children can be kill()ed. Don't do this when using pipes,
3805 * because stdin is not a tty, we would loose /dev/tty. */
3806 if (p_stmp)
3807 (void)setsid();
3808 # endif
3809 # ifdef FEAT_GUI
3810 if (pty_slave_fd >= 0)
3812 /* push stream discipline modules */
3813 if (options & SHELL_COOKED)
3814 SetupSlavePTY(pty_slave_fd);
3815 # ifdef TIOCSCTTY
3816 /* Try to become controlling tty (probably doesn't work,
3817 * unless run by root) */
3818 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
3819 # endif
3821 # endif
3822 /* Simulate to have a dumb terminal (for now) */
3823 # ifdef HAVE_SETENV
3824 setenv("TERM", "dumb", 1);
3825 sprintf((char *)envbuf, "%ld", Rows);
3826 setenv("ROWS", (char *)envbuf, 1);
3827 sprintf((char *)envbuf, "%ld", Rows);
3828 setenv("LINES", (char *)envbuf, 1);
3829 sprintf((char *)envbuf, "%ld", Columns);
3830 setenv("COLUMNS", (char *)envbuf, 1);
3831 # else
3833 * Putenv does not copy the string, it has to remain valid.
3834 * Use a static array to avoid loosing allocated memory.
3836 putenv("TERM=dumb");
3837 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
3838 putenv(envbuf_Rows);
3839 sprintf(envbuf_Rows, "LINES=%ld", Rows);
3840 putenv(envbuf_Rows);
3841 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
3842 putenv(envbuf_Columns);
3843 # endif
3846 * stderr is only redirected when using the GUI, so that a
3847 * program like gpg can still access the terminal to get a
3848 * passphrase using stderr.
3850 # ifdef FEAT_GUI
3851 if (pty_master_fd >= 0)
3853 close(pty_master_fd); /* close master side of pty */
3855 /* set up stdin/stdout/stderr for the child */
3856 close(0);
3857 dup(pty_slave_fd);
3858 close(1);
3859 dup(pty_slave_fd);
3860 if (gui.in_use)
3862 close(2);
3863 dup(pty_slave_fd);
3866 close(pty_slave_fd); /* has been dupped, close it now */
3868 else
3869 # endif
3871 /* set up stdin for the child */
3872 close(fd_toshell[1]);
3873 close(0);
3874 dup(fd_toshell[0]);
3875 close(fd_toshell[0]);
3877 /* set up stdout for the child */
3878 close(fd_fromshell[0]);
3879 close(1);
3880 dup(fd_fromshell[1]);
3881 close(fd_fromshell[1]);
3883 # ifdef FEAT_GUI
3884 if (gui.in_use)
3886 /* set up stderr for the child */
3887 close(2);
3888 dup(1);
3890 # endif
3895 * There is no type cast for the argv, because the type may be
3896 * different on different machines. This may cause a warning
3897 * message with strict compilers, don't worry about it.
3898 * Call _exit() instead of exit() to avoid closing the connection
3899 * to the X server (esp. with GTK, which uses atexit()).
3901 execvp(argv[0], argv);
3902 _exit(EXEC_FAILED); /* exec failed, return failure code */
3904 else /* parent */
3907 * While child is running, ignore terminating signals.
3908 * Do catch CTRL-C, so that "got_int" is set.
3910 catch_signals(SIG_IGN, SIG_ERR);
3911 catch_int_signal();
3914 * For the GUI we redirect stdin, stdout and stderr to our window.
3915 * This is also used to pipe stdin/stdout to/from the external
3916 * command.
3918 if ((options & (SHELL_READ|SHELL_WRITE))
3919 # ifdef FEAT_GUI
3920 || (gui.in_use && show_shell_mess)
3921 # endif
3924 # define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
3925 char_u buffer[BUFLEN + 1];
3926 # ifdef FEAT_MBYTE
3927 int buffer_off = 0; /* valid bytes in buffer[] */
3928 # endif
3929 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3930 int ta_len = 0; /* valid bytes in ta_buf[] */
3931 int len;
3932 int p_more_save;
3933 int old_State;
3934 int c;
3935 int toshell_fd;
3936 int fromshell_fd;
3937 garray_T ga;
3938 int noread_cnt;
3940 # ifdef FEAT_GUI
3941 if (pty_master_fd >= 0)
3943 close(pty_slave_fd); /* close slave side of pty */
3944 fromshell_fd = pty_master_fd;
3945 toshell_fd = dup(pty_master_fd);
3947 else
3948 # endif
3950 close(fd_toshell[0]);
3951 close(fd_fromshell[1]);
3952 toshell_fd = fd_toshell[1];
3953 fromshell_fd = fd_fromshell[0];
3957 * Write to the child if there are typed characters.
3958 * Read from the child if there are characters available.
3959 * Repeat the reading a few times if more characters are
3960 * available. Need to check for typed keys now and then, but
3961 * not too often (delays when no chars are available).
3962 * This loop is quit if no characters can be read from the pty
3963 * (WaitForChar detected special condition), or there are no
3964 * characters available and the child has exited.
3965 * Only check if the child has exited when there is no more
3966 * output. The child may exit before all the output has
3967 * been printed.
3969 * Currently this busy loops!
3970 * This can probably dead-lock when the write blocks!
3972 p_more_save = p_more;
3973 p_more = FALSE;
3974 old_State = State;
3975 State = EXTERNCMD; /* don't redraw at window resize */
3977 if ((options & SHELL_WRITE) && toshell_fd >= 0)
3979 /* Fork a process that will write the lines to the
3980 * external program. */
3981 if ((wpid = fork()) == -1)
3983 MSG_PUTS(_("\nCannot fork\n"));
3985 else if (wpid == 0)
3987 linenr_T lnum = curbuf->b_op_start.lnum;
3988 int written = 0;
3989 char_u *lp = ml_get(lnum);
3990 char_u *s;
3991 size_t l;
3993 /* child */
3994 close(fromshell_fd);
3995 for (;;)
3997 l = STRLEN(lp + written);
3998 if (l == 0)
3999 len = 0;
4000 else if (lp[written] == NL)
4001 /* NL -> NUL translation */
4002 len = write(toshell_fd, "", (size_t)1);
4003 else
4005 s = vim_strchr(lp + written, NL);
4006 len = write(toshell_fd, (char *)lp + written,
4007 s == NULL ? l : s - (lp + written));
4009 if (len == l)
4011 /* Finished a line, add a NL, unless this line
4012 * should not have one. */
4013 if (lnum != curbuf->b_op_end.lnum
4014 || !curbuf->b_p_bin
4015 || (lnum != write_no_eol_lnum
4016 && (lnum !=
4017 curbuf->b_ml.ml_line_count
4018 || curbuf->b_p_eol)))
4019 write(toshell_fd, "\n", (size_t)1);
4020 ++lnum;
4021 if (lnum > curbuf->b_op_end.lnum)
4023 /* finished all the lines, close pipe */
4024 close(toshell_fd);
4025 toshell_fd = -1;
4026 break;
4028 lp = ml_get(lnum);
4029 written = 0;
4031 else if (len > 0)
4032 written += len;
4034 _exit(0);
4036 else
4038 close(toshell_fd);
4039 toshell_fd = -1;
4043 if (options & SHELL_READ)
4044 ga_init2(&ga, 1, BUFLEN);
4046 noread_cnt = 0;
4048 for (;;)
4051 * Check if keys have been typed, write them to the child
4052 * if there are any.
4053 * Don't do this if we are expanding wild cards (would eat
4054 * typeahead).
4055 * Don't do this when filtering and terminal is in cooked
4056 * mode, the shell command will handle the I/O. Avoids
4057 * that a typed password is echoed for ssh or gpg command.
4058 * Don't get characters when the child has already
4059 * finished (wait_pid == 0).
4060 * Don't get extra characters when we already have one.
4061 * Don't read characters unless we didn't get output for a
4062 * while, avoids that ":r !ls" eats typeahead.
4064 len = 0;
4065 if (!(options & SHELL_EXPAND)
4066 && ((options &
4067 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4068 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4069 #ifdef FEAT_GUI
4070 || gui.in_use
4071 #endif
4073 && wait_pid == 0
4074 && (ta_len > 0
4075 || (noread_cnt > 4
4076 && (len = ui_inchar(ta_buf,
4077 BUFLEN, 10L, 0)) > 0)))
4080 * For pipes:
4081 * Check for CTRL-C: send interrupt signal to child.
4082 * Check for CTRL-D: EOF, close pipe to child.
4084 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4086 # ifdef SIGINT
4088 * Send SIGINT to the child's group or all
4089 * processes in our group.
4091 if (ta_buf[ta_len] == Ctrl_C
4092 || ta_buf[ta_len] == intr_char)
4094 # ifdef HAVE_SETSID
4095 kill(-pid, SIGINT);
4096 # else
4097 kill(0, SIGINT);
4098 # endif
4099 if (wpid > 0)
4100 kill(wpid, SIGINT);
4102 # endif
4103 if (pty_master_fd < 0 && toshell_fd >= 0
4104 && ta_buf[ta_len] == Ctrl_D)
4106 close(toshell_fd);
4107 toshell_fd = -1;
4111 /* replace K_BS by <BS> and K_DEL by <DEL> */
4112 for (i = ta_len; i < ta_len + len; ++i)
4114 if (ta_buf[i] == CSI && len - i > 2)
4116 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4117 if (c == K_DEL || c == K_KDEL || c == K_BS)
4119 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4120 (size_t)(len - i - 2));
4121 if (c == K_DEL || c == K_KDEL)
4122 ta_buf[i] = DEL;
4123 else
4124 ta_buf[i] = Ctrl_H;
4125 len -= 2;
4128 else if (ta_buf[i] == '\r')
4129 ta_buf[i] = '\n';
4130 # ifdef FEAT_MBYTE
4131 if (has_mbyte)
4132 i += (*mb_ptr2len)(ta_buf + i) - 1;
4133 # endif
4137 * For pipes: echo the typed characters.
4138 * For a pty this does not seem to work.
4140 if (pty_master_fd < 0)
4142 for (i = ta_len; i < ta_len + len; ++i)
4144 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4145 msg_putchar(ta_buf[i]);
4146 # ifdef FEAT_MBYTE
4147 else if (has_mbyte)
4149 int l = (*mb_ptr2len)(ta_buf + i);
4151 msg_outtrans_len(ta_buf + i, l);
4152 i += l - 1;
4154 # endif
4155 else
4156 msg_outtrans_len(ta_buf + i, 1);
4158 windgoto(msg_row, msg_col);
4159 out_flush();
4162 ta_len += len;
4165 * Write the characters to the child, unless EOF has
4166 * been typed for pipes. Write one character at a
4167 * time, to avoid loosing too much typeahead.
4168 * When writing buffer lines, drop the typed
4169 * characters (only check for CTRL-C).
4171 if (options & SHELL_WRITE)
4172 ta_len = 0;
4173 else if (toshell_fd >= 0)
4175 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4176 if (len > 0)
4178 ta_len -= len;
4179 mch_memmove(ta_buf, ta_buf + len, ta_len);
4180 noread_cnt = 0;
4185 if (got_int)
4187 /* CTRL-C sends a signal to the child, we ignore it
4188 * ourselves */
4189 # ifdef HAVE_SETSID
4190 kill(-pid, SIGINT);
4191 # else
4192 kill(0, SIGINT);
4193 # endif
4194 if (wpid > 0)
4195 kill(wpid, SIGINT);
4196 got_int = FALSE;
4200 * Check if the child has any characters to be printed.
4201 * Read them and write them to our window. Repeat this as
4202 * long as there is something to do, avoid the 10ms wait
4203 * for mch_inchar(), or sending typeahead characters to
4204 * the external process.
4205 * TODO: This should handle escape sequences, compatible
4206 * to some terminal (vt52?).
4208 ++noread_cnt;
4209 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4211 len = read(fromshell_fd, (char *)buffer
4212 # ifdef FEAT_MBYTE
4213 + buffer_off, (size_t)(BUFLEN - buffer_off)
4214 # else
4215 , (size_t)BUFLEN
4216 # endif
4218 if (len <= 0) /* end of file or error */
4219 goto finished;
4221 noread_cnt = 0;
4222 if (options & SHELL_READ)
4224 /* Do NUL -> NL translation, append NL separated
4225 * lines to the current buffer. */
4226 for (i = 0; i < len; ++i)
4228 if (buffer[i] == NL)
4229 append_ga_line(&ga);
4230 else if (buffer[i] == NUL)
4231 ga_append(&ga, NL);
4232 else
4233 ga_append(&ga, buffer[i]);
4236 # ifdef FEAT_MBYTE
4237 else if (has_mbyte)
4239 int l;
4241 len += buffer_off;
4242 buffer[len] = NUL;
4244 /* Check if the last character in buffer[] is
4245 * incomplete, keep these bytes for the next
4246 * round. */
4247 for (p = buffer; p < buffer + len; p += l)
4249 l = mb_cptr2len(p);
4250 if (l == 0)
4251 l = 1; /* NUL byte? */
4252 else if (MB_BYTE2LEN(*p) != l)
4253 break;
4255 if (p == buffer) /* no complete character */
4257 /* avoid getting stuck at an illegal byte */
4258 if (len >= 12)
4259 ++p;
4260 else
4262 buffer_off = len;
4263 continue;
4266 c = *p;
4267 *p = NUL;
4268 msg_puts(buffer);
4269 if (p < buffer + len)
4271 *p = c;
4272 buffer_off = (buffer + len) - p;
4273 mch_memmove(buffer, p, buffer_off);
4274 continue;
4276 buffer_off = 0;
4278 # endif /* FEAT_MBYTE */
4279 else
4281 buffer[len] = NUL;
4282 msg_puts(buffer);
4285 windgoto(msg_row, msg_col);
4286 cursor_on();
4287 out_flush();
4288 if (got_int)
4289 break;
4292 /* If we already detected the child has finished break the
4293 * loop now. */
4294 if (wait_pid == pid)
4295 break;
4298 * Check if the child still exists, before checking for
4299 * typed characters (otherwise we would loose typeahead).
4301 # ifdef __NeXT__
4302 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
4303 # else
4304 wait_pid = waitpid(pid, &status, WNOHANG);
4305 # endif
4306 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4307 || (wait_pid == pid && WIFEXITED(status)))
4309 /* Don't break the loop yet, try reading more
4310 * characters from "fromshell_fd" first. When using
4311 * pipes there might still be something to read and
4312 * then we'll break the loop at the "break" above. */
4313 wait_pid = pid;
4315 else
4316 wait_pid = 0;
4318 finished:
4319 p_more = p_more_save;
4320 if (options & SHELL_READ)
4322 if (ga.ga_len > 0)
4324 append_ga_line(&ga);
4325 /* remember that the NL was missing */
4326 write_no_eol_lnum = curwin->w_cursor.lnum;
4328 else
4329 write_no_eol_lnum = 0;
4330 ga_clear(&ga);
4334 * Give all typeahead that wasn't used back to ui_inchar().
4336 if (ta_len)
4337 ui_inchar_undo(ta_buf, ta_len);
4338 State = old_State;
4339 if (toshell_fd >= 0)
4340 close(toshell_fd);
4341 close(fromshell_fd);
4345 * Wait until our child has exited.
4346 * Ignore wait() returning pids of other children and returning
4347 * because of some signal like SIGWINCH.
4348 * Don't wait if wait_pid was already set above, indicating the
4349 * child already exited.
4351 while (wait_pid != pid)
4353 # ifdef _THREAD_SAFE
4354 /* Ugly hack: when compiled with Python threads are probably
4355 * used, in which case wait() sometimes hangs for no obvious
4356 * reason. Use waitpid() instead and loop (like the GUI). */
4357 # ifdef __NeXT__
4358 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4359 # else
4360 wait_pid = waitpid(pid, &status, WNOHANG);
4361 # endif
4362 if (wait_pid == 0)
4364 /* Wait for 1/100 sec before trying again. */
4365 mch_delay(10L, TRUE);
4366 continue;
4368 # else
4369 wait_pid = wait(&status);
4370 # endif
4371 if (wait_pid <= 0
4372 # ifdef ECHILD
4373 && errno == ECHILD
4374 # endif
4376 break;
4379 /* Make sure the child that writes to the external program is
4380 * dead. */
4381 if (wpid > 0)
4382 kill(wpid, SIGKILL);
4385 * Set to raw mode right now, otherwise a CTRL-C after
4386 * catch_signals() will kill Vim.
4388 if (tmode == TMODE_RAW)
4389 settmode(TMODE_RAW);
4390 did_settmode = TRUE;
4391 set_signals();
4393 if (WIFEXITED(status))
4395 /* LINTED avoid "bitwise operation on signed value" */
4396 retval = WEXITSTATUS(status);
4397 if (retval && !emsg_silent)
4399 if (retval == EXEC_FAILED)
4401 MSG_PUTS(_("\nCannot execute shell "));
4402 msg_outtrans(p_sh);
4403 msg_putchar('\n');
4405 else if (!(options & SHELL_SILENT))
4407 MSG_PUTS(_("\nshell returned "));
4408 msg_outnum((long)retval);
4409 msg_putchar('\n');
4413 else
4414 MSG_PUTS(_("\nCommand terminated\n"));
4417 vim_free(argv);
4419 error:
4420 if (!did_settmode)
4421 if (tmode == TMODE_RAW)
4422 settmode(TMODE_RAW); /* set to raw mode */
4423 # ifdef FEAT_TITLE
4424 resettitle();
4425 # endif
4426 vim_free(newcmd);
4428 return retval;
4430 #endif /* USE_SYSTEM */
4434 * Check for CTRL-C typed by reading all available characters.
4435 * In cooked mode we should get SIGINT, no need to check.
4437 void
4438 mch_breakcheck()
4440 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4441 fill_input_buf(FALSE);
4445 * Wait "msec" msec until a character is available from the keyboard or from
4446 * inbuf[]. msec == -1 will block forever.
4447 * When a GUI is being used, this will never get called -- webb
4449 static int
4450 WaitForChar(msec)
4451 long msec;
4453 #ifdef FEAT_MOUSE_GPM
4454 int gpm_process_wanted;
4455 #endif
4456 #ifdef FEAT_XCLIPBOARD
4457 int rest;
4458 #endif
4459 int avail;
4461 if (input_available()) /* something in inbuf[] */
4462 return 1;
4464 #if defined(FEAT_MOUSE_DEC)
4465 /* May need to query the mouse position. */
4466 if (WantQueryMouse)
4468 WantQueryMouse = FALSE;
4469 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4471 #endif
4474 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4475 * events. This is a bit complicated, because they might both be defined.
4477 #if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4478 # ifdef FEAT_XCLIPBOARD
4479 rest = 0;
4480 if (do_xterm_trace())
4481 rest = msec;
4482 # endif
4485 # ifdef FEAT_XCLIPBOARD
4486 if (rest != 0)
4488 msec = XT_TRACE_DELAY;
4489 if (rest >= 0 && rest < XT_TRACE_DELAY)
4490 msec = rest;
4491 if (rest >= 0)
4492 rest -= msec;
4494 # endif
4495 # ifdef FEAT_MOUSE_GPM
4496 gpm_process_wanted = 0;
4497 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4498 # else
4499 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4500 # endif
4501 if (!avail)
4503 if (input_available())
4504 return 1;
4505 # ifdef FEAT_XCLIPBOARD
4506 if (rest == 0 || !do_xterm_trace())
4507 # endif
4508 break;
4511 while (FALSE
4512 # ifdef FEAT_MOUSE_GPM
4513 || (gpm_process_wanted && mch_gpm_process() == 0)
4514 # endif
4515 # ifdef FEAT_XCLIPBOARD
4516 || (!avail && rest != 0)
4517 # endif
4520 #else
4521 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4522 #endif
4523 return avail;
4527 * Wait "msec" msec until a character is available from file descriptor "fd".
4528 * Time == -1 will block forever.
4529 * When a GUI is being used, this will not be used for input -- webb
4530 * Returns also, when a request from Sniff is waiting -- toni.
4531 * Or when a Linux GPM mouse event is waiting.
4533 /* ARGSUSED */
4534 #if defined(__BEOS__)
4536 #else
4537 static int
4538 #endif
4539 RealWaitForChar(fd, msec, check_for_gpm)
4540 int fd;
4541 long msec;
4542 int *check_for_gpm;
4544 int ret;
4545 #if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4546 static int busy = FALSE;
4548 /* May retry getting characters after an event was handled. */
4549 # define MAY_LOOP
4551 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4552 /* Remember at what time we started, so that we know how much longer we
4553 * should wait after being interrupted. */
4554 # define USE_START_TV
4555 struct timeval start_tv;
4557 if (msec > 0 && (
4558 # ifdef FEAT_XCLIPBOARD
4559 xterm_Shell != (Widget)0
4560 # if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4562 # endif
4563 # endif
4564 # ifdef USE_XSMP
4565 xsmp_icefd != -1
4566 # ifdef FEAT_MZSCHEME
4568 # endif
4569 # endif
4570 # ifdef FEAT_MZSCHEME
4571 (mzthreads_allowed() && p_mzq > 0)
4572 # endif
4574 gettimeofday(&start_tv, NULL);
4575 # endif
4577 /* Handle being called recursively. This may happen for the session
4578 * manager stuff, it may save the file, which does a breakcheck. */
4579 if (busy)
4580 return 0;
4581 #endif
4583 #ifdef MAY_LOOP
4584 for (;;)
4585 #endif
4587 #ifdef MAY_LOOP
4588 int finished = TRUE; /* default is to 'loop' just once */
4589 # ifdef FEAT_MZSCHEME
4590 int mzquantum_used = FALSE;
4591 # endif
4592 #endif
4593 #ifndef HAVE_SELECT
4594 struct pollfd fds[5];
4595 int nfd;
4596 # ifdef FEAT_XCLIPBOARD
4597 int xterm_idx = -1;
4598 # endif
4599 # ifdef FEAT_MOUSE_GPM
4600 int gpm_idx = -1;
4601 # endif
4602 # ifdef USE_XSMP
4603 int xsmp_idx = -1;
4604 # endif
4605 int towait = (int)msec;
4607 # ifdef FEAT_MZSCHEME
4608 mzvim_check_threads();
4609 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4611 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4612 mzquantum_used = TRUE;
4614 # endif
4615 fds[0].fd = fd;
4616 fds[0].events = POLLIN;
4617 nfd = 1;
4619 # ifdef FEAT_SNIFF
4620 # define SNIFF_IDX 1
4621 if (want_sniff_request)
4623 fds[SNIFF_IDX].fd = fd_from_sniff;
4624 fds[SNIFF_IDX].events = POLLIN;
4625 nfd++;
4627 # endif
4628 # ifdef FEAT_XCLIPBOARD
4629 if (xterm_Shell != (Widget)0)
4631 xterm_idx = nfd;
4632 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4633 fds[nfd].events = POLLIN;
4634 nfd++;
4636 # endif
4637 # ifdef FEAT_MOUSE_GPM
4638 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4640 gpm_idx = nfd;
4641 fds[nfd].fd = gpm_fd;
4642 fds[nfd].events = POLLIN;
4643 nfd++;
4645 # endif
4646 # ifdef USE_XSMP
4647 if (xsmp_icefd != -1)
4649 xsmp_idx = nfd;
4650 fds[nfd].fd = xsmp_icefd;
4651 fds[nfd].events = POLLIN;
4652 nfd++;
4654 # endif
4656 ret = poll(fds, nfd, towait);
4657 # ifdef FEAT_MZSCHEME
4658 if (ret == 0 && mzquantum_used)
4659 /* MzThreads scheduling is required and timeout occurred */
4660 finished = FALSE;
4661 # endif
4663 # ifdef FEAT_SNIFF
4664 if (ret < 0)
4665 sniff_disconnect(1);
4666 else if (want_sniff_request)
4668 if (fds[SNIFF_IDX].revents & POLLHUP)
4669 sniff_disconnect(1);
4670 if (fds[SNIFF_IDX].revents & POLLIN)
4671 sniff_request_waiting = 1;
4673 # endif
4674 # ifdef FEAT_XCLIPBOARD
4675 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4677 xterm_update(); /* Maybe we should hand out clipboard */
4678 if (--ret == 0 && !input_available())
4679 /* Try again */
4680 finished = FALSE;
4682 # endif
4683 # ifdef FEAT_MOUSE_GPM
4684 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4686 *check_for_gpm = 1;
4688 # endif
4689 # ifdef USE_XSMP
4690 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4692 if (fds[xsmp_idx].revents & POLLIN)
4694 busy = TRUE;
4695 xsmp_handle_requests();
4696 busy = FALSE;
4698 else if (fds[xsmp_idx].revents & POLLHUP)
4700 if (p_verbose > 0)
4701 verb_msg((char_u *)_("XSMP lost ICE connection"));
4702 xsmp_close();
4704 if (--ret == 0)
4705 finished = FALSE; /* Try again */
4707 # endif
4710 #else /* HAVE_SELECT */
4712 struct timeval tv;
4713 struct timeval *tvp;
4714 fd_set rfds, efds;
4715 int maxfd;
4716 long towait = msec;
4718 # ifdef FEAT_MZSCHEME
4719 mzvim_check_threads();
4720 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4722 towait = p_mzq; /* don't wait longer than 'mzquantum' */
4723 mzquantum_used = TRUE;
4725 # endif
4726 # ifdef __EMX__
4727 /* don't check for incoming chars if not in raw mode, because select()
4728 * always returns TRUE then (in some version of emx.dll) */
4729 if (curr_tmode != TMODE_RAW)
4730 return 0;
4731 # endif
4733 if (towait >= 0)
4735 tv.tv_sec = towait / 1000;
4736 tv.tv_usec = (towait % 1000) * (1000000/1000);
4737 tvp = &tv;
4739 else
4740 tvp = NULL;
4743 * Select on ready for reading and exceptional condition (end of file).
4745 FD_ZERO(&rfds); /* calls bzero() on a sun */
4746 FD_ZERO(&efds);
4747 FD_SET(fd, &rfds);
4748 # if !defined(__QNX__) && !defined(__CYGWIN32__)
4749 /* For QNX select() always returns 1 if this is set. Why? */
4750 FD_SET(fd, &efds);
4751 # endif
4752 maxfd = fd;
4754 # ifdef FEAT_SNIFF
4755 if (want_sniff_request)
4757 FD_SET(fd_from_sniff, &rfds);
4758 FD_SET(fd_from_sniff, &efds);
4759 if (maxfd < fd_from_sniff)
4760 maxfd = fd_from_sniff;
4762 # endif
4763 # ifdef FEAT_XCLIPBOARD
4764 if (xterm_Shell != (Widget)0)
4766 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
4767 if (maxfd < ConnectionNumber(xterm_dpy))
4768 maxfd = ConnectionNumber(xterm_dpy);
4770 # endif
4771 # ifdef FEAT_MOUSE_GPM
4772 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4774 FD_SET(gpm_fd, &rfds);
4775 FD_SET(gpm_fd, &efds);
4776 if (maxfd < gpm_fd)
4777 maxfd = gpm_fd;
4779 # endif
4780 # ifdef USE_XSMP
4781 if (xsmp_icefd != -1)
4783 FD_SET(xsmp_icefd, &rfds);
4784 FD_SET(xsmp_icefd, &efds);
4785 if (maxfd < xsmp_icefd)
4786 maxfd = xsmp_icefd;
4788 # endif
4790 # ifdef OLD_VMS
4791 /* Old VMS as v6.2 and older have broken select(). It waits more than
4792 * required. Should not be used */
4793 ret = 0;
4794 # else
4795 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
4796 # endif
4797 # ifdef __TANDEM
4798 if (ret == -1 && errno == ENOTSUP)
4800 FD_ZERO(&rfds);
4801 FD_ZERO(&efds);
4802 ret = 0;
4804 #endif
4805 # ifdef FEAT_MZSCHEME
4806 if (ret == 0 && mzquantum_used)
4807 /* loop if MzThreads must be scheduled and timeout occurred */
4808 finished = FALSE;
4809 # endif
4811 # ifdef FEAT_SNIFF
4812 if (ret < 0 )
4813 sniff_disconnect(1);
4814 else if (ret > 0 && want_sniff_request)
4816 if (FD_ISSET(fd_from_sniff, &efds))
4817 sniff_disconnect(1);
4818 if (FD_ISSET(fd_from_sniff, &rfds))
4819 sniff_request_waiting = 1;
4821 # endif
4822 # ifdef FEAT_XCLIPBOARD
4823 if (ret > 0 && xterm_Shell != (Widget)0
4824 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
4826 xterm_update(); /* Maybe we should hand out clipboard */
4827 /* continue looping when we only got the X event and the input
4828 * buffer is empty */
4829 if (--ret == 0 && !input_available())
4831 /* Try again */
4832 finished = FALSE;
4835 # endif
4836 # ifdef FEAT_MOUSE_GPM
4837 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
4839 if (FD_ISSET(gpm_fd, &efds))
4840 gpm_close();
4841 else if (FD_ISSET(gpm_fd, &rfds))
4842 *check_for_gpm = 1;
4844 # endif
4845 # ifdef USE_XSMP
4846 if (ret > 0 && xsmp_icefd != -1)
4848 if (FD_ISSET(xsmp_icefd, &efds))
4850 if (p_verbose > 0)
4851 verb_msg((char_u *)_("XSMP lost ICE connection"));
4852 xsmp_close();
4853 if (--ret == 0)
4854 finished = FALSE; /* keep going if event was only one */
4856 else if (FD_ISSET(xsmp_icefd, &rfds))
4858 busy = TRUE;
4859 xsmp_handle_requests();
4860 busy = FALSE;
4861 if (--ret == 0)
4862 finished = FALSE; /* keep going if event was only one */
4865 # endif
4867 #endif /* HAVE_SELECT */
4869 #ifdef MAY_LOOP
4870 if (finished || msec == 0)
4871 break;
4873 /* We're going to loop around again, find out for how long */
4874 if (msec > 0)
4876 # ifdef USE_START_TV
4877 struct timeval mtv;
4879 /* Compute remaining wait time. */
4880 gettimeofday(&mtv, NULL);
4881 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
4882 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
4883 # else
4884 /* Guess we got interrupted halfway. */
4885 msec = msec / 2;
4886 # endif
4887 if (msec <= 0)
4888 break; /* waited long enough */
4890 #endif
4893 return (ret > 0);
4896 #ifndef VMS
4898 #ifndef NO_EXPANDPATH
4900 * Expand a path into all matching files and/or directories. Handles "*",
4901 * "?", "[a-z]", "**", etc.
4902 * "path" has backslashes before chars that are not to be expanded.
4903 * Returns the number of matches found.
4906 mch_expandpath(gap, path, flags)
4907 garray_T *gap;
4908 char_u *path;
4909 int flags; /* EW_* flags */
4911 return unix_expandpath(gap, path, 0, flags, FALSE);
4913 #endif
4916 * mch_expand_wildcards() - this code does wild-card pattern matching using
4917 * the shell
4919 * return OK for success, FAIL for error (you may lose some memory) and put
4920 * an error message in *file.
4922 * num_pat is number of input patterns
4923 * pat is array of pointers to input patterns
4924 * num_file is pointer to number of matched file names
4925 * file is pointer to array of pointers to matched file names
4928 #ifndef SEEK_SET
4929 # define SEEK_SET 0
4930 #endif
4931 #ifndef SEEK_END
4932 # define SEEK_END 2
4933 #endif
4935 #define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
4937 /* ARGSUSED */
4939 mch_expand_wildcards(num_pat, pat, num_file, file, flags)
4940 int num_pat;
4941 char_u **pat;
4942 int *num_file;
4943 char_u ***file;
4944 int flags; /* EW_* flags */
4946 int i;
4947 size_t len;
4948 char_u *p;
4949 int dir;
4950 #ifdef __EMX__
4952 * This is the OS/2 implementation.
4954 # define EXPL_ALLOC_INC 16
4955 char_u **expl_files;
4956 size_t files_alloced, files_free;
4957 char_u *buf;
4958 int has_wildcard;
4960 *num_file = 0; /* default: no files found */
4961 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
4962 files_free = EXPL_ALLOC_INC; /* how much space is not used */
4963 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
4964 if (*file == NULL)
4965 return FAIL;
4967 for (; num_pat > 0; num_pat--, pat++)
4969 expl_files = NULL;
4970 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
4971 /* expand environment var or home dir */
4972 buf = expand_env_save(*pat);
4973 else
4974 buf = vim_strsave(*pat);
4975 expl_files = NULL;
4976 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
4977 if (has_wildcard) /* yes, so expand them */
4978 expl_files = (char_u **)_fnexplode(buf);
4981 * return value of buf if no wildcards left,
4982 * OR if no match AND EW_NOTFOUND is set.
4984 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
4985 || (expl_files == NULL && (flags & EW_NOTFOUND)))
4986 { /* simply save the current contents of *buf */
4987 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
4988 if (expl_files != NULL)
4990 expl_files[0] = vim_strsave(buf);
4991 expl_files[1] = NULL;
4994 vim_free(buf);
4997 * Count number of names resulting from expansion,
4998 * At the same time add a backslash to the end of names that happen to
4999 * be directories, and replace slashes with backslashes.
5001 if (expl_files)
5003 for (i = 0; (p = expl_files[i]) != NULL; i++)
5005 dir = mch_isdir(p);
5006 /* If we don't want dirs and this is one, skip it */
5007 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5008 continue;
5010 /* Skip files that are not executable if we check for that. */
5011 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5012 continue;
5014 if (--files_free == 0)
5016 /* need more room in table of pointers */
5017 files_alloced += EXPL_ALLOC_INC;
5018 *file = (char_u **)vim_realloc(*file,
5019 sizeof(char_u **) * files_alloced);
5020 if (*file == NULL)
5022 EMSG(_(e_outofmem));
5023 *num_file = 0;
5024 return FAIL;
5026 files_free = EXPL_ALLOC_INC;
5028 slash_adjust(p);
5029 if (dir)
5031 /* For a directory we add a '/', unless it's already
5032 * there. */
5033 len = STRLEN(p);
5034 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5036 STRCPY((*file)[*num_file], p);
5037 if (!after_pathsep((*file)[*num_file],
5038 (*file)[*num_file] + len))
5040 (*file)[*num_file][len] = psepc;
5041 (*file)[*num_file][len + 1] = NUL;
5045 else
5047 (*file)[*num_file] = vim_strsave(p);
5051 * Error message already given by either alloc or vim_strsave.
5052 * Should return FAIL, but returning OK works also.
5054 if ((*file)[*num_file] == NULL)
5055 break;
5056 (*num_file)++;
5058 _fnexplodefree((char **)expl_files);
5061 return OK;
5063 #else /* __EMX__ */
5065 * This is the non-OS/2 implementation (really Unix).
5067 int j;
5068 char_u *tempname;
5069 char_u *command;
5070 FILE *fd;
5071 char_u *buffer;
5072 #define STYLE_ECHO 0 /* use "echo", the default */
5073 #define STYLE_GLOB 1 /* use "glob", for csh */
5074 #define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
5075 #define STYLE_PRINT 3 /* use "print -N", for zsh */
5076 #define STYLE_BT 4 /* `cmd` expansion, execute the pattern
5077 * directly */
5078 int shell_style = STYLE_ECHO;
5079 int check_spaces;
5080 static int did_find_nul = FALSE;
5081 int ampersent = FALSE;
5082 /* vimglob() function to define for Posix shell */
5083 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo -n \"$1\"; echo; shift; done }; vimglob >";
5085 *num_file = 0; /* default: no files found */
5086 *file = NULL;
5089 * If there are no wildcards, just copy the names to allocated memory.
5090 * Saves a lot of time, because we don't have to start a new shell.
5092 if (!have_wildcard(num_pat, pat))
5093 return save_patterns(num_pat, pat, num_file, file);
5095 # ifdef HAVE_SANDBOX
5096 /* Don't allow any shell command in the sandbox. */
5097 if (sandbox != 0 && check_secure())
5098 return FAIL;
5099 # endif
5102 * Don't allow the use of backticks in secure and restricted mode.
5104 if (secure || restricted)
5105 for (i = 0; i < num_pat; ++i)
5106 if (vim_strchr(pat[i], '`') != NULL
5107 && (check_restricted() || check_secure()))
5108 return FAIL;
5111 * get a name for the temp file
5113 if ((tempname = vim_tempname('o')) == NULL)
5115 EMSG(_(e_notmp));
5116 return FAIL;
5120 * Let the shell expand the patterns and write the result into the temp
5121 * file.
5122 * STYLE_BT: NL separated
5123 * If expanding `cmd` execute it directly.
5124 * STYLE_GLOB: NUL separated
5125 * If we use *csh, "glob" will work better than "echo".
5126 * STYLE_PRINT: NL or NUL separated
5127 * If we use *zsh, "print -N" will work better than "glob".
5128 * STYLE_VIMGLOB: NL separated
5129 * If we use *sh*, we define "vimglob()".
5130 * STYLE_ECHO: space separated.
5131 * A shell we don't know, stay safe and use "echo".
5133 if (num_pat == 1 && *pat[0] == '`'
5134 && (len = STRLEN(pat[0])) > 2
5135 && *(pat[0] + len - 1) == '`')
5136 shell_style = STYLE_BT;
5137 else if ((len = STRLEN(p_sh)) >= 3)
5139 if (STRCMP(p_sh + len - 3, "csh") == 0)
5140 shell_style = STYLE_GLOB;
5141 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5142 shell_style = STYLE_PRINT;
5144 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
5145 "sh") != NULL)
5146 shell_style = STYLE_VIMGLOB;
5148 /* Compute the length of the command. We need 2 extra bytes: for the
5149 * optional '&' and for the NUL.
5150 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
5151 len = STRLEN(tempname) + 29;
5152 if (shell_style == STYLE_VIMGLOB)
5153 len += STRLEN(sh_vimglob_func);
5155 for (i = 0; i < num_pat; ++i)
5157 /* Count the length of the patterns in the same way as they are put in
5158 * "command" below. */
5159 #ifdef USE_SYSTEM
5160 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
5161 #else
5162 ++len; /* add space */
5163 for (j = 0; pat[i][j] != NUL; ++j)
5165 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5166 ++len; /* may add a backslash */
5167 ++len;
5169 #endif
5171 command = alloc(len);
5172 if (command == NULL)
5174 /* out of memory */
5175 vim_free(tempname);
5176 return FAIL;
5180 * Build the shell command:
5181 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5182 * recognizes this).
5183 * - Add the shell command to print the expanded names.
5184 * - Add the temp file name.
5185 * - Add the file name patterns.
5187 if (shell_style == STYLE_BT)
5189 /* change `command; command& ` to (command; command ) */
5190 STRCPY(command, "(");
5191 STRCAT(command, pat[0] + 1); /* exclude first backtick */
5192 p = command + STRLEN(command) - 1;
5193 *p-- = ')'; /* remove last backtick */
5194 while (p > command && vim_iswhite(*p))
5195 --p;
5196 if (*p == '&') /* remove trailing '&' */
5198 ampersent = TRUE;
5199 *p = ' ';
5201 STRCAT(command, ">");
5203 else
5205 if (flags & EW_NOTFOUND)
5206 STRCPY(command, "set nonomatch; ");
5207 else
5208 STRCPY(command, "unset nonomatch; ");
5209 if (shell_style == STYLE_GLOB)
5210 STRCAT(command, "glob >");
5211 else if (shell_style == STYLE_PRINT)
5212 STRCAT(command, "print -N >");
5213 else if (shell_style == STYLE_VIMGLOB)
5214 STRCAT(command, sh_vimglob_func);
5215 else
5216 STRCAT(command, "echo >");
5219 STRCAT(command, tempname);
5221 if (shell_style != STYLE_BT)
5222 for (i = 0; i < num_pat; ++i)
5224 /* When using system() always add extra quotes, because the shell
5225 * is started twice. Otherwise put a backslash before special
5226 * characters, except inside ``. */
5227 #ifdef USE_SYSTEM
5228 STRCAT(command, " \"");
5229 STRCAT(command, pat[i]);
5230 STRCAT(command, "\"");
5231 #else
5232 int intick = FALSE;
5234 p = command + STRLEN(command);
5235 *p++ = ' ';
5236 for (j = 0; pat[i][j] != NUL; ++j)
5238 if (pat[i][j] == '`')
5239 intick = !intick;
5240 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5242 /* Remove a backslash, take char literally. But keep
5243 * backslash inside backticks, before a special character
5244 * and before a backtick. */
5245 if (intick
5246 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5247 || pat[i][j + 1] == '`')
5248 *p++ = '\\';
5249 ++j;
5251 else if (!intick && vim_strchr(SHELL_SPECIAL,
5252 pat[i][j]) != NULL)
5253 /* Put a backslash before a special character, but not
5254 * when inside ``. */
5255 *p++ = '\\';
5257 /* Copy one character. */
5258 *p++ = pat[i][j];
5260 *p = NUL;
5261 #endif
5263 if (flags & EW_SILENT)
5264 show_shell_mess = FALSE;
5265 if (ampersent)
5266 STRCAT(command, "&"); /* put the '&' after the redirection */
5269 * Using zsh -G: If a pattern has no matches, it is just deleted from
5270 * the argument list, otherwise zsh gives an error message and doesn't
5271 * expand any other pattern.
5273 if (shell_style == STYLE_PRINT)
5274 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5277 * If we use -f then shell variables set in .cshrc won't get expanded.
5278 * vi can do it, so we will too, but it is only necessary if there is a "$"
5279 * in one of the patterns, otherwise we can still use the fast option.
5281 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5282 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5285 * execute the shell command
5287 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5289 /* When running in the background, give it some time to create the temp
5290 * file, but don't wait for it to finish. */
5291 if (ampersent)
5292 mch_delay(10L, TRUE);
5294 extra_shell_arg = NULL; /* cleanup */
5295 show_shell_mess = TRUE;
5296 vim_free(command);
5298 if (i != 0) /* mch_call_shell() failed */
5300 mch_remove(tempname);
5301 vim_free(tempname);
5303 * With interactive completion, the error message is not printed.
5304 * However with USE_SYSTEM, I don't know how to turn off error messages
5305 * from the shell, so screen may still get messed up -- webb.
5307 #ifndef USE_SYSTEM
5308 if (!(flags & EW_SILENT))
5309 #endif
5311 redraw_later_clear(); /* probably messed up screen */
5312 msg_putchar('\n'); /* clear bottom line quickly */
5313 cmdline_row = Rows - 1; /* continue on last line */
5314 #ifdef USE_SYSTEM
5315 if (!(flags & EW_SILENT))
5316 #endif
5318 MSG(_(e_wildexpand));
5319 msg_start(); /* don't overwrite this message */
5322 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5323 * EW_NOTFOUND is given */
5324 if (shell_style == STYLE_BT)
5325 return FAIL;
5326 goto notfound;
5330 * read the names from the file into memory
5332 fd = fopen((char *)tempname, READBIN);
5333 if (fd == NULL)
5335 /* Something went wrong, perhaps a file name with a special char. */
5336 if (!(flags & EW_SILENT))
5338 MSG(_(e_wildexpand));
5339 msg_start(); /* don't overwrite this message */
5341 vim_free(tempname);
5342 goto notfound;
5344 fseek(fd, 0L, SEEK_END);
5345 len = ftell(fd); /* get size of temp file */
5346 fseek(fd, 0L, SEEK_SET);
5347 buffer = alloc(len + 1);
5348 if (buffer == NULL)
5350 /* out of memory */
5351 mch_remove(tempname);
5352 vim_free(tempname);
5353 fclose(fd);
5354 return FAIL;
5356 i = fread((char *)buffer, 1, len, fd);
5357 fclose(fd);
5358 mch_remove(tempname);
5359 if (i != len)
5361 /* unexpected read error */
5362 EMSG2(_(e_notread), tempname);
5363 vim_free(tempname);
5364 vim_free(buffer);
5365 return FAIL;
5367 vim_free(tempname);
5369 # if defined(__CYGWIN__) || defined(__CYGWIN32__)
5370 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5371 p = buffer;
5372 for (i = 0; i < len; ++i)
5373 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5374 *p++ = buffer[i];
5375 len = p - buffer;
5376 # endif
5379 /* file names are separated with Space */
5380 if (shell_style == STYLE_ECHO)
5382 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5383 p = buffer;
5384 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5386 while (*p != ' ' && *p != '\n')
5387 ++p;
5388 p = skipwhite(p); /* skip to next entry */
5391 /* file names are separated with NL */
5392 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
5394 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5395 p = buffer;
5396 for (i = 0; *p != NUL; ++i) /* count number of entries */
5398 while (*p != '\n' && *p != NUL)
5399 ++p;
5400 if (*p != NUL)
5401 ++p;
5402 p = skipwhite(p); /* skip leading white space */
5405 /* file names are separated with NUL */
5406 else
5409 * Some versions of zsh use spaces instead of NULs to separate
5410 * results. Only do this when there is no NUL before the end of the
5411 * buffer, otherwise we would never be able to use file names with
5412 * embedded spaces when zsh does use NULs.
5413 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5414 * don't check for spaces again.
5416 check_spaces = FALSE;
5417 if (shell_style == STYLE_PRINT && !did_find_nul)
5419 /* If there is a NUL, set did_find_nul, else set check_spaces */
5420 if (len && (int)STRLEN(buffer) < len - 1)
5421 did_find_nul = TRUE;
5422 else
5423 check_spaces = TRUE;
5427 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5428 * already is one, for STYLE_GLOB it needs to be added.
5430 if (len && buffer[len - 1] == NUL)
5431 --len;
5432 else
5433 buffer[len] = NUL;
5434 i = 0;
5435 for (p = buffer; p < buffer + len; ++p)
5436 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5438 ++i;
5439 *p = NUL;
5441 if (len)
5442 ++i; /* count last entry */
5444 if (i == 0)
5447 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5448 * /bin/sh will happily expand it to nothing rather than returning an
5449 * error; and hey, it's good to check anyway -- webb.
5451 vim_free(buffer);
5452 goto notfound;
5454 *num_file = i;
5455 *file = (char_u **)alloc(sizeof(char_u *) * i);
5456 if (*file == NULL)
5458 /* out of memory */
5459 vim_free(buffer);
5460 return FAIL;
5464 * Isolate the individual file names.
5466 p = buffer;
5467 for (i = 0; i < *num_file; ++i)
5469 (*file)[i] = p;
5470 /* Space or NL separates */
5471 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
5472 || shell_style == STYLE_VIMGLOB)
5474 while (!(shell_style == STYLE_ECHO && *p == ' ')
5475 && *p != '\n' && *p != NUL)
5476 ++p;
5477 if (p == buffer + len) /* last entry */
5478 *p = NUL;
5479 else
5481 *p++ = NUL;
5482 p = skipwhite(p); /* skip to next entry */
5485 else /* NUL separates */
5487 while (*p && p < buffer + len) /* skip entry */
5488 ++p;
5489 ++p; /* skip NUL */
5494 * Move the file names to allocated memory.
5496 for (j = 0, i = 0; i < *num_file; ++i)
5498 /* Require the files to exist. Helps when using /bin/sh */
5499 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5500 continue;
5502 /* check if this entry should be included */
5503 dir = (mch_isdir((*file)[i]));
5504 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5505 continue;
5507 /* Skip files that are not executable if we check for that. */
5508 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5509 continue;
5511 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5512 if (p)
5514 STRCPY(p, (*file)[i]);
5515 if (dir)
5516 add_pathsep(p); /* add '/' to a directory name */
5517 (*file)[j++] = p;
5520 vim_free(buffer);
5521 *num_file = j;
5523 if (*num_file == 0) /* rejected all entries */
5525 vim_free(*file);
5526 *file = NULL;
5527 goto notfound;
5530 return OK;
5532 notfound:
5533 if (flags & EW_NOTFOUND)
5534 return save_patterns(num_pat, pat, num_file, file);
5535 return FAIL;
5537 #endif /* __EMX__ */
5540 #endif /* VMS */
5542 #ifndef __EMX__
5543 static int
5544 save_patterns(num_pat, pat, num_file, file)
5545 int num_pat;
5546 char_u **pat;
5547 int *num_file;
5548 char_u ***file;
5550 int i;
5551 char_u *s;
5553 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5554 if (*file == NULL)
5555 return FAIL;
5556 for (i = 0; i < num_pat; i++)
5558 s = vim_strsave(pat[i]);
5559 if (s != NULL)
5560 /* Be compatible with expand_filename(): halve the number of
5561 * backslashes. */
5562 backslash_halve(s);
5563 (*file)[i] = s;
5565 *num_file = num_pat;
5566 return OK;
5568 #endif
5572 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5573 * expand.
5576 mch_has_exp_wildcard(p)
5577 char_u *p;
5579 for ( ; *p; mb_ptr_adv(p))
5581 #ifndef OS2
5582 if (*p == '\\' && p[1] != NUL)
5583 ++p;
5584 else
5585 #endif
5586 if (vim_strchr((char_u *)
5587 #ifdef VMS
5588 "*?%"
5589 #else
5590 # ifdef OS2
5591 "*?"
5592 # else
5593 "*?[{'"
5594 # endif
5595 #endif
5596 , *p) != NULL)
5597 return TRUE;
5599 return FALSE;
5603 * Return TRUE if the string "p" contains a wildcard.
5604 * Don't recognize '~' at the end as a wildcard.
5607 mch_has_wildcard(p)
5608 char_u *p;
5610 for ( ; *p; mb_ptr_adv(p))
5612 #ifndef OS2
5613 if (*p == '\\' && p[1] != NUL)
5614 ++p;
5615 else
5616 #endif
5617 if (vim_strchr((char_u *)
5618 #ifdef VMS
5619 "*?%$"
5620 #else
5621 # ifdef OS2
5622 # ifdef VIM_BACKTICK
5623 "*?$`"
5624 # else
5625 "*?$"
5626 # endif
5627 # else
5628 "*?[{`'$"
5629 # endif
5630 #endif
5631 , *p) != NULL
5632 || (*p == '~' && p[1] != NUL))
5633 return TRUE;
5635 return FALSE;
5638 #ifndef __EMX__
5639 static int
5640 have_wildcard(num, file)
5641 int num;
5642 char_u **file;
5644 int i;
5646 for (i = 0; i < num; i++)
5647 if (mch_has_wildcard(file[i]))
5648 return 1;
5649 return 0;
5652 static int
5653 have_dollars(num, file)
5654 int num;
5655 char_u **file;
5657 int i;
5659 for (i = 0; i < num; i++)
5660 if (vim_strchr(file[i], '$') != NULL)
5661 return TRUE;
5662 return FALSE;
5664 #endif /* ifndef __EMX__ */
5666 #ifndef HAVE_RENAME
5668 * Scaled-down version of rename(), which is missing in Xenix.
5669 * This version can only move regular files and will fail if the
5670 * destination exists.
5673 mch_rename(src, dest)
5674 const char *src, *dest;
5676 struct stat st;
5678 if (stat(dest, &st) >= 0) /* fail if destination exists */
5679 return -1;
5680 if (link(src, dest) != 0) /* link file to new name */
5681 return -1;
5682 if (mch_remove(src) == 0) /* delete link to old name */
5683 return 0;
5684 return -1;
5686 #endif /* !HAVE_RENAME */
5688 #ifdef FEAT_MOUSE_GPM
5690 * Initializes connection with gpm (if it isn't already opened)
5691 * Return 1 if succeeded (or connection already opened), 0 if failed
5693 static int
5694 gpm_open()
5696 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
5698 if (!gpm_flag)
5700 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
5701 gpm_connect.defaultMask = ~GPM_HARD;
5702 /* Default handling for mouse move*/
5703 gpm_connect.minMod = 0; /* Handle any modifier keys */
5704 gpm_connect.maxMod = 0xffff;
5705 if (Gpm_Open(&gpm_connect, 0) > 0)
5707 /* gpm library tries to handling TSTP causes
5708 * problems. Anyways, we close connection to Gpm whenever
5709 * we are going to suspend or starting an external process
5710 * so we shouldn't have problem with this
5712 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
5713 return 1; /* succeed */
5715 if (gpm_fd == -2)
5716 Gpm_Close(); /* We don't want to talk to xterm via gpm */
5717 return 0;
5719 return 1; /* already open */
5723 * Closes connection to gpm
5724 * returns non-zero if connection successfully closed
5726 static void
5727 gpm_close()
5729 if (gpm_flag && gpm_fd >= 0) /* if Open */
5730 Gpm_Close();
5733 /* Reads gpm event and adds special keys to input buf. Returns length of
5734 * generated key sequence.
5735 * This function is made after gui_send_mouse_event
5737 static int
5738 mch_gpm_process()
5740 int button;
5741 static Gpm_Event gpm_event;
5742 char_u string[6];
5743 int_u vim_modifiers;
5744 int row,col;
5745 unsigned char buttons_mask;
5746 unsigned char gpm_modifiers;
5747 static unsigned char old_buttons = 0;
5749 Gpm_GetEvent(&gpm_event);
5751 #ifdef FEAT_GUI
5752 /* Don't put events in the input queue now. */
5753 if (hold_gui_events)
5754 return 0;
5755 #endif
5757 row = gpm_event.y - 1;
5758 col = gpm_event.x - 1;
5760 string[0] = ESC; /* Our termcode */
5761 string[1] = 'M';
5762 string[2] = 'G';
5763 switch (GPM_BARE_EVENTS(gpm_event.type))
5765 case GPM_DRAG:
5766 string[3] = MOUSE_DRAG;
5767 break;
5768 case GPM_DOWN:
5769 buttons_mask = gpm_event.buttons & ~old_buttons;
5770 old_buttons = gpm_event.buttons;
5771 switch (buttons_mask)
5773 case GPM_B_LEFT:
5774 button = MOUSE_LEFT;
5775 break;
5776 case GPM_B_MIDDLE:
5777 button = MOUSE_MIDDLE;
5778 break;
5779 case GPM_B_RIGHT:
5780 button = MOUSE_RIGHT;
5781 break;
5782 default:
5783 return 0;
5784 /*Don't know what to do. Can more than one button be
5785 * reported in one event? */
5787 string[3] = (char_u)(button | 0x20);
5788 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
5789 break;
5790 case GPM_UP:
5791 string[3] = MOUSE_RELEASE;
5792 old_buttons &= ~gpm_event.buttons;
5793 break;
5794 default:
5795 return 0;
5797 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
5798 gpm_modifiers = gpm_event.modifiers;
5799 vim_modifiers = 0x0;
5800 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
5801 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
5802 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
5804 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
5805 vim_modifiers |= MOUSE_SHIFT;
5807 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
5808 vim_modifiers |= MOUSE_CTRL;
5809 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
5810 vim_modifiers |= MOUSE_ALT;
5811 string[3] |= vim_modifiers;
5812 string[4] = (char_u)(col + ' ' + 1);
5813 string[5] = (char_u)(row + ' ' + 1);
5814 add_to_input_buf(string, 6);
5815 return 6;
5817 #endif /* FEAT_MOUSE_GPM */
5819 #if defined(FEAT_LIBCALL) || defined(PROTO)
5820 typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
5821 typedef char_u * (*INTPROCSTR)__ARGS((int));
5822 typedef int (*STRPROCINT)__ARGS((char_u *));
5823 typedef int (*INTPROCINT)__ARGS((int));
5826 * Call a DLL routine which takes either a string or int param
5827 * and returns an allocated string.
5830 mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
5831 char_u *libname;
5832 char_u *funcname;
5833 char_u *argstring; /* NULL when using a argint */
5834 int argint;
5835 char_u **string_result;/* NULL when using number_result */
5836 int *number_result;
5838 # if defined(USE_DLOPEN)
5839 void *hinstLib;
5840 char *dlerr = NULL;
5841 # else
5842 shl_t hinstLib;
5843 # endif
5844 STRPROCSTR ProcAdd;
5845 INTPROCSTR ProcAddI;
5846 char_u *retval_str = NULL;
5847 int retval_int = 0;
5848 int success = FALSE;
5851 * Get a handle to the DLL module.
5853 # if defined(USE_DLOPEN)
5854 /* First clear any error, it's not cleared by the dlopen() call. */
5855 (void)dlerror();
5857 hinstLib = dlopen((char *)libname, RTLD_LAZY
5858 # ifdef RTLD_LOCAL
5859 | RTLD_LOCAL
5860 # endif
5862 if (hinstLib == NULL)
5864 /* "dlerr" must be used before dlclose() */
5865 dlerr = (char *)dlerror();
5866 if (dlerr != NULL)
5867 EMSG2(_("dlerror = \"%s\""), dlerr);
5869 # else
5870 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
5871 # endif
5873 /* If the handle is valid, try to get the function address. */
5874 if (hinstLib != NULL)
5876 # ifdef HAVE_SETJMP_H
5878 * Catch a crash when calling the library function. For example when
5879 * using a number where a string pointer is expected.
5881 mch_startjmp();
5882 if (SETJMP(lc_jump_env) != 0)
5884 success = FALSE;
5885 # if defined(USE_DLOPEN)
5886 dlerr = NULL;
5887 # endif
5888 mch_didjmp();
5890 else
5891 # endif
5893 retval_str = NULL;
5894 retval_int = 0;
5896 if (argstring != NULL)
5898 # if defined(USE_DLOPEN)
5899 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
5900 dlerr = (char *)dlerror();
5901 # else
5902 if (shl_findsym(&hinstLib, (const char *)funcname,
5903 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
5904 ProcAdd = NULL;
5905 # endif
5906 if ((success = (ProcAdd != NULL
5907 # if defined(USE_DLOPEN)
5908 && dlerr == NULL
5909 # endif
5912 if (string_result == NULL)
5913 retval_int = ((STRPROCINT)ProcAdd)(argstring);
5914 else
5915 retval_str = (ProcAdd)(argstring);
5918 else
5920 # if defined(USE_DLOPEN)
5921 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
5922 dlerr = (char *)dlerror();
5923 # else
5924 if (shl_findsym(&hinstLib, (const char *)funcname,
5925 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
5926 ProcAddI = NULL;
5927 # endif
5928 if ((success = (ProcAddI != NULL
5929 # if defined(USE_DLOPEN)
5930 && dlerr == NULL
5931 # endif
5934 if (string_result == NULL)
5935 retval_int = ((INTPROCINT)ProcAddI)(argint);
5936 else
5937 retval_str = (ProcAddI)(argint);
5941 /* Save the string before we free the library. */
5942 /* Assume that a "1" or "-1" result is an illegal pointer. */
5943 if (string_result == NULL)
5944 *number_result = retval_int;
5945 else if (retval_str != NULL
5946 && retval_str != (char_u *)1
5947 && retval_str != (char_u *)-1)
5948 *string_result = vim_strsave(retval_str);
5951 # ifdef HAVE_SETJMP_H
5952 mch_endjmp();
5953 # ifdef SIGHASARG
5954 if (lc_signal != 0)
5956 int i;
5958 /* try to find the name of this signal */
5959 for (i = 0; signal_info[i].sig != -1; i++)
5960 if (lc_signal == signal_info[i].sig)
5961 break;
5962 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
5964 # endif
5965 # endif
5967 # if defined(USE_DLOPEN)
5968 /* "dlerr" must be used before dlclose() */
5969 if (dlerr != NULL)
5970 EMSG2(_("dlerror = \"%s\""), dlerr);
5972 /* Free the DLL module. */
5973 (void)dlclose(hinstLib);
5974 # else
5975 (void)shl_unload(hinstLib);
5976 # endif
5979 if (!success)
5981 EMSG2(_(e_libcall), funcname);
5982 return FAIL;
5985 return OK;
5987 #endif
5989 #if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
5990 static int xterm_trace = -1; /* default: disabled */
5991 static int xterm_button;
5994 * Setup a dummy window for X selections in a terminal.
5996 void
5997 setup_term_clip()
5999 int z = 0;
6000 char *strp = "";
6001 Widget AppShell;
6003 if (!x_connect_to_server())
6004 return;
6006 open_app_context();
6007 if (app_context != NULL && xterm_Shell == (Widget)0)
6009 int (*oldhandler)();
6010 #if defined(HAVE_SETJMP_H)
6011 int (*oldIOhandler)();
6012 #endif
6013 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6014 struct timeval start_tv;
6016 if (p_verbose > 0)
6017 gettimeofday(&start_tv, NULL);
6018 # endif
6020 /* Ignore X errors while opening the display */
6021 oldhandler = XSetErrorHandler(x_error_check);
6023 #if defined(HAVE_SETJMP_H)
6024 /* Ignore X IO errors while opening the display */
6025 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
6026 mch_startjmp();
6027 if (SETJMP(lc_jump_env) != 0)
6029 mch_didjmp();
6030 xterm_dpy = NULL;
6032 else
6033 #endif
6035 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6036 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6037 #if defined(HAVE_SETJMP_H)
6038 mch_endjmp();
6039 #endif
6042 #if defined(HAVE_SETJMP_H)
6043 /* Now handle X IO errors normally. */
6044 (void)XSetIOErrorHandler(oldIOhandler);
6045 #endif
6046 /* Now handle X errors normally. */
6047 (void)XSetErrorHandler(oldhandler);
6049 if (xterm_dpy == NULL)
6051 if (p_verbose > 0)
6052 verb_msg((char_u *)_("Opening the X display failed"));
6053 return;
6056 /* Catch terminating error of the X server connection. */
6057 (void)XSetIOErrorHandler(x_IOerror_handler);
6059 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6060 if (p_verbose > 0)
6062 verbose_enter();
6063 xopen_message(&start_tv);
6064 verbose_leave();
6066 # endif
6068 /* Create a Shell to make converters work. */
6069 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6070 applicationShellWidgetClass, xterm_dpy,
6071 NULL);
6072 if (AppShell == (Widget)0)
6073 return;
6074 xterm_Shell = XtVaCreatePopupShell("VIM",
6075 topLevelShellWidgetClass, AppShell,
6076 XtNmappedWhenManaged, 0,
6077 XtNwidth, 1,
6078 XtNheight, 1,
6079 NULL);
6080 if (xterm_Shell == (Widget)0)
6081 return;
6083 x11_setup_atoms(xterm_dpy);
6084 if (x11_display == NULL)
6085 x11_display = xterm_dpy;
6087 XtRealizeWidget(xterm_Shell);
6088 XSync(xterm_dpy, False);
6089 xterm_update();
6091 if (xterm_Shell != (Widget)0)
6093 clip_init(TRUE);
6094 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6095 x11_window = (Window)atol(strp);
6096 /* Check if $WINDOWID is valid. */
6097 if (test_x11_window(xterm_dpy) == FAIL)
6098 x11_window = 0;
6099 if (x11_window != 0)
6100 xterm_trace = 0;
6104 void
6105 start_xterm_trace(button)
6106 int button;
6108 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6109 return;
6110 xterm_trace = 1;
6111 xterm_button = button;
6112 do_xterm_trace();
6116 void
6117 stop_xterm_trace()
6119 if (xterm_trace < 0)
6120 return;
6121 xterm_trace = 0;
6125 * Query the xterm pointer and generate mouse termcodes if necessary
6126 * return TRUE if dragging is active, else FALSE
6128 static int
6129 do_xterm_trace()
6131 Window root, child;
6132 int root_x, root_y;
6133 int win_x, win_y;
6134 int row, col;
6135 int_u mask_return;
6136 char_u buf[50];
6137 char_u *strp;
6138 long got_hints;
6139 static char_u *mouse_code;
6140 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6141 static int prev_row = 0, prev_col = 0;
6142 static XSizeHints xterm_hints;
6144 if (xterm_trace <= 0)
6145 return FALSE;
6147 if (xterm_trace == 1)
6149 /* Get the hints just before tracking starts. The font size might
6150 * have changed recently. */
6151 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
6152 || !(got_hints & PResizeInc)
6153 || xterm_hints.width_inc <= 1
6154 || xterm_hints.height_inc <= 1)
6156 xterm_trace = -1; /* Not enough data -- disable tracing */
6157 return FALSE;
6160 /* Rely on the same mouse code for the duration of this */
6161 mouse_code = find_termcode(mouse_name);
6162 prev_row = mouse_row;
6163 prev_row = mouse_col;
6164 xterm_trace = 2;
6166 /* Find the offset of the chars, there might be a scrollbar on the
6167 * left of the window and/or a menu on the top (eterm etc.) */
6168 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6169 &win_x, &win_y, &mask_return);
6170 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6171 - (xterm_hints.height_inc / 2);
6172 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6173 xterm_hints.y = 2;
6174 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6175 - (xterm_hints.width_inc / 2);
6176 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6177 xterm_hints.x = 2;
6178 return TRUE;
6180 if (mouse_code == NULL)
6182 xterm_trace = 0;
6183 return FALSE;
6186 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6187 &win_x, &win_y, &mask_return);
6189 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6190 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6191 if (row == prev_row && col == prev_col)
6192 return TRUE;
6194 STRCPY(buf, mouse_code);
6195 strp = buf + STRLEN(buf);
6196 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6197 *strp++ = (char_u)(col + ' ' + 1);
6198 *strp++ = (char_u)(row + ' ' + 1);
6199 *strp = 0;
6200 add_to_input_buf(buf, STRLEN(buf));
6202 prev_row = row;
6203 prev_col = col;
6204 return TRUE;
6207 # if defined(FEAT_GUI) || defined(PROTO)
6209 * Destroy the display, window and app_context. Required for GTK.
6211 void
6212 clear_xterm_clip()
6214 if (xterm_Shell != (Widget)0)
6216 XtDestroyWidget(xterm_Shell);
6217 xterm_Shell = (Widget)0;
6219 if (xterm_dpy != NULL)
6221 #if 0
6222 /* Lesstif and Solaris crash here, lose some memory */
6223 XtCloseDisplay(xterm_dpy);
6224 #endif
6225 if (x11_display == xterm_dpy)
6226 x11_display = NULL;
6227 xterm_dpy = NULL;
6229 #if 0
6230 if (app_context != (XtAppContext)NULL)
6232 /* Lesstif and Solaris crash here, lose some memory */
6233 XtDestroyApplicationContext(app_context);
6234 app_context = (XtAppContext)NULL;
6236 #endif
6238 # endif
6241 * Catch up with any queued X events. This may put keyboard input into the
6242 * input buffer, call resize call-backs, trigger timers etc. If there is
6243 * nothing in the X event queue (& no timers pending), then we return
6244 * immediately.
6246 static void
6247 xterm_update()
6249 XEvent event;
6251 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6253 XtAppNextEvent(app_context, &event);
6254 #ifdef FEAT_CLIENTSERVER
6256 XPropertyEvent *e = (XPropertyEvent *)&event;
6258 if (e->type == PropertyNotify && e->window == commWindow
6259 && e->atom == commProperty && e->state == PropertyNewValue)
6260 serverEventProc(xterm_dpy, &event);
6262 #endif
6263 XtDispatchEvent(&event);
6268 clip_xterm_own_selection(cbd)
6269 VimClipboard *cbd;
6271 if (xterm_Shell != (Widget)0)
6272 return clip_x11_own_selection(xterm_Shell, cbd);
6273 return FAIL;
6276 void
6277 clip_xterm_lose_selection(cbd)
6278 VimClipboard *cbd;
6280 if (xterm_Shell != (Widget)0)
6281 clip_x11_lose_selection(xterm_Shell, cbd);
6284 void
6285 clip_xterm_request_selection(cbd)
6286 VimClipboard *cbd;
6288 if (xterm_Shell != (Widget)0)
6289 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6292 void
6293 clip_xterm_set_selection(cbd)
6294 VimClipboard *cbd;
6296 clip_x11_set_selection(cbd);
6298 #endif
6301 #if defined(USE_XSMP) || defined(PROTO)
6303 * Code for X Session Management Protocol.
6305 static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6306 static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6307 static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6308 static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6309 static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6312 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6313 static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6316 * This is our chance to ask the user if they want to save,
6317 * or abort the logout
6319 /*ARGSUSED*/
6320 static void
6321 xsmp_handle_interaction(smc_conn, client_data)
6322 SmcConn smc_conn;
6323 SmPointer client_data;
6325 cmdmod_T save_cmdmod;
6326 int cancel_shutdown = False;
6328 save_cmdmod = cmdmod;
6329 cmdmod.confirm = TRUE;
6330 if (check_changed_any(FALSE))
6331 /* Mustn't logout */
6332 cancel_shutdown = True;
6333 cmdmod = save_cmdmod;
6334 setcursor(); /* position cursor */
6335 out_flush();
6337 /* Done interaction */
6338 SmcInteractDone(smc_conn, cancel_shutdown);
6340 /* Finish off
6341 * Only end save-yourself here if we're not cancelling shutdown;
6342 * we'll get a cancelled callback later in which we'll end it.
6343 * Hopefully get around glitchy SMs (like GNOME-1)
6345 if (!cancel_shutdown)
6347 xsmp.save_yourself = False;
6348 SmcSaveYourselfDone(smc_conn, True);
6351 # endif
6354 * Callback that starts save-yourself.
6356 /*ARGSUSED*/
6357 static void
6358 xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6359 shutdown, interact_style, fast)
6360 SmcConn smc_conn;
6361 SmPointer client_data;
6362 int save_type;
6363 Bool shutdown;
6364 int interact_style;
6365 Bool fast;
6367 /* Handle already being in saveyourself */
6368 if (xsmp.save_yourself)
6369 SmcSaveYourselfDone(smc_conn, True);
6370 xsmp.save_yourself = True;
6371 xsmp.shutdown = shutdown;
6373 /* First up, preserve all files */
6374 out_flush();
6375 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6377 if (p_verbose > 0)
6378 verb_msg((char_u *)_("XSMP handling save-yourself request"));
6380 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6381 /* Now see if we can ask about unsaved files */
6382 if (shutdown && !fast && gui.in_use)
6383 /* Need to interact with user, but need SM's permission */
6384 SmcInteractRequest(smc_conn, SmDialogError,
6385 xsmp_handle_interaction, client_data);
6386 else
6387 # endif
6389 /* Can stop the cycle here */
6390 SmcSaveYourselfDone(smc_conn, True);
6391 xsmp.save_yourself = False;
6397 * Callback to warn us of imminent death.
6399 /*ARGSUSED*/
6400 static void
6401 xsmp_die(smc_conn, client_data)
6402 SmcConn smc_conn;
6403 SmPointer client_data;
6405 xsmp_close();
6407 /* quit quickly leaving swapfiles for modified buffers behind */
6408 getout_preserve_modified(0);
6413 * Callback to tell us that save-yourself has completed.
6415 /*ARGSUSED*/
6416 static void
6417 xsmp_save_complete(smc_conn, client_data)
6418 SmcConn smc_conn;
6419 SmPointer client_data;
6421 xsmp.save_yourself = False;
6426 * Callback to tell us that an instigated shutdown was cancelled
6427 * (maybe even by us)
6429 /*ARGSUSED*/
6430 static void
6431 xsmp_shutdown_cancelled(smc_conn, client_data)
6432 SmcConn smc_conn;
6433 SmPointer client_data;
6435 if (xsmp.save_yourself)
6436 SmcSaveYourselfDone(smc_conn, True);
6437 xsmp.save_yourself = False;
6438 xsmp.shutdown = False;
6443 * Callback to tell us that a new ICE connection has been established.
6445 /*ARGSUSED*/
6446 static void
6447 xsmp_ice_connection(iceConn, clientData, opening, watchData)
6448 IceConn iceConn;
6449 IcePointer clientData;
6450 Bool opening;
6451 IcePointer *watchData;
6453 /* Intercept creation of ICE connection fd */
6454 if (opening)
6456 xsmp_icefd = IceConnectionNumber(iceConn);
6457 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6462 /* Handle any ICE processing that's required; return FAIL if SM lost */
6464 xsmp_handle_requests()
6466 Bool rep;
6468 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6469 == IceProcessMessagesIOError)
6471 /* Lost ICE */
6472 if (p_verbose > 0)
6473 verb_msg((char_u *)_("XSMP lost ICE connection"));
6474 xsmp_close();
6475 return FAIL;
6477 else
6478 return OK;
6481 static int dummy;
6483 /* Set up X Session Management Protocol */
6484 void
6485 xsmp_init(void)
6487 char errorstring[80];
6488 char *clientid;
6489 SmcCallbacks smcallbacks;
6490 #if 0
6491 SmPropValue smname;
6492 SmProp smnameprop;
6493 SmProp *smprops[1];
6494 #endif
6496 if (p_verbose > 0)
6497 verb_msg((char_u *)_("XSMP opening connection"));
6499 xsmp.save_yourself = xsmp.shutdown = False;
6501 /* Set up SM callbacks - must have all, even if they're not used */
6502 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6503 smcallbacks.save_yourself.client_data = NULL;
6504 smcallbacks.die.callback = xsmp_die;
6505 smcallbacks.die.client_data = NULL;
6506 smcallbacks.save_complete.callback = xsmp_save_complete;
6507 smcallbacks.save_complete.client_data = NULL;
6508 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6509 smcallbacks.shutdown_cancelled.client_data = NULL;
6511 /* Set up a watch on ICE connection creations. The "dummy" argument is
6512 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6513 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6515 if (p_verbose > 0)
6516 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
6517 return;
6520 /* Create an SM connection */
6521 xsmp.smcconn = SmcOpenConnection(
6522 NULL,
6523 NULL,
6524 SmProtoMajor,
6525 SmProtoMinor,
6526 SmcSaveYourselfProcMask | SmcDieProcMask
6527 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6528 &smcallbacks,
6529 NULL,
6530 &clientid,
6531 sizeof(errorstring),
6532 errorstring);
6533 if (xsmp.smcconn == NULL)
6535 char errorreport[132];
6537 if (p_verbose > 0)
6539 vim_snprintf(errorreport, sizeof(errorreport),
6540 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6541 verb_msg((char_u *)errorreport);
6543 return;
6545 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6547 #if 0
6548 /* ID ourselves */
6549 smname.value = "vim";
6550 smname.length = 3;
6551 smnameprop.name = "SmProgram";
6552 smnameprop.type = "SmARRAY8";
6553 smnameprop.num_vals = 1;
6554 smnameprop.vals = &smname;
6556 smprops[0] = &smnameprop;
6557 SmcSetProperties(xsmp.smcconn, 1, smprops);
6558 #endif
6562 /* Shut down XSMP comms. */
6563 void
6564 xsmp_close()
6566 if (xsmp_icefd != -1)
6568 SmcCloseConnection(xsmp.smcconn, 0, NULL);
6569 xsmp_icefd = -1;
6572 #endif /* USE_XSMP */
6575 #ifdef EBCDIC
6576 /* Translate character to its CTRL- value */
6577 char CtrlTable[] =
6579 /* 00 - 5E */
6580 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6581 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6582 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6583 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6584 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6585 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6586 /* ^ */ 0x1E,
6587 /* - */ 0x1F,
6588 /* 61 - 6C */
6589 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6590 /* _ */ 0x1F,
6591 /* 6E - 80 */
6592 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6593 /* a */ 0x01,
6594 /* b */ 0x02,
6595 /* c */ 0x03,
6596 /* d */ 0x37,
6597 /* e */ 0x2D,
6598 /* f */ 0x2E,
6599 /* g */ 0x2F,
6600 /* h */ 0x16,
6601 /* i */ 0x05,
6602 /* 8A - 90 */
6603 0, 0, 0, 0, 0, 0, 0,
6604 /* j */ 0x15,
6605 /* k */ 0x0B,
6606 /* l */ 0x0C,
6607 /* m */ 0x0D,
6608 /* n */ 0x0E,
6609 /* o */ 0x0F,
6610 /* p */ 0x10,
6611 /* q */ 0x11,
6612 /* r */ 0x12,
6613 /* 9A - A1 */
6614 0, 0, 0, 0, 0, 0, 0, 0,
6615 /* s */ 0x13,
6616 /* t */ 0x3C,
6617 /* u */ 0x3D,
6618 /* v */ 0x32,
6619 /* w */ 0x26,
6620 /* x */ 0x18,
6621 /* y */ 0x19,
6622 /* z */ 0x3F,
6623 /* AA - AC */
6624 0, 0, 0,
6625 /* [ */ 0x27,
6626 /* AE - BC */
6627 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6628 /* ] */ 0x1D,
6629 /* BE - C0 */ 0, 0, 0,
6630 /* A */ 0x01,
6631 /* B */ 0x02,
6632 /* C */ 0x03,
6633 /* D */ 0x37,
6634 /* E */ 0x2D,
6635 /* F */ 0x2E,
6636 /* G */ 0x2F,
6637 /* H */ 0x16,
6638 /* I */ 0x05,
6639 /* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
6640 /* J */ 0x15,
6641 /* K */ 0x0B,
6642 /* L */ 0x0C,
6643 /* M */ 0x0D,
6644 /* N */ 0x0E,
6645 /* O */ 0x0F,
6646 /* P */ 0x10,
6647 /* Q */ 0x11,
6648 /* R */ 0x12,
6649 /* DA - DF */ 0, 0, 0, 0, 0, 0,
6650 /* \ */ 0x1C,
6651 /* E1 */ 0,
6652 /* S */ 0x13,
6653 /* T */ 0x3C,
6654 /* U */ 0x3D,
6655 /* V */ 0x32,
6656 /* W */ 0x26,
6657 /* X */ 0x18,
6658 /* Y */ 0x19,
6659 /* Z */ 0x3F,
6660 /* EA - FF*/ 0, 0, 0, 0, 0, 0,
6661 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6664 char MetaCharTable[]=
6665 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6666 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
6667 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
6668 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
6669 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
6673 /* TODO: Use characters NOT numbers!!! */
6674 char CtrlCharTable[]=
6675 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6676 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
6677 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
6678 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
6679 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
6683 #endif