Preserve swap files after crash
[MacVim.git] / src / os_unix.c
blob9acb344ef771c8033d688fc5fe1998a88feca754
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 funcion.
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 /* Checked it already. */
1571 if (x11_display_from == XD_XTERM)
1572 return OK;
1575 * If the X11 display was opened here before, for the window where Vim
1576 * 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;
1582 if (test_x11_window(x11_display) == FAIL)
1584 /* probably bad $WINDOWID */
1585 x11_window = 0;
1586 x11_display = NULL;
1587 x11_display_from = XD_NONE;
1588 return FAIL;
1590 return OK;
1592 #endif
1594 if (x11_window == 0 || x11_display == NULL)
1595 result = -1;
1597 if (result != -1) /* Have already been here and set this */
1598 return result; /* Don't do all these X calls again */
1600 if (x11_window != 0 && x11_display == NULL)
1602 #ifdef SET_SIG_ALARM
1603 RETSIGTYPE (*sig_save)();
1604 #endif
1605 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1606 struct timeval start_tv;
1608 if (p_verbose > 0)
1609 gettimeofday(&start_tv, NULL);
1610 #endif
1612 #ifdef SET_SIG_ALARM
1614 * Opening the Display may hang if the DISPLAY setting is wrong, or
1615 * the network connection is bad. Set an alarm timer to get out.
1617 sig_alarm_called = FALSE;
1618 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1619 (RETSIGTYPE (*)())sig_alarm);
1620 alarm(2);
1621 #endif
1622 x11_display = XOpenDisplay(NULL);
1624 #ifdef SET_SIG_ALARM
1625 alarm(0);
1626 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1627 if (p_verbose > 0 && sig_alarm_called)
1628 verb_msg((char_u *)_("Opening the X display timed out"));
1629 #endif
1630 if (x11_display != NULL)
1632 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1633 if (p_verbose > 0)
1635 verbose_enter();
1636 xopen_message(&start_tv);
1637 verbose_leave();
1639 # endif
1640 if (test_x11_window(x11_display) == FAIL)
1642 /* Maybe window id is bad */
1643 x11_window = 0;
1644 XCloseDisplay(x11_display);
1645 x11_display = NULL;
1647 else
1648 x11_display_from = XD_HERE;
1651 if (x11_window == 0 || x11_display == NULL)
1652 return (result = FAIL);
1653 return (result = OK);
1657 * Determine original x11 Window Title
1659 static int
1660 get_x11_title(test_only)
1661 int test_only;
1663 return get_x11_thing(TRUE, test_only);
1667 * Determine original x11 Window icon
1669 static int
1670 get_x11_icon(test_only)
1671 int test_only;
1673 int retval = FALSE;
1675 retval = get_x11_thing(FALSE, test_only);
1677 /* could not get old icon, use terminal name */
1678 if (oldicon == NULL && !test_only)
1680 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1681 oldicon = T_NAME + 8;
1682 else
1683 oldicon = T_NAME;
1686 return retval;
1689 static int
1690 get_x11_thing(get_title, test_only)
1691 int get_title; /* get title string */
1692 int test_only;
1694 XTextProperty text_prop;
1695 int retval = FALSE;
1696 Status status;
1698 if (get_x11_windis() == OK)
1700 /* Get window/icon name if any */
1701 if (get_title)
1702 status = XGetWMName(x11_display, x11_window, &text_prop);
1703 else
1704 status = XGetWMIconName(x11_display, x11_window, &text_prop);
1707 * If terminal is xterm, then x11_window may be a child window of the
1708 * outer xterm window that actually contains the window/icon name, so
1709 * keep traversing up the tree until a window with a title/icon is
1710 * found.
1712 /* Previously this was only done for xterm and alikes. I don't see a
1713 * reason why it would fail for other terminal emulators.
1714 * if (term_is_xterm) */
1716 Window root;
1717 Window parent;
1718 Window win = x11_window;
1719 Window *children;
1720 unsigned int num_children;
1722 while (!status || text_prop.value == NULL)
1724 if (!XQueryTree(x11_display, win, &root, &parent, &children,
1725 &num_children))
1726 break;
1727 if (children)
1728 XFree((void *)children);
1729 if (parent == root || parent == 0)
1730 break;
1732 win = parent;
1733 if (get_title)
1734 status = XGetWMName(x11_display, win, &text_prop);
1735 else
1736 status = XGetWMIconName(x11_display, win, &text_prop);
1739 if (status && text_prop.value != NULL)
1741 retval = TRUE;
1742 if (!test_only)
1744 #ifdef FEAT_XFONTSET
1745 if (text_prop.encoding == XA_STRING)
1747 #endif
1748 if (get_title)
1749 oldtitle = vim_strsave((char_u *)text_prop.value);
1750 else
1751 oldicon = vim_strsave((char_u *)text_prop.value);
1752 #ifdef FEAT_XFONTSET
1754 else
1756 char **cl;
1757 Status transform_status;
1758 int n = 0;
1760 transform_status = XmbTextPropertyToTextList(x11_display,
1761 &text_prop,
1762 &cl, &n);
1763 if (transform_status >= Success && n > 0 && cl[0])
1765 if (get_title)
1766 oldtitle = vim_strsave((char_u *) cl[0]);
1767 else
1768 oldicon = vim_strsave((char_u *) cl[0]);
1769 XFreeStringList(cl);
1771 else
1773 if (get_title)
1774 oldtitle = vim_strsave((char_u *)text_prop.value);
1775 else
1776 oldicon = vim_strsave((char_u *)text_prop.value);
1779 #endif
1781 XFree((void *)text_prop.value);
1784 return retval;
1787 /* Are Xutf8 functions available? Avoid error from old compilers. */
1788 #if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1789 # if X_HAVE_UTF8_STRING
1790 # define USE_UTF8_STRING
1791 # endif
1792 #endif
1795 * Set x11 Window Title
1797 * get_x11_windis() must be called before this and have returned OK
1799 static void
1800 set_x11_title(title)
1801 char_u *title;
1803 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1804 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1805 * supported everywhere and STRING doesn't work for multi-byte titles.
1807 #ifdef USE_UTF8_STRING
1808 if (enc_utf8)
1809 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
1810 NULL, NULL, 0, NULL, NULL, NULL);
1811 else
1812 #endif
1814 #if XtSpecificationRelease >= 4
1815 # ifdef FEAT_XFONTSET
1816 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
1817 NULL, NULL, 0, NULL, NULL, NULL);
1818 # else
1819 XTextProperty text_prop;
1820 char *c_title = (char *)title;
1822 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
1823 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
1824 XSetWMProperties(x11_display, x11_window, &text_prop,
1825 NULL, NULL, 0, NULL, NULL, NULL);
1826 # endif
1827 #else
1828 XStoreName(x11_display, x11_window, (char *)title);
1829 #endif
1831 XFlush(x11_display);
1835 * Set x11 Window icon
1837 * get_x11_windis() must be called before this and have returned OK
1839 static void
1840 set_x11_icon(icon)
1841 char_u *icon;
1843 /* See above for comments about using X*SetWMProperties(). */
1844 #ifdef USE_UTF8_STRING
1845 if (enc_utf8)
1846 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1847 NULL, 0, NULL, NULL, NULL);
1848 else
1849 #endif
1851 #if XtSpecificationRelease >= 4
1852 # ifdef FEAT_XFONTSET
1853 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
1854 NULL, 0, NULL, NULL, NULL);
1855 # else
1856 XTextProperty text_prop;
1857 char *c_icon = (char *)icon;
1859 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
1860 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
1861 NULL, 0, NULL, NULL, NULL);
1862 # endif
1863 #else
1864 XSetIconName(x11_display, x11_window, (char *)icon);
1865 #endif
1867 XFlush(x11_display);
1870 #else /* FEAT_X11 */
1872 /*ARGSUSED*/
1873 static int
1874 get_x11_title(test_only)
1875 int test_only;
1877 return FALSE;
1880 static int
1881 get_x11_icon(test_only)
1882 int test_only;
1884 if (!test_only)
1886 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
1887 oldicon = T_NAME + 8;
1888 else
1889 oldicon = T_NAME;
1891 return FALSE;
1894 #endif /* FEAT_X11 */
1897 mch_can_restore_title()
1899 return get_x11_title(TRUE);
1903 mch_can_restore_icon()
1905 return get_x11_icon(TRUE);
1909 * Set the window title and icon.
1911 void
1912 mch_settitle(title, icon)
1913 char_u *title;
1914 char_u *icon;
1916 int type = 0;
1917 static int recursive = 0;
1919 if (T_NAME == NULL) /* no terminal name (yet) */
1920 return;
1921 if (title == NULL && icon == NULL) /* nothing to do */
1922 return;
1924 /* When one of the X11 functions causes a deadly signal, we get here again
1925 * recursively. Avoid hanging then (something is probably locked). */
1926 if (recursive)
1927 return;
1928 ++recursive;
1931 * if the window ID and the display is known, we may use X11 calls
1933 #ifdef FEAT_X11
1934 if (get_x11_windis() == OK)
1935 type = 1;
1936 #else
1937 # if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) \
1938 || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM)
1939 if (gui.in_use)
1940 type = 1;
1941 # endif
1942 #endif
1945 * Note: if "t_TS" is set, title is set with escape sequence rather
1946 * than x11 calls, because the x11 calls don't always work
1948 if ((type || *T_TS != NUL) && title != NULL)
1950 if (oldtitle == NULL
1951 #ifdef FEAT_GUI
1952 && !gui.in_use
1953 #endif
1954 ) /* first call but not in GUI, save title */
1955 (void)get_x11_title(FALSE);
1957 if (*T_TS != NUL) /* it's OK if t_fs is empty */
1958 term_settitle(title);
1959 #ifdef FEAT_X11
1960 else
1961 # ifdef FEAT_GUI_GTK
1962 if (!gui.in_use) /* don't do this if GTK+ is running */
1963 # endif
1964 set_x11_title(title); /* x11 */
1965 #endif
1966 #if defined(FEAT_GUI_GTK) \
1967 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) \
1968 || defined(FEAT_GUI_MACVIM)
1969 else
1970 gui_mch_settitle(title, icon);
1971 #endif
1972 did_set_title = TRUE;
1975 if ((type || *T_CIS != NUL) && icon != NULL)
1977 if (oldicon == NULL
1978 #ifdef FEAT_GUI
1979 && !gui.in_use
1980 #endif
1981 ) /* first call, save icon */
1982 get_x11_icon(FALSE);
1984 if (*T_CIS != NUL)
1986 out_str(T_CIS); /* set icon start */
1987 out_str_nf(icon);
1988 out_str(T_CIE); /* set icon end */
1989 out_flush();
1991 #ifdef FEAT_X11
1992 else
1993 # ifdef FEAT_GUI_GTK
1994 if (!gui.in_use) /* don't do this if GTK+ is running */
1995 # endif
1996 set_x11_icon(icon); /* x11 */
1997 #endif
1998 did_set_icon = TRUE;
2000 --recursive;
2004 * Restore the window/icon title.
2005 * "which" is one of:
2006 * 1 only restore title
2007 * 2 only restore icon
2008 * 3 restore title and icon
2010 void
2011 mch_restore_title(which)
2012 int which;
2014 /* only restore the title or icon when it has been set */
2015 mch_settitle(((which & 1) && did_set_title) ?
2016 (oldtitle ? oldtitle : p_titleold) : NULL,
2017 ((which & 2) && did_set_icon) ? oldicon : NULL);
2020 #endif /* FEAT_TITLE */
2023 * Return TRUE if "name" looks like some xterm name.
2024 * Seiichi Sato mentioned that "mlterm" works like xterm.
2027 vim_is_xterm(name)
2028 char_u *name;
2030 if (name == NULL)
2031 return FALSE;
2032 return (STRNICMP(name, "xterm", 5) == 0
2033 || STRNICMP(name, "nxterm", 6) == 0
2034 || STRNICMP(name, "kterm", 5) == 0
2035 || STRNICMP(name, "mlterm", 6) == 0
2036 || STRNICMP(name, "rxvt", 4) == 0
2037 || STRCMP(name, "builtin_xterm") == 0);
2040 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2042 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2043 * Return 1 for "xterm".
2044 * Return 2 for "xterm2".
2047 use_xterm_mouse()
2049 if (ttym_flags == TTYM_XTERM2)
2050 return 2;
2051 if (ttym_flags == TTYM_XTERM)
2052 return 1;
2053 return 0;
2055 #endif
2058 vim_is_iris(name)
2059 char_u *name;
2061 if (name == NULL)
2062 return FALSE;
2063 return (STRNICMP(name, "iris-ansi", 9) == 0
2064 || STRCMP(name, "builtin_iris-ansi") == 0);
2068 vim_is_vt300(name)
2069 char_u *name;
2071 if (name == NULL)
2072 return FALSE; /* actually all ANSI comp. terminals should be here */
2073 /* catch VT100 - VT5xx */
2074 return ((STRNICMP(name, "vt", 2) == 0
2075 && vim_strchr((char_u *)"12345", name[2]) != NULL)
2076 || STRCMP(name, "builtin_vt320") == 0);
2080 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2081 * This should include all windowed terminal emulators.
2084 vim_is_fastterm(name)
2085 char_u *name;
2087 if (name == NULL)
2088 return FALSE;
2089 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2090 return TRUE;
2091 return ( STRNICMP(name, "hpterm", 6) == 0
2092 || STRNICMP(name, "sun-cmd", 7) == 0
2093 || STRNICMP(name, "screen", 6) == 0
2094 || STRNICMP(name, "dtterm", 6) == 0);
2098 * Insert user name in s[len].
2099 * Return OK if a name found.
2102 mch_get_user_name(s, len)
2103 char_u *s;
2104 int len;
2106 #ifdef VMS
2107 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
2108 return OK;
2109 #else
2110 return mch_get_uname(getuid(), s, len);
2111 #endif
2115 * Insert user name for "uid" in s[len].
2116 * Return OK if a name found.
2119 mch_get_uname(uid, s, len)
2120 uid_t uid;
2121 char_u *s;
2122 int len;
2124 #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2125 struct passwd *pw;
2127 if ((pw = getpwuid(uid)) != NULL
2128 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2130 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
2131 return OK;
2133 #endif
2134 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2135 return FAIL; /* a number is not a name */
2139 * Insert host name is s[len].
2142 #ifdef HAVE_SYS_UTSNAME_H
2143 void
2144 mch_get_host_name(s, len)
2145 char_u *s;
2146 int len;
2148 struct utsname vutsname;
2150 if (uname(&vutsname) < 0)
2151 *s = NUL;
2152 else
2153 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
2155 #else /* HAVE_SYS_UTSNAME_H */
2157 # ifdef HAVE_SYS_SYSTEMINFO_H
2158 # define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2159 # endif
2161 void
2162 mch_get_host_name(s, len)
2163 char_u *s;
2164 int len;
2166 # ifdef VAXC
2167 vaxc$gethostname((char *)s, len);
2168 # else
2169 gethostname((char *)s, len);
2170 # endif
2171 s[len - 1] = NUL; /* make sure it's terminated */
2173 #endif /* HAVE_SYS_UTSNAME_H */
2176 * return process ID
2178 long
2179 mch_get_pid()
2181 return (long)getpid();
2184 #if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2185 static char *strerror __ARGS((int));
2187 static char *
2188 strerror(err)
2189 int err;
2191 extern int sys_nerr;
2192 extern char *sys_errlist[];
2193 static char er[20];
2195 if (err > 0 && err < sys_nerr)
2196 return (sys_errlist[err]);
2197 sprintf(er, "Error %d", err);
2198 return er;
2200 #endif
2203 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2204 * Return OK for success, FAIL for failure.
2207 mch_dirname(buf, len)
2208 char_u *buf;
2209 int len;
2211 #if defined(USE_GETCWD)
2212 if (getcwd((char *)buf, len) == NULL)
2214 STRCPY(buf, strerror(errno));
2215 return FAIL;
2217 return OK;
2218 #else
2219 return (getwd((char *)buf) != NULL ? OK : FAIL);
2220 #endif
2223 #if defined(OS2) || defined(PROTO)
2225 * Replace all slashes by backslashes.
2226 * When 'shellslash' set do it the other way around.
2228 void
2229 slash_adjust(p)
2230 char_u *p;
2232 while (*p)
2234 if (*p == psepcN)
2235 *p = psepc;
2236 mb_ptr_adv(p);
2239 #endif
2242 * Get absolute file name into "buf[len]".
2244 * return FAIL for failure, OK for success
2247 mch_FullName(fname, buf, len, force)
2248 char_u *fname, *buf;
2249 int len;
2250 int force; /* also expand when already absolute path */
2252 int l;
2253 #ifdef OS2
2254 int only_drive; /* file name is only a drive letter */
2255 #endif
2256 #ifdef HAVE_FCHDIR
2257 int fd = -1;
2258 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
2259 #endif
2260 char_u olddir[MAXPATHL];
2261 char_u *p;
2262 int retval = OK;
2264 #ifdef VMS
2265 fname = vms_fixfilename(fname);
2266 #endif
2268 #ifdef __CYGWIN__
2270 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2272 cygwin_conv_to_posix_path(fname, fname);
2273 #endif
2275 /* expand it if forced or not an absolute path */
2276 if (force || !mch_isFullName(fname))
2279 * If the file name has a path, change to that directory for a moment,
2280 * and then do the getwd() (and get back to where we were).
2281 * This will get the correct path name with "../" things.
2283 #ifdef OS2
2284 only_drive = 0;
2285 if (((p = vim_strrchr(fname, '/')) != NULL)
2286 || ((p = vim_strrchr(fname, '\\')) != NULL)
2287 || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive))
2288 #else
2289 if ((p = vim_strrchr(fname, '/')) != NULL)
2290 #endif
2292 #ifdef HAVE_FCHDIR
2294 * Use fchdir() if possible, it's said to be faster and more
2295 * reliable. But on SunOS 4 it might not work. Check this by
2296 * doing a fchdir() right now.
2298 if (!dont_fchdir)
2300 fd = open(".", O_RDONLY | O_EXTRA, 0);
2301 if (fd >= 0 && fchdir(fd) < 0)
2303 close(fd);
2304 fd = -1;
2305 dont_fchdir = TRUE; /* don't try again */
2308 #endif
2310 /* Only change directory when we are sure we can return to where
2311 * we are now. After doing "su" chdir(".") might not work. */
2312 if (
2313 #ifdef HAVE_FCHDIR
2314 fd < 0 &&
2315 #endif
2316 (mch_dirname(olddir, MAXPATHL) == FAIL
2317 || mch_chdir((char *)olddir) != 0))
2319 p = NULL; /* can't get current dir: don't chdir */
2320 retval = FAIL;
2322 else
2324 #ifdef OS2
2326 * compensate for case where ':' from "D:" was the only
2327 * path separator detected in the file name; the _next_
2328 * character has to be removed, and then restored later.
2330 if (only_drive)
2331 p++;
2332 #endif
2333 /* The directory is copied into buf[], to be able to remove
2334 * the file name without changing it (could be a string in
2335 * read-only memory) */
2336 if (p - fname >= len)
2337 retval = FAIL;
2338 else
2340 vim_strncpy(buf, fname, p - fname);
2341 if (mch_chdir((char *)buf))
2342 retval = FAIL;
2343 else
2344 fname = p + 1;
2345 *buf = NUL;
2347 #ifdef OS2
2348 if (only_drive)
2350 p--;
2351 if (retval != FAIL)
2352 fname--;
2354 #endif
2357 if (mch_dirname(buf, len) == FAIL)
2359 retval = FAIL;
2360 *buf = NUL;
2362 if (p != NULL)
2364 #ifdef HAVE_FCHDIR
2365 if (fd >= 0)
2367 l = fchdir(fd);
2368 close(fd);
2370 else
2371 #endif
2372 l = mch_chdir((char *)olddir);
2373 if (l != 0)
2374 EMSG(_(e_prev_dir));
2377 l = STRLEN(buf);
2378 if (l >= len)
2379 retval = FAIL;
2380 #ifndef VMS
2381 else
2383 if (l > 0 && buf[l - 1] != '/' && *fname != NUL
2384 && STRCMP(fname, ".") != 0)
2385 STRCAT(buf, "/");
2387 #endif
2390 /* Catch file names which are too long. */
2391 if (retval == FAIL || STRLEN(buf) + STRLEN(fname) >= len)
2392 return FAIL;
2394 /* Do not append ".", "/dir/." is equal to "/dir". */
2395 if (STRCMP(fname, ".") != 0)
2396 STRCAT(buf, fname);
2398 return OK;
2402 * Return TRUE if "fname" does not depend on the current directory.
2405 mch_isFullName(fname)
2406 char_u *fname;
2408 #ifdef __EMX__
2409 return _fnisabs(fname);
2410 #else
2411 # ifdef VMS
2412 return ( fname[0] == '/' || fname[0] == '.' ||
2413 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2414 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2415 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
2416 # else
2417 return (*fname == '/' || *fname == '~');
2418 # endif
2419 #endif
2422 #if defined(USE_FNAME_CASE) || defined(PROTO)
2424 * Set the case of the file name, if it already exists. This will cause the
2425 * file name to remain exactly the same.
2426 * Only required for file systems where case is ingored and preserved.
2428 /*ARGSUSED*/
2429 void
2430 fname_case(name, len)
2431 char_u *name;
2432 int len; /* buffer size, only used when name gets longer */
2434 struct stat st;
2435 char_u *slash, *tail;
2436 DIR *dirp;
2437 struct dirent *dp;
2439 if (lstat((char *)name, &st) >= 0)
2441 /* Open the directory where the file is located. */
2442 slash = vim_strrchr(name, '/');
2443 if (slash == NULL)
2445 dirp = opendir(".");
2446 tail = name;
2448 else
2450 *slash = NUL;
2451 dirp = opendir((char *)name);
2452 *slash = '/';
2453 tail = slash + 1;
2456 if (dirp != NULL)
2458 while ((dp = readdir(dirp)) != NULL)
2460 /* Only accept names that differ in case and are the same byte
2461 * length. TODO: accept different length name. */
2462 if (STRICMP(tail, dp->d_name) == 0
2463 && STRLEN(tail) == STRLEN(dp->d_name))
2465 char_u newname[MAXPATHL + 1];
2466 struct stat st2;
2468 /* Verify the inode is equal. */
2469 vim_strncpy(newname, name, MAXPATHL);
2470 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2471 MAXPATHL - (tail - name));
2472 if (lstat((char *)newname, &st2) >= 0
2473 && st.st_ino == st2.st_ino
2474 && st.st_dev == st2.st_dev)
2476 STRCPY(tail, dp->d_name);
2477 break;
2482 closedir(dirp);
2486 #endif
2489 * Get file permissions for 'name'.
2490 * Returns -1 when it doesn't exist.
2492 long
2493 mch_getperm(name)
2494 char_u *name;
2496 struct stat statb;
2498 /* Keep the #ifdef outside of stat(), it may be a macro. */
2499 #ifdef VMS
2500 if (stat((char *)vms_fixfilename(name), &statb))
2501 #else
2502 if (stat((char *)name, &statb))
2503 #endif
2504 return -1;
2505 #ifdef __INTERIX
2506 /* The top bit makes the value negative, which means the file doesn't
2507 * exist. Remove the bit, we don't use it. */
2508 return statb.st_mode & ~S_ADDACE;
2509 #else
2510 return statb.st_mode;
2511 #endif
2515 * set file permission for 'name' to 'perm'
2517 * return FAIL for failure, OK otherwise
2520 mch_setperm(name, perm)
2521 char_u *name;
2522 long perm;
2524 return (chmod((char *)
2525 #ifdef VMS
2526 vms_fixfilename(name),
2527 #else
2528 name,
2529 #endif
2530 (mode_t)perm) == 0 ? OK : FAIL);
2533 #if defined(HAVE_ACL) || defined(PROTO)
2534 # ifdef HAVE_SYS_ACL_H
2535 # include <sys/acl.h>
2536 # endif
2537 # ifdef HAVE_SYS_ACCESS_H
2538 # include <sys/access.h>
2539 # endif
2541 # ifdef HAVE_SOLARIS_ACL
2542 typedef struct vim_acl_solaris_T {
2543 int acl_cnt;
2544 aclent_t *acl_entry;
2545 } vim_acl_solaris_T;
2546 # endif
2549 * Return a pointer to the ACL of file "fname" in allocated memory.
2550 * Return NULL if the ACL is not available for whatever reason.
2552 vim_acl_T
2553 mch_get_acl(fname)
2554 char_u *fname;
2556 vim_acl_T ret = NULL;
2557 #ifdef HAVE_POSIX_ACL
2558 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2559 #else
2560 #ifdef HAVE_SOLARIS_ACL
2561 vim_acl_solaris_T *aclent;
2563 aclent = malloc(sizeof(vim_acl_solaris_T));
2564 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
2566 free(aclent);
2567 return NULL;
2569 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
2570 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
2572 free(aclent->acl_entry);
2573 free(aclent);
2574 return NULL;
2576 ret = (vim_acl_T)aclent;
2577 #else
2578 #if defined(HAVE_AIX_ACL)
2579 int aclsize;
2580 struct acl *aclent;
2582 aclsize = sizeof(struct acl);
2583 aclent = malloc(aclsize);
2584 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2586 if (errno == ENOSPC)
2588 aclsize = aclent->acl_len;
2589 aclent = realloc(aclent, aclsize);
2590 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
2592 free(aclent);
2593 return NULL;
2596 else
2598 free(aclent);
2599 return NULL;
2602 ret = (vim_acl_T)aclent;
2603 #endif /* HAVE_AIX_ACL */
2604 #endif /* HAVE_SOLARIS_ACL */
2605 #endif /* HAVE_POSIX_ACL */
2606 return ret;
2610 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2612 void
2613 mch_set_acl(fname, aclent)
2614 char_u *fname;
2615 vim_acl_T aclent;
2617 if (aclent == NULL)
2618 return;
2619 #ifdef HAVE_POSIX_ACL
2620 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
2621 #else
2622 #ifdef HAVE_SOLARIS_ACL
2623 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
2624 ((vim_acl_solaris_T *)aclent)->acl_entry);
2625 #else
2626 #ifdef HAVE_AIX_ACL
2627 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
2628 #endif /* HAVE_AIX_ACL */
2629 #endif /* HAVE_SOLARIS_ACL */
2630 #endif /* HAVE_POSIX_ACL */
2633 void
2634 mch_free_acl(aclent)
2635 vim_acl_T aclent;
2637 if (aclent == NULL)
2638 return;
2639 #ifdef HAVE_POSIX_ACL
2640 acl_free((acl_t)aclent);
2641 #else
2642 #ifdef HAVE_SOLARIS_ACL
2643 free(((vim_acl_solaris_T *)aclent)->acl_entry);
2644 free(aclent);
2645 #else
2646 #ifdef HAVE_AIX_ACL
2647 free(aclent);
2648 #endif /* HAVE_AIX_ACL */
2649 #endif /* HAVE_SOLARIS_ACL */
2650 #endif /* HAVE_POSIX_ACL */
2652 #endif
2655 * Set hidden flag for "name".
2657 /* ARGSUSED */
2658 void
2659 mch_hide(name)
2660 char_u *name;
2662 /* can't hide a file */
2666 * return TRUE if "name" is a directory
2667 * return FALSE if "name" is not a directory
2668 * return FALSE for error
2671 mch_isdir(name)
2672 char_u *name;
2674 struct stat statb;
2676 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
2677 return FALSE;
2678 if (stat((char *)name, &statb))
2679 return FALSE;
2680 #ifdef _POSIX_SOURCE
2681 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
2682 #else
2683 return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE);
2684 #endif
2687 static int executable_file __ARGS((char_u *name));
2690 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2692 static int
2693 executable_file(name)
2694 char_u *name;
2696 struct stat st;
2698 if (stat((char *)name, &st))
2699 return 0;
2700 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
2704 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2705 * Return -1 if unknown.
2708 mch_can_exe(name)
2709 char_u *name;
2711 char_u *buf;
2712 char_u *p, *e;
2713 int retval;
2715 /* If it's an absolute or relative path don't need to use $PATH. */
2716 if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/'
2717 || (name[1] == '.' && name[2] == '/'))))
2718 return executable_file(name);
2720 p = (char_u *)getenv("PATH");
2721 if (p == NULL || *p == NUL)
2722 return -1;
2723 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
2724 if (buf == NULL)
2725 return -1;
2728 * Walk through all entries in $PATH to check if "name" exists there and
2729 * is an executable file.
2731 for (;;)
2733 e = (char_u *)strchr((char *)p, ':');
2734 if (e == NULL)
2735 e = p + STRLEN(p);
2736 if (e - p <= 1) /* empty entry means current dir */
2737 STRCPY(buf, "./");
2738 else
2740 vim_strncpy(buf, p, e - p);
2741 add_pathsep(buf);
2743 STRCAT(buf, name);
2744 retval = executable_file(buf);
2745 if (retval == 1)
2746 break;
2748 if (*e != ':')
2749 break;
2750 p = e + 1;
2753 vim_free(buf);
2754 return retval;
2758 * Check what "name" is:
2759 * NODE_NORMAL: file or directory (or doesn't exist)
2760 * NODE_WRITABLE: writable device, socket, fifo, etc.
2761 * NODE_OTHER: non-writable things
2764 mch_nodetype(name)
2765 char_u *name;
2767 struct stat st;
2769 if (stat((char *)name, &st))
2770 return NODE_NORMAL;
2771 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
2772 return NODE_NORMAL;
2773 #ifndef OS2
2774 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
2775 return NODE_OTHER;
2776 #endif
2777 /* Everything else is writable? */
2778 return NODE_WRITABLE;
2781 void
2782 mch_early_init()
2784 #ifdef HAVE_CHECK_STACK_GROWTH
2785 int i;
2787 check_stack_growth((char *)&i);
2789 # ifdef HAVE_STACK_LIMIT
2790 get_stack_limit();
2791 # endif
2793 #endif
2796 * Setup an alternative stack for signals. Helps to catch signals when
2797 * running out of stack space.
2798 * Use of sigaltstack() is preferred, it's more portable.
2799 * Ignore any errors.
2801 #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2802 signal_stack = malloc(SIGSTKSZ);
2803 init_signal_stack();
2804 #endif
2807 #if defined(EXITFREE) || defined(PROTO)
2808 void
2809 mch_free_mem()
2811 # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2812 if (clip_star.owned)
2813 clip_lose_selection(&clip_star);
2814 if (clip_plus.owned)
2815 clip_lose_selection(&clip_plus);
2816 # endif
2817 # if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
2818 if (xterm_Shell != (Widget)0)
2819 XtDestroyWidget(xterm_Shell);
2820 if (xterm_dpy != NULL)
2821 XtCloseDisplay(xterm_dpy);
2822 if (app_context != (XtAppContext)NULL)
2823 XtDestroyApplicationContext(app_context);
2824 # endif
2825 # ifdef FEAT_X11
2826 if (x11_display != NULL && x11_display != xterm_dpy)
2827 XCloseDisplay(x11_display);
2828 # endif
2829 # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2830 vim_free(signal_stack);
2831 signal_stack = NULL;
2832 # endif
2833 # ifdef FEAT_TITLE
2834 vim_free(oldtitle);
2835 vim_free(oldicon);
2836 # endif
2838 #endif
2840 static void exit_scroll __ARGS((void));
2843 * Output a newline when exiting.
2844 * Make sure the newline goes to the same stream as the text.
2846 static void
2847 exit_scroll()
2849 if (silent_mode)
2850 return;
2851 if (newline_on_exit || msg_didout)
2853 if (msg_use_printf())
2855 if (info_message)
2856 mch_msg("\n");
2857 else
2858 mch_errmsg("\r\n");
2860 else
2861 out_char('\n');
2863 else
2865 restore_cterm_colors(); /* get original colors back */
2866 msg_clr_eos_force(); /* clear the rest of the display */
2867 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
2871 void
2872 mch_exit(r)
2873 int r;
2875 exiting = TRUE;
2877 #if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
2878 x11_export_final_selection();
2879 #endif
2881 #ifdef FEAT_GUI
2882 if (!gui.in_use)
2883 #endif
2885 settmode(TMODE_COOK);
2886 #ifdef FEAT_TITLE
2887 mch_restore_title(3); /* restore xterm title and icon name */
2888 #endif
2890 * When t_ti is not empty but it doesn't cause swapping terminal
2891 * pages, need to output a newline when msg_didout is set. But when
2892 * t_ti does swap pages it should not go to the shell page. Do this
2893 * before stoptermcap().
2895 if (swapping_screen() && !newline_on_exit)
2896 exit_scroll();
2898 /* Stop termcap: May need to check for T_CRV response, which
2899 * requires RAW mode. */
2900 stoptermcap();
2903 * A newline is only required after a message in the alternate screen.
2904 * This is set to TRUE by wait_return().
2906 if (!swapping_screen() || newline_on_exit)
2907 exit_scroll();
2909 /* Cursor may have been switched off without calling starttermcap()
2910 * when doing "vim -u vimrc" and vimrc contains ":q". */
2911 if (full_screen)
2912 cursor_on();
2914 out_flush();
2915 ml_close_all(TRUE); /* remove all memfiles */
2916 may_core_dump();
2917 #ifdef FEAT_GUI
2918 if (gui.in_use)
2919 gui_exit(r);
2920 #endif
2922 #ifdef MACOS_CONVERT
2923 mac_conv_cleanup();
2924 #endif
2926 #ifdef __QNX__
2927 /* A core dump won't be created if the signal handler
2928 * doesn't return, so we can't call exit() */
2929 if (deadly_signal != 0)
2930 return;
2931 #endif
2933 #ifdef FEAT_NETBEANS_INTG
2934 if (usingNetbeans)
2935 netbeans_send_disconnect();
2936 #endif
2938 #ifdef EXITFREE
2939 free_all_mem();
2940 #endif
2942 exit(r);
2945 static void
2946 may_core_dump()
2948 if (deadly_signal != 0)
2950 signal(deadly_signal, SIG_DFL);
2951 kill(getpid(), deadly_signal); /* Die using the signal we caught */
2955 #ifndef VMS
2957 void
2958 mch_settmode(tmode)
2959 int tmode;
2961 static int first = TRUE;
2963 /* Why is NeXT excluded here (and not in os_unixx.h)? */
2964 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
2966 * for "new" tty systems
2968 # ifdef HAVE_TERMIOS_H
2969 static struct termios told;
2970 struct termios tnew;
2971 # else
2972 static struct termio told;
2973 struct termio tnew;
2974 # endif
2976 if (first)
2978 first = FALSE;
2979 # if defined(HAVE_TERMIOS_H)
2980 tcgetattr(read_cmd_fd, &told);
2981 # else
2982 ioctl(read_cmd_fd, TCGETA, &told);
2983 # endif
2986 tnew = told;
2987 if (tmode == TMODE_RAW)
2990 * ~ICRNL enables typing ^V^M
2992 tnew.c_iflag &= ~ICRNL;
2993 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
2994 # if defined(IEXTEN) && !defined(__MINT__)
2995 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
2996 /* but it breaks function keys on MINT */
2997 # endif
2999 # ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3000 tnew.c_oflag &= ~ONLCR;
3001 # endif
3002 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3003 tnew.c_cc[VTIME] = 0; /* don't wait */
3005 else if (tmode == TMODE_SLEEP)
3006 tnew.c_lflag &= ~(ECHO);
3008 # if defined(HAVE_TERMIOS_H)
3010 int n = 10;
3012 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3013 * few times. */
3014 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3015 && errno == EINTR && n > 0)
3016 --n;
3018 # else
3019 ioctl(read_cmd_fd, TCSETA, &tnew);
3020 # endif
3022 #else
3025 * for "old" tty systems
3027 # ifndef TIOCSETN
3028 # define TIOCSETN TIOCSETP /* for hpux 9.0 */
3029 # endif
3030 static struct sgttyb ttybold;
3031 struct sgttyb ttybnew;
3033 if (first)
3035 first = FALSE;
3036 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3039 ttybnew = ttybold;
3040 if (tmode == TMODE_RAW)
3042 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3043 ttybnew.sg_flags |= RAW;
3045 else if (tmode == TMODE_SLEEP)
3046 ttybnew.sg_flags &= ~(ECHO);
3047 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3048 #endif
3049 curr_tmode = tmode;
3053 * Try to get the code for "t_kb" from the stty setting
3055 * Even if termcap claims a backspace key, the user's setting *should*
3056 * prevail. stty knows more about reality than termcap does, and if
3057 * somebody's usual erase key is DEL (which, for most BSD users, it will
3058 * be), they're going to get really annoyed if their erase key starts
3059 * doing forward deletes for no reason. (Eric Fischer)
3061 void
3062 get_stty()
3064 char_u buf[2];
3065 char_u *p;
3067 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3068 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3069 /* for "new" tty systems */
3070 # ifdef HAVE_TERMIOS_H
3071 struct termios keys;
3072 # else
3073 struct termio keys;
3074 # endif
3076 # if defined(HAVE_TERMIOS_H)
3077 if (tcgetattr(read_cmd_fd, &keys) != -1)
3078 # else
3079 if (ioctl(read_cmd_fd, TCGETA, &keys) != -1)
3080 # endif
3082 buf[0] = keys.c_cc[VERASE];
3083 intr_char = keys.c_cc[VINTR];
3084 #else
3085 /* for "old" tty systems */
3086 struct sgttyb keys;
3088 if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1)
3090 buf[0] = keys.sg_erase;
3091 intr_char = keys.sg_kill;
3092 #endif
3093 buf[1] = NUL;
3094 add_termcode((char_u *)"kb", buf, FALSE);
3097 * If <BS> and <DEL> are now the same, redefine <DEL>.
3099 p = find_termcode((char_u *)"kD");
3100 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3101 do_fixdel(NULL);
3103 #if 0
3104 } /* to keep cindent happy */
3105 #endif
3108 #endif /* VMS */
3110 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3112 * Set mouse clicks on or off.
3114 void
3115 mch_setmouse(on)
3116 int on;
3118 static int ison = FALSE;
3119 int xterm_mouse_vers;
3121 if (on == ison) /* return quickly if nothing to do */
3122 return;
3124 xterm_mouse_vers = use_xterm_mouse();
3125 if (xterm_mouse_vers > 0)
3127 if (on) /* enable mouse events, use mouse tracking if available */
3128 out_str_nf((char_u *)
3129 (xterm_mouse_vers > 1
3130 ? IF_EB("\033[?1002h", ESC_STR "[?1002h")
3131 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3132 else /* disable mouse events, could probably always send the same */
3133 out_str_nf((char_u *)
3134 (xterm_mouse_vers > 1
3135 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3136 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
3137 ison = on;
3140 # ifdef FEAT_MOUSE_DEC
3141 else if (ttym_flags == TTYM_DEC)
3143 if (on) /* enable mouse events */
3144 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3145 else /* disable mouse events */
3146 out_str_nf((char_u *)"\033['z");
3147 ison = on;
3149 # endif
3151 # ifdef FEAT_MOUSE_GPM
3152 else
3154 if (on)
3156 if (gpm_open())
3157 ison = TRUE;
3159 else
3161 gpm_close();
3162 ison = FALSE;
3165 # endif
3167 # ifdef FEAT_MOUSE_JSB
3168 else
3170 if (on)
3172 /* D - Enable Mouse up/down messages
3173 * L - Enable Left Button Reporting
3174 * M - Enable Middle Button Reporting
3175 * R - Enable Right Button Reporting
3176 * K - Enable SHIFT and CTRL key Reporting
3177 * + - Enable Advanced messaging of mouse moves and up/down messages
3178 * Q - Quiet No Ack
3179 * # - Numeric value of mouse pointer required
3180 * 0 = Multiview 2000 cursor, used as standard
3181 * 1 = Windows Arrow
3182 * 2 = Windows I Beam
3183 * 3 = Windows Hour Glass
3184 * 4 = Windows Cross Hair
3185 * 5 = Windows UP Arrow
3187 #ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3188 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3189 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
3190 #else
3191 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3192 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
3193 #endif
3194 ison = TRUE;
3196 else
3198 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3199 ESC_STR "[0~ZwQ" ESC_STR "\\"));
3200 ison = FALSE;
3203 # endif
3204 # ifdef FEAT_MOUSE_PTERM
3205 else
3207 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3208 if (on)
3209 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3210 else
3211 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3212 ison = on;
3214 # endif
3218 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3220 void
3221 check_mouse_termcode()
3223 # ifdef FEAT_MOUSE_XTERM
3224 if (use_xterm_mouse()
3225 # ifdef FEAT_GUI
3226 && !gui.in_use
3227 # endif
3230 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3231 ? IF_EB("\233M", CSI_STR "M")
3232 : IF_EB("\033[M", ESC_STR "[M")));
3233 if (*p_mouse != NUL)
3235 /* force mouse off and maybe on to send possibly new mouse
3236 * activation sequence to the xterm, with(out) drag tracing. */
3237 mch_setmouse(FALSE);
3238 setmouse();
3241 else
3242 del_mouse_termcode(KS_MOUSE);
3243 # endif
3245 # ifdef FEAT_MOUSE_GPM
3246 if (!use_xterm_mouse()
3247 # ifdef FEAT_GUI
3248 && !gui.in_use
3249 # endif
3251 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3252 # endif
3254 # ifdef FEAT_MOUSE_JSB
3255 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3256 if (!use_xterm_mouse()
3257 # ifdef FEAT_GUI
3258 && !gui.in_use
3259 # endif
3261 set_mouse_termcode(KS_JSBTERM_MOUSE,
3262 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3263 else
3264 del_mouse_termcode(KS_JSBTERM_MOUSE);
3265 # endif
3267 # ifdef FEAT_MOUSE_NET
3268 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
3269 * define it in the GUI or when using an xterm. */
3270 if (!use_xterm_mouse()
3271 # ifdef FEAT_GUI
3272 && !gui.in_use
3273 # endif
3275 set_mouse_termcode(KS_NETTERM_MOUSE,
3276 (char_u *)IF_EB("\033}", ESC_STR "}"));
3277 else
3278 del_mouse_termcode(KS_NETTERM_MOUSE);
3279 # endif
3281 # ifdef FEAT_MOUSE_DEC
3282 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3283 if (!use_xterm_mouse()
3284 # ifdef FEAT_GUI
3285 && !gui.in_use
3286 # endif
3288 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3289 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
3290 else
3291 del_mouse_termcode(KS_DEC_MOUSE);
3292 # endif
3293 # ifdef FEAT_MOUSE_PTERM
3294 /* same as the dec mouse */
3295 if (!use_xterm_mouse()
3296 # ifdef FEAT_GUI
3297 && !gui.in_use
3298 # endif
3300 set_mouse_termcode(KS_PTERM_MOUSE,
3301 (char_u *) IF_EB("\033[", ESC_STR "["));
3302 else
3303 del_mouse_termcode(KS_PTERM_MOUSE);
3304 # endif
3306 #endif
3309 * set screen mode, always fails.
3311 /* ARGSUSED */
3313 mch_screenmode(arg)
3314 char_u *arg;
3316 EMSG(_(e_screenmode));
3317 return FAIL;
3320 #ifndef VMS
3323 * Try to get the current window size:
3324 * 1. with an ioctl(), most accurate method
3325 * 2. from the environment variables LINES and COLUMNS
3326 * 3. from the termcap
3327 * 4. keep using the old values
3328 * Return OK when size could be determined, FAIL otherwise.
3331 mch_get_shellsize()
3333 long rows = 0;
3334 long columns = 0;
3335 char_u *p;
3338 * For OS/2 use _scrsize().
3340 # ifdef __EMX__
3342 int s[2];
3344 _scrsize(s);
3345 columns = s[0];
3346 rows = s[1];
3348 # endif
3351 * 1. try using an ioctl. It is the most accurate method.
3353 * Try using TIOCGWINSZ first, some systems that have it also define
3354 * TIOCGSIZE but don't have a struct ttysize.
3356 # ifdef TIOCGWINSZ
3358 struct winsize ws;
3359 int fd = 1;
3361 /* When stdout is not a tty, use stdin for the ioctl(). */
3362 if (!isatty(fd) && isatty(read_cmd_fd))
3363 fd = read_cmd_fd;
3364 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
3366 columns = ws.ws_col;
3367 rows = ws.ws_row;
3370 # else /* TIOCGWINSZ */
3371 # ifdef TIOCGSIZE
3373 struct ttysize ts;
3374 int fd = 1;
3376 /* When stdout is not a tty, use stdin for the ioctl(). */
3377 if (!isatty(fd) && isatty(read_cmd_fd))
3378 fd = read_cmd_fd;
3379 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
3381 columns = ts.ts_cols;
3382 rows = ts.ts_lines;
3385 # endif /* TIOCGSIZE */
3386 # endif /* TIOCGWINSZ */
3389 * 2. get size from environment
3390 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3391 * the ioctl() values!
3393 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
3395 if ((p = (char_u *)getenv("LINES")))
3396 rows = atoi((char *)p);
3397 if ((p = (char_u *)getenv("COLUMNS")))
3398 columns = atoi((char *)p);
3401 #ifdef HAVE_TGETENT
3403 * 3. try reading "co" and "li" entries from termcap
3405 if (columns == 0 || rows == 0)
3406 getlinecol(&columns, &rows);
3407 #endif
3410 * 4. If everything fails, use the old values
3412 if (columns <= 0 || rows <= 0)
3413 return FAIL;
3415 Rows = rows;
3416 Columns = columns;
3417 return OK;
3421 * Try to set the window size to Rows and Columns.
3423 void
3424 mch_set_shellsize()
3426 if (*T_CWS)
3429 * NOTE: if you get an error here that term_set_winsize() is
3430 * undefined, check the output of configure. It could probably not
3431 * find a ncurses, termcap or termlib library.
3433 term_set_winsize((int)Rows, (int)Columns);
3434 out_flush();
3435 screen_start(); /* don't know where cursor is now */
3439 #endif /* VMS */
3442 * Rows and/or Columns has changed.
3444 void
3445 mch_new_shellsize()
3447 /* Nothing to do. */
3450 #ifndef USE_SYSTEM
3451 static void append_ga_line __ARGS((garray_T *gap));
3454 * Append the text in "gap" below the cursor line and clear "gap".
3456 static void
3457 append_ga_line(gap)
3458 garray_T *gap;
3460 /* Remove trailing CR. */
3461 if (gap->ga_len > 0
3462 && !curbuf->b_p_bin
3463 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
3464 --gap->ga_len;
3465 ga_append(gap, NUL);
3466 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
3467 gap->ga_len = 0;
3469 #endif
3472 mch_call_shell(cmd, options)
3473 char_u *cmd;
3474 int options; /* SHELL_*, see vim.h */
3476 #ifdef VMS
3477 char *ifn = NULL;
3478 char *ofn = NULL;
3479 #endif
3480 int tmode = cur_tmode;
3481 #ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3482 int x;
3483 # ifndef __EMX__
3484 char_u *newcmd; /* only needed for unix */
3485 # else
3487 * Set the preferred shell in the EMXSHELL environment variable (but
3488 * only if it is different from what is already in the environment).
3489 * Emx then takes care of whether to use "/c" or "-c" in an
3490 * intelligent way. Simply pass the whole thing to emx's system() call.
3491 * Emx also starts an interactive shell if system() is passed an empty
3492 * string.
3494 char_u *p, *old;
3496 if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh))
3498 /* should check HAVE_SETENV, but I know we don't have it. */
3499 p = alloc(10 + strlen(p_sh));
3500 if (p)
3502 sprintf((char *)p, "EMXSHELL=%s", p_sh);
3503 putenv((char *)p); /* don't free the pointer! */
3506 # endif
3508 out_flush();
3510 if (options & SHELL_COOKED)
3511 settmode(TMODE_COOK); /* set to normal mode */
3513 # ifdef __EMX__
3514 if (cmd == NULL)
3515 x = system(""); /* this starts an interactive shell in emx */
3516 else
3517 x = system((char *)cmd);
3518 /* system() returns -1 when error occurs in starting shell */
3519 if (x == -1 && !emsg_silent)
3521 MSG_PUTS(_("\nCannot execute shell "));
3522 msg_outtrans(p_sh);
3523 msg_putchar('\n');
3525 # else /* not __EMX__ */
3526 if (cmd == NULL)
3527 x = system((char *)p_sh);
3528 else
3530 # ifdef VMS
3531 if (ofn = strchr((char *)cmd, '>'))
3532 *ofn++ = '\0';
3533 if (ifn = strchr((char *)cmd, '<'))
3535 char *p;
3537 *ifn++ = '\0';
3538 p = strchr(ifn,' '); /* chop off any trailing spaces */
3539 if (p)
3540 *p = '\0';
3542 if (ofn)
3543 x = vms_sys((char *)cmd, ofn, ifn);
3544 else
3545 x = system((char *)cmd);
3546 # else
3547 newcmd = lalloc(STRLEN(p_sh)
3548 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
3549 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
3550 if (newcmd == NULL)
3551 x = 0;
3552 else
3554 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
3555 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
3556 (char *)p_shcf,
3557 (char *)cmd);
3558 x = system((char *)newcmd);
3559 vim_free(newcmd);
3561 # endif
3563 # ifdef VMS
3564 x = vms_sys_status(x);
3565 # endif
3566 if (emsg_silent)
3568 else if (x == 127)
3569 MSG_PUTS(_("\nCannot execute shell sh\n"));
3570 # endif /* __EMX__ */
3571 else if (x && !(options & SHELL_SILENT))
3573 MSG_PUTS(_("\nshell returned "));
3574 msg_outnum((long)x);
3575 msg_putchar('\n');
3578 if (tmode == TMODE_RAW)
3579 settmode(TMODE_RAW); /* set to raw mode */
3580 # ifdef FEAT_TITLE
3581 resettitle();
3582 # endif
3583 return x;
3585 #else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3587 # define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3588 127, some shells use that already */
3590 char_u *newcmd = NULL;
3591 pid_t pid;
3592 pid_t wpid = 0;
3593 pid_t wait_pid = 0;
3594 # ifdef HAVE_UNION_WAIT
3595 union wait status;
3596 # else
3597 int status = -1;
3598 # endif
3599 int retval = -1;
3600 char **argv = NULL;
3601 int argc;
3602 int i;
3603 char_u *p;
3604 int inquote;
3605 int pty_master_fd = -1; /* for pty's */
3606 # ifdef FEAT_GUI
3607 int pty_slave_fd = -1;
3608 char *tty_name;
3609 # endif
3610 int fd_toshell[2]; /* for pipes */
3611 int fd_fromshell[2];
3612 int pipe_error = FALSE;
3613 # ifdef HAVE_SETENV
3614 char envbuf[50];
3615 # else
3616 static char envbuf_Rows[20];
3617 static char envbuf_Columns[20];
3618 # endif
3619 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
3621 out_flush();
3622 if (options & SHELL_COOKED)
3623 settmode(TMODE_COOK); /* set to normal mode */
3625 newcmd = vim_strsave(p_sh);
3626 if (newcmd == NULL) /* out of memory */
3627 goto error;
3630 * Do this loop twice:
3631 * 1: find number of arguments
3632 * 2: separate them and build argv[]
3634 for (i = 0; i < 2; ++i)
3636 p = newcmd;
3637 inquote = FALSE;
3638 argc = 0;
3639 for (;;)
3641 if (i == 1)
3642 argv[argc] = (char *)p;
3643 ++argc;
3644 while (*p && (inquote || (*p != ' ' && *p != TAB)))
3646 if (*p == '"')
3647 inquote = !inquote;
3648 ++p;
3650 if (*p == NUL)
3651 break;
3652 if (i == 1)
3653 *p++ = NUL;
3654 p = skipwhite(p);
3656 if (argv == NULL)
3658 argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *)));
3659 if (argv == NULL) /* out of memory */
3660 goto error;
3663 if (cmd != NULL)
3665 if (extra_shell_arg != NULL)
3666 argv[argc++] = (char *)extra_shell_arg;
3667 argv[argc++] = (char *)p_shcf;
3668 argv[argc++] = (char *)cmd;
3670 argv[argc] = NULL;
3673 * For the GUI, when writing the output into the buffer and when reading
3674 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3675 * of the executed command into the Vim window. Or use a pipe.
3677 if ((options & (SHELL_READ|SHELL_WRITE))
3678 # ifdef FEAT_GUI
3679 || (gui.in_use && show_shell_mess)
3680 # endif
3683 # ifdef FEAT_GUI
3685 * Try to open a master pty.
3686 * If this works, open the slave pty.
3687 * If the slave can't be opened, close the master pty.
3689 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
3691 pty_master_fd = OpenPTY(&tty_name); /* open pty */
3692 if (pty_master_fd >= 0 && ((pty_slave_fd =
3693 open(tty_name, O_RDWR | O_EXTRA, 0)) < 0))
3695 close(pty_master_fd);
3696 pty_master_fd = -1;
3700 * If not opening a pty or it didn't work, try using pipes.
3702 if (pty_master_fd < 0)
3703 # endif
3705 pipe_error = (pipe(fd_toshell) < 0);
3706 if (!pipe_error) /* pipe create OK */
3708 pipe_error = (pipe(fd_fromshell) < 0);
3709 if (pipe_error) /* pipe create failed */
3711 close(fd_toshell[0]);
3712 close(fd_toshell[1]);
3715 if (pipe_error)
3717 MSG_PUTS(_("\nCannot create pipes\n"));
3718 out_flush();
3723 if (!pipe_error) /* pty or pipe opened or not used */
3725 # ifdef __BEOS__
3726 beos_cleanup_read_thread();
3727 # endif
3729 if ((pid = fork()) == -1) /* maybe we should use vfork() */
3731 MSG_PUTS(_("\nCannot fork\n"));
3732 if ((options & (SHELL_READ|SHELL_WRITE))
3733 # ifdef FEAT_GUI
3734 || (gui.in_use && show_shell_mess)
3735 # endif
3738 # ifdef FEAT_GUI
3739 if (pty_master_fd >= 0) /* close the pseudo tty */
3741 close(pty_master_fd);
3742 close(pty_slave_fd);
3744 else /* close the pipes */
3745 # endif
3747 close(fd_toshell[0]);
3748 close(fd_toshell[1]);
3749 close(fd_fromshell[0]);
3750 close(fd_fromshell[1]);
3754 else if (pid == 0) /* child */
3756 reset_signals(); /* handle signals normally */
3758 if (!show_shell_mess || (options & SHELL_EXPAND))
3760 int fd;
3763 * Don't want to show any message from the shell. Can't just
3764 * close stdout and stderr though, because some systems will
3765 * break if you try to write to them after that, so we must
3766 * use dup() to replace them with something else -- webb
3767 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3768 * waiting for input.
3770 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
3771 fclose(stdin);
3772 fclose(stdout);
3773 fclose(stderr);
3776 * If any of these open()'s and dup()'s fail, we just continue
3777 * anyway. It's not fatal, and on most systems it will make
3778 * no difference at all. On a few it will cause the execvp()
3779 * to exit with a non-zero status even when the completion
3780 * could be done, which is nothing too serious. If the open()
3781 * or dup() failed we'd just do the same thing ourselves
3782 * anyway -- webb
3784 if (fd >= 0)
3786 dup(fd); /* To replace stdin (file descriptor 0) */
3787 dup(fd); /* To replace stdout (file descriptor 1) */
3788 dup(fd); /* To replace stderr (file descriptor 2) */
3790 /* Don't need this now that we've duplicated it */
3791 close(fd);
3794 else if ((options & (SHELL_READ|SHELL_WRITE))
3795 # ifdef FEAT_GUI
3796 || gui.in_use
3797 # endif
3801 # ifdef HAVE_SETSID
3802 /* Create our own process group, so that the child and all its
3803 * children can be kill()ed. Don't do this when using pipes,
3804 * because stdin is not a tty, we would loose /dev/tty. */
3805 if (p_stmp)
3806 (void)setsid();
3807 # endif
3808 # ifdef FEAT_GUI
3809 if (pty_slave_fd >= 0)
3811 /* push stream discipline modules */
3812 if (options & SHELL_COOKED)
3813 SetupSlavePTY(pty_slave_fd);
3814 # ifdef TIOCSCTTY
3815 /* Try to become controlling tty (probably doesn't work,
3816 * unless run by root) */
3817 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
3818 # endif
3820 # endif
3821 /* Simulate to have a dumb terminal (for now) */
3822 # ifdef HAVE_SETENV
3823 setenv("TERM", "dumb", 1);
3824 sprintf((char *)envbuf, "%ld", Rows);
3825 setenv("ROWS", (char *)envbuf, 1);
3826 sprintf((char *)envbuf, "%ld", Rows);
3827 setenv("LINES", (char *)envbuf, 1);
3828 sprintf((char *)envbuf, "%ld", Columns);
3829 setenv("COLUMNS", (char *)envbuf, 1);
3830 # else
3832 * Putenv does not copy the string, it has to remain valid.
3833 * Use a static array to avoid loosing allocated memory.
3835 putenv("TERM=dumb");
3836 sprintf(envbuf_Rows, "ROWS=%ld", Rows);
3837 putenv(envbuf_Rows);
3838 sprintf(envbuf_Rows, "LINES=%ld", Rows);
3839 putenv(envbuf_Rows);
3840 sprintf(envbuf_Columns, "COLUMNS=%ld", Columns);
3841 putenv(envbuf_Columns);
3842 # endif
3845 * stderr is only redirected when using the GUI, so that a
3846 * program like gpg can still access the terminal to get a
3847 * passphrase using stderr.
3849 # ifdef FEAT_GUI
3850 if (pty_master_fd >= 0)
3852 close(pty_master_fd); /* close master side of pty */
3854 /* set up stdin/stdout/stderr for the child */
3855 close(0);
3856 dup(pty_slave_fd);
3857 close(1);
3858 dup(pty_slave_fd);
3859 if (gui.in_use)
3861 close(2);
3862 dup(pty_slave_fd);
3865 close(pty_slave_fd); /* has been dupped, close it now */
3867 else
3868 # endif
3870 /* set up stdin for the child */
3871 close(fd_toshell[1]);
3872 close(0);
3873 dup(fd_toshell[0]);
3874 close(fd_toshell[0]);
3876 /* set up stdout for the child */
3877 close(fd_fromshell[0]);
3878 close(1);
3879 dup(fd_fromshell[1]);
3880 close(fd_fromshell[1]);
3882 # ifdef FEAT_GUI
3883 if (gui.in_use)
3885 /* set up stderr for the child */
3886 close(2);
3887 dup(1);
3889 # endif
3894 * There is no type cast for the argv, because the type may be
3895 * different on different machines. This may cause a warning
3896 * message with strict compilers, don't worry about it.
3897 * Call _exit() instead of exit() to avoid closing the connection
3898 * to the X server (esp. with GTK, which uses atexit()).
3900 execvp(argv[0], argv);
3901 _exit(EXEC_FAILED); /* exec failed, return failure code */
3903 else /* parent */
3906 * While child is running, ignore terminating signals.
3907 * Do catch CTRL-C, so that "got_int" is set.
3909 catch_signals(SIG_IGN, SIG_ERR);
3910 catch_int_signal();
3913 * For the GUI we redirect stdin, stdout and stderr to our window.
3914 * This is also used to pipe stdin/stdout to/from the external
3915 * command.
3917 if ((options & (SHELL_READ|SHELL_WRITE))
3918 # ifdef FEAT_GUI
3919 || (gui.in_use && show_shell_mess)
3920 # endif
3923 # define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
3924 char_u buffer[BUFLEN + 1];
3925 # ifdef FEAT_MBYTE
3926 int buffer_off = 0; /* valid bytes in buffer[] */
3927 # endif
3928 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3929 int ta_len = 0; /* valid bytes in ta_buf[] */
3930 int len;
3931 int p_more_save;
3932 int old_State;
3933 int c;
3934 int toshell_fd;
3935 int fromshell_fd;
3936 garray_T ga;
3937 int noread_cnt;
3939 # ifdef FEAT_GUI
3940 if (pty_master_fd >= 0)
3942 close(pty_slave_fd); /* close slave side of pty */
3943 fromshell_fd = pty_master_fd;
3944 toshell_fd = dup(pty_master_fd);
3946 else
3947 # endif
3949 close(fd_toshell[0]);
3950 close(fd_fromshell[1]);
3951 toshell_fd = fd_toshell[1];
3952 fromshell_fd = fd_fromshell[0];
3956 * Write to the child if there are typed characters.
3957 * Read from the child if there are characters available.
3958 * Repeat the reading a few times if more characters are
3959 * available. Need to check for typed keys now and then, but
3960 * not too often (delays when no chars are available).
3961 * This loop is quit if no characters can be read from the pty
3962 * (WaitForChar detected special condition), or there are no
3963 * characters available and the child has exited.
3964 * Only check if the child has exited when there is no more
3965 * output. The child may exit before all the output has
3966 * been printed.
3968 * Currently this busy loops!
3969 * This can probably dead-lock when the write blocks!
3971 p_more_save = p_more;
3972 p_more = FALSE;
3973 old_State = State;
3974 State = EXTERNCMD; /* don't redraw at window resize */
3976 if ((options & SHELL_WRITE) && toshell_fd >= 0)
3978 /* Fork a process that will write the lines to the
3979 * external program. */
3980 if ((wpid = fork()) == -1)
3982 MSG_PUTS(_("\nCannot fork\n"));
3984 else if (wpid == 0)
3986 linenr_T lnum = curbuf->b_op_start.lnum;
3987 int written = 0;
3988 char_u *lp = ml_get(lnum);
3989 char_u *s;
3990 size_t l;
3992 /* child */
3993 close(fromshell_fd);
3994 for (;;)
3996 l = STRLEN(lp + written);
3997 if (l == 0)
3998 len = 0;
3999 else if (lp[written] == NL)
4000 /* NL -> NUL translation */
4001 len = write(toshell_fd, "", (size_t)1);
4002 else
4004 s = vim_strchr(lp + written, NL);
4005 len = write(toshell_fd, (char *)lp + written,
4006 s == NULL ? l : s - (lp + written));
4008 if (len == l)
4010 /* Finished a line, add a NL, unless this line
4011 * should not have one. */
4012 if (lnum != curbuf->b_op_end.lnum
4013 || !curbuf->b_p_bin
4014 || (lnum != write_no_eol_lnum
4015 && (lnum !=
4016 curbuf->b_ml.ml_line_count
4017 || curbuf->b_p_eol)))
4018 write(toshell_fd, "\n", (size_t)1);
4019 ++lnum;
4020 if (lnum > curbuf->b_op_end.lnum)
4022 /* finished all the lines, close pipe */
4023 close(toshell_fd);
4024 toshell_fd = -1;
4025 break;
4027 lp = ml_get(lnum);
4028 written = 0;
4030 else if (len > 0)
4031 written += len;
4033 _exit(0);
4035 else
4037 close(toshell_fd);
4038 toshell_fd = -1;
4042 if (options & SHELL_READ)
4043 ga_init2(&ga, 1, BUFLEN);
4045 noread_cnt = 0;
4047 for (;;)
4050 * Check if keys have been typed, write them to the child
4051 * if there are any.
4052 * Don't do this if we are expanding wild cards (would eat
4053 * typeahead).
4054 * Don't do this when filtering and terminal is in cooked
4055 * mode, the shell command will handle the I/O. Avoids
4056 * that a typed password is echoed for ssh or gpg command.
4057 * Don't get characters when the child has already
4058 * finished (wait_pid == 0).
4059 * Don't get extra characters when we already have one.
4060 * Don't read characters unless we didn't get output for a
4061 * while, avoids that ":r !ls" eats typeahead.
4063 len = 0;
4064 if (!(options & SHELL_EXPAND)
4065 && ((options &
4066 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4067 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4068 #ifdef FEAT_GUI
4069 || gui.in_use
4070 #endif
4072 && wait_pid == 0
4073 && (ta_len > 0
4074 || (noread_cnt > 4
4075 && (len = ui_inchar(ta_buf,
4076 BUFLEN, 10L, 0)) > 0)))
4079 * For pipes:
4080 * Check for CTRL-C: send interrupt signal to child.
4081 * Check for CTRL-D: EOF, close pipe to child.
4083 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
4085 # ifdef SIGINT
4087 * Send SIGINT to the child's group or all
4088 * processes in our group.
4090 if (ta_buf[ta_len] == Ctrl_C
4091 || ta_buf[ta_len] == intr_char)
4093 # ifdef HAVE_SETSID
4094 kill(-pid, SIGINT);
4095 # else
4096 kill(0, SIGINT);
4097 # endif
4098 if (wpid > 0)
4099 kill(wpid, SIGINT);
4101 # endif
4102 if (pty_master_fd < 0 && toshell_fd >= 0
4103 && ta_buf[ta_len] == Ctrl_D)
4105 close(toshell_fd);
4106 toshell_fd = -1;
4110 /* replace K_BS by <BS> and K_DEL by <DEL> */
4111 for (i = ta_len; i < ta_len + len; ++i)
4113 if (ta_buf[i] == CSI && len - i > 2)
4115 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4116 if (c == K_DEL || c == K_KDEL || c == K_BS)
4118 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4119 (size_t)(len - i - 2));
4120 if (c == K_DEL || c == K_KDEL)
4121 ta_buf[i] = DEL;
4122 else
4123 ta_buf[i] = Ctrl_H;
4124 len -= 2;
4127 else if (ta_buf[i] == '\r')
4128 ta_buf[i] = '\n';
4129 # ifdef FEAT_MBYTE
4130 if (has_mbyte)
4131 i += (*mb_ptr2len)(ta_buf + i) - 1;
4132 # endif
4136 * For pipes: echo the typed characters.
4137 * For a pty this does not seem to work.
4139 if (pty_master_fd < 0)
4141 for (i = ta_len; i < ta_len + len; ++i)
4143 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4144 msg_putchar(ta_buf[i]);
4145 # ifdef FEAT_MBYTE
4146 else if (has_mbyte)
4148 int l = (*mb_ptr2len)(ta_buf + i);
4150 msg_outtrans_len(ta_buf + i, l);
4151 i += l - 1;
4153 # endif
4154 else
4155 msg_outtrans_len(ta_buf + i, 1);
4157 windgoto(msg_row, msg_col);
4158 out_flush();
4161 ta_len += len;
4164 * Write the characters to the child, unless EOF has
4165 * been typed for pipes. Write one character at a
4166 * time, to avoid loosing too much typeahead.
4167 * When writing buffer lines, drop the typed
4168 * characters (only check for CTRL-C).
4170 if (options & SHELL_WRITE)
4171 ta_len = 0;
4172 else if (toshell_fd >= 0)
4174 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
4175 if (len > 0)
4177 ta_len -= len;
4178 mch_memmove(ta_buf, ta_buf + len, ta_len);
4179 noread_cnt = 0;
4184 if (got_int)
4186 /* CTRL-C sends a signal to the child, we ignore it
4187 * ourselves */
4188 # ifdef HAVE_SETSID
4189 kill(-pid, SIGINT);
4190 # else
4191 kill(0, SIGINT);
4192 # endif
4193 if (wpid > 0)
4194 kill(wpid, SIGINT);
4195 got_int = FALSE;
4199 * Check if the child has any characters to be printed.
4200 * Read them and write them to our window. Repeat this as
4201 * long as there is something to do, avoid the 10ms wait
4202 * for mch_inchar(), or sending typeahead characters to
4203 * the external process.
4204 * TODO: This should handle escape sequences, compatible
4205 * to some terminal (vt52?).
4207 ++noread_cnt;
4208 while (RealWaitForChar(fromshell_fd, 10L, NULL))
4210 len = read(fromshell_fd, (char *)buffer
4211 # ifdef FEAT_MBYTE
4212 + buffer_off, (size_t)(BUFLEN - buffer_off)
4213 # else
4214 , (size_t)BUFLEN
4215 # endif
4217 if (len <= 0) /* end of file or error */
4218 goto finished;
4220 noread_cnt = 0;
4221 if (options & SHELL_READ)
4223 /* Do NUL -> NL translation, append NL separated
4224 * lines to the current buffer. */
4225 for (i = 0; i < len; ++i)
4227 if (buffer[i] == NL)
4228 append_ga_line(&ga);
4229 else if (buffer[i] == NUL)
4230 ga_append(&ga, NL);
4231 else
4232 ga_append(&ga, buffer[i]);
4235 # ifdef FEAT_MBYTE
4236 else if (has_mbyte)
4238 int l;
4240 len += buffer_off;
4241 buffer[len] = NUL;
4243 /* Check if the last character in buffer[] is
4244 * incomplete, keep these bytes for the next
4245 * round. */
4246 for (p = buffer; p < buffer + len; p += l)
4248 l = mb_cptr2len(p);
4249 if (l == 0)
4250 l = 1; /* NUL byte? */
4251 else if (MB_BYTE2LEN(*p) != l)
4252 break;
4254 if (p == buffer) /* no complete character */
4256 /* avoid getting stuck at an illegal byte */
4257 if (len >= 12)
4258 ++p;
4259 else
4261 buffer_off = len;
4262 continue;
4265 c = *p;
4266 *p = NUL;
4267 msg_puts(buffer);
4268 if (p < buffer + len)
4270 *p = c;
4271 buffer_off = (buffer + len) - p;
4272 mch_memmove(buffer, p, buffer_off);
4273 continue;
4275 buffer_off = 0;
4277 # endif /* FEAT_MBYTE */
4278 else
4280 buffer[len] = NUL;
4281 msg_puts(buffer);
4284 windgoto(msg_row, msg_col);
4285 cursor_on();
4286 out_flush();
4287 if (got_int)
4288 break;
4291 /* If we already detected the child has finished break the
4292 * loop now. */
4293 if (wait_pid == pid)
4294 break;
4297 * Check if the child still exists, before checking for
4298 * typed characters (otherwise we would loose typeahead).
4300 # ifdef __NeXT__
4301 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *) 0);
4302 # else
4303 wait_pid = waitpid(pid, &status, WNOHANG);
4304 # endif
4305 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
4306 || (wait_pid == pid && WIFEXITED(status)))
4308 /* Don't break the loop yet, try reading more
4309 * characters from "fromshell_fd" first. When using
4310 * pipes there might still be something to read and
4311 * then we'll break the loop at the "break" above. */
4312 wait_pid = pid;
4314 else
4315 wait_pid = 0;
4317 finished:
4318 p_more = p_more_save;
4319 if (options & SHELL_READ)
4321 if (ga.ga_len > 0)
4323 append_ga_line(&ga);
4324 /* remember that the NL was missing */
4325 write_no_eol_lnum = curwin->w_cursor.lnum;
4327 else
4328 write_no_eol_lnum = 0;
4329 ga_clear(&ga);
4333 * Give all typeahead that wasn't used back to ui_inchar().
4335 if (ta_len)
4336 ui_inchar_undo(ta_buf, ta_len);
4337 State = old_State;
4338 if (toshell_fd >= 0)
4339 close(toshell_fd);
4340 close(fromshell_fd);
4344 * Wait until our child has exited.
4345 * Ignore wait() returning pids of other children and returning
4346 * because of some signal like SIGWINCH.
4347 * Don't wait if wait_pid was already set above, indicating the
4348 * child already exited.
4350 while (wait_pid != pid)
4352 # ifdef _THREAD_SAFE
4353 /* Ugly hack: when compiled with Python threads are probably
4354 * used, in which case wait() sometimes hangs for no obvious
4355 * reason. Use waitpid() instead and loop (like the GUI). */
4356 # ifdef __NeXT__
4357 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
4358 # else
4359 wait_pid = waitpid(pid, &status, WNOHANG);
4360 # endif
4361 if (wait_pid == 0)
4363 /* Wait for 1/100 sec before trying again. */
4364 mch_delay(10L, TRUE);
4365 continue;
4367 # else
4368 wait_pid = wait(&status);
4369 # endif
4370 if (wait_pid <= 0
4371 # ifdef ECHILD
4372 && errno == ECHILD
4373 # endif
4375 break;
4378 /* Make sure the child that writes to the external program is
4379 * dead. */
4380 if (wpid > 0)
4381 kill(wpid, SIGKILL);
4384 * Set to raw mode right now, otherwise a CTRL-C after
4385 * catch_signals() will kill Vim.
4387 if (tmode == TMODE_RAW)
4388 settmode(TMODE_RAW);
4389 did_settmode = TRUE;
4390 set_signals();
4392 if (WIFEXITED(status))
4394 /* LINTED avoid "bitwise operation on signed value" */
4395 retval = WEXITSTATUS(status);
4396 if (retval && !emsg_silent)
4398 if (retval == EXEC_FAILED)
4400 MSG_PUTS(_("\nCannot execute shell "));
4401 msg_outtrans(p_sh);
4402 msg_putchar('\n');
4404 else if (!(options & SHELL_SILENT))
4406 MSG_PUTS(_("\nshell returned "));
4407 msg_outnum((long)retval);
4408 msg_putchar('\n');
4412 else
4413 MSG_PUTS(_("\nCommand terminated\n"));
4416 vim_free(argv);
4418 error:
4419 if (!did_settmode)
4420 if (tmode == TMODE_RAW)
4421 settmode(TMODE_RAW); /* set to raw mode */
4422 # ifdef FEAT_TITLE
4423 resettitle();
4424 # endif
4425 vim_free(newcmd);
4427 return retval;
4429 #endif /* USE_SYSTEM */
4433 * Check for CTRL-C typed by reading all available characters.
4434 * In cooked mode we should get SIGINT, no need to check.
4436 void
4437 mch_breakcheck()
4439 if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL))
4440 fill_input_buf(FALSE);
4444 * Wait "msec" msec until a character is available from the keyboard or from
4445 * inbuf[]. msec == -1 will block forever.
4446 * When a GUI is being used, this will never get called -- webb
4448 static int
4449 WaitForChar(msec)
4450 long msec;
4452 #ifdef FEAT_MOUSE_GPM
4453 int gpm_process_wanted;
4454 #endif
4455 #ifdef FEAT_XCLIPBOARD
4456 int rest;
4457 #endif
4458 int avail;
4460 if (input_available()) /* something in inbuf[] */
4461 return 1;
4463 #if defined(FEAT_MOUSE_DEC)
4464 /* May need to query the mouse position. */
4465 if (WantQueryMouse)
4467 WantQueryMouse = FALSE;
4468 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
4470 #endif
4473 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4474 * events. This is a bit complicated, because they might both be defined.
4476 #if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4477 # ifdef FEAT_XCLIPBOARD
4478 rest = 0;
4479 if (do_xterm_trace())
4480 rest = msec;
4481 # endif
4484 # ifdef FEAT_XCLIPBOARD
4485 if (rest != 0)
4487 msec = XT_TRACE_DELAY;
4488 if (rest >= 0 && rest < XT_TRACE_DELAY)
4489 msec = rest;
4490 if (rest >= 0)
4491 rest -= msec;
4493 # endif
4494 # ifdef FEAT_MOUSE_GPM
4495 gpm_process_wanted = 0;
4496 avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted);
4497 # else
4498 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4499 # endif
4500 if (!avail)
4502 if (input_available())
4503 return 1;
4504 # ifdef FEAT_XCLIPBOARD
4505 if (rest == 0 || !do_xterm_trace())
4506 # endif
4507 break;
4510 while (FALSE
4511 # ifdef FEAT_MOUSE_GPM
4512 || (gpm_process_wanted && mch_gpm_process() == 0)
4513 # endif
4514 # ifdef FEAT_XCLIPBOARD
4515 || (!avail && rest != 0)
4516 # endif
4519 #else
4520 avail = RealWaitForChar(read_cmd_fd, msec, NULL);
4521 #endif
4522 return avail;
4526 * Wait "msec" msec until a character is available from file descriptor "fd".
4527 * Time == -1 will block forever.
4528 * When a GUI is being used, this will not be used for input -- webb
4529 * Returns also, when a request from Sniff is waiting -- toni.
4530 * Or when a Linux GPM mouse event is waiting.
4532 /* ARGSUSED */
4533 #if defined(__BEOS__)
4535 #else
4536 static int
4537 #endif
4538 RealWaitForChar(fd, msec, check_for_gpm)
4539 int fd;
4540 long msec;
4541 int *check_for_gpm;
4543 int ret;
4544 #if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4545 static int busy = FALSE;
4547 /* May retry getting characters after an event was handled. */
4548 # define MAY_LOOP
4550 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4551 /* Remember at what time we started, so that we know how much longer we
4552 * should wait after being interrupted. */
4553 # define USE_START_TV
4554 struct timeval start_tv;
4556 if (msec > 0 && (
4557 # ifdef FEAT_XCLIPBOARD
4558 xterm_Shell != (Widget)0
4559 # if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4561 # endif
4562 # endif
4563 # ifdef USE_XSMP
4564 xsmp_icefd != -1
4565 # ifdef FEAT_MZSCHEME
4567 # endif
4568 # endif
4569 # ifdef FEAT_MZSCHEME
4570 (mzthreads_allowed() && p_mzq > 0)
4571 # endif
4573 gettimeofday(&start_tv, NULL);
4574 # endif
4576 /* Handle being called recursively. This may happen for the session
4577 * manager stuff, it may save the file, which does a breakcheck. */
4578 if (busy)
4579 return 0;
4580 #endif
4582 #ifdef MAY_LOOP
4583 for (;;)
4584 #endif
4586 #ifdef MAY_LOOP
4587 int finished = TRUE; /* default is to 'loop' just once */
4588 # ifdef FEAT_MZSCHEME
4589 int mzquantum_used = FALSE;
4590 # endif
4591 #endif
4592 #ifndef HAVE_SELECT
4593 struct pollfd fds[5];
4594 int nfd;
4595 # ifdef FEAT_XCLIPBOARD
4596 int xterm_idx = -1;
4597 # endif
4598 # ifdef FEAT_MOUSE_GPM
4599 int gpm_idx = -1;
4600 # endif
4601 # ifdef USE_XSMP
4602 int xsmp_idx = -1;
4603 # endif
4604 int towait = (int)msec;
4606 # ifdef FEAT_MZSCHEME
4607 mzvim_check_threads();
4608 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4610 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
4611 mzquantum_used = TRUE;
4613 # endif
4614 fds[0].fd = fd;
4615 fds[0].events = POLLIN;
4616 nfd = 1;
4618 # ifdef FEAT_SNIFF
4619 # define SNIFF_IDX 1
4620 if (want_sniff_request)
4622 fds[SNIFF_IDX].fd = fd_from_sniff;
4623 fds[SNIFF_IDX].events = POLLIN;
4624 nfd++;
4626 # endif
4627 # ifdef FEAT_XCLIPBOARD
4628 if (xterm_Shell != (Widget)0)
4630 xterm_idx = nfd;
4631 fds[nfd].fd = ConnectionNumber(xterm_dpy);
4632 fds[nfd].events = POLLIN;
4633 nfd++;
4635 # endif
4636 # ifdef FEAT_MOUSE_GPM
4637 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4639 gpm_idx = nfd;
4640 fds[nfd].fd = gpm_fd;
4641 fds[nfd].events = POLLIN;
4642 nfd++;
4644 # endif
4645 # ifdef USE_XSMP
4646 if (xsmp_icefd != -1)
4648 xsmp_idx = nfd;
4649 fds[nfd].fd = xsmp_icefd;
4650 fds[nfd].events = POLLIN;
4651 nfd++;
4653 # endif
4655 ret = poll(fds, nfd, towait);
4656 # ifdef FEAT_MZSCHEME
4657 if (ret == 0 && mzquantum_used)
4658 /* MzThreads scheduling is required and timeout occured */
4659 finished = FALSE;
4660 # endif
4662 # ifdef FEAT_SNIFF
4663 if (ret < 0)
4664 sniff_disconnect(1);
4665 else if (want_sniff_request)
4667 if (fds[SNIFF_IDX].revents & POLLHUP)
4668 sniff_disconnect(1);
4669 if (fds[SNIFF_IDX].revents & POLLIN)
4670 sniff_request_waiting = 1;
4672 # endif
4673 # ifdef FEAT_XCLIPBOARD
4674 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
4676 xterm_update(); /* Maybe we should hand out clipboard */
4677 if (--ret == 0 && !input_available())
4678 /* Try again */
4679 finished = FALSE;
4681 # endif
4682 # ifdef FEAT_MOUSE_GPM
4683 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
4685 *check_for_gpm = 1;
4687 # endif
4688 # ifdef USE_XSMP
4689 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
4691 if (fds[xsmp_idx].revents & POLLIN)
4693 busy = TRUE;
4694 xsmp_handle_requests();
4695 busy = FALSE;
4697 else if (fds[xsmp_idx].revents & POLLHUP)
4699 if (p_verbose > 0)
4700 verb_msg((char_u *)_("XSMP lost ICE connection"));
4701 xsmp_close();
4703 if (--ret == 0)
4704 finished = FALSE; /* Try again */
4706 # endif
4709 #else /* HAVE_SELECT */
4711 struct timeval tv;
4712 struct timeval *tvp;
4713 fd_set rfds, efds;
4714 int maxfd;
4715 long towait = msec;
4717 # ifdef FEAT_MZSCHEME
4718 mzvim_check_threads();
4719 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
4721 towait = p_mzq; /* don't wait longer than 'mzquantum' */
4722 mzquantum_used = TRUE;
4724 # endif
4725 # ifdef __EMX__
4726 /* don't check for incoming chars if not in raw mode, because select()
4727 * always returns TRUE then (in some version of emx.dll) */
4728 if (curr_tmode != TMODE_RAW)
4729 return 0;
4730 # endif
4732 if (towait >= 0)
4734 tv.tv_sec = towait / 1000;
4735 tv.tv_usec = (towait % 1000) * (1000000/1000);
4736 tvp = &tv;
4738 else
4739 tvp = NULL;
4742 * Select on ready for reading and exceptional condition (end of file).
4744 FD_ZERO(&rfds); /* calls bzero() on a sun */
4745 FD_ZERO(&efds);
4746 FD_SET(fd, &rfds);
4747 # if !defined(__QNX__) && !defined(__CYGWIN32__)
4748 /* For QNX select() always returns 1 if this is set. Why? */
4749 FD_SET(fd, &efds);
4750 # endif
4751 maxfd = fd;
4753 # ifdef FEAT_SNIFF
4754 if (want_sniff_request)
4756 FD_SET(fd_from_sniff, &rfds);
4757 FD_SET(fd_from_sniff, &efds);
4758 if (maxfd < fd_from_sniff)
4759 maxfd = fd_from_sniff;
4761 # endif
4762 # ifdef FEAT_XCLIPBOARD
4763 if (xterm_Shell != (Widget)0)
4765 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
4766 if (maxfd < ConnectionNumber(xterm_dpy))
4767 maxfd = ConnectionNumber(xterm_dpy);
4769 # endif
4770 # ifdef FEAT_MOUSE_GPM
4771 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
4773 FD_SET(gpm_fd, &rfds);
4774 FD_SET(gpm_fd, &efds);
4775 if (maxfd < gpm_fd)
4776 maxfd = gpm_fd;
4778 # endif
4779 # ifdef USE_XSMP
4780 if (xsmp_icefd != -1)
4782 FD_SET(xsmp_icefd, &rfds);
4783 FD_SET(xsmp_icefd, &efds);
4784 if (maxfd < xsmp_icefd)
4785 maxfd = xsmp_icefd;
4787 # endif
4789 # ifdef OLD_VMS
4790 /* Old VMS as v6.2 and older have broken select(). It waits more than
4791 * required. Should not be used */
4792 ret = 0;
4793 # else
4794 ret = select(maxfd + 1, &rfds, NULL, &efds, tvp);
4795 # endif
4796 # ifdef __TANDEM
4797 if (ret == -1 && errno == ENOTSUP)
4799 FD_ZERO(&rfds);
4800 FD_ZERO(&efds);
4801 ret = 0;
4803 #endif
4804 # ifdef FEAT_MZSCHEME
4805 if (ret == 0 && mzquantum_used)
4806 /* loop if MzThreads must be scheduled and timeout occured */
4807 finished = FALSE;
4808 # endif
4810 # ifdef FEAT_SNIFF
4811 if (ret < 0 )
4812 sniff_disconnect(1);
4813 else if (ret > 0 && want_sniff_request)
4815 if (FD_ISSET(fd_from_sniff, &efds))
4816 sniff_disconnect(1);
4817 if (FD_ISSET(fd_from_sniff, &rfds))
4818 sniff_request_waiting = 1;
4820 # endif
4821 # ifdef FEAT_XCLIPBOARD
4822 if (ret > 0 && xterm_Shell != (Widget)0
4823 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
4825 xterm_update(); /* Maybe we should hand out clipboard */
4826 /* continue looping when we only got the X event and the input
4827 * buffer is empty */
4828 if (--ret == 0 && !input_available())
4830 /* Try again */
4831 finished = FALSE;
4834 # endif
4835 # ifdef FEAT_MOUSE_GPM
4836 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
4838 if (FD_ISSET(gpm_fd, &efds))
4839 gpm_close();
4840 else if (FD_ISSET(gpm_fd, &rfds))
4841 *check_for_gpm = 1;
4843 # endif
4844 # ifdef USE_XSMP
4845 if (ret > 0 && xsmp_icefd != -1)
4847 if (FD_ISSET(xsmp_icefd, &efds))
4849 if (p_verbose > 0)
4850 verb_msg((char_u *)_("XSMP lost ICE connection"));
4851 xsmp_close();
4852 if (--ret == 0)
4853 finished = FALSE; /* keep going if event was only one */
4855 else if (FD_ISSET(xsmp_icefd, &rfds))
4857 busy = TRUE;
4858 xsmp_handle_requests();
4859 busy = FALSE;
4860 if (--ret == 0)
4861 finished = FALSE; /* keep going if event was only one */
4864 # endif
4866 #endif /* HAVE_SELECT */
4868 #ifdef MAY_LOOP
4869 if (finished || msec == 0)
4870 break;
4872 /* We're going to loop around again, find out for how long */
4873 if (msec > 0)
4875 # ifdef USE_START_TV
4876 struct timeval mtv;
4878 /* Compute remaining wait time. */
4879 gettimeofday(&mtv, NULL);
4880 msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L
4881 + (mtv.tv_usec - start_tv.tv_usec) / 1000L;
4882 # else
4883 /* Guess we got interrupted halfway. */
4884 msec = msec / 2;
4885 # endif
4886 if (msec <= 0)
4887 break; /* waited long enough */
4889 #endif
4892 return (ret > 0);
4895 #ifndef VMS
4897 #ifndef NO_EXPANDPATH
4899 * Expand a path into all matching files and/or directories. Handles "*",
4900 * "?", "[a-z]", "**", etc.
4901 * "path" has backslashes before chars that are not to be expanded.
4902 * Returns the number of matches found.
4905 mch_expandpath(gap, path, flags)
4906 garray_T *gap;
4907 char_u *path;
4908 int flags; /* EW_* flags */
4910 return unix_expandpath(gap, path, 0, flags, FALSE);
4912 #endif
4915 * mch_expand_wildcards() - this code does wild-card pattern matching using
4916 * the shell
4918 * return OK for success, FAIL for error (you may lose some memory) and put
4919 * an error message in *file.
4921 * num_pat is number of input patterns
4922 * pat is array of pointers to input patterns
4923 * num_file is pointer to number of matched file names
4924 * file is pointer to array of pointers to matched file names
4927 #ifndef SEEK_SET
4928 # define SEEK_SET 0
4929 #endif
4930 #ifndef SEEK_END
4931 # define SEEK_END 2
4932 #endif
4934 #define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
4936 /* ARGSUSED */
4938 mch_expand_wildcards(num_pat, pat, num_file, file, flags)
4939 int num_pat;
4940 char_u **pat;
4941 int *num_file;
4942 char_u ***file;
4943 int flags; /* EW_* flags */
4945 int i;
4946 size_t len;
4947 char_u *p;
4948 int dir;
4949 #ifdef __EMX__
4950 # define EXPL_ALLOC_INC 16
4951 char_u **expl_files;
4952 size_t files_alloced, files_free;
4953 char_u *buf;
4954 int has_wildcard;
4956 *num_file = 0; /* default: no files found */
4957 files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */
4958 files_free = EXPL_ALLOC_INC; /* how much space is not used */
4959 *file = (char_u **)alloc(sizeof(char_u **) * files_alloced);
4960 if (*file == NULL)
4961 return FAIL;
4963 for (; num_pat > 0; num_pat--, pat++)
4965 expl_files = NULL;
4966 if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~'))
4967 /* expand environment var or home dir */
4968 buf = expand_env_save(*pat);
4969 else
4970 buf = vim_strsave(*pat);
4971 expl_files = NULL;
4972 has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */
4973 if (has_wildcard) /* yes, so expand them */
4974 expl_files = (char_u **)_fnexplode(buf);
4977 * return value of buf if no wildcards left,
4978 * OR if no match AND EW_NOTFOUND is set.
4980 if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0))
4981 || (expl_files == NULL && (flags & EW_NOTFOUND)))
4982 { /* simply save the current contents of *buf */
4983 expl_files = (char_u **)alloc(sizeof(char_u **) * 2);
4984 if (expl_files != NULL)
4986 expl_files[0] = vim_strsave(buf);
4987 expl_files[1] = NULL;
4990 vim_free(buf);
4993 * Count number of names resulting from expansion,
4994 * At the same time add a backslash to the end of names that happen to
4995 * be directories, and replace slashes with backslashes.
4997 if (expl_files)
4999 for (i = 0; (p = expl_files[i]) != NULL; i++)
5001 dir = mch_isdir(p);
5002 /* If we don't want dirs and this is one, skip it */
5003 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5004 continue;
5006 /* Skip files that are not executable if we check for that. */
5007 if (!dir && (flags & EW_EXEC) && !mch_can_exe(p))
5008 continue;
5010 if (--files_free == 0)
5012 /* need more room in table of pointers */
5013 files_alloced += EXPL_ALLOC_INC;
5014 *file = (char_u **)vim_realloc(*file,
5015 sizeof(char_u **) * files_alloced);
5016 if (*file == NULL)
5018 EMSG(_(e_outofmem));
5019 *num_file = 0;
5020 return FAIL;
5022 files_free = EXPL_ALLOC_INC;
5024 slash_adjust(p);
5025 if (dir)
5027 /* For a directory we add a '/', unless it's already
5028 * there. */
5029 len = STRLEN(p);
5030 if (((*file)[*num_file] = alloc(len + 2)) != NULL)
5032 STRCPY((*file)[*num_file], p);
5033 if (!after_pathsep((*file)[*num_file],
5034 (*file)[*num_file] + len))
5036 (*file)[*num_file][len] = psepc;
5037 (*file)[*num_file][len + 1] = NUL;
5041 else
5043 (*file)[*num_file] = vim_strsave(p);
5047 * Error message already given by either alloc or vim_strsave.
5048 * Should return FAIL, but returning OK works also.
5050 if ((*file)[*num_file] == NULL)
5051 break;
5052 (*num_file)++;
5054 _fnexplodefree((char **)expl_files);
5057 return OK;
5059 #else /* __EMX__ */
5061 int j;
5062 char_u *tempname;
5063 char_u *command;
5064 FILE *fd;
5065 char_u *buffer;
5066 #define STYLE_ECHO 0 /* use "echo" to expand */
5067 #define STYLE_GLOB 1 /* use "glob" to expand, for csh */
5068 #define STYLE_PRINT 2 /* use "print -N" to expand, for zsh */
5069 #define STYLE_BT 3 /* `cmd` expansion, execute the pattern directly */
5070 int shell_style = STYLE_ECHO;
5071 int check_spaces;
5072 static int did_find_nul = FALSE;
5073 int ampersent = FALSE;
5075 *num_file = 0; /* default: no files found */
5076 *file = NULL;
5079 * If there are no wildcards, just copy the names to allocated memory.
5080 * Saves a lot of time, because we don't have to start a new shell.
5082 if (!have_wildcard(num_pat, pat))
5083 return save_patterns(num_pat, pat, num_file, file);
5085 # ifdef HAVE_SANDBOX
5086 /* Don't allow any shell command in the sandbox. */
5087 if (sandbox != 0 && check_secure())
5088 return FAIL;
5089 # endif
5092 * Don't allow the use of backticks in secure and restricted mode.
5094 if (secure || restricted)
5095 for (i = 0; i < num_pat; ++i)
5096 if (vim_strchr(pat[i], '`') != NULL
5097 && (check_restricted() || check_secure()))
5098 return FAIL;
5101 * get a name for the temp file
5103 if ((tempname = vim_tempname('o')) == NULL)
5105 EMSG(_(e_notmp));
5106 return FAIL;
5110 * Let the shell expand the patterns and write the result into the temp
5111 * file. if expanding `cmd` execute it directly.
5112 * If we use csh, glob will work better than echo.
5113 * If we use zsh, print -N will work better than glob.
5115 if (num_pat == 1 && *pat[0] == '`'
5116 && (len = STRLEN(pat[0])) > 2
5117 && *(pat[0] + len - 1) == '`')
5118 shell_style = STYLE_BT;
5119 else if ((len = STRLEN(p_sh)) >= 3)
5121 if (STRCMP(p_sh + len - 3, "csh") == 0)
5122 shell_style = STYLE_GLOB;
5123 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
5124 shell_style = STYLE_PRINT;
5127 /* "unset nonomatch; print -N >" plus two is 29 */
5128 len = STRLEN(tempname) + 29;
5129 for (i = 0; i < num_pat; ++i)
5131 /* Count the length of the patterns in the same way as they are put in
5132 * "command" below. */
5133 #ifdef USE_SYSTEM
5134 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
5135 #else
5136 ++len; /* add space */
5137 for (j = 0; pat[i][j] != NUL; ++j)
5139 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
5140 ++len; /* may add a backslash */
5141 ++len;
5143 #endif
5145 command = alloc(len);
5146 if (command == NULL)
5148 /* out of memory */
5149 vim_free(tempname);
5150 return FAIL;
5154 * Build the shell command:
5155 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5156 * recognizes this).
5157 * - Add the shell command to print the expanded names.
5158 * - Add the temp file name.
5159 * - Add the file name patterns.
5161 if (shell_style == STYLE_BT)
5163 /* change `command; command& ` to (command; command ) */
5164 STRCPY(command, "(");
5165 STRCAT(command, pat[0] + 1); /* exclude first backtick */
5166 p = command + STRLEN(command) - 1;
5167 *p-- = ')'; /* remove last backtick */
5168 while (p > command && vim_iswhite(*p))
5169 --p;
5170 if (*p == '&') /* remove trailing '&' */
5172 ampersent = TRUE;
5173 *p = ' ';
5175 STRCAT(command, ">");
5177 else
5179 if (flags & EW_NOTFOUND)
5180 STRCPY(command, "set nonomatch; ");
5181 else
5182 STRCPY(command, "unset nonomatch; ");
5183 if (shell_style == STYLE_GLOB)
5184 STRCAT(command, "glob >");
5185 else if (shell_style == STYLE_PRINT)
5186 STRCAT(command, "print -N >");
5187 else
5188 STRCAT(command, "echo >");
5190 STRCAT(command, tempname);
5191 if (shell_style != STYLE_BT)
5192 for (i = 0; i < num_pat; ++i)
5194 /* When using system() always add extra quotes, because the shell
5195 * is started twice. Otherwise put a backslash before special
5196 * characters, except insice ``. */
5197 #ifdef USE_SYSTEM
5198 STRCAT(command, " \"");
5199 STRCAT(command, pat[i]);
5200 STRCAT(command, "\"");
5201 #else
5202 int intick = FALSE;
5204 p = command + STRLEN(command);
5205 *p++ = ' ';
5206 for (j = 0; pat[i][j] != NUL; ++j)
5208 if (pat[i][j] == '`')
5209 intick = !intick;
5210 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
5212 /* Remove a backslash, take char literally. But keep
5213 * backslash inside backticks, before a special character
5214 * and before a backtick. */
5215 if (intick
5216 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
5217 || pat[i][j + 1] == '`')
5218 *p++ = '\\';
5219 ++j;
5221 else if (!intick && vim_strchr(SHELL_SPECIAL,
5222 pat[i][j]) != NULL)
5223 /* Put a backslash before a special character, but not
5224 * when inside ``. */
5225 *p++ = '\\';
5227 /* Copy one character. */
5228 *p++ = pat[i][j];
5230 *p = NUL;
5231 #endif
5233 if (flags & EW_SILENT)
5234 show_shell_mess = FALSE;
5235 if (ampersent)
5236 STRCAT(command, "&"); /* put the '&' back after the
5237 redirection */
5240 * Using zsh -G: If a pattern has no matches, it is just deleted from
5241 * the argument list, otherwise zsh gives an error message and doesn't
5242 * expand any other pattern.
5244 if (shell_style == STYLE_PRINT)
5245 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
5248 * If we use -f then shell variables set in .cshrc won't get expanded.
5249 * vi can do it, so we will too, but it is only necessary if there is a "$"
5250 * in one of the patterns, otherwise we can still use the fast option.
5252 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
5253 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
5256 * execute the shell command
5258 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
5260 /* When running in the background, give it some time to create the temp
5261 * file, but don't wait for it to finish. */
5262 if (ampersent)
5263 mch_delay(10L, TRUE);
5265 extra_shell_arg = NULL; /* cleanup */
5266 show_shell_mess = TRUE;
5267 vim_free(command);
5269 if (i) /* mch_call_shell() failed */
5271 mch_remove(tempname);
5272 vim_free(tempname);
5274 * With interactive completion, the error message is not printed.
5275 * However with USE_SYSTEM, I don't know how to turn off error messages
5276 * from the shell, so screen may still get messed up -- webb.
5278 #ifndef USE_SYSTEM
5279 if (!(flags & EW_SILENT))
5280 #endif
5282 redraw_later_clear(); /* probably messed up screen */
5283 msg_putchar('\n'); /* clear bottom line quickly */
5284 cmdline_row = Rows - 1; /* continue on last line */
5285 #ifdef USE_SYSTEM
5286 if (!(flags & EW_SILENT))
5287 #endif
5289 MSG(_(e_wildexpand));
5290 msg_start(); /* don't overwrite this message */
5293 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5294 * EW_NOTFOUND is given */
5295 if (shell_style == STYLE_BT)
5296 return FAIL;
5297 goto notfound;
5301 * read the names from the file into memory
5303 fd = fopen((char *)tempname, READBIN);
5304 if (fd == NULL)
5306 /* Something went wrong, perhaps a file name with a special char. */
5307 if (!(flags & EW_SILENT))
5309 MSG(_(e_wildexpand));
5310 msg_start(); /* don't overwrite this message */
5312 vim_free(tempname);
5313 goto notfound;
5315 fseek(fd, 0L, SEEK_END);
5316 len = ftell(fd); /* get size of temp file */
5317 fseek(fd, 0L, SEEK_SET);
5318 buffer = alloc(len + 1);
5319 if (buffer == NULL)
5321 /* out of memory */
5322 mch_remove(tempname);
5323 vim_free(tempname);
5324 fclose(fd);
5325 return FAIL;
5327 i = fread((char *)buffer, 1, len, fd);
5328 fclose(fd);
5329 mch_remove(tempname);
5330 if (i != len)
5332 /* unexpected read error */
5333 EMSG2(_(e_notread), tempname);
5334 vim_free(tempname);
5335 vim_free(buffer);
5336 return FAIL;
5338 vim_free(tempname);
5340 #if defined(__CYGWIN__) || defined(__CYGWIN32__)
5341 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5342 p = buffer;
5343 for (i = 0; i < len; ++i)
5344 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
5345 *p++ = buffer[i];
5346 len = p - buffer;
5347 # endif
5350 /* file names are separated with Space */
5351 if (shell_style == STYLE_ECHO)
5353 buffer[len] = '\n'; /* make sure the buffer ends in NL */
5354 p = buffer;
5355 for (i = 0; *p != '\n'; ++i) /* count number of entries */
5357 while (*p != ' ' && *p != '\n')
5358 ++p;
5359 p = skipwhite(p); /* skip to next entry */
5362 /* file names are separated with NL */
5363 else if (shell_style == STYLE_BT)
5365 buffer[len] = NUL; /* make sure the buffer ends in NUL */
5366 p = buffer;
5367 for (i = 0; *p != NUL; ++i) /* count number of entries */
5369 while (*p != '\n' && *p != NUL)
5370 ++p;
5371 if (*p != NUL)
5372 ++p;
5373 p = skipwhite(p); /* skip leading white space */
5376 /* file names are separated with NUL */
5377 else
5380 * Some versions of zsh use spaces instead of NULs to separate
5381 * results. Only do this when there is no NUL before the end of the
5382 * buffer, otherwise we would never be able to use file names with
5383 * embedded spaces when zsh does use NULs.
5384 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5385 * don't check for spaces again.
5387 check_spaces = FALSE;
5388 if (shell_style == STYLE_PRINT && !did_find_nul)
5390 /* If there is a NUL, set did_find_nul, else set check_spaces */
5391 if (len && (int)STRLEN(buffer) < len - 1)
5392 did_find_nul = TRUE;
5393 else
5394 check_spaces = TRUE;
5398 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5399 * already is one, for STYLE_GLOB it needs to be added.
5401 if (len && buffer[len - 1] == NUL)
5402 --len;
5403 else
5404 buffer[len] = NUL;
5405 i = 0;
5406 for (p = buffer; p < buffer + len; ++p)
5407 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
5409 ++i;
5410 *p = NUL;
5412 if (len)
5413 ++i; /* count last entry */
5415 if (i == 0)
5418 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5419 * /bin/sh will happily expand it to nothing rather than returning an
5420 * error; and hey, it's good to check anyway -- webb.
5422 vim_free(buffer);
5423 goto notfound;
5425 *num_file = i;
5426 *file = (char_u **)alloc(sizeof(char_u *) * i);
5427 if (*file == NULL)
5429 /* out of memory */
5430 vim_free(buffer);
5431 return FAIL;
5435 * Isolate the individual file names.
5437 p = buffer;
5438 for (i = 0; i < *num_file; ++i)
5440 (*file)[i] = p;
5441 /* Space or NL separates */
5442 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT)
5444 while (!(shell_style == STYLE_ECHO && *p == ' ')
5445 && *p != '\n' && *p != NUL)
5446 ++p;
5447 if (p == buffer + len) /* last entry */
5448 *p = NUL;
5449 else
5451 *p++ = NUL;
5452 p = skipwhite(p); /* skip to next entry */
5455 else /* NUL separates */
5457 while (*p && p < buffer + len) /* skip entry */
5458 ++p;
5459 ++p; /* skip NUL */
5464 * Move the file names to allocated memory.
5466 for (j = 0, i = 0; i < *num_file; ++i)
5468 /* Require the files to exist. Helps when using /bin/sh */
5469 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
5470 continue;
5472 /* check if this entry should be included */
5473 dir = (mch_isdir((*file)[i]));
5474 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
5475 continue;
5477 /* Skip files that are not executable if we check for that. */
5478 if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i]))
5479 continue;
5481 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
5482 if (p)
5484 STRCPY(p, (*file)[i]);
5485 if (dir)
5486 STRCAT(p, "/"); /* add '/' to a directory name */
5487 (*file)[j++] = p;
5490 vim_free(buffer);
5491 *num_file = j;
5493 if (*num_file == 0) /* rejected all entries */
5495 vim_free(*file);
5496 *file = NULL;
5497 goto notfound;
5500 return OK;
5502 notfound:
5503 if (flags & EW_NOTFOUND)
5504 return save_patterns(num_pat, pat, num_file, file);
5505 return FAIL;
5507 #endif /* __EMX__ */
5510 #endif /* VMS */
5512 #ifndef __EMX__
5513 static int
5514 save_patterns(num_pat, pat, num_file, file)
5515 int num_pat;
5516 char_u **pat;
5517 int *num_file;
5518 char_u ***file;
5520 int i;
5521 char_u *s;
5523 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
5524 if (*file == NULL)
5525 return FAIL;
5526 for (i = 0; i < num_pat; i++)
5528 s = vim_strsave(pat[i]);
5529 if (s != NULL)
5530 /* Be compatible with expand_filename(): halve the number of
5531 * backslashes. */
5532 backslash_halve(s);
5533 (*file)[i] = s;
5535 *num_file = num_pat;
5536 return OK;
5538 #endif
5542 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5543 * expand.
5546 mch_has_exp_wildcard(p)
5547 char_u *p;
5549 for ( ; *p; mb_ptr_adv(p))
5551 #ifndef OS2
5552 if (*p == '\\' && p[1] != NUL)
5553 ++p;
5554 else
5555 #endif
5556 if (vim_strchr((char_u *)
5557 #ifdef VMS
5558 "*?%"
5559 #else
5560 # ifdef OS2
5561 "*?"
5562 # else
5563 "*?[{'"
5564 # endif
5565 #endif
5566 , *p) != NULL)
5567 return TRUE;
5569 return FALSE;
5573 * Return TRUE if the string "p" contains a wildcard.
5574 * Don't recognize '~' at the end as a wildcard.
5577 mch_has_wildcard(p)
5578 char_u *p;
5580 for ( ; *p; mb_ptr_adv(p))
5582 #ifndef OS2
5583 if (*p == '\\' && p[1] != NUL)
5584 ++p;
5585 else
5586 #endif
5587 if (vim_strchr((char_u *)
5588 #ifdef VMS
5589 "*?%$"
5590 #else
5591 # ifdef OS2
5592 # ifdef VIM_BACKTICK
5593 "*?$`"
5594 # else
5595 "*?$"
5596 # endif
5597 # else
5598 "*?[{`'$"
5599 # endif
5600 #endif
5601 , *p) != NULL
5602 || (*p == '~' && p[1] != NUL))
5603 return TRUE;
5605 return FALSE;
5608 #ifndef __EMX__
5609 static int
5610 have_wildcard(num, file)
5611 int num;
5612 char_u **file;
5614 int i;
5616 for (i = 0; i < num; i++)
5617 if (mch_has_wildcard(file[i]))
5618 return 1;
5619 return 0;
5622 static int
5623 have_dollars(num, file)
5624 int num;
5625 char_u **file;
5627 int i;
5629 for (i = 0; i < num; i++)
5630 if (vim_strchr(file[i], '$') != NULL)
5631 return TRUE;
5632 return FALSE;
5634 #endif /* ifndef __EMX__ */
5636 #ifndef HAVE_RENAME
5638 * Scaled-down version of rename(), which is missing in Xenix.
5639 * This version can only move regular files and will fail if the
5640 * destination exists.
5643 mch_rename(src, dest)
5644 const char *src, *dest;
5646 struct stat st;
5648 if (stat(dest, &st) >= 0) /* fail if destination exists */
5649 return -1;
5650 if (link(src, dest) != 0) /* link file to new name */
5651 return -1;
5652 if (mch_remove(src) == 0) /* delete link to old name */
5653 return 0;
5654 return -1;
5656 #endif /* !HAVE_RENAME */
5658 #ifdef FEAT_MOUSE_GPM
5660 * Initializes connection with gpm (if it isn't already opened)
5661 * Return 1 if succeeded (or connection already opened), 0 if failed
5663 static int
5664 gpm_open()
5666 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
5668 if (!gpm_flag)
5670 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
5671 gpm_connect.defaultMask = ~GPM_HARD;
5672 /* Default handling for mouse move*/
5673 gpm_connect.minMod = 0; /* Handle any modifier keys */
5674 gpm_connect.maxMod = 0xffff;
5675 if (Gpm_Open(&gpm_connect, 0) > 0)
5677 /* gpm library tries to handling TSTP causes
5678 * problems. Anyways, we close connection to Gpm whenever
5679 * we are going to suspend or starting an external process
5680 * so we should'nt have problem with this
5682 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
5683 return 1; /* succeed */
5685 if (gpm_fd == -2)
5686 Gpm_Close(); /* We don't want to talk to xterm via gpm */
5687 return 0;
5689 return 1; /* already open */
5693 * Closes connection to gpm
5694 * returns non-zero if connection successfully closed
5696 static void
5697 gpm_close()
5699 if (gpm_flag && gpm_fd >= 0) /* if Open */
5700 Gpm_Close();
5703 /* Reads gpm event and adds special keys to input buf. Returns length of
5704 * generated key sequence.
5705 * This function is made after gui_send_mouse_event
5707 static int
5708 mch_gpm_process()
5710 int button;
5711 static Gpm_Event gpm_event;
5712 char_u string[6];
5713 int_u vim_modifiers;
5714 int row,col;
5715 unsigned char buttons_mask;
5716 unsigned char gpm_modifiers;
5717 static unsigned char old_buttons = 0;
5719 Gpm_GetEvent(&gpm_event);
5721 #ifdef FEAT_GUI
5722 /* Don't put events in the input queue now. */
5723 if (hold_gui_events)
5724 return 0;
5725 #endif
5727 row = gpm_event.y - 1;
5728 col = gpm_event.x - 1;
5730 string[0] = ESC; /* Our termcode */
5731 string[1] = 'M';
5732 string[2] = 'G';
5733 switch (GPM_BARE_EVENTS(gpm_event.type))
5735 case GPM_DRAG:
5736 string[3] = MOUSE_DRAG;
5737 break;
5738 case GPM_DOWN:
5739 buttons_mask = gpm_event.buttons & ~old_buttons;
5740 old_buttons = gpm_event.buttons;
5741 switch (buttons_mask)
5743 case GPM_B_LEFT:
5744 button = MOUSE_LEFT;
5745 break;
5746 case GPM_B_MIDDLE:
5747 button = MOUSE_MIDDLE;
5748 break;
5749 case GPM_B_RIGHT:
5750 button = MOUSE_RIGHT;
5751 break;
5752 default:
5753 return 0;
5754 /*Don't know what to do. Can more than one button be
5755 * reported in one event? */
5757 string[3] = (char_u)(button | 0x20);
5758 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
5759 break;
5760 case GPM_UP:
5761 string[3] = MOUSE_RELEASE;
5762 old_buttons &= ~gpm_event.buttons;
5763 break;
5764 default:
5765 return 0;
5767 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
5768 gpm_modifiers = gpm_event.modifiers;
5769 vim_modifiers = 0x0;
5770 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
5771 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
5772 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
5774 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
5775 vim_modifiers |= MOUSE_SHIFT;
5777 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
5778 vim_modifiers |= MOUSE_CTRL;
5779 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
5780 vim_modifiers |= MOUSE_ALT;
5781 string[3] |= vim_modifiers;
5782 string[4] = (char_u)(col + ' ' + 1);
5783 string[5] = (char_u)(row + ' ' + 1);
5784 add_to_input_buf(string, 6);
5785 return 6;
5787 #endif /* FEAT_MOUSE_GPM */
5789 #if defined(FEAT_LIBCALL) || defined(PROTO)
5790 typedef char_u * (*STRPROCSTR)__ARGS((char_u *));
5791 typedef char_u * (*INTPROCSTR)__ARGS((int));
5792 typedef int (*STRPROCINT)__ARGS((char_u *));
5793 typedef int (*INTPROCINT)__ARGS((int));
5796 * Call a DLL routine which takes either a string or int param
5797 * and returns an allocated string.
5800 mch_libcall(libname, funcname, argstring, argint, string_result, number_result)
5801 char_u *libname;
5802 char_u *funcname;
5803 char_u *argstring; /* NULL when using a argint */
5804 int argint;
5805 char_u **string_result;/* NULL when using number_result */
5806 int *number_result;
5808 # if defined(USE_DLOPEN)
5809 void *hinstLib;
5810 char *dlerr = NULL;
5811 # else
5812 shl_t hinstLib;
5813 # endif
5814 STRPROCSTR ProcAdd;
5815 INTPROCSTR ProcAddI;
5816 char_u *retval_str = NULL;
5817 int retval_int = 0;
5818 int success = FALSE;
5821 * Get a handle to the DLL module.
5823 # if defined(USE_DLOPEN)
5824 /* First clear any error, it's not cleared by the dlopen() call. */
5825 (void)dlerror();
5827 hinstLib = dlopen((char *)libname, RTLD_LAZY
5828 # ifdef RTLD_LOCAL
5829 | RTLD_LOCAL
5830 # endif
5832 if (hinstLib == NULL)
5834 /* "dlerr" must be used before dlclose() */
5835 dlerr = (char *)dlerror();
5836 if (dlerr != NULL)
5837 EMSG2(_("dlerror = \"%s\""), dlerr);
5839 # else
5840 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
5841 # endif
5843 /* If the handle is valid, try to get the function address. */
5844 if (hinstLib != NULL)
5846 # ifdef HAVE_SETJMP_H
5848 * Catch a crash when calling the library function. For example when
5849 * using a number where a string pointer is expected.
5851 mch_startjmp();
5852 if (SETJMP(lc_jump_env) != 0)
5854 success = FALSE;
5855 # if defined(USE_DLOPEN)
5856 dlerr = NULL;
5857 # endif
5858 mch_didjmp();
5860 else
5861 # endif
5863 retval_str = NULL;
5864 retval_int = 0;
5866 if (argstring != NULL)
5868 # if defined(USE_DLOPEN)
5869 ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname);
5870 dlerr = (char *)dlerror();
5871 # else
5872 if (shl_findsym(&hinstLib, (const char *)funcname,
5873 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
5874 ProcAdd = NULL;
5875 # endif
5876 if ((success = (ProcAdd != NULL
5877 # if defined(USE_DLOPEN)
5878 && dlerr == NULL
5879 # endif
5882 if (string_result == NULL)
5883 retval_int = ((STRPROCINT)ProcAdd)(argstring);
5884 else
5885 retval_str = (ProcAdd)(argstring);
5888 else
5890 # if defined(USE_DLOPEN)
5891 ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname);
5892 dlerr = (char *)dlerror();
5893 # else
5894 if (shl_findsym(&hinstLib, (const char *)funcname,
5895 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
5896 ProcAddI = NULL;
5897 # endif
5898 if ((success = (ProcAddI != NULL
5899 # if defined(USE_DLOPEN)
5900 && dlerr == NULL
5901 # endif
5904 if (string_result == NULL)
5905 retval_int = ((INTPROCINT)ProcAddI)(argint);
5906 else
5907 retval_str = (ProcAddI)(argint);
5911 /* Save the string before we free the library. */
5912 /* Assume that a "1" or "-1" result is an illegal pointer. */
5913 if (string_result == NULL)
5914 *number_result = retval_int;
5915 else if (retval_str != NULL
5916 && retval_str != (char_u *)1
5917 && retval_str != (char_u *)-1)
5918 *string_result = vim_strsave(retval_str);
5921 # ifdef HAVE_SETJMP_H
5922 mch_endjmp();
5923 # ifdef SIGHASARG
5924 if (lc_signal != 0)
5926 int i;
5928 /* try to find the name of this signal */
5929 for (i = 0; signal_info[i].sig != -1; i++)
5930 if (lc_signal == signal_info[i].sig)
5931 break;
5932 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
5934 # endif
5935 # endif
5937 # if defined(USE_DLOPEN)
5938 /* "dlerr" must be used before dlclose() */
5939 if (dlerr != NULL)
5940 EMSG2(_("dlerror = \"%s\""), dlerr);
5942 /* Free the DLL module. */
5943 (void)dlclose(hinstLib);
5944 # else
5945 (void)shl_unload(hinstLib);
5946 # endif
5949 if (!success)
5951 EMSG2(_(e_libcall), funcname);
5952 return FAIL;
5955 return OK;
5957 #endif
5959 #if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
5960 static int xterm_trace = -1; /* default: disabled */
5961 static int xterm_button;
5964 * Setup a dummy window for X selections in a terminal.
5966 void
5967 setup_term_clip()
5969 int z = 0;
5970 char *strp = "";
5971 Widget AppShell;
5973 if (!x_connect_to_server())
5974 return;
5976 open_app_context();
5977 if (app_context != NULL && xterm_Shell == (Widget)0)
5979 int (*oldhandler)();
5980 #if defined(HAVE_SETJMP_H)
5981 int (*oldIOhandler)();
5982 #endif
5983 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5984 struct timeval start_tv;
5986 if (p_verbose > 0)
5987 gettimeofday(&start_tv, NULL);
5988 # endif
5990 /* Ignore X errors while opening the display */
5991 oldhandler = XSetErrorHandler(x_error_check);
5993 #if defined(HAVE_SETJMP_H)
5994 /* Ignore X IO errors while opening the display */
5995 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
5996 mch_startjmp();
5997 if (SETJMP(lc_jump_env) != 0)
5999 mch_didjmp();
6000 xterm_dpy = NULL;
6002 else
6003 #endif
6005 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
6006 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
6007 #if defined(HAVE_SETJMP_H)
6008 mch_endjmp();
6009 #endif
6012 #if defined(HAVE_SETJMP_H)
6013 /* Now handle X IO errors normally. */
6014 (void)XSetIOErrorHandler(oldIOhandler);
6015 #endif
6016 /* Now handle X errors normally. */
6017 (void)XSetErrorHandler(oldhandler);
6019 if (xterm_dpy == NULL)
6021 if (p_verbose > 0)
6022 verb_msg((char_u *)_("Opening the X display failed"));
6023 return;
6026 /* Catch terminating error of the X server connection. */
6027 (void)XSetIOErrorHandler(x_IOerror_handler);
6029 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6030 if (p_verbose > 0)
6032 verbose_enter();
6033 xopen_message(&start_tv);
6034 verbose_leave();
6036 # endif
6038 /* Create a Shell to make converters work. */
6039 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6040 applicationShellWidgetClass, xterm_dpy,
6041 NULL);
6042 if (AppShell == (Widget)0)
6043 return;
6044 xterm_Shell = XtVaCreatePopupShell("VIM",
6045 topLevelShellWidgetClass, AppShell,
6046 XtNmappedWhenManaged, 0,
6047 XtNwidth, 1,
6048 XtNheight, 1,
6049 NULL);
6050 if (xterm_Shell == (Widget)0)
6051 return;
6053 x11_setup_atoms(xterm_dpy);
6054 if (x11_display == NULL)
6055 x11_display = xterm_dpy;
6057 XtRealizeWidget(xterm_Shell);
6058 XSync(xterm_dpy, False);
6059 xterm_update();
6061 if (xterm_Shell != (Widget)0)
6063 clip_init(TRUE);
6064 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
6065 x11_window = (Window)atol(strp);
6066 /* Check if $WINDOWID is valid. */
6067 if (test_x11_window(xterm_dpy) == FAIL)
6068 x11_window = 0;
6069 if (x11_window != 0)
6070 xterm_trace = 0;
6074 void
6075 start_xterm_trace(button)
6076 int button;
6078 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
6079 return;
6080 xterm_trace = 1;
6081 xterm_button = button;
6082 do_xterm_trace();
6086 void
6087 stop_xterm_trace()
6089 if (xterm_trace < 0)
6090 return;
6091 xterm_trace = 0;
6095 * Query the xterm pointer and generate mouse termcodes if necessary
6096 * return TRUE if dragging is active, else FALSE
6098 static int
6099 do_xterm_trace()
6101 Window root, child;
6102 int root_x, root_y;
6103 int win_x, win_y;
6104 int row, col;
6105 int_u mask_return;
6106 char_u buf[50];
6107 char_u *strp;
6108 long got_hints;
6109 static char_u *mouse_code;
6110 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
6111 static int prev_row = 0, prev_col = 0;
6112 static XSizeHints xterm_hints;
6114 if (xterm_trace <= 0)
6115 return FALSE;
6117 if (xterm_trace == 1)
6119 /* Get the hints just before tracking starts. The font size might
6120 * have changed recently */
6121 XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints);
6122 if (!(got_hints & PResizeInc)
6123 || xterm_hints.width_inc <= 1
6124 || xterm_hints.height_inc <= 1)
6126 xterm_trace = -1; /* Not enough data -- disable tracing */
6127 return FALSE;
6130 /* Rely on the same mouse code for the duration of this */
6131 mouse_code = find_termcode(mouse_name);
6132 prev_row = mouse_row;
6133 prev_row = mouse_col;
6134 xterm_trace = 2;
6136 /* Find the offset of the chars, there might be a scrollbar on the
6137 * left of the window and/or a menu on the top (eterm etc.) */
6138 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6139 &win_x, &win_y, &mask_return);
6140 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
6141 - (xterm_hints.height_inc / 2);
6142 if (xterm_hints.y <= xterm_hints.height_inc / 2)
6143 xterm_hints.y = 2;
6144 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
6145 - (xterm_hints.width_inc / 2);
6146 if (xterm_hints.x <= xterm_hints.width_inc / 2)
6147 xterm_hints.x = 2;
6148 return TRUE;
6150 if (mouse_code == NULL)
6152 xterm_trace = 0;
6153 return FALSE;
6156 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
6157 &win_x, &win_y, &mask_return);
6159 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
6160 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
6161 if (row == prev_row && col == prev_col)
6162 return TRUE;
6164 STRCPY(buf, mouse_code);
6165 strp = buf + STRLEN(buf);
6166 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
6167 *strp++ = (char_u)(col + ' ' + 1);
6168 *strp++ = (char_u)(row + ' ' + 1);
6169 *strp = 0;
6170 add_to_input_buf(buf, STRLEN(buf));
6172 prev_row = row;
6173 prev_col = col;
6174 return TRUE;
6177 # if defined(FEAT_GUI) || defined(PROTO)
6179 * Destroy the display, window and app_context. Required for GTK.
6181 void
6182 clear_xterm_clip()
6184 if (xterm_Shell != (Widget)0)
6186 XtDestroyWidget(xterm_Shell);
6187 xterm_Shell = (Widget)0;
6189 if (xterm_dpy != NULL)
6191 #if 0
6192 /* Lesstif and Solaris crash here, lose some memory */
6193 XtCloseDisplay(xterm_dpy);
6194 #endif
6195 if (x11_display == xterm_dpy)
6196 x11_display = NULL;
6197 xterm_dpy = NULL;
6199 #if 0
6200 if (app_context != (XtAppContext)NULL)
6202 /* Lesstif and Solaris crash here, lose some memory */
6203 XtDestroyApplicationContext(app_context);
6204 app_context = (XtAppContext)NULL;
6206 #endif
6208 # endif
6211 * Catch up with any queued X events. This may put keyboard input into the
6212 * input buffer, call resize call-backs, trigger timers etc. If there is
6213 * nothing in the X event queue (& no timers pending), then we return
6214 * immediately.
6216 static void
6217 xterm_update()
6219 XEvent event;
6221 while (XtAppPending(app_context) && !vim_is_input_buf_full())
6223 XtAppNextEvent(app_context, &event);
6224 #ifdef FEAT_CLIENTSERVER
6226 XPropertyEvent *e = (XPropertyEvent *)&event;
6228 if (e->type == PropertyNotify && e->window == commWindow
6229 && e->atom == commProperty && e->state == PropertyNewValue)
6230 serverEventProc(xterm_dpy, &event);
6232 #endif
6233 XtDispatchEvent(&event);
6238 clip_xterm_own_selection(cbd)
6239 VimClipboard *cbd;
6241 if (xterm_Shell != (Widget)0)
6242 return clip_x11_own_selection(xterm_Shell, cbd);
6243 return FAIL;
6246 void
6247 clip_xterm_lose_selection(cbd)
6248 VimClipboard *cbd;
6250 if (xterm_Shell != (Widget)0)
6251 clip_x11_lose_selection(xterm_Shell, cbd);
6254 void
6255 clip_xterm_request_selection(cbd)
6256 VimClipboard *cbd;
6258 if (xterm_Shell != (Widget)0)
6259 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
6262 void
6263 clip_xterm_set_selection(cbd)
6264 VimClipboard *cbd;
6266 clip_x11_set_selection(cbd);
6268 #endif
6271 #if defined(USE_XSMP) || defined(PROTO)
6273 * Code for X Session Management Protocol.
6275 static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast));
6276 static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data));
6277 static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data));
6278 static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data));
6279 static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData));
6282 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6283 static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data));
6286 * This is our chance to ask the user if they want to save,
6287 * or abort the logout
6289 /*ARGSUSED*/
6290 static void
6291 xsmp_handle_interaction(smc_conn, client_data)
6292 SmcConn smc_conn;
6293 SmPointer client_data;
6295 cmdmod_T save_cmdmod;
6296 int cancel_shutdown = False;
6298 save_cmdmod = cmdmod;
6299 cmdmod.confirm = TRUE;
6300 if (check_changed_any(FALSE))
6301 /* Mustn't logout */
6302 cancel_shutdown = True;
6303 cmdmod = save_cmdmod;
6304 setcursor(); /* position cursor */
6305 out_flush();
6307 /* Done interaction */
6308 SmcInteractDone(smc_conn, cancel_shutdown);
6310 /* Finish off
6311 * Only end save-yourself here if we're not cancelling shutdown;
6312 * we'll get a cancelled callback later in which we'll end it.
6313 * Hopefully get around glitchy SMs (like GNOME-1)
6315 if (!cancel_shutdown)
6317 xsmp.save_yourself = False;
6318 SmcSaveYourselfDone(smc_conn, True);
6321 # endif
6324 * Callback that starts save-yourself.
6326 /*ARGSUSED*/
6327 static void
6328 xsmp_handle_save_yourself(smc_conn, client_data, save_type,
6329 shutdown, interact_style, fast)
6330 SmcConn smc_conn;
6331 SmPointer client_data;
6332 int save_type;
6333 Bool shutdown;
6334 int interact_style;
6335 Bool fast;
6337 /* Handle already being in saveyourself */
6338 if (xsmp.save_yourself)
6339 SmcSaveYourselfDone(smc_conn, True);
6340 xsmp.save_yourself = True;
6341 xsmp.shutdown = shutdown;
6343 /* First up, preserve all files */
6344 out_flush();
6345 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
6347 if (p_verbose > 0)
6348 verb_msg((char_u *)_("XSMP handling save-yourself request"));
6350 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6351 /* Now see if we can ask about unsaved files */
6352 if (shutdown && !fast && gui.in_use)
6353 /* Need to interact with user, but need SM's permission */
6354 SmcInteractRequest(smc_conn, SmDialogError,
6355 xsmp_handle_interaction, client_data);
6356 else
6357 # endif
6359 /* Can stop the cycle here */
6360 SmcSaveYourselfDone(smc_conn, True);
6361 xsmp.save_yourself = False;
6367 * Callback to warn us of imminent death.
6369 /*ARGSUSED*/
6370 static void
6371 xsmp_die(smc_conn, client_data)
6372 SmcConn smc_conn;
6373 SmPointer client_data;
6375 xsmp_close();
6377 /* quit quickly leaving swapfiles for modified buffers behind */
6378 getout_preserve_modified(0);
6383 * Callback to tell us that save-yourself has completed.
6385 /*ARGSUSED*/
6386 static void
6387 xsmp_save_complete(smc_conn, client_data)
6388 SmcConn smc_conn;
6389 SmPointer client_data;
6391 xsmp.save_yourself = False;
6396 * Callback to tell us that an instigated shutdown was cancelled
6397 * (maybe even by us)
6399 /*ARGSUSED*/
6400 static void
6401 xsmp_shutdown_cancelled(smc_conn, client_data)
6402 SmcConn smc_conn;
6403 SmPointer client_data;
6405 if (xsmp.save_yourself)
6406 SmcSaveYourselfDone(smc_conn, True);
6407 xsmp.save_yourself = False;
6408 xsmp.shutdown = False;
6413 * Callback to tell us that a new ICE connection has been established.
6415 /*ARGSUSED*/
6416 static void
6417 xsmp_ice_connection(iceConn, clientData, opening, watchData)
6418 IceConn iceConn;
6419 IcePointer clientData;
6420 Bool opening;
6421 IcePointer *watchData;
6423 /* Intercept creation of ICE connection fd */
6424 if (opening)
6426 xsmp_icefd = IceConnectionNumber(iceConn);
6427 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
6432 /* Handle any ICE processing that's required; return FAIL if SM lost */
6434 xsmp_handle_requests()
6436 Bool rep;
6438 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
6439 == IceProcessMessagesIOError)
6441 /* Lost ICE */
6442 if (p_verbose > 0)
6443 verb_msg((char_u *)_("XSMP lost ICE connection"));
6444 xsmp_close();
6445 return FAIL;
6447 else
6448 return OK;
6451 static int dummy;
6453 /* Set up X Session Management Protocol */
6454 void
6455 xsmp_init(void)
6457 char errorstring[80];
6458 char *clientid;
6459 SmcCallbacks smcallbacks;
6460 #if 0
6461 SmPropValue smname;
6462 SmProp smnameprop;
6463 SmProp *smprops[1];
6464 #endif
6466 if (p_verbose > 0)
6467 verb_msg((char_u *)_("XSMP opening connection"));
6469 xsmp.save_yourself = xsmp.shutdown = False;
6471 /* Set up SM callbacks - must have all, even if they're not used */
6472 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
6473 smcallbacks.save_yourself.client_data = NULL;
6474 smcallbacks.die.callback = xsmp_die;
6475 smcallbacks.die.client_data = NULL;
6476 smcallbacks.save_complete.callback = xsmp_save_complete;
6477 smcallbacks.save_complete.client_data = NULL;
6478 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
6479 smcallbacks.shutdown_cancelled.client_data = NULL;
6481 /* Set up a watch on ICE connection creations. The "dummy" argument is
6482 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6483 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
6485 if (p_verbose > 0)
6486 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
6487 return;
6490 /* Create an SM connection */
6491 xsmp.smcconn = SmcOpenConnection(
6492 NULL,
6493 NULL,
6494 SmProtoMajor,
6495 SmProtoMinor,
6496 SmcSaveYourselfProcMask | SmcDieProcMask
6497 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
6498 &smcallbacks,
6499 NULL,
6500 &clientid,
6501 sizeof(errorstring),
6502 errorstring);
6503 if (xsmp.smcconn == NULL)
6505 char errorreport[132];
6507 if (p_verbose > 0)
6509 vim_snprintf(errorreport, sizeof(errorreport),
6510 _("XSMP SmcOpenConnection failed: %s"), errorstring);
6511 verb_msg((char_u *)errorreport);
6513 return;
6515 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
6517 #if 0
6518 /* ID ourselves */
6519 smname.value = "vim";
6520 smname.length = 3;
6521 smnameprop.name = "SmProgram";
6522 smnameprop.type = "SmARRAY8";
6523 smnameprop.num_vals = 1;
6524 smnameprop.vals = &smname;
6526 smprops[0] = &smnameprop;
6527 SmcSetProperties(xsmp.smcconn, 1, smprops);
6528 #endif
6532 /* Shut down XSMP comms. */
6533 void
6534 xsmp_close()
6536 if (xsmp_icefd != -1)
6538 SmcCloseConnection(xsmp.smcconn, 0, NULL);
6539 xsmp_icefd = -1;
6542 #endif /* USE_XSMP */
6545 #ifdef EBCDIC
6546 /* Translate character to its CTRL- value */
6547 char CtrlTable[] =
6549 /* 00 - 5E */
6550 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6551 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6552 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6553 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6554 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6555 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6556 /* ^ */ 0x1E,
6557 /* - */ 0x1F,
6558 /* 61 - 6C */
6559 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6560 /* _ */ 0x1F,
6561 /* 6E - 80 */
6562 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6563 /* a */ 0x01,
6564 /* b */ 0x02,
6565 /* c */ 0x03,
6566 /* d */ 0x37,
6567 /* e */ 0x2D,
6568 /* f */ 0x2E,
6569 /* g */ 0x2F,
6570 /* h */ 0x16,
6571 /* i */ 0x05,
6572 /* 8A - 90 */
6573 0, 0, 0, 0, 0, 0, 0,
6574 /* j */ 0x15,
6575 /* k */ 0x0B,
6576 /* l */ 0x0C,
6577 /* m */ 0x0D,
6578 /* n */ 0x0E,
6579 /* o */ 0x0F,
6580 /* p */ 0x10,
6581 /* q */ 0x11,
6582 /* r */ 0x12,
6583 /* 9A - A1 */
6584 0, 0, 0, 0, 0, 0, 0, 0,
6585 /* s */ 0x13,
6586 /* t */ 0x3C,
6587 /* u */ 0x3D,
6588 /* v */ 0x32,
6589 /* w */ 0x26,
6590 /* x */ 0x18,
6591 /* y */ 0x19,
6592 /* z */ 0x3F,
6593 /* AA - AC */
6594 0, 0, 0,
6595 /* [ */ 0x27,
6596 /* AE - BC */
6597 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6598 /* ] */ 0x1D,
6599 /* BE - C0 */ 0, 0, 0,
6600 /* A */ 0x01,
6601 /* B */ 0x02,
6602 /* C */ 0x03,
6603 /* D */ 0x37,
6604 /* E */ 0x2D,
6605 /* F */ 0x2E,
6606 /* G */ 0x2F,
6607 /* H */ 0x16,
6608 /* I */ 0x05,
6609 /* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
6610 /* J */ 0x15,
6611 /* K */ 0x0B,
6612 /* L */ 0x0C,
6613 /* M */ 0x0D,
6614 /* N */ 0x0E,
6615 /* O */ 0x0F,
6616 /* P */ 0x10,
6617 /* Q */ 0x11,
6618 /* R */ 0x12,
6619 /* DA - DF */ 0, 0, 0, 0, 0, 0,
6620 /* \ */ 0x1C,
6621 /* E1 */ 0,
6622 /* S */ 0x13,
6623 /* T */ 0x3C,
6624 /* U */ 0x3D,
6625 /* V */ 0x32,
6626 /* W */ 0x26,
6627 /* X */ 0x18,
6628 /* Y */ 0x19,
6629 /* Z */ 0x3F,
6630 /* EA - FF*/ 0, 0, 0, 0, 0, 0,
6631 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6634 char MetaCharTable[]=
6635 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6636 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
6637 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
6638 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
6639 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
6643 /* TODO: Use characters NOT numbers!!! */
6644 char CtrlCharTable[]=
6645 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6646 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
6647 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
6648 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
6649 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
6653 #endif