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
35 # include "if_mzsch.h"
42 #include "os_unixx.h" /* unix includes for os_unix.c only */
45 # include <X11/SM/SMlib.h>
49 * Use this prototype for select, some include files have a wrong prototype
54 # define select beos_select
60 # include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() */
64 #if defined(HAVE_SELECT)
65 extern int select
__ARGS((int, fd_set
*, fd_set
*, fd_set
*, struct timeval
*));
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> */
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));
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)
105 #if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
106 # define SIGWINCH SIGWINDOW
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));
121 # if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
122 Window x11_window
= 0;
124 Display
*x11_display
= NULL
;
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
*));
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
;
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 *));
149 static int RealWaitForChar
__ARGS((int, long, int *));
152 #ifdef FEAT_XCLIPBOARD
153 static int do_xterm_trace
__ARGS((void));
154 # define XT_TRACE_DELAY 50 /* delay for xterm tracing */
157 static void handle_resize
__ARGS((void));
159 #if defined(SIGWINCH)
160 static RETSIGTYPE sig_winch
__ARGS(SIGPROTOARG
);
163 static RETSIGTYPE catch_sigint
__ARGS(SIGPROTOARG
);
166 static RETSIGTYPE catch_sigpwr
__ARGS(SIGPROTOARG
);
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
;
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
)()));
180 static int have_wildcard
__ARGS((int, char_u
**));
181 static int have_dollars
__ARGS((int, char_u
**));
185 static int save_patterns
__ARGS((int num_pat
, char_u
**pat
, int *num_file
, char_u
***file
));
189 # define SIG_ERR ((RETSIGTYPE (*)())-1)
192 static int do_resize
= FALSE
;
194 static char_u
*extra_shell_arg
= NULL
;
195 static int show_shell_mess
= TRUE
;
197 static int deadly_signal
= 0; /* The signal we caught */
199 static int curr_tmode
= TMODE_COOK
; /* contains current terminal mode */
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 */
210 static xsmp_config_T xsmp
;
213 #ifdef SYS_SIGLIST_DECLARED
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
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? */
233 {SIGHUP
, "HUP", TRUE
},
236 {SIGQUIT
, "QUIT", TRUE
},
239 {SIGILL
, "ILL", TRUE
},
242 {SIGTRAP
, "TRAP", TRUE
},
245 {SIGABRT
, "ABRT", TRUE
},
248 {SIGEMT
, "EMT", TRUE
},
251 {SIGFPE
, "FPE", TRUE
},
254 {SIGBUS
, "BUS", TRUE
},
257 {SIGSEGV
, "SEGV", TRUE
},
260 {SIGSYS
, "SYS", TRUE
},
263 {SIGALRM
, "ALRM", FALSE
}, /* Perl's alarm() can trigger it */
266 {SIGTERM
, "TERM", TRUE
},
269 {SIGVTALRM
, "VTALRM", TRUE
},
271 #if defined(SIGPROF) && !defined(FEAT_MZSCHEME)
272 /* MzScheme uses SIGPROF for its own needs */
273 {SIGPROF
, "PROF", TRUE
},
276 {SIGXCPU
, "XCPU", TRUE
},
279 {SIGXFSZ
, "XFSZ", TRUE
},
282 {SIGUSR1
, "USR1", TRUE
},
285 {SIGUSR2
, "USR2", TRUE
},
288 {SIGINT
, "INT", FALSE
},
291 {SIGWINCH
, "WINCH", FALSE
},
294 {SIGTSTP
, "TSTP", FALSE
},
297 {SIGPIPE
, "PIPE", FALSE
},
299 {-1, "Unknown!", FALSE
}
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
)
324 long wtime
; /* don't use "time", MIPS cannot handle it */
329 /* Check if window changed size while we were busy, perhaps the ":set
330 * columns=99" command was used. */
336 while (WaitForChar(wtime
) == 0) /* no character available */
338 if (!do_resize
) /* return if not interrupted by 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)
353 if (trigger_cursorhold() && maxlen
>= 3
354 && !typebuf_changed(tb_change_cnt
))
358 buf
[2] = (int)KE_CURSORHOLD
;
366 for (;;) /* repeat until we got a character */
368 while (do_resize
) /* window changed size */
371 * we want to be interrupted by the winch signal
374 if (do_resize
) /* interrupted by SIGWINCH signal */
377 /* If input was put directly in typeahead buffer bail out here. */
378 if (typebuf_changed(tb_change_cnt
))
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
388 len
= read_from_input_buf(buf
, (long)maxlen
);
394 for (i
= 0; i
< len
; i
++)
411 * return non-zero if a character is available
416 return WaitForChar(0L);
419 #if defined(HAVE_TOTAL_MEM) || defined(PROTO)
420 # ifdef HAVE_SYS_RESOURCE_H
421 # include <sys/resource.h>
423 # if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
424 # include <sys/sysctl.h>
426 # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
427 # include <sys/sysinfo.h>
431 * Return total amount of memory available in Kbyte.
432 * Doesn't change when memory has been allocated.
436 mch_total_mem(special
)
440 return ulimit(3, 0L) >> 10; /* always 32MB? */
443 long_u shiftright
= 10; /* how much to shift "mem" right for Kbyte */
449 /* BSD way of getting the amount of RAM available. */
452 len
= sizeof(physmem
);
453 if (sysctl(mib
, 2, &physmem
, &len
, NULL
, 0) == 0)
454 mem
= (long_u
)physmem
;
457 # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
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;
472 mem
= sinfo
.totalram
* sinfo
.mem_unit
;
474 mem
= sinfo
.totalram
;
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;
496 mem
= (long_u
)pagesize
* pagecount
;
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)
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
512 && ((long_u
)rlp
.rlim_cur
>> 10) < (mem
>> shiftright
)
515 mem
= (long_u
)rlp
.rlim_cur
;
522 return mem
>> shiftright
;
523 return (long_u
)0x1fffff;
529 mch_delay(msec
, ignoreinput
)
535 long total
= msec
; /* remember original value */
540 /* Go to cooked mode without echo, to allow SIGINT interrupting us
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
554 /* if total is large enough, wait by portions in p_mzq */
561 #ifdef HAVE_NANOSLEEP
565 ts
.tv_sec
= msec
/ 1000;
566 ts
.tv_nsec
= (msec
% 1000) * 1000000;
567 (void)nanosleep(&ts
, NULL
);
573 usleep((unsigned int)(999 * 1000));
576 usleep((unsigned int)(msec
* 1000));
579 poll(NULL
, 0, (int)msec
);
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 */
610 #if 0 /* disabled, no longer needed now that regmatch() is not recursive */
611 # if defined(HAVE_GETRLIMIT)
612 # define HAVE_STACK_LIMIT
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
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.
635 check_stack_growth(p
)
640 stack_grows_downwards
= (p
> (char *)&i
);
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>
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
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
673 lim
= (long)rlp
.rlim_cur
;
674 #if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
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
)
688 pthread_attr_destroy(&attr
);
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);
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.
715 if (stack_limit
!= NULL
)
717 if (stack_grows_downwards
)
722 else if (p
> stack_limit
)
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
738 # define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
741 # ifdef HAVE_SIGALTSTACK
742 static stack_t sigstk
; /* for sigaltstack() */
744 static struct sigstack sigstk
; /* for sigstack() */
747 static void init_signal_stack
__ARGS((void));
748 static char *signal_stack
;
753 if (signal_stack
!= NULL
)
755 # ifdef HAVE_SIGALTSTACK
757 /* missing prototype. Adding it to osdef?.h.in doesn't work, because
758 * "struct sigaltstack" needs to be declared. */
759 extern int sigaltstack
__ARGS((const struct sigaltstack
*ss
, struct sigaltstack
*oss
));
763 sigstk
.ss_base
= signal_stack
;
765 sigstk
.ss_sp
= signal_stack
;
767 sigstk
.ss_size
= SIGSTKSZ
;
769 (void)sigaltstack(&sigstk
, NULL
);
771 sigstk
.ss_sp
= signal_stack
;
772 if (stack_grows_downwards
)
773 sigstk
.ss_sp
+= SIGSTKSZ
- 1;
774 sigstk
.ss_onstack
= 0;
775 (void)sigstack(&sigstk
, NULL
);
782 * We need correct potatotypes for a signal function, otherwise mean compilers
783 * will barf when the second argument to signal() is ``wrong''.
784 * Let me try it with a few tricky defines from my own osdef.h (jw).
786 #if defined(SIGWINCH)
789 sig_winch
SIGDEFARG(sigarg
)
791 /* this is not required on all systems, but it doesn't hurt anybody */
792 signal(SIGWINCH
, (RETSIGTYPE (*)())sig_winch
);
801 catch_sigint
SIGDEFARG(sigarg
)
803 /* this is not required on all systems, but it doesn't hurt anybody */
804 signal(SIGINT
, (RETSIGTYPE (*)())catch_sigint
);
813 catch_sigpwr
SIGDEFARG(sigarg
)
815 /* this is not required on all systems, but it doesn't hurt anybody */
816 signal(SIGPWR
, (RETSIGTYPE (*)())catch_sigpwr
);
818 * I'm not sure we get the SIGPWR signal when the system is really going
819 * down or when the batteries are almost empty. Just preserve the swap
820 * files and don't exit, that can't do any harm.
822 ml_sync_all(FALSE
, FALSE
);
829 * signal function for alarm().
833 sig_alarm
SIGDEFARG(sigarg
)
835 /* doesn't do anything, just to break a system call */
836 sig_alarm_called
= TRUE
;
841 #if (defined(HAVE_SETJMP_H) \
842 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
843 || defined(FEAT_LIBCALL))) \
846 * A simplistic version of setjmp() that only allows one level of using.
847 * Don't call twice before calling mch_endjmp()!.
850 * if (SETJMP(lc_jump_env) != 0)
860 * Note: Can't move SETJMP() here, because a function calling setjmp() must
861 * not return before the saved environment is used.
862 * Returns OK for normal return, FAIL when the protected code caused a
863 * problem and LONGJMP() was used.
883 # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
884 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
885 * otherwise catching the signal only works once. */
892 * This function handles deadly signals.
893 * It tries to preserve any swap file and exit properly.
894 * (partly from Elvis).
897 deathtrap
SIGDEFARG(sigarg
)
899 static int entered
= 0; /* count the number of times we got here.
900 Note: when memory has been corrupted
901 this may get an arbitrary value! */
906 #if defined(HAVE_SETJMP_H)
908 * Catch a crash in protected code.
909 * Restores the environment saved in lc_jump_env, which looks like
910 * SETJMP() returns 1.
914 # if defined(SIGHASARG)
917 lc_active
= FALSE
; /* don't jump again */
918 LONGJMP(lc_jump_env
, 1);
924 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
925 * here. This avoids that a non-reentrant function is interrupted, e.g.,
926 * free(). Calling free() again may then cause a crash. */
948 && !vim_handle_signal(sigarg
))
952 /* Remember how often we have been called. */
956 /* Set the v:dying variable. */
957 set_vim_var_nr(VV_DYING
, (long)entered
);
960 #ifdef HAVE_STACK_LIMIT
961 /* Since we are now using the signal stack, need to reset the stack
962 * limit. Otherwise using a regexp will fail. */
967 /* This is for opening gdb the moment Vim crashes.
968 * You need to manually adjust the file name and Vim executable name.
969 * Suggested by SungHyun Nam. */
971 # define VI_GDB_FILE "/tmp/vimgdb"
972 # define VIM_NAME "/usr/bin/vim"
973 FILE *fp
= fopen(VI_GDB_FILE
, "w");
981 , VIM_NAME
, getpid());
983 system("xterm -e gdb -x "VI_GDB_FILE
);
990 /* try to find the name of this signal */
991 for (i
= 0; signal_info
[i
].sig
!= -1; i
++)
992 if (sigarg
== signal_info
[i
].sig
)
994 deadly_signal
= sigarg
;
997 full_screen
= FALSE
; /* don't write message to the GUI, it might be
998 * part of the problem... */
1000 * If something goes wrong after entering here, we may get here again.
1001 * When this happens, give a message and try to exit nicely (resetting the
1002 * terminal mode, etc.)
1003 * When this happens twice, just exit, don't even try to give a message,
1004 * stack may be corrupt or something weird.
1005 * When this still happens again (or memory was corrupted in such a way
1006 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1010 reset_signals(); /* don't catch any signals anymore */
1018 OUT_STR(_("Vim: Double signal, exiting\n"));
1024 sprintf((char *)IObuff
, _("Vim: Caught deadly signal %s\n"),
1025 signal_info
[i
].name
);
1027 sprintf((char *)IObuff
, _("Vim: Caught deadly signal\n"));
1029 preserve_exit(); /* preserve files and exit */
1042 * On Solaris with multi-threading, suspending might not work immediately.
1043 * Catch the SIGCONT signal, which will be used as an indication whether the
1044 * suspending has been done or not.
1046 static int sigcont_received
;
1047 static RETSIGTYPE sigcont_handler
__ARGS(SIGPROTOARG
);
1050 * signal handler for SIGCONT
1054 sigcont_handler
SIGDEFARG(sigarg
)
1056 sigcont_received
= TRUE
;
1062 * If the machine has job control, use it to suspend the program,
1063 * otherwise fake it by starting a new shell.
1068 /* BeOS does have SIGTSTP, but it doesn't work. */
1069 #if defined(SIGTSTP) && !defined(__BEOS__)
1070 out_flush(); /* needed to make cursor visible on some systems */
1071 settmode(TMODE_COOK
);
1072 out_flush(); /* needed to disable mouse on some systems */
1074 # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
1075 /* Since we are going to sleep, we can't respond to requests for the X
1076 * selections. Lose them, otherwise other applications will hang. But
1077 * first copy the text to cut buffer 0. */
1078 if (clip_star
.owned
|| clip_plus
.owned
)
1080 x11_export_final_selection();
1081 if (clip_star
.owned
)
1082 clip_lose_selection(&clip_star
);
1083 if (clip_plus
.owned
)
1084 clip_lose_selection(&clip_plus
);
1085 if (x11_display
!= NULL
)
1086 XFlush(x11_display
);
1091 sigcont_received
= FALSE
;
1093 kill(0, SIGTSTP
); /* send ourselves a STOP signal */
1095 /* When we didn't suspend immediately in the kill(), do it now. Happens
1096 * on multi-threaded Solaris. */
1097 if (!sigcont_received
)
1103 * Set oldtitle to NULL, so the current title is obtained again.
1108 settmode(TMODE_RAW
);
1109 need_check_timestamps
= TRUE
;
1110 did_check_timestamps
= FALSE
;
1125 #ifdef MACOS_CONVERT
1133 #if defined(SIGWINCH)
1135 * WINDOW CHANGE signal is handled with sig_winch().
1137 signal(SIGWINCH
, (RETSIGTYPE (*)())sig_winch
);
1141 * We want the STOP signal to work, to make mch_suspend() work.
1142 * For "rvim" the STOP signal is ignored.
1145 signal(SIGTSTP
, restricted
? SIG_IGN
: SIG_DFL
);
1148 signal(SIGCONT
, sigcont_handler
);
1152 * We want to ignore breaking of PIPEs.
1155 signal(SIGPIPE
, SIG_IGN
);
1163 * Ignore alarm signals (Perl's alarm() generates it).
1166 signal(SIGALRM
, SIG_IGN
);
1170 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1171 * work will be lost.
1174 signal(SIGPWR
, (RETSIGTYPE (*)())catch_sigpwr
);
1178 * Arrange for other signals to gracefully shutdown Vim.
1180 catch_signals(deathtrap
, SIG_ERR
);
1182 #if defined(FEAT_GUI) && defined(SIGHUP)
1184 * When the GUI is running, ignore the hangup signal.
1187 signal(SIGHUP
, SIG_IGN
);
1191 #if defined(SIGINT) || defined(PROTO)
1193 * Catch CTRL-C (only works while in Cooked mode).
1198 signal(SIGINT
, (RETSIGTYPE (*)())catch_sigint
);
1205 catch_signals(SIG_DFL
, SIG_DFL
);
1207 /* SIGCONT isn't in the list, because its default action is ignore */
1208 signal(SIGCONT
, SIG_DFL
);
1213 catch_signals(func_deadly
, func_other
)
1214 RETSIGTYPE (*func_deadly
)();
1215 RETSIGTYPE (*func_other
)();
1219 for (i
= 0; signal_info
[i
].sig
!= -1; i
++)
1220 if (signal_info
[i
].deadly
)
1222 #if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1223 struct sigaction sa
;
1225 /* Setup to use the alternate stack for the signal function. */
1226 sa
.sa_handler
= func_deadly
;
1227 sigemptyset(&sa
.sa_mask
);
1228 # if defined(__linux__) && defined(_REENTRANT)
1229 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1230 * thread handling in combination with using the alternate stack:
1231 * pthread library functions try to use the stack pointer to
1232 * identify the current thread, causing a SEGV signal, which
1233 * recursively calls deathtrap() and hangs. */
1236 sa
.sa_flags
= SA_ONSTACK
;
1238 sigaction(signal_info
[i
].sig
, &sa
, NULL
);
1240 # if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1243 /* Setup to use the alternate stack for the signal function. */
1244 sv
.sv_handler
= func_deadly
;
1246 sv
.sv_flags
= SV_ONSTACK
;
1247 sigvec(signal_info
[i
].sig
, &sv
, NULL
);
1249 signal(signal_info
[i
].sig
, func_deadly
);
1253 else if (func_other
!= SIG_ERR
)
1254 signal(signal_info
[i
].sig
, func_other
);
1258 * Handling of SIGHUP, SIGQUIT and SIGTERM:
1259 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1261 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1262 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
1264 * Returns TRUE when Vim should exit.
1267 vim_handle_signal(sig
)
1270 static int got_signal
= 0;
1271 static int blocked
= TRUE
;
1275 case SIGNAL_BLOCK
: blocked
= TRUE
;
1278 case SIGNAL_UNBLOCK
: blocked
= FALSE
;
1279 if (got_signal
!= 0)
1281 kill(getpid(), got_signal
);
1286 default: if (!blocked
)
1287 return TRUE
; /* exit! */
1292 got_int
= TRUE
; /* break any loops */
1299 * Check_win checks whether we have an interactive stdout.
1303 mch_check_win(argc
, argv
)
1309 * Store argv[0], may be used for $VIM. Only use it if it is an absolute
1310 * name, mostly it's just "vim" and found in the path, which is unusable.
1312 if (mch_isFullName(argv
[0]))
1313 exe_name
= vim_strsave((char_u
*)argv
[0]);
1321 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1326 if (isatty(read_cmd_fd
))
1333 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \
1334 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1336 static void xopen_message
__ARGS((struct timeval
*tvp
));
1339 * Give a message about the elapsed time for opening the X window.
1343 struct timeval
*tvp
; /* must contain start time */
1345 struct timeval end_tv
;
1347 /* Compute elapsed time. */
1348 gettimeofday(&end_tv
, NULL
);
1349 smsg((char_u
*)_("Opening the X display took %ld msec"),
1350 (end_tv
.tv_sec
- tvp
->tv_sec
) * 1000L
1351 + (end_tv
.tv_usec
- tvp
->tv_usec
) / 1000L);
1356 #if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1358 * A few functions shared by X11 title and clipboard code.
1360 static int x_error_handler
__ARGS((Display
*dpy
, XErrorEvent
*error_event
));
1361 static int x_error_check
__ARGS((Display
*dpy
, XErrorEvent
*error_event
));
1362 static int x_connect_to_server
__ARGS((void));
1363 static int test_x11_window
__ARGS((Display
*dpy
));
1365 static int got_x_error
= FALSE
;
1368 * X Error handler, otherwise X just exits! (very rude) -- webb
1371 x_error_handler(dpy
, error_event
)
1373 XErrorEvent
*error_event
;
1375 XGetErrorText(dpy
, error_event
->error_code
, (char *)IObuff
, IOSIZE
);
1376 STRCAT(IObuff
, _("\nVim: Got X error\n"));
1378 /* We cannot print a message and continue, because no X calls are allowed
1379 * here (causes my system to hang). Silently continuing might be an
1381 preserve_exit(); /* preserve files and exit */
1383 return 0; /* NOTREACHED */
1387 * Another X Error handler, just used to check for errors.
1391 x_error_check(dpy
, error_event
)
1393 XErrorEvent
*error_event
;
1399 #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1400 # if defined(HAVE_SETJMP_H)
1402 * An X IO Error handler, used to catch error while opening the display.
1404 static int x_IOerror_check
__ARGS((Display
*dpy
));
1408 x_IOerror_check(dpy
)
1411 /* This function should not return, it causes exit(). Longjump instead. */
1412 LONGJMP(lc_jump_env
, 1);
1419 * An X IO Error handler, used to catch terminal errors.
1421 static int x_IOerror_handler
__ARGS((Display
*dpy
));
1425 x_IOerror_handler(dpy
)
1431 xterm_Shell
= (Widget
)0;
1433 /* This function should not return, it causes exit(). Longjump instead. */
1434 LONGJMP(x_jump_env
, 1);
1441 * Return TRUE when connection to the X server is desired.
1444 x_connect_to_server()
1446 regmatch_T regmatch
;
1448 #if defined(FEAT_CLIENTSERVER)
1449 if (x_force_connect
)
1455 /* Check for a match with "exclude:" from 'clipboard'. */
1456 if (clip_exclude_prog
!= NULL
)
1458 regmatch
.rm_ic
= FALSE
; /* Don't ignore case */
1459 regmatch
.regprog
= clip_exclude_prog
;
1460 if (vim_regexec(®match
, T_NAME
, (colnr_T
)0))
1467 * Test if "dpy" and x11_window are valid by getting the window title.
1468 * I don't actually want it yet, so there may be a simpler call to use, but
1469 * this will cause the error handler x_error_check() to be called if anything
1470 * is wrong, such as the window pointer being invalid (as can happen when the
1471 * user changes his DISPLAY, but not his WINDOWID) -- webb
1474 test_x11_window(dpy
)
1477 int (*old_handler
)();
1478 XTextProperty text_prop
;
1480 old_handler
= XSetErrorHandler(x_error_check
);
1481 got_x_error
= FALSE
;
1482 if (XGetWMName(dpy
, x11_window
, &text_prop
))
1483 XFree((void *)text_prop
.value
);
1485 (void)XSetErrorHandler(old_handler
);
1487 if (p_verbose
> 0 && got_x_error
)
1488 verb_msg((char_u
*)_("Testing the X display failed"));
1490 return (got_x_error
? FAIL
: OK
);
1498 static int get_x11_thing
__ARGS((int get_title
, int test_only
));
1501 * try to get x11 window and display
1503 * return FAIL for failure, OK otherwise
1509 static int result
= -1;
1510 #define XD_NONE 0 /* x11_display not set here */
1511 #define XD_HERE 1 /* x11_display opened here */
1512 #define XD_GUI 2 /* x11_display used from gui.dpy */
1513 #define XD_XTERM 3 /* x11_display used from xterm_dpy */
1514 static int x11_display_from
= XD_NONE
;
1515 static int did_set_error_handler
= FALSE
;
1517 if (!did_set_error_handler
)
1519 /* X just exits if it finds an error otherwise! */
1520 (void)XSetErrorHandler(x_error_handler
);
1521 did_set_error_handler
= TRUE
;
1524 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
1528 * If the X11 display was opened here before, for the window where Vim
1529 * was started, close that one now to avoid a memory leak.
1531 if (x11_display_from
== XD_HERE
&& x11_display
!= NULL
)
1533 XCloseDisplay(x11_display
);
1534 x11_display_from
= XD_NONE
;
1536 if (gui_get_x11_windis(&x11_window
, &x11_display
) == OK
)
1538 x11_display_from
= XD_GUI
;
1544 else if (x11_display_from
== XD_GUI
)
1546 /* GUI must have stopped somehow, clear x11_display */
1549 x11_display_from
= XD_NONE
;
1553 /* When started with the "-X" argument, don't try connecting. */
1554 if (!x_connect_to_server())
1558 * If WINDOWID not set, should try another method to find out
1559 * what the current window number is. The only code I know for
1560 * this is very complicated.
1561 * We assume that zero is invalid for WINDOWID.
1563 if (x11_window
== 0 && (winid
= getenv("WINDOWID")) != NULL
)
1564 x11_window
= (Window
)atol(winid
);
1566 #ifdef FEAT_XCLIPBOARD
1567 if (xterm_dpy
!= NULL
&& x11_window
!= 0)
1569 /* Checked it already. */
1570 if (x11_display_from
== XD_XTERM
)
1574 * If the X11 display was opened here before, for the window where Vim
1575 * was started, close that one now to avoid a memory leak.
1577 if (x11_display_from
== XD_HERE
&& x11_display
!= NULL
)
1578 XCloseDisplay(x11_display
);
1579 x11_display
= xterm_dpy
;
1580 x11_display_from
= XD_XTERM
;
1581 if (test_x11_window(x11_display
) == FAIL
)
1583 /* probably bad $WINDOWID */
1586 x11_display_from
= XD_NONE
;
1593 if (x11_window
== 0 || x11_display
== NULL
)
1596 if (result
!= -1) /* Have already been here and set this */
1597 return result
; /* Don't do all these X calls again */
1599 if (x11_window
!= 0 && x11_display
== NULL
)
1601 #ifdef SET_SIG_ALARM
1602 RETSIGTYPE (*sig_save
)();
1604 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1605 struct timeval start_tv
;
1608 gettimeofday(&start_tv
, NULL
);
1611 #ifdef SET_SIG_ALARM
1613 * Opening the Display may hang if the DISPLAY setting is wrong, or
1614 * the network connection is bad. Set an alarm timer to get out.
1616 sig_alarm_called
= FALSE
;
1617 sig_save
= (RETSIGTYPE (*)())signal(SIGALRM
,
1618 (RETSIGTYPE (*)())sig_alarm
);
1621 x11_display
= XOpenDisplay(NULL
);
1623 #ifdef SET_SIG_ALARM
1625 signal(SIGALRM
, (RETSIGTYPE (*)())sig_save
);
1626 if (p_verbose
> 0 && sig_alarm_called
)
1627 verb_msg((char_u
*)_("Opening the X display timed out"));
1629 if (x11_display
!= NULL
)
1631 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1635 xopen_message(&start_tv
);
1639 if (test_x11_window(x11_display
) == FAIL
)
1641 /* Maybe window id is bad */
1643 XCloseDisplay(x11_display
);
1647 x11_display_from
= XD_HERE
;
1650 if (x11_window
== 0 || x11_display
== NULL
)
1651 return (result
= FAIL
);
1652 return (result
= OK
);
1656 * Determine original x11 Window Title
1659 get_x11_title(test_only
)
1662 return get_x11_thing(TRUE
, test_only
);
1666 * Determine original x11 Window icon
1669 get_x11_icon(test_only
)
1674 retval
= get_x11_thing(FALSE
, test_only
);
1676 /* could not get old icon, use terminal name */
1677 if (oldicon
== NULL
&& !test_only
)
1679 if (STRNCMP(T_NAME
, "builtin_", 8) == 0)
1680 oldicon
= T_NAME
+ 8;
1689 get_x11_thing(get_title
, test_only
)
1690 int get_title
; /* get title string */
1693 XTextProperty text_prop
;
1697 if (get_x11_windis() == OK
)
1699 /* Get window/icon name if any */
1701 status
= XGetWMName(x11_display
, x11_window
, &text_prop
);
1703 status
= XGetWMIconName(x11_display
, x11_window
, &text_prop
);
1706 * If terminal is xterm, then x11_window may be a child window of the
1707 * outer xterm window that actually contains the window/icon name, so
1708 * keep traversing up the tree until a window with a title/icon is
1711 /* Previously this was only done for xterm and alikes. I don't see a
1712 * reason why it would fail for other terminal emulators.
1713 * if (term_is_xterm) */
1717 Window win
= x11_window
;
1719 unsigned int num_children
;
1721 while (!status
|| text_prop
.value
== NULL
)
1723 if (!XQueryTree(x11_display
, win
, &root
, &parent
, &children
,
1727 XFree((void *)children
);
1728 if (parent
== root
|| parent
== 0)
1733 status
= XGetWMName(x11_display
, win
, &text_prop
);
1735 status
= XGetWMIconName(x11_display
, win
, &text_prop
);
1738 if (status
&& text_prop
.value
!= NULL
)
1743 #ifdef FEAT_XFONTSET
1744 if (text_prop
.encoding
== XA_STRING
)
1748 oldtitle
= vim_strsave((char_u
*)text_prop
.value
);
1750 oldicon
= vim_strsave((char_u
*)text_prop
.value
);
1751 #ifdef FEAT_XFONTSET
1756 Status transform_status
;
1759 transform_status
= XmbTextPropertyToTextList(x11_display
,
1762 if (transform_status
>= Success
&& n
> 0 && cl
[0])
1765 oldtitle
= vim_strsave((char_u
*) cl
[0]);
1767 oldicon
= vim_strsave((char_u
*) cl
[0]);
1768 XFreeStringList(cl
);
1773 oldtitle
= vim_strsave((char_u
*)text_prop
.value
);
1775 oldicon
= vim_strsave((char_u
*)text_prop
.value
);
1780 XFree((void *)text_prop
.value
);
1786 /* Are Xutf8 functions available? Avoid error from old compilers. */
1787 #if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
1788 # if X_HAVE_UTF8_STRING
1789 # define USE_UTF8_STRING
1794 * Set x11 Window Title
1796 * get_x11_windis() must be called before this and have returned OK
1799 set_x11_title(title
)
1802 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
1803 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
1804 * supported everywhere and STRING doesn't work for multi-byte titles.
1806 #ifdef USE_UTF8_STRING
1808 Xutf8SetWMProperties(x11_display
, x11_window
, (const char *)title
,
1809 NULL
, NULL
, 0, NULL
, NULL
, NULL
);
1813 #if XtSpecificationRelease >= 4
1814 # ifdef FEAT_XFONTSET
1815 XmbSetWMProperties(x11_display
, x11_window
, (const char *)title
,
1816 NULL
, NULL
, 0, NULL
, NULL
, NULL
);
1818 XTextProperty text_prop
;
1819 char *c_title
= (char *)title
;
1821 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
1822 (void)XStringListToTextProperty(&c_title
, 1, &text_prop
);
1823 XSetWMProperties(x11_display
, x11_window
, &text_prop
,
1824 NULL
, NULL
, 0, NULL
, NULL
, NULL
);
1827 XStoreName(x11_display
, x11_window
, (char *)title
);
1830 XFlush(x11_display
);
1834 * Set x11 Window icon
1836 * get_x11_windis() must be called before this and have returned OK
1842 /* See above for comments about using X*SetWMProperties(). */
1843 #ifdef USE_UTF8_STRING
1845 Xutf8SetWMProperties(x11_display
, x11_window
, NULL
, (const char *)icon
,
1846 NULL
, 0, NULL
, NULL
, NULL
);
1850 #if XtSpecificationRelease >= 4
1851 # ifdef FEAT_XFONTSET
1852 XmbSetWMProperties(x11_display
, x11_window
, NULL
, (const char *)icon
,
1853 NULL
, 0, NULL
, NULL
, NULL
);
1855 XTextProperty text_prop
;
1856 char *c_icon
= (char *)icon
;
1858 (void)XStringListToTextProperty(&c_icon
, 1, &text_prop
);
1859 XSetWMProperties(x11_display
, x11_window
, NULL
, &text_prop
,
1860 NULL
, 0, NULL
, NULL
, NULL
);
1863 XSetIconName(x11_display
, x11_window
, (char *)icon
);
1866 XFlush(x11_display
);
1869 #else /* FEAT_X11 */
1873 get_x11_title(test_only
)
1880 get_x11_icon(test_only
)
1885 if (STRNCMP(T_NAME
, "builtin_", 8) == 0)
1886 oldicon
= T_NAME
+ 8;
1893 #endif /* FEAT_X11 */
1896 mch_can_restore_title()
1898 return get_x11_title(TRUE
);
1902 mch_can_restore_icon()
1904 return get_x11_icon(TRUE
);
1908 * Set the window title and icon.
1911 mch_settitle(title
, icon
)
1916 static int recursive
= 0;
1918 if (T_NAME
== NULL
) /* no terminal name (yet) */
1920 if (title
== NULL
&& icon
== NULL
) /* nothing to do */
1923 /* When one of the X11 functions causes a deadly signal, we get here again
1924 * recursively. Avoid hanging then (something is probably locked). */
1930 * if the window ID and the display is known, we may use X11 calls
1933 if (get_x11_windis() == OK
)
1936 # if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
1943 * Note: if "t_TS" is set, title is set with escape sequence rather
1944 * than x11 calls, because the x11 calls don't always work
1946 if ((type
|| *T_TS
!= NUL
) && title
!= NULL
)
1948 if (oldtitle
== NULL
1952 ) /* first call but not in GUI, save title */
1953 (void)get_x11_title(FALSE
);
1955 if (*T_TS
!= NUL
) /* it's OK if t_fs is empty */
1956 term_settitle(title
);
1959 # ifdef FEAT_GUI_GTK
1960 if (!gui
.in_use
) /* don't do this if GTK+ is running */
1962 set_x11_title(title
); /* x11 */
1964 #if defined(FEAT_GUI_GTK) \
1965 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
1967 gui_mch_settitle(title
, icon
);
1969 did_set_title
= TRUE
;
1972 if ((type
|| *T_CIS
!= NUL
) && icon
!= NULL
)
1978 ) /* first call, save icon */
1979 get_x11_icon(FALSE
);
1983 out_str(T_CIS
); /* set icon start */
1985 out_str(T_CIE
); /* set icon end */
1990 # ifdef FEAT_GUI_GTK
1991 if (!gui
.in_use
) /* don't do this if GTK+ is running */
1993 set_x11_icon(icon
); /* x11 */
1995 did_set_icon
= TRUE
;
2001 * Restore the window/icon title.
2002 * "which" is one of:
2003 * 1 only restore title
2004 * 2 only restore icon
2005 * 3 restore title and icon
2008 mch_restore_title(which
)
2011 /* only restore the title or icon when it has been set */
2012 mch_settitle(((which
& 1) && did_set_title
) ?
2013 (oldtitle
? oldtitle
: p_titleold
) : NULL
,
2014 ((which
& 2) && did_set_icon
) ? oldicon
: NULL
);
2017 #endif /* FEAT_TITLE */
2020 * Return TRUE if "name" looks like some xterm name.
2021 * Seiichi Sato mentioned that "mlterm" works like xterm.
2029 return (STRNICMP(name
, "xterm", 5) == 0
2030 || STRNICMP(name
, "nxterm", 6) == 0
2031 || STRNICMP(name
, "kterm", 5) == 0
2032 || STRNICMP(name
, "mlterm", 6) == 0
2033 || STRNICMP(name
, "rxvt", 4) == 0
2034 || STRCMP(name
, "builtin_xterm") == 0);
2037 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2039 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2040 * Return 1 for "xterm".
2041 * Return 2 for "xterm2".
2046 if (ttym_flags
== TTYM_XTERM2
)
2048 if (ttym_flags
== TTYM_XTERM
)
2060 return (STRNICMP(name
, "iris-ansi", 9) == 0
2061 || STRCMP(name
, "builtin_iris-ansi") == 0);
2069 return FALSE
; /* actually all ANSI comp. terminals should be here */
2070 /* catch VT100 - VT5xx */
2071 return ((STRNICMP(name
, "vt", 2) == 0
2072 && vim_strchr((char_u
*)"12345", name
[2]) != NULL
)
2073 || STRCMP(name
, "builtin_vt320") == 0);
2077 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2078 * This should include all windowed terminal emulators.
2081 vim_is_fastterm(name
)
2086 if (vim_is_xterm(name
) || vim_is_vt300(name
) || vim_is_iris(name
))
2088 return ( STRNICMP(name
, "hpterm", 6) == 0
2089 || STRNICMP(name
, "sun-cmd", 7) == 0
2090 || STRNICMP(name
, "screen", 6) == 0
2091 || STRNICMP(name
, "dtterm", 6) == 0);
2095 * Insert user name in s[len].
2096 * Return OK if a name found.
2099 mch_get_user_name(s
, len
)
2104 vim_strncpy(s
, (char_u
*)cuserid(NULL
), len
- 1);
2107 return mch_get_uname(getuid(), s
, len
);
2112 * Insert user name for "uid" in s[len].
2113 * Return OK if a name found.
2116 mch_get_uname(uid
, s
, len
)
2121 #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2124 if ((pw
= getpwuid(uid
)) != NULL
2125 && pw
->pw_name
!= NULL
&& *(pw
->pw_name
) != NUL
)
2127 vim_strncpy(s
, (char_u
*)pw
->pw_name
, len
- 1);
2131 sprintf((char *)s
, "%d", (int)uid
); /* assumes s is long enough */
2132 return FAIL
; /* a number is not a name */
2136 * Insert host name is s[len].
2139 #ifdef HAVE_SYS_UTSNAME_H
2141 mch_get_host_name(s
, len
)
2145 struct utsname vutsname
;
2147 if (uname(&vutsname
) < 0)
2150 vim_strncpy(s
, (char_u
*)vutsname
.nodename
, len
- 1);
2152 #else /* HAVE_SYS_UTSNAME_H */
2154 # ifdef HAVE_SYS_SYSTEMINFO_H
2155 # define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2159 mch_get_host_name(s
, len
)
2164 vaxc$
gethostname((char *)s
, len
);
2166 gethostname((char *)s
, len
);
2168 s
[len
- 1] = NUL
; /* make sure it's terminated */
2170 #endif /* HAVE_SYS_UTSNAME_H */
2178 return (long)getpid();
2181 #if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
2182 static char *strerror
__ARGS((int));
2188 extern int sys_nerr
;
2189 extern char *sys_errlist
[];
2192 if (err
> 0 && err
< sys_nerr
)
2193 return (sys_errlist
[err
]);
2194 sprintf(er
, "Error %d", err
);
2200 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2201 * Return OK for success, FAIL for failure.
2204 mch_dirname(buf
, len
)
2208 #if defined(USE_GETCWD)
2209 if (getcwd((char *)buf
, len
) == NULL
)
2211 STRCPY(buf
, strerror(errno
));
2216 return (getwd((char *)buf
) != NULL
? OK
: FAIL
);
2220 #if defined(OS2) || defined(PROTO)
2222 * Replace all slashes by backslashes.
2223 * When 'shellslash' set do it the other way around.
2239 * Get absolute file name into "buf[len]".
2241 * return FAIL for failure, OK for success
2244 mch_FullName(fname
, buf
, len
, force
)
2245 char_u
*fname
, *buf
;
2247 int force
; /* also expand when already absolute path */
2251 int only_drive
; /* file name is only a drive letter */
2255 static int dont_fchdir
= FALSE
; /* TRUE when fchdir() doesn't work */
2257 char_u olddir
[MAXPATHL
];
2262 fname
= vms_fixfilename(fname
);
2267 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2269 cygwin_conv_to_posix_path(fname
, fname
);
2272 /* expand it if forced or not an absolute path */
2273 if (force
|| !mch_isFullName(fname
))
2276 * If the file name has a path, change to that directory for a moment,
2277 * and then do the getwd() (and get back to where we were).
2278 * This will get the correct path name with "../" things.
2282 if (((p
= vim_strrchr(fname
, '/')) != NULL
)
2283 || ((p
= vim_strrchr(fname
, '\\')) != NULL
)
2284 || (((p
= vim_strchr(fname
, ':')) != NULL
) && ++only_drive
))
2286 if ((p
= vim_strrchr(fname
, '/')) != NULL
)
2291 * Use fchdir() if possible, it's said to be faster and more
2292 * reliable. But on SunOS 4 it might not work. Check this by
2293 * doing a fchdir() right now.
2297 fd
= open(".", O_RDONLY
| O_EXTRA
, 0);
2298 if (fd
>= 0 && fchdir(fd
) < 0)
2302 dont_fchdir
= TRUE
; /* don't try again */
2307 /* Only change directory when we are sure we can return to where
2308 * we are now. After doing "su" chdir(".") might not work. */
2313 (mch_dirname(olddir
, MAXPATHL
) == FAIL
2314 || mch_chdir((char *)olddir
) != 0))
2316 p
= NULL
; /* can't get current dir: don't chdir */
2323 * compensate for case where ':' from "D:" was the only
2324 * path separator detected in the file name; the _next_
2325 * character has to be removed, and then restored later.
2330 /* The directory is copied into buf[], to be able to remove
2331 * the file name without changing it (could be a string in
2332 * read-only memory) */
2333 if (p
- fname
>= len
)
2337 vim_strncpy(buf
, fname
, p
- fname
);
2338 if (mch_chdir((char *)buf
))
2354 if (mch_dirname(buf
, len
) == FAIL
)
2369 l
= mch_chdir((char *)olddir
);
2371 EMSG(_(e_prev_dir
));
2380 if (l
> 0 && buf
[l
- 1] != '/' && *fname
!= NUL
2381 && STRCMP(fname
, ".") != 0)
2387 /* Catch file names which are too long. */
2388 if (retval
== FAIL
|| STRLEN(buf
) + STRLEN(fname
) >= len
)
2391 /* Do not append ".", "/dir/." is equal to "/dir". */
2392 if (STRCMP(fname
, ".") != 0)
2399 * Return TRUE if "fname" does not depend on the current directory.
2402 mch_isFullName(fname
)
2406 return _fnisabs(fname
);
2409 return ( fname
[0] == '/' || fname
[0] == '.' ||
2410 strchr((char *)fname
,':') || strchr((char *)fname
,'"') ||
2411 (strchr((char *)fname
,'[') && strchr((char *)fname
,']'))||
2412 (strchr((char *)fname
,'<') && strchr((char *)fname
,'>')) );
2414 return (*fname
== '/' || *fname
== '~');
2419 #if defined(USE_FNAME_CASE) || defined(PROTO)
2421 * Set the case of the file name, if it already exists. This will cause the
2422 * file name to remain exactly the same.
2423 * Only required for file systems where case is ingored and preserved.
2427 fname_case(name
, len
)
2429 int len
; /* buffer size, only used when name gets longer */
2432 char_u
*slash
, *tail
;
2436 if (lstat((char *)name
, &st
) >= 0)
2438 /* Open the directory where the file is located. */
2439 slash
= vim_strrchr(name
, '/');
2442 dirp
= opendir(".");
2448 dirp
= opendir((char *)name
);
2455 while ((dp
= readdir(dirp
)) != NULL
)
2457 /* Only accept names that differ in case and are the same byte
2458 * length. TODO: accept different length name. */
2459 if (STRICMP(tail
, dp
->d_name
) == 0
2460 && STRLEN(tail
) == STRLEN(dp
->d_name
))
2462 char_u newname
[MAXPATHL
+ 1];
2465 /* Verify the inode is equal. */
2466 vim_strncpy(newname
, name
, MAXPATHL
);
2467 vim_strncpy(newname
+ (tail
- name
), (char_u
*)dp
->d_name
,
2468 MAXPATHL
- (tail
- name
));
2469 if (lstat((char *)newname
, &st2
) >= 0
2470 && st
.st_ino
== st2
.st_ino
2471 && st
.st_dev
== st2
.st_dev
)
2473 STRCPY(tail
, dp
->d_name
);
2486 * Get file permissions for 'name'.
2487 * Returns -1 when it doesn't exist.
2495 /* Keep the #ifdef outside of stat(), it may be a macro. */
2497 if (stat((char *)vms_fixfilename(name
), &statb
))
2499 if (stat((char *)name
, &statb
))
2502 return statb
.st_mode
;
2506 * set file permission for 'name' to 'perm'
2508 * return FAIL for failure, OK otherwise
2511 mch_setperm(name
, perm
)
2515 return (chmod((char *)
2517 vms_fixfilename(name
),
2521 (mode_t
)perm
) == 0 ? OK
: FAIL
);
2524 #if defined(HAVE_ACL) || defined(PROTO)
2525 # ifdef HAVE_SYS_ACL_H
2526 # include <sys/acl.h>
2528 # ifdef HAVE_SYS_ACCESS_H
2529 # include <sys/access.h>
2532 # ifdef HAVE_SOLARIS_ACL
2533 typedef struct vim_acl_solaris_T
{
2535 aclent_t
*acl_entry
;
2536 } vim_acl_solaris_T
;
2540 * Return a pointer to the ACL of file "fname" in allocated memory.
2541 * Return NULL if the ACL is not available for whatever reason.
2547 vim_acl_T ret
= NULL
;
2548 #ifdef HAVE_POSIX_ACL
2549 ret
= (vim_acl_T
)acl_get_file((char *)fname
, ACL_TYPE_ACCESS
);
2551 #ifdef HAVE_SOLARIS_ACL
2552 vim_acl_solaris_T
*aclent
;
2554 aclent
= malloc(sizeof(vim_acl_solaris_T
));
2555 if ((aclent
->acl_cnt
= acl((char *)fname
, GETACLCNT
, 0, NULL
)) < 0)
2560 aclent
->acl_entry
= malloc(aclent
->acl_cnt
* sizeof(aclent_t
));
2561 if (acl((char *)fname
, GETACL
, aclent
->acl_cnt
, aclent
->acl_entry
) < 0)
2563 free(aclent
->acl_entry
);
2567 ret
= (vim_acl_T
)aclent
;
2569 #if defined(HAVE_AIX_ACL)
2573 aclsize
= sizeof(struct acl
);
2574 aclent
= malloc(aclsize
);
2575 if (statacl((char *)fname
, STX_NORMAL
, aclent
, aclsize
) < 0)
2577 if (errno
== ENOSPC
)
2579 aclsize
= aclent
->acl_len
;
2580 aclent
= realloc(aclent
, aclsize
);
2581 if (statacl((char *)fname
, STX_NORMAL
, aclent
, aclsize
) < 0)
2593 ret
= (vim_acl_T
)aclent
;
2594 #endif /* HAVE_AIX_ACL */
2595 #endif /* HAVE_SOLARIS_ACL */
2596 #endif /* HAVE_POSIX_ACL */
2601 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2604 mch_set_acl(fname
, aclent
)
2610 #ifdef HAVE_POSIX_ACL
2611 acl_set_file((char *)fname
, ACL_TYPE_ACCESS
, (acl_t
)aclent
);
2613 #ifdef HAVE_SOLARIS_ACL
2614 acl((char *)fname
, SETACL
, ((vim_acl_solaris_T
*)aclent
)->acl_cnt
,
2615 ((vim_acl_solaris_T
*)aclent
)->acl_entry
);
2618 chacl((char *)fname
, aclent
, ((struct acl
*)aclent
)->acl_len
);
2619 #endif /* HAVE_AIX_ACL */
2620 #endif /* HAVE_SOLARIS_ACL */
2621 #endif /* HAVE_POSIX_ACL */
2625 mch_free_acl(aclent
)
2630 #ifdef HAVE_POSIX_ACL
2631 acl_free((acl_t
)aclent
);
2633 #ifdef HAVE_SOLARIS_ACL
2634 free(((vim_acl_solaris_T
*)aclent
)->acl_entry
);
2639 #endif /* HAVE_AIX_ACL */
2640 #endif /* HAVE_SOLARIS_ACL */
2641 #endif /* HAVE_POSIX_ACL */
2646 * Set hidden flag for "name".
2653 /* can't hide a file */
2657 * return TRUE if "name" is a directory
2658 * return FALSE if "name" is not a directory
2659 * return FALSE for error
2667 if (*name
== NUL
) /* Some stat()s don't flag "" as an error. */
2669 if (stat((char *)name
, &statb
))
2671 #ifdef _POSIX_SOURCE
2672 return (S_ISDIR(statb
.st_mode
) ? TRUE
: FALSE
);
2674 return ((statb
.st_mode
& S_IFMT
) == S_IFDIR
? TRUE
: FALSE
);
2678 static int executable_file
__ARGS((char_u
*name
));
2681 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
2684 executable_file(name
)
2689 if (stat((char *)name
, &st
))
2691 return S_ISREG(st
.st_mode
) && mch_access((char *)name
, X_OK
) == 0;
2695 * Return 1 if "name" can be found in $PATH and executed, 0 if not.
2696 * Return -1 if unknown.
2706 /* If it's an absolute or relative path don't need to use $PATH. */
2707 if (mch_isFullName(name
) || (name
[0] == '.' && (name
[1] == '/'
2708 || (name
[1] == '.' && name
[2] == '/'))))
2709 return executable_file(name
);
2711 p
= (char_u
*)getenv("PATH");
2712 if (p
== NULL
|| *p
== NUL
)
2714 buf
= alloc((unsigned)(STRLEN(name
) + STRLEN(p
) + 2));
2719 * Walk through all entries in $PATH to check if "name" exists there and
2720 * is an executable file.
2724 e
= (char_u
*)strchr((char *)p
, ':');
2727 if (e
- p
<= 1) /* empty entry means current dir */
2731 vim_strncpy(buf
, p
, e
- p
);
2735 retval
= executable_file(buf
);
2749 * Check what "name" is:
2750 * NODE_NORMAL: file or directory (or doesn't exist)
2751 * NODE_WRITABLE: writable device, socket, fifo, etc.
2752 * NODE_OTHER: non-writable things
2760 if (stat((char *)name
, &st
))
2762 if (S_ISREG(st
.st_mode
) || S_ISDIR(st
.st_mode
))
2765 if (S_ISBLK(st
.st_mode
)) /* block device isn't writable */
2768 /* Everything else is writable? */
2769 return NODE_WRITABLE
;
2775 #ifdef HAVE_CHECK_STACK_GROWTH
2778 check_stack_growth((char *)&i
);
2780 # ifdef HAVE_STACK_LIMIT
2787 * Setup an alternative stack for signals. Helps to catch signals when
2788 * running out of stack space.
2789 * Use of sigaltstack() is preferred, it's more portable.
2790 * Ignore any errors.
2792 #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2793 signal_stack
= malloc(SIGSTKSZ
);
2794 init_signal_stack();
2798 #if defined(EXITFREE) || defined(PROTO)
2802 # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
2803 if (clip_star
.owned
)
2804 clip_lose_selection(&clip_star
);
2805 if (clip_plus
.owned
)
2806 clip_lose_selection(&clip_plus
);
2808 # if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
2809 if (xterm_Shell
!= (Widget
)0)
2810 XtDestroyWidget(xterm_Shell
);
2811 if (xterm_dpy
!= NULL
)
2812 XtCloseDisplay(xterm_dpy
);
2813 if (app_context
!= (XtAppContext
)NULL
)
2814 XtDestroyApplicationContext(app_context
);
2817 if (x11_display
!= NULL
&& x11_display
!= xterm_dpy
)
2818 XCloseDisplay(x11_display
);
2820 # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
2821 vim_free(signal_stack
);
2822 signal_stack
= NULL
;
2831 static void exit_scroll
__ARGS((void));
2834 * Output a newline when exiting.
2835 * Make sure the newline goes to the same stream as the text.
2842 if (newline_on_exit
|| msg_didout
)
2844 if (msg_use_printf())
2856 restore_cterm_colors(); /* get original colors back */
2857 msg_clr_eos_force(); /* clear the rest of the display */
2858 windgoto((int)Rows
- 1, 0); /* may have moved the cursor */
2868 #if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
2869 x11_export_final_selection();
2876 settmode(TMODE_COOK
);
2878 mch_restore_title(3); /* restore xterm title and icon name */
2881 * When t_ti is not empty but it doesn't cause swapping terminal
2882 * pages, need to output a newline when msg_didout is set. But when
2883 * t_ti does swap pages it should not go to the shell page. Do this
2884 * before stoptermcap().
2886 if (swapping_screen() && !newline_on_exit
)
2889 /* Stop termcap: May need to check for T_CRV response, which
2890 * requires RAW mode. */
2894 * A newline is only required after a message in the alternate screen.
2895 * This is set to TRUE by wait_return().
2897 if (!swapping_screen() || newline_on_exit
)
2900 /* Cursor may have been switched off without calling starttermcap()
2901 * when doing "vim -u vimrc" and vimrc contains ":q". */
2906 ml_close_all(TRUE
); /* remove all memfiles */
2913 #ifdef MACOS_CONVERT
2918 /* A core dump won't be created if the signal handler
2919 * doesn't return, so we can't call exit() */
2920 if (deadly_signal
!= 0)
2924 #ifdef FEAT_NETBEANS_INTG
2926 netbeans_send_disconnect();
2939 if (deadly_signal
!= 0)
2941 signal(deadly_signal
, SIG_DFL
);
2942 kill(getpid(), deadly_signal
); /* Die using the signal we caught */
2952 static int first
= TRUE
;
2954 /* Why is NeXT excluded here (and not in os_unixx.h)? */
2955 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
2957 * for "new" tty systems
2959 # ifdef HAVE_TERMIOS_H
2960 static struct termios told
;
2961 struct termios tnew
;
2963 static struct termio told
;
2970 # if defined(HAVE_TERMIOS_H)
2971 tcgetattr(read_cmd_fd
, &told
);
2973 ioctl(read_cmd_fd
, TCGETA
, &told
);
2978 if (tmode
== TMODE_RAW
)
2981 * ~ICRNL enables typing ^V^M
2983 tnew
.c_iflag
&= ~ICRNL
;
2984 tnew
.c_lflag
&= ~(ICANON
| ECHO
| ISIG
| ECHOE
2985 # if defined(IEXTEN) && !defined(__MINT__)
2986 | IEXTEN
/* IEXTEN enables typing ^V on SOLARIS */
2987 /* but it breaks function keys on MINT */
2990 # ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
2991 tnew
.c_oflag
&= ~ONLCR
;
2993 tnew
.c_cc
[VMIN
] = 1; /* return after 1 char */
2994 tnew
.c_cc
[VTIME
] = 0; /* don't wait */
2996 else if (tmode
== TMODE_SLEEP
)
2997 tnew
.c_lflag
&= ~(ECHO
);
2999 # if defined(HAVE_TERMIOS_H)
3003 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3005 while (tcsetattr(read_cmd_fd
, TCSANOW
, &tnew
) == -1
3006 && errno
== EINTR
&& n
> 0)
3010 ioctl(read_cmd_fd
, TCSETA
, &tnew
);
3016 * for "old" tty systems
3019 # define TIOCSETN TIOCSETP /* for hpux 9.0 */
3021 static struct sgttyb ttybold
;
3022 struct sgttyb ttybnew
;
3027 ioctl(read_cmd_fd
, TIOCGETP
, &ttybold
);
3031 if (tmode
== TMODE_RAW
)
3033 ttybnew
.sg_flags
&= ~(CRMOD
| ECHO
);
3034 ttybnew
.sg_flags
|= RAW
;
3036 else if (tmode
== TMODE_SLEEP
)
3037 ttybnew
.sg_flags
&= ~(ECHO
);
3038 ioctl(read_cmd_fd
, TIOCSETN
, &ttybnew
);
3044 * Try to get the code for "t_kb" from the stty setting
3046 * Even if termcap claims a backspace key, the user's setting *should*
3047 * prevail. stty knows more about reality than termcap does, and if
3048 * somebody's usual erase key is DEL (which, for most BSD users, it will
3049 * be), they're going to get really annoyed if their erase key starts
3050 * doing forward deletes for no reason. (Eric Fischer)
3058 /* Why is NeXT excluded here (and not in os_unixx.h)? */
3059 #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
3060 /* for "new" tty systems */
3061 # ifdef HAVE_TERMIOS_H
3062 struct termios keys
;
3067 # if defined(HAVE_TERMIOS_H)
3068 if (tcgetattr(read_cmd_fd
, &keys
) != -1)
3070 if (ioctl(read_cmd_fd
, TCGETA
, &keys
) != -1)
3073 buf
[0] = keys
.c_cc
[VERASE
];
3074 intr_char
= keys
.c_cc
[VINTR
];
3076 /* for "old" tty systems */
3079 if (ioctl(read_cmd_fd
, TIOCGETP
, &keys
) != -1)
3081 buf
[0] = keys
.sg_erase
;
3082 intr_char
= keys
.sg_kill
;
3085 add_termcode((char_u
*)"kb", buf
, FALSE
);
3088 * If <BS> and <DEL> are now the same, redefine <DEL>.
3090 p
= find_termcode((char_u
*)"kD");
3091 if (p
!= NULL
&& p
[0] == buf
[0] && p
[1] == buf
[1])
3095 } /* to keep cindent happy */
3101 #if defined(FEAT_MOUSE_TTY) || defined(PROTO)
3103 * Set mouse clicks on or off.
3109 static int ison
= FALSE
;
3110 int xterm_mouse_vers
;
3112 if (on
== ison
) /* return quickly if nothing to do */
3115 xterm_mouse_vers
= use_xterm_mouse();
3116 if (xterm_mouse_vers
> 0)
3118 if (on
) /* enable mouse events, use mouse tracking if available */
3119 out_str_nf((char_u
*)
3120 (xterm_mouse_vers
> 1
3121 ? IF_EB("\033[?1002h", ESC_STR
"[?1002h")
3122 : IF_EB("\033[?1000h", ESC_STR
"[?1000h")));
3123 else /* disable mouse events, could probably always send the same */
3124 out_str_nf((char_u
*)
3125 (xterm_mouse_vers
> 1
3126 ? IF_EB("\033[?1002l", ESC_STR
"[?1002l")
3127 : IF_EB("\033[?1000l", ESC_STR
"[?1000l")));
3131 # ifdef FEAT_MOUSE_DEC
3132 else if (ttym_flags
== TTYM_DEC
)
3134 if (on
) /* enable mouse events */
3135 out_str_nf((char_u
*)"\033[1;2'z\033[1;3'{");
3136 else /* disable mouse events */
3137 out_str_nf((char_u
*)"\033['z");
3142 # ifdef FEAT_MOUSE_GPM
3158 # ifdef FEAT_MOUSE_JSB
3163 /* D - Enable Mouse up/down messages
3164 * L - Enable Left Button Reporting
3165 * M - Enable Middle Button Reporting
3166 * R - Enable Right Button Reporting
3167 * K - Enable SHIFT and CTRL key Reporting
3168 * + - Enable Advanced messaging of mouse moves and up/down messages
3170 * # - Numeric value of mouse pointer required
3171 * 0 = Multiview 2000 cursor, used as standard
3173 * 2 = Windows I Beam
3174 * 3 = Windows Hour Glass
3175 * 4 = Windows Cross Hair
3176 * 5 = Windows UP Arrow
3178 #ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */
3179 out_str_nf((char_u
*)IF_EB("\033[0~ZwLMRK1Q\033\\",
3180 ESC_STR
"[0~ZwLMRK1Q" ESC_STR
"\\"));
3182 out_str_nf((char_u
*)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3183 ESC_STR
"[0~ZwLMRK+1Q" ESC_STR
"\\"));
3189 out_str_nf((char_u
*)IF_EB("\033[0~ZwQ\033\\",
3190 ESC_STR
"[0~ZwQ" ESC_STR
"\\"));
3195 # ifdef FEAT_MOUSE_PTERM
3198 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3200 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3202 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
3209 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3212 check_mouse_termcode()
3214 # ifdef FEAT_MOUSE_XTERM
3215 if (use_xterm_mouse()
3221 set_mouse_termcode(KS_MOUSE
, (char_u
*)(term_is_8bit(T_NAME
)
3222 ? IF_EB("\233M", CSI_STR
"M")
3223 : IF_EB("\033[M", ESC_STR
"[M")));
3224 if (*p_mouse
!= NUL
)
3226 /* force mouse off and maybe on to send possibly new mouse
3227 * activation sequence to the xterm, with(out) drag tracing. */
3228 mch_setmouse(FALSE
);
3233 del_mouse_termcode(KS_MOUSE
);
3236 # ifdef FEAT_MOUSE_GPM
3237 if (!use_xterm_mouse()
3242 set_mouse_termcode(KS_MOUSE
, (char_u
*)IF_EB("\033MG", ESC_STR
"MG"));
3245 # ifdef FEAT_MOUSE_JSB
3246 /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */
3247 if (!use_xterm_mouse()
3252 set_mouse_termcode(KS_JSBTERM_MOUSE
,
3253 (char_u
*)IF_EB("\033[0~zw", ESC_STR
"[0~zw"));
3255 del_mouse_termcode(KS_JSBTERM_MOUSE
);
3258 # ifdef FEAT_MOUSE_NET
3259 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
3260 * define it in the GUI or when using an xterm. */
3261 if (!use_xterm_mouse()
3266 set_mouse_termcode(KS_NETTERM_MOUSE
,
3267 (char_u
*)IF_EB("\033}", ESC_STR
"}"));
3269 del_mouse_termcode(KS_NETTERM_MOUSE
);
3272 # ifdef FEAT_MOUSE_DEC
3273 /* conflicts with xterm mouse: "\033[" and "\033[M" */
3274 if (!use_xterm_mouse()
3279 set_mouse_termcode(KS_DEC_MOUSE
, (char_u
*)(term_is_8bit(T_NAME
)
3280 ? IF_EB("\233", CSI_STR
) : IF_EB("\033[", ESC_STR
"[")));
3282 del_mouse_termcode(KS_DEC_MOUSE
);
3284 # ifdef FEAT_MOUSE_PTERM
3285 /* same as the dec mouse */
3286 if (!use_xterm_mouse()
3291 set_mouse_termcode(KS_PTERM_MOUSE
,
3292 (char_u
*) IF_EB("\033[", ESC_STR
"["));
3294 del_mouse_termcode(KS_PTERM_MOUSE
);
3300 * set screen mode, always fails.
3307 EMSG(_(e_screenmode
));
3314 * Try to get the current window size:
3315 * 1. with an ioctl(), most accurate method
3316 * 2. from the environment variables LINES and COLUMNS
3317 * 3. from the termcap
3318 * 4. keep using the old values
3319 * Return OK when size could be determined, FAIL otherwise.
3329 * For OS/2 use _scrsize().
3342 * 1. try using an ioctl. It is the most accurate method.
3344 * Try using TIOCGWINSZ first, some systems that have it also define
3345 * TIOCGSIZE but don't have a struct ttysize.
3352 /* When stdout is not a tty, use stdin for the ioctl(). */
3353 if (!isatty(fd
) && isatty(read_cmd_fd
))
3355 if (ioctl(fd
, TIOCGWINSZ
, &ws
) == 0)
3357 columns
= ws
.ws_col
;
3361 # else /* TIOCGWINSZ */
3367 /* When stdout is not a tty, use stdin for the ioctl(). */
3368 if (!isatty(fd
) && isatty(read_cmd_fd
))
3370 if (ioctl(fd
, TIOCGSIZE
, &ts
) == 0)
3372 columns
= ts
.ts_cols
;
3376 # endif /* TIOCGSIZE */
3377 # endif /* TIOCGWINSZ */
3380 * 2. get size from environment
3381 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
3382 * the ioctl() values!
3384 if (columns
== 0 || rows
== 0 || vim_strchr(p_cpo
, CPO_TSIZE
) != NULL
)
3386 if ((p
= (char_u
*)getenv("LINES")))
3387 rows
= atoi((char *)p
);
3388 if ((p
= (char_u
*)getenv("COLUMNS")))
3389 columns
= atoi((char *)p
);
3394 * 3. try reading "co" and "li" entries from termcap
3396 if (columns
== 0 || rows
== 0)
3397 getlinecol(&columns
, &rows
);
3401 * 4. If everything fails, use the old values
3403 if (columns
<= 0 || rows
<= 0)
3412 * Try to set the window size to Rows and Columns.
3420 * NOTE: if you get an error here that term_set_winsize() is
3421 * undefined, check the output of configure. It could probably not
3422 * find a ncurses, termcap or termlib library.
3424 term_set_winsize((int)Rows
, (int)Columns
);
3426 screen_start(); /* don't know where cursor is now */
3433 * Rows and/or Columns has changed.
3438 /* Nothing to do. */
3442 static void append_ga_line
__ARGS((garray_T
*gap
));
3445 * Append the text in "gap" below the cursor line and clear "gap".
3451 /* Remove trailing CR. */
3454 && ((char_u
*)gap
->ga_data
)[gap
->ga_len
- 1] == CAR
)
3456 ga_append(gap
, NUL
);
3457 ml_append(curwin
->w_cursor
.lnum
++, gap
->ga_data
, 0, FALSE
);
3463 mch_call_shell(cmd
, options
)
3465 int options
; /* SHELL_*, see vim.h */
3471 int tmode
= cur_tmode
;
3472 #ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */
3475 char_u
*newcmd
; /* only needed for unix */
3478 * Set the preferred shell in the EMXSHELL environment variable (but
3479 * only if it is different from what is already in the environment).
3480 * Emx then takes care of whether to use "/c" or "-c" in an
3481 * intelligent way. Simply pass the whole thing to emx's system() call.
3482 * Emx also starts an interactive shell if system() is passed an empty
3487 if (((old
= (char_u
*)getenv("EMXSHELL")) == NULL
) || STRCMP(old
, p_sh
))
3489 /* should check HAVE_SETENV, but I know we don't have it. */
3490 p
= alloc(10 + strlen(p_sh
));
3493 sprintf((char *)p
, "EMXSHELL=%s", p_sh
);
3494 putenv((char *)p
); /* don't free the pointer! */
3501 if (options
& SHELL_COOKED
)
3502 settmode(TMODE_COOK
); /* set to normal mode */
3506 x
= system(""); /* this starts an interactive shell in emx */
3508 x
= system((char *)cmd
);
3509 /* system() returns -1 when error occurs in starting shell */
3510 if (x
== -1 && !emsg_silent
)
3512 MSG_PUTS(_("\nCannot execute shell "));
3516 # else /* not __EMX__ */
3518 x
= system((char *)p_sh
);
3522 if (ofn
= strchr((char *)cmd
, '>'))
3524 if (ifn
= strchr((char *)cmd
, '<'))
3529 p
= strchr(ifn
,' '); /* chop off any trailing spaces */
3534 x
= vms_sys((char *)cmd
, ofn
, ifn
);
3536 x
= system((char *)cmd
);
3538 newcmd
= lalloc(STRLEN(p_sh
)
3539 + (extra_shell_arg
== NULL
? 0 : STRLEN(extra_shell_arg
))
3540 + STRLEN(p_shcf
) + STRLEN(cmd
) + 4, TRUE
);
3545 sprintf((char *)newcmd
, "%s %s %s %s", p_sh
,
3546 extra_shell_arg
== NULL
? "" : (char *)extra_shell_arg
,
3549 x
= system((char *)newcmd
);
3555 x
= vms_sys_status(x
);
3560 MSG_PUTS(_("\nCannot execute shell sh\n"));
3561 # endif /* __EMX__ */
3562 else if (x
&& !(options
& SHELL_SILENT
))
3564 MSG_PUTS(_("\nshell returned "));
3565 msg_outnum((long)x
);
3569 if (tmode
== TMODE_RAW
)
3570 settmode(TMODE_RAW
); /* set to raw mode */
3576 #else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */
3578 # define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
3579 127, some shells use that already */
3581 char_u
*newcmd
= NULL
;
3585 # ifdef HAVE_UNION_WAIT
3596 int pty_master_fd
= -1; /* for pty's */
3598 int pty_slave_fd
= -1;
3601 int fd_toshell
[2]; /* for pipes */
3602 int fd_fromshell
[2];
3603 int pipe_error
= FALSE
;
3607 static char envbuf_Rows
[20];
3608 static char envbuf_Columns
[20];
3610 int did_settmode
= FALSE
; /* settmode(TMODE_RAW) called */
3613 if (options
& SHELL_COOKED
)
3614 settmode(TMODE_COOK
); /* set to normal mode */
3616 newcmd
= vim_strsave(p_sh
);
3617 if (newcmd
== NULL
) /* out of memory */
3621 * Do this loop twice:
3622 * 1: find number of arguments
3623 * 2: separate them and build argv[]
3625 for (i
= 0; i
< 2; ++i
)
3633 argv
[argc
] = (char *)p
;
3635 while (*p
&& (inquote
|| (*p
!= ' ' && *p
!= TAB
)))
3649 argv
= (char **)alloc((unsigned)((argc
+ 4) * sizeof(char *)));
3650 if (argv
== NULL
) /* out of memory */
3656 if (extra_shell_arg
!= NULL
)
3657 argv
[argc
++] = (char *)extra_shell_arg
;
3658 argv
[argc
++] = (char *)p_shcf
;
3659 argv
[argc
++] = (char *)cmd
;
3664 * For the GUI, when writing the output into the buffer and when reading
3665 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
3666 * of the executed command into the Vim window. Or use a pipe.
3668 if ((options
& (SHELL_READ
|SHELL_WRITE
))
3670 || (gui
.in_use
&& show_shell_mess
)
3676 * Try to open a master pty.
3677 * If this works, open the slave pty.
3678 * If the slave can't be opened, close the master pty.
3680 if (p_guipty
&& !(options
& (SHELL_READ
|SHELL_WRITE
)))
3682 pty_master_fd
= OpenPTY(&tty_name
); /* open pty */
3683 if (pty_master_fd
>= 0 && ((pty_slave_fd
=
3684 open(tty_name
, O_RDWR
| O_EXTRA
, 0)) < 0))
3686 close(pty_master_fd
);
3691 * If not opening a pty or it didn't work, try using pipes.
3693 if (pty_master_fd
< 0)
3696 pipe_error
= (pipe(fd_toshell
) < 0);
3697 if (!pipe_error
) /* pipe create OK */
3699 pipe_error
= (pipe(fd_fromshell
) < 0);
3700 if (pipe_error
) /* pipe create failed */
3702 close(fd_toshell
[0]);
3703 close(fd_toshell
[1]);
3708 MSG_PUTS(_("\nCannot create pipes\n"));
3714 if (!pipe_error
) /* pty or pipe opened or not used */
3717 beos_cleanup_read_thread();
3720 if ((pid
= fork()) == -1) /* maybe we should use vfork() */
3722 MSG_PUTS(_("\nCannot fork\n"));
3723 if ((options
& (SHELL_READ
|SHELL_WRITE
))
3725 || (gui
.in_use
&& show_shell_mess
)
3730 if (pty_master_fd
>= 0) /* close the pseudo tty */
3732 close(pty_master_fd
);
3733 close(pty_slave_fd
);
3735 else /* close the pipes */
3738 close(fd_toshell
[0]);
3739 close(fd_toshell
[1]);
3740 close(fd_fromshell
[0]);
3741 close(fd_fromshell
[1]);
3745 else if (pid
== 0) /* child */
3747 reset_signals(); /* handle signals normally */
3749 if (!show_shell_mess
|| (options
& SHELL_EXPAND
))
3754 * Don't want to show any message from the shell. Can't just
3755 * close stdout and stderr though, because some systems will
3756 * break if you try to write to them after that, so we must
3757 * use dup() to replace them with something else -- webb
3758 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
3759 * waiting for input.
3761 fd
= open("/dev/null", O_RDWR
| O_EXTRA
, 0);
3767 * If any of these open()'s and dup()'s fail, we just continue
3768 * anyway. It's not fatal, and on most systems it will make
3769 * no difference at all. On a few it will cause the execvp()
3770 * to exit with a non-zero status even when the completion
3771 * could be done, which is nothing too serious. If the open()
3772 * or dup() failed we'd just do the same thing ourselves
3777 dup(fd
); /* To replace stdin (file descriptor 0) */
3778 dup(fd
); /* To replace stdout (file descriptor 1) */
3779 dup(fd
); /* To replace stderr (file descriptor 2) */
3781 /* Don't need this now that we've duplicated it */
3785 else if ((options
& (SHELL_READ
|SHELL_WRITE
))
3793 /* Create our own process group, so that the child and all its
3794 * children can be kill()ed. Don't do this when using pipes,
3795 * because stdin is not a tty, we would loose /dev/tty. */
3800 if (pty_slave_fd
>= 0)
3802 /* push stream discipline modules */
3803 if (options
& SHELL_COOKED
)
3804 SetupSlavePTY(pty_slave_fd
);
3806 /* Try to become controlling tty (probably doesn't work,
3807 * unless run by root) */
3808 ioctl(pty_slave_fd
, TIOCSCTTY
, (char *)NULL
);
3812 /* Simulate to have a dumb terminal (for now) */
3814 setenv("TERM", "dumb", 1);
3815 sprintf((char *)envbuf
, "%ld", Rows
);
3816 setenv("ROWS", (char *)envbuf
, 1);
3817 sprintf((char *)envbuf
, "%ld", Rows
);
3818 setenv("LINES", (char *)envbuf
, 1);
3819 sprintf((char *)envbuf
, "%ld", Columns
);
3820 setenv("COLUMNS", (char *)envbuf
, 1);
3823 * Putenv does not copy the string, it has to remain valid.
3824 * Use a static array to avoid loosing allocated memory.
3826 putenv("TERM=dumb");
3827 sprintf(envbuf_Rows
, "ROWS=%ld", Rows
);
3828 putenv(envbuf_Rows
);
3829 sprintf(envbuf_Rows
, "LINES=%ld", Rows
);
3830 putenv(envbuf_Rows
);
3831 sprintf(envbuf_Columns
, "COLUMNS=%ld", Columns
);
3832 putenv(envbuf_Columns
);
3836 * stderr is only redirected when using the GUI, so that a
3837 * program like gpg can still access the terminal to get a
3838 * passphrase using stderr.
3841 if (pty_master_fd
>= 0)
3843 close(pty_master_fd
); /* close master side of pty */
3845 /* set up stdin/stdout/stderr for the child */
3856 close(pty_slave_fd
); /* has been dupped, close it now */
3861 /* set up stdin for the child */
3862 close(fd_toshell
[1]);
3865 close(fd_toshell
[0]);
3867 /* set up stdout for the child */
3868 close(fd_fromshell
[0]);
3870 dup(fd_fromshell
[1]);
3871 close(fd_fromshell
[1]);
3876 /* set up stderr for the child */
3885 * There is no type cast for the argv, because the type may be
3886 * different on different machines. This may cause a warning
3887 * message with strict compilers, don't worry about it.
3888 * Call _exit() instead of exit() to avoid closing the connection
3889 * to the X server (esp. with GTK, which uses atexit()).
3891 execvp(argv
[0], argv
);
3892 _exit(EXEC_FAILED
); /* exec failed, return failure code */
3897 * While child is running, ignore terminating signals.
3898 * Do catch CTRL-C, so that "got_int" is set.
3900 catch_signals(SIG_IGN
, SIG_ERR
);
3904 * For the GUI we redirect stdin, stdout and stderr to our window.
3905 * This is also used to pipe stdin/stdout to/from the external
3908 if ((options
& (SHELL_READ
|SHELL_WRITE
))
3910 || (gui
.in_use
&& show_shell_mess
)
3914 # define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
3915 char_u buffer
[BUFLEN
+ 1];
3917 int buffer_off
= 0; /* valid bytes in buffer[] */
3919 char_u ta_buf
[BUFLEN
+ 1]; /* TypeAHead */
3920 int ta_len
= 0; /* valid bytes in ta_buf[] */
3931 if (pty_master_fd
>= 0)
3933 close(pty_slave_fd
); /* close slave side of pty */
3934 fromshell_fd
= pty_master_fd
;
3935 toshell_fd
= dup(pty_master_fd
);
3940 close(fd_toshell
[0]);
3941 close(fd_fromshell
[1]);
3942 toshell_fd
= fd_toshell
[1];
3943 fromshell_fd
= fd_fromshell
[0];
3947 * Write to the child if there are typed characters.
3948 * Read from the child if there are characters available.
3949 * Repeat the reading a few times if more characters are
3950 * available. Need to check for typed keys now and then, but
3951 * not too often (delays when no chars are available).
3952 * This loop is quit if no characters can be read from the pty
3953 * (WaitForChar detected special condition), or there are no
3954 * characters available and the child has exited.
3955 * Only check if the child has exited when there is no more
3956 * output. The child may exit before all the output has
3959 * Currently this busy loops!
3960 * This can probably dead-lock when the write blocks!
3962 p_more_save
= p_more
;
3965 State
= EXTERNCMD
; /* don't redraw at window resize */
3967 if ((options
& SHELL_WRITE
) && toshell_fd
>= 0)
3969 /* Fork a process that will write the lines to the
3970 * external program. */
3971 if ((wpid
= fork()) == -1)
3973 MSG_PUTS(_("\nCannot fork\n"));
3977 linenr_T lnum
= curbuf
->b_op_start
.lnum
;
3979 char_u
*lp
= ml_get(lnum
);
3984 close(fromshell_fd
);
3987 l
= STRLEN(lp
+ written
);
3990 else if (lp
[written
] == NL
)
3991 /* NL -> NUL translation */
3992 len
= write(toshell_fd
, "", (size_t)1);
3995 s
= vim_strchr(lp
+ written
, NL
);
3996 len
= write(toshell_fd
, (char *)lp
+ written
,
3997 s
== NULL
? l
: s
- (lp
+ written
));
4001 /* Finished a line, add a NL, unless this line
4002 * should not have one. */
4003 if (lnum
!= curbuf
->b_op_end
.lnum
4005 || (lnum
!= write_no_eol_lnum
4007 curbuf
->b_ml
.ml_line_count
4008 || curbuf
->b_p_eol
)))
4009 write(toshell_fd
, "\n", (size_t)1);
4011 if (lnum
> curbuf
->b_op_end
.lnum
)
4013 /* finished all the lines, close pipe */
4033 if (options
& SHELL_READ
)
4034 ga_init2(&ga
, 1, BUFLEN
);
4041 * Check if keys have been typed, write them to the child
4043 * Don't do this if we are expanding wild cards (would eat
4045 * Don't do this when filtering and terminal is in cooked
4046 * mode, the shell command will handle the I/O. Avoids
4047 * that a typed password is echoed for ssh or gpg command.
4048 * Don't get characters when the child has already
4049 * finished (wait_pid == 0).
4050 * Don't get extra characters when we already have one.
4051 * Don't read characters unless we didn't get output for a
4052 * while, avoids that ":r !ls" eats typeahead.
4055 if (!(options
& SHELL_EXPAND
)
4057 (SHELL_READ
|SHELL_WRITE
|SHELL_COOKED
))
4058 != (SHELL_READ
|SHELL_WRITE
|SHELL_COOKED
)
4066 && (len
= ui_inchar(ta_buf
,
4067 BUFLEN
, 10L, 0)) > 0)))
4071 * Check for CTRL-C: send interrupt signal to child.
4072 * Check for CTRL-D: EOF, close pipe to child.
4074 if (len
== 1 && (pty_master_fd
< 0 || cmd
!= NULL
))
4078 * Send SIGINT to the child's group or all
4079 * processes in our group.
4081 if (ta_buf
[ta_len
] == Ctrl_C
4082 || ta_buf
[ta_len
] == intr_char
)
4093 if (pty_master_fd
< 0 && toshell_fd
>= 0
4094 && ta_buf
[ta_len
] == Ctrl_D
)
4101 /* replace K_BS by <BS> and K_DEL by <DEL> */
4102 for (i
= ta_len
; i
< ta_len
+ len
; ++i
)
4104 if (ta_buf
[i
] == CSI
&& len
- i
> 2)
4106 c
= TERMCAP2KEY(ta_buf
[i
+ 1], ta_buf
[i
+ 2]);
4107 if (c
== K_DEL
|| c
== K_KDEL
|| c
== K_BS
)
4109 mch_memmove(ta_buf
+ i
+ 1, ta_buf
+ i
+ 3,
4110 (size_t)(len
- i
- 2));
4111 if (c
== K_DEL
|| c
== K_KDEL
)
4118 else if (ta_buf
[i
] == '\r')
4122 i
+= (*mb_ptr2len
)(ta_buf
+ i
) - 1;
4127 * For pipes: echo the typed characters.
4128 * For a pty this does not seem to work.
4130 if (pty_master_fd
< 0)
4132 for (i
= ta_len
; i
< ta_len
+ len
; ++i
)
4134 if (ta_buf
[i
] == '\n' || ta_buf
[i
] == '\b')
4135 msg_putchar(ta_buf
[i
]);
4139 int l
= (*mb_ptr2len
)(ta_buf
+ i
);
4141 msg_outtrans_len(ta_buf
+ i
, l
);
4146 msg_outtrans_len(ta_buf
+ i
, 1);
4148 windgoto(msg_row
, msg_col
);
4155 * Write the characters to the child, unless EOF has
4156 * been typed for pipes. Write one character at a
4157 * time, to avoid loosing too much typeahead.
4158 * When writing buffer lines, drop the typed
4159 * characters (only check for CTRL-C).
4161 if (options
& SHELL_WRITE
)
4163 else if (toshell_fd
>= 0)
4165 len
= write(toshell_fd
, (char *)ta_buf
, (size_t)1);
4169 mch_memmove(ta_buf
, ta_buf
+ len
, ta_len
);
4177 /* CTRL-C sends a signal to the child, we ignore it
4190 * Check if the child has any characters to be printed.
4191 * Read them and write them to our window. Repeat this as
4192 * long as there is something to do, avoid the 10ms wait
4193 * for mch_inchar(), or sending typeahead characters to
4194 * the external process.
4195 * TODO: This should handle escape sequences, compatible
4196 * to some terminal (vt52?).
4199 while (RealWaitForChar(fromshell_fd
, 10L, NULL
))
4201 len
= read(fromshell_fd
, (char *)buffer
4203 + buffer_off
, (size_t)(BUFLEN
- buffer_off
)
4208 if (len
<= 0) /* end of file or error */
4212 if (options
& SHELL_READ
)
4214 /* Do NUL -> NL translation, append NL separated
4215 * lines to the current buffer. */
4216 for (i
= 0; i
< len
; ++i
)
4218 if (buffer
[i
] == NL
)
4219 append_ga_line(&ga
);
4220 else if (buffer
[i
] == NUL
)
4223 ga_append(&ga
, buffer
[i
]);
4234 /* Check if the last character in buffer[] is
4235 * incomplete, keep these bytes for the next
4237 for (p
= buffer
; p
< buffer
+ len
; p
+= l
)
4241 l
= 1; /* NUL byte? */
4242 else if (MB_BYTE2LEN(*p
) != l
)
4245 if (p
== buffer
) /* no complete character */
4247 /* avoid getting stuck at an illegal byte */
4259 if (p
< buffer
+ len
)
4262 buffer_off
= (buffer
+ len
) - p
;
4263 mch_memmove(buffer
, p
, buffer_off
);
4268 # endif /* FEAT_MBYTE */
4275 windgoto(msg_row
, msg_col
);
4282 /* If we already detected the child has finished break the
4284 if (wait_pid
== pid
)
4288 * Check if the child still exists, before checking for
4289 * typed characters (otherwise we would loose typeahead).
4292 wait_pid
= wait4(pid
, &status
, WNOHANG
, (struct rusage
*) 0);
4294 wait_pid
= waitpid(pid
, &status
, WNOHANG
);
4296 if ((wait_pid
== (pid_t
)-1 && errno
== ECHILD
)
4297 || (wait_pid
== pid
&& WIFEXITED(status
)))
4299 /* Don't break the loop yet, try reading more
4300 * characters from "fromshell_fd" first. When using
4301 * pipes there might still be something to read and
4302 * then we'll break the loop at the "break" above. */
4309 p_more
= p_more_save
;
4310 if (options
& SHELL_READ
)
4314 append_ga_line(&ga
);
4315 /* remember that the NL was missing */
4316 write_no_eol_lnum
= curwin
->w_cursor
.lnum
;
4319 write_no_eol_lnum
= 0;
4324 * Give all typeahead that wasn't used back to ui_inchar().
4327 ui_inchar_undo(ta_buf
, ta_len
);
4329 if (toshell_fd
>= 0)
4331 close(fromshell_fd
);
4335 * Wait until our child has exited.
4336 * Ignore wait() returning pids of other children and returning
4337 * because of some signal like SIGWINCH.
4338 * Don't wait if wait_pid was already set above, indicating the
4339 * child already exited.
4341 while (wait_pid
!= pid
)
4343 # ifdef _THREAD_SAFE
4344 /* Ugly hack: when compiled with Python threads are probably
4345 * used, in which case wait() sometimes hangs for no obvious
4346 * reason. Use waitpid() instead and loop (like the GUI). */
4348 wait_pid
= wait4(pid
, &status
, WNOHANG
, (struct rusage
*)0);
4350 wait_pid
= waitpid(pid
, &status
, WNOHANG
);
4354 /* Wait for 1/100 sec before trying again. */
4355 mch_delay(10L, TRUE
);
4359 wait_pid
= wait(&status
);
4369 /* Make sure the child that writes to the external program is
4372 kill(wpid
, SIGKILL
);
4375 * Set to raw mode right now, otherwise a CTRL-C after
4376 * catch_signals() will kill Vim.
4378 if (tmode
== TMODE_RAW
)
4379 settmode(TMODE_RAW
);
4380 did_settmode
= TRUE
;
4383 if (WIFEXITED(status
))
4385 /* LINTED avoid "bitwise operation on signed value" */
4386 retval
= WEXITSTATUS(status
);
4387 if (retval
&& !emsg_silent
)
4389 if (retval
== EXEC_FAILED
)
4391 MSG_PUTS(_("\nCannot execute shell "));
4395 else if (!(options
& SHELL_SILENT
))
4397 MSG_PUTS(_("\nshell returned "));
4398 msg_outnum((long)retval
);
4404 MSG_PUTS(_("\nCommand terminated\n"));
4411 if (tmode
== TMODE_RAW
)
4412 settmode(TMODE_RAW
); /* set to raw mode */
4420 #endif /* USE_SYSTEM */
4424 * Check for CTRL-C typed by reading all available characters.
4425 * In cooked mode we should get SIGINT, no need to check.
4430 if (curr_tmode
== TMODE_RAW
&& RealWaitForChar(read_cmd_fd
, 0L, NULL
))
4431 fill_input_buf(FALSE
);
4435 * Wait "msec" msec until a character is available from the keyboard or from
4436 * inbuf[]. msec == -1 will block forever.
4437 * When a GUI is being used, this will never get called -- webb
4443 #ifdef FEAT_MOUSE_GPM
4444 int gpm_process_wanted
;
4446 #ifdef FEAT_XCLIPBOARD
4451 if (input_available()) /* something in inbuf[] */
4454 #if defined(FEAT_MOUSE_DEC)
4455 /* May need to query the mouse position. */
4458 WantQueryMouse
= FALSE
;
4459 mch_write((char_u
*)IF_EB("\033[1'|", ESC_STR
"[1'|"), 5);
4464 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
4465 * events. This is a bit complicated, because they might both be defined.
4467 #if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
4468 # ifdef FEAT_XCLIPBOARD
4470 if (do_xterm_trace())
4475 # ifdef FEAT_XCLIPBOARD
4478 msec
= XT_TRACE_DELAY
;
4479 if (rest
>= 0 && rest
< XT_TRACE_DELAY
)
4485 # ifdef FEAT_MOUSE_GPM
4486 gpm_process_wanted
= 0;
4487 avail
= RealWaitForChar(read_cmd_fd
, msec
, &gpm_process_wanted
);
4489 avail
= RealWaitForChar(read_cmd_fd
, msec
, NULL
);
4493 if (input_available())
4495 # ifdef FEAT_XCLIPBOARD
4496 if (rest
== 0 || !do_xterm_trace())
4502 # ifdef FEAT_MOUSE_GPM
4503 || (gpm_process_wanted
&& mch_gpm_process() == 0)
4505 # ifdef FEAT_XCLIPBOARD
4506 || (!avail
&& rest
!= 0)
4511 avail
= RealWaitForChar(read_cmd_fd
, msec
, NULL
);
4517 * Wait "msec" msec until a character is available from file descriptor "fd".
4518 * Time == -1 will block forever.
4519 * When a GUI is being used, this will not be used for input -- webb
4520 * Returns also, when a request from Sniff is waiting -- toni.
4521 * Or when a Linux GPM mouse event is waiting.
4524 #if defined(__BEOS__)
4529 RealWaitForChar(fd
, msec
, check_for_gpm
)
4535 #if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4536 static int busy
= FALSE
;
4538 /* May retry getting characters after an event was handled. */
4541 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4542 /* Remember at what time we started, so that we know how much longer we
4543 * should wait after being interrupted. */
4544 # define USE_START_TV
4545 struct timeval start_tv
;
4548 # ifdef FEAT_XCLIPBOARD
4549 xterm_Shell
!= (Widget
)0
4550 # if defined(USE_XSMP) || defined(FEAT_MZSCHEME)
4556 # ifdef FEAT_MZSCHEME
4560 # ifdef FEAT_MZSCHEME
4561 (mzthreads_allowed() && p_mzq
> 0)
4564 gettimeofday(&start_tv
, NULL
);
4567 /* Handle being called recursively. This may happen for the session
4568 * manager stuff, it may save the file, which does a breakcheck. */
4578 int finished
= TRUE
; /* default is to 'loop' just once */
4579 # ifdef FEAT_MZSCHEME
4580 int mzquantum_used
= FALSE
;
4584 struct pollfd fds
[5];
4586 # ifdef FEAT_XCLIPBOARD
4589 # ifdef FEAT_MOUSE_GPM
4595 int towait
= (int)msec
;
4597 # ifdef FEAT_MZSCHEME
4598 mzvim_check_threads();
4599 if (mzthreads_allowed() && p_mzq
> 0 && (msec
< 0 || msec
> p_mzq
))
4601 towait
= (int)p_mzq
; /* don't wait longer than 'mzquantum' */
4602 mzquantum_used
= TRUE
;
4606 fds
[0].events
= POLLIN
;
4610 # define SNIFF_IDX 1
4611 if (want_sniff_request
)
4613 fds
[SNIFF_IDX
].fd
= fd_from_sniff
;
4614 fds
[SNIFF_IDX
].events
= POLLIN
;
4618 # ifdef FEAT_XCLIPBOARD
4619 if (xterm_Shell
!= (Widget
)0)
4622 fds
[nfd
].fd
= ConnectionNumber(xterm_dpy
);
4623 fds
[nfd
].events
= POLLIN
;
4627 # ifdef FEAT_MOUSE_GPM
4628 if (check_for_gpm
!= NULL
&& gpm_flag
&& gpm_fd
>= 0)
4631 fds
[nfd
].fd
= gpm_fd
;
4632 fds
[nfd
].events
= POLLIN
;
4637 if (xsmp_icefd
!= -1)
4640 fds
[nfd
].fd
= xsmp_icefd
;
4641 fds
[nfd
].events
= POLLIN
;
4646 ret
= poll(fds
, nfd
, towait
);
4647 # ifdef FEAT_MZSCHEME
4648 if (ret
== 0 && mzquantum_used
)
4649 /* MzThreads scheduling is required and timeout occured */
4655 sniff_disconnect(1);
4656 else if (want_sniff_request
)
4658 if (fds
[SNIFF_IDX
].revents
& POLLHUP
)
4659 sniff_disconnect(1);
4660 if (fds
[SNIFF_IDX
].revents
& POLLIN
)
4661 sniff_request_waiting
= 1;
4664 # ifdef FEAT_XCLIPBOARD
4665 if (xterm_Shell
!= (Widget
)0 && (fds
[xterm_idx
].revents
& POLLIN
))
4667 xterm_update(); /* Maybe we should hand out clipboard */
4668 if (--ret
== 0 && !input_available())
4673 # ifdef FEAT_MOUSE_GPM
4674 if (gpm_idx
>= 0 && (fds
[gpm_idx
].revents
& POLLIN
))
4680 if (xsmp_idx
>= 0 && (fds
[xsmp_idx
].revents
& (POLLIN
| POLLHUP
)))
4682 if (fds
[xsmp_idx
].revents
& POLLIN
)
4685 xsmp_handle_requests();
4688 else if (fds
[xsmp_idx
].revents
& POLLHUP
)
4691 verb_msg((char_u
*)_("XSMP lost ICE connection"));
4695 finished
= FALSE
; /* Try again */
4700 #else /* HAVE_SELECT */
4703 struct timeval
*tvp
;
4708 # ifdef FEAT_MZSCHEME
4709 mzvim_check_threads();
4710 if (mzthreads_allowed() && p_mzq
> 0 && (msec
< 0 || msec
> p_mzq
))
4712 towait
= p_mzq
; /* don't wait longer than 'mzquantum' */
4713 mzquantum_used
= TRUE
;
4717 /* don't check for incoming chars if not in raw mode, because select()
4718 * always returns TRUE then (in some version of emx.dll) */
4719 if (curr_tmode
!= TMODE_RAW
)
4725 tv
.tv_sec
= towait
/ 1000;
4726 tv
.tv_usec
= (towait
% 1000) * (1000000/1000);
4733 * Select on ready for reading and exceptional condition (end of file).
4735 FD_ZERO(&rfds
); /* calls bzero() on a sun */
4738 # if !defined(__QNX__) && !defined(__CYGWIN32__)
4739 /* For QNX select() always returns 1 if this is set. Why? */
4745 if (want_sniff_request
)
4747 FD_SET(fd_from_sniff
, &rfds
);
4748 FD_SET(fd_from_sniff
, &efds
);
4749 if (maxfd
< fd_from_sniff
)
4750 maxfd
= fd_from_sniff
;
4753 # ifdef FEAT_XCLIPBOARD
4754 if (xterm_Shell
!= (Widget
)0)
4756 FD_SET(ConnectionNumber(xterm_dpy
), &rfds
);
4757 if (maxfd
< ConnectionNumber(xterm_dpy
))
4758 maxfd
= ConnectionNumber(xterm_dpy
);
4761 # ifdef FEAT_MOUSE_GPM
4762 if (check_for_gpm
!= NULL
&& gpm_flag
&& gpm_fd
>= 0)
4764 FD_SET(gpm_fd
, &rfds
);
4765 FD_SET(gpm_fd
, &efds
);
4771 if (xsmp_icefd
!= -1)
4773 FD_SET(xsmp_icefd
, &rfds
);
4774 FD_SET(xsmp_icefd
, &efds
);
4775 if (maxfd
< xsmp_icefd
)
4781 /* Old VMS as v6.2 and older have broken select(). It waits more than
4782 * required. Should not be used */
4785 ret
= select(maxfd
+ 1, &rfds
, NULL
, &efds
, tvp
);
4788 if (ret
== -1 && errno
== ENOTSUP
)
4795 # ifdef FEAT_MZSCHEME
4796 if (ret
== 0 && mzquantum_used
)
4797 /* loop if MzThreads must be scheduled and timeout occured */
4803 sniff_disconnect(1);
4804 else if (ret
> 0 && want_sniff_request
)
4806 if (FD_ISSET(fd_from_sniff
, &efds
))
4807 sniff_disconnect(1);
4808 if (FD_ISSET(fd_from_sniff
, &rfds
))
4809 sniff_request_waiting
= 1;
4812 # ifdef FEAT_XCLIPBOARD
4813 if (ret
> 0 && xterm_Shell
!= (Widget
)0
4814 && FD_ISSET(ConnectionNumber(xterm_dpy
), &rfds
))
4816 xterm_update(); /* Maybe we should hand out clipboard */
4817 /* continue looping when we only got the X event and the input
4818 * buffer is empty */
4819 if (--ret
== 0 && !input_available())
4826 # ifdef FEAT_MOUSE_GPM
4827 if (ret
> 0 && gpm_flag
&& check_for_gpm
!= NULL
&& gpm_fd
>= 0)
4829 if (FD_ISSET(gpm_fd
, &efds
))
4831 else if (FD_ISSET(gpm_fd
, &rfds
))
4836 if (ret
> 0 && xsmp_icefd
!= -1)
4838 if (FD_ISSET(xsmp_icefd
, &efds
))
4841 verb_msg((char_u
*)_("XSMP lost ICE connection"));
4844 finished
= FALSE
; /* keep going if event was only one */
4846 else if (FD_ISSET(xsmp_icefd
, &rfds
))
4849 xsmp_handle_requests();
4852 finished
= FALSE
; /* keep going if event was only one */
4857 #endif /* HAVE_SELECT */
4860 if (finished
|| msec
== 0)
4863 /* We're going to loop around again, find out for how long */
4866 # ifdef USE_START_TV
4869 /* Compute remaining wait time. */
4870 gettimeofday(&mtv
, NULL
);
4871 msec
-= (mtv
.tv_sec
- start_tv
.tv_sec
) * 1000L
4872 + (mtv
.tv_usec
- start_tv
.tv_usec
) / 1000L;
4874 /* Guess we got interrupted halfway. */
4878 break; /* waited long enough */
4888 #ifndef NO_EXPANDPATH
4890 * Expand a path into all matching files and/or directories. Handles "*",
4891 * "?", "[a-z]", "**", etc.
4892 * "path" has backslashes before chars that are not to be expanded.
4893 * Returns the number of matches found.
4896 mch_expandpath(gap
, path
, flags
)
4899 int flags
; /* EW_* flags */
4901 return unix_expandpath(gap
, path
, 0, flags
, FALSE
);
4906 * mch_expand_wildcards() - this code does wild-card pattern matching using
4909 * return OK for success, FAIL for error (you may lose some memory) and put
4910 * an error message in *file.
4912 * num_pat is number of input patterns
4913 * pat is array of pointers to input patterns
4914 * num_file is pointer to number of matched file names
4915 * file is pointer to array of pointers to matched file names
4925 #define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
4929 mch_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
)
4934 int flags
; /* EW_* flags */
4941 # define EXPL_ALLOC_INC 16
4942 char_u
**expl_files
;
4943 size_t files_alloced
, files_free
;
4947 *num_file
= 0; /* default: no files found */
4948 files_alloced
= EXPL_ALLOC_INC
; /* how much space is allocated */
4949 files_free
= EXPL_ALLOC_INC
; /* how much space is not used */
4950 *file
= (char_u
**)alloc(sizeof(char_u
**) * files_alloced
);
4954 for (; num_pat
> 0; num_pat
--, pat
++)
4957 if (vim_strchr(*pat
, '$') || vim_strchr(*pat
, '~'))
4958 /* expand environment var or home dir */
4959 buf
= expand_env_save(*pat
);
4961 buf
= vim_strsave(*pat
);
4963 has_wildcard
= mch_has_exp_wildcard(buf
); /* (still) wildcards? */
4964 if (has_wildcard
) /* yes, so expand them */
4965 expl_files
= (char_u
**)_fnexplode(buf
);
4968 * return value of buf if no wildcards left,
4969 * OR if no match AND EW_NOTFOUND is set.
4971 if ((!has_wildcard
&& ((flags
& EW_NOTFOUND
) || mch_getperm(buf
) >= 0))
4972 || (expl_files
== NULL
&& (flags
& EW_NOTFOUND
)))
4973 { /* simply save the current contents of *buf */
4974 expl_files
= (char_u
**)alloc(sizeof(char_u
**) * 2);
4975 if (expl_files
!= NULL
)
4977 expl_files
[0] = vim_strsave(buf
);
4978 expl_files
[1] = NULL
;
4984 * Count number of names resulting from expansion,
4985 * At the same time add a backslash to the end of names that happen to
4986 * be directories, and replace slashes with backslashes.
4990 for (i
= 0; (p
= expl_files
[i
]) != NULL
; i
++)
4993 /* If we don't want dirs and this is one, skip it */
4994 if ((dir
&& !(flags
& EW_DIR
)) || (!dir
&& !(flags
& EW_FILE
)))
4997 /* Skip files that are not executable if we check for that. */
4998 if (!dir
&& (flags
& EW_EXEC
) && !mch_can_exe(p
))
5001 if (--files_free
== 0)
5003 /* need more room in table of pointers */
5004 files_alloced
+= EXPL_ALLOC_INC
;
5005 *file
= (char_u
**)vim_realloc(*file
,
5006 sizeof(char_u
**) * files_alloced
);
5009 EMSG(_(e_outofmem
));
5013 files_free
= EXPL_ALLOC_INC
;
5018 /* For a directory we add a '/', unless it's already
5021 if (((*file
)[*num_file
] = alloc(len
+ 2)) != NULL
)
5023 STRCPY((*file
)[*num_file
], p
);
5024 if (!after_pathsep((*file
)[*num_file
],
5025 (*file
)[*num_file
] + len
))
5027 (*file
)[*num_file
][len
] = psepc
;
5028 (*file
)[*num_file
][len
+ 1] = NUL
;
5034 (*file
)[*num_file
] = vim_strsave(p
);
5038 * Error message already given by either alloc or vim_strsave.
5039 * Should return FAIL, but returning OK works also.
5041 if ((*file
)[*num_file
] == NULL
)
5045 _fnexplodefree((char **)expl_files
);
5057 #define STYLE_ECHO 0 /* use "echo" to expand */
5058 #define STYLE_GLOB 1 /* use "glob" to expand, for csh */
5059 #define STYLE_PRINT 2 /* use "print -N" to expand, for zsh */
5060 #define STYLE_BT 3 /* `cmd` expansion, execute the pattern directly */
5061 int shell_style
= STYLE_ECHO
;
5063 static int did_find_nul
= FALSE
;
5064 int ampersent
= FALSE
;
5066 *num_file
= 0; /* default: no files found */
5070 * If there are no wildcards, just copy the names to allocated memory.
5071 * Saves a lot of time, because we don't have to start a new shell.
5073 if (!have_wildcard(num_pat
, pat
))
5074 return save_patterns(num_pat
, pat
, num_file
, file
);
5076 # ifdef HAVE_SANDBOX
5077 /* Don't allow any shell command in the sandbox. */
5078 if (sandbox
!= 0 && check_secure())
5083 * Don't allow the use of backticks in secure and restricted mode.
5085 if (secure
|| restricted
)
5086 for (i
= 0; i
< num_pat
; ++i
)
5087 if (vim_strchr(pat
[i
], '`') != NULL
5088 && (check_restricted() || check_secure()))
5092 * get a name for the temp file
5094 if ((tempname
= vim_tempname('o')) == NULL
)
5101 * Let the shell expand the patterns and write the result into the temp
5102 * file. if expanding `cmd` execute it directly.
5103 * If we use csh, glob will work better than echo.
5104 * If we use zsh, print -N will work better than glob.
5106 if (num_pat
== 1 && *pat
[0] == '`'
5107 && (len
= STRLEN(pat
[0])) > 2
5108 && *(pat
[0] + len
- 1) == '`')
5109 shell_style
= STYLE_BT
;
5110 else if ((len
= STRLEN(p_sh
)) >= 3)
5112 if (STRCMP(p_sh
+ len
- 3, "csh") == 0)
5113 shell_style
= STYLE_GLOB
;
5114 else if (STRCMP(p_sh
+ len
- 3, "zsh") == 0)
5115 shell_style
= STYLE_PRINT
;
5118 /* "unset nonomatch; print -N >" plus two is 29 */
5119 len
= STRLEN(tempname
) + 29;
5120 for (i
= 0; i
< num_pat
; ++i
)
5122 /* Count the length of the patterns in the same way as they are put in
5123 * "command" below. */
5125 len
+= STRLEN(pat
[i
]) + 3; /* add space and two quotes */
5127 ++len
; /* add space */
5128 for (j
= 0; pat
[i
][j
] != NUL
; ++j
)
5130 if (vim_strchr(SHELL_SPECIAL
, pat
[i
][j
]) != NULL
)
5131 ++len
; /* may add a backslash */
5136 command
= alloc(len
);
5137 if (command
== NULL
)
5145 * Build the shell command:
5146 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
5148 * - Add the shell command to print the expanded names.
5149 * - Add the temp file name.
5150 * - Add the file name patterns.
5152 if (shell_style
== STYLE_BT
)
5154 /* change `command; command& ` to (command; command ) */
5155 STRCPY(command
, "(");
5156 STRCAT(command
, pat
[0] + 1); /* exclude first backtick */
5157 p
= command
+ STRLEN(command
) - 1;
5158 *p
-- = ')'; /* remove last backtick */
5159 while (p
> command
&& vim_iswhite(*p
))
5161 if (*p
== '&') /* remove trailing '&' */
5166 STRCAT(command
, ">");
5170 if (flags
& EW_NOTFOUND
)
5171 STRCPY(command
, "set nonomatch; ");
5173 STRCPY(command
, "unset nonomatch; ");
5174 if (shell_style
== STYLE_GLOB
)
5175 STRCAT(command
, "glob >");
5176 else if (shell_style
== STYLE_PRINT
)
5177 STRCAT(command
, "print -N >");
5179 STRCAT(command
, "echo >");
5181 STRCAT(command
, tempname
);
5182 if (shell_style
!= STYLE_BT
)
5183 for (i
= 0; i
< num_pat
; ++i
)
5185 /* When using system() always add extra quotes, because the shell
5186 * is started twice. Otherwise put a backslash before special
5187 * characters, except insice ``. */
5189 STRCAT(command
, " \"");
5190 STRCAT(command
, pat
[i
]);
5191 STRCAT(command
, "\"");
5195 p
= command
+ STRLEN(command
);
5197 for (j
= 0; pat
[i
][j
] != NUL
; ++j
)
5199 if (pat
[i
][j
] == '`')
5201 else if (pat
[i
][j
] == '\\' && pat
[i
][j
+ 1] != NUL
)
5203 /* Remove a backslash, take char literally. But keep
5204 * backslash inside backticks, before a special character
5205 * and before a backtick. */
5207 || vim_strchr(SHELL_SPECIAL
, pat
[i
][j
+ 1]) != NULL
5208 || pat
[i
][j
+ 1] == '`')
5212 else if (!intick
&& vim_strchr(SHELL_SPECIAL
,
5214 /* Put a backslash before a special character, but not
5215 * when inside ``. */
5218 /* Copy one character. */
5224 if (flags
& EW_SILENT
)
5225 show_shell_mess
= FALSE
;
5227 STRCAT(command
, "&"); /* put the '&' back after the
5231 * Using zsh -G: If a pattern has no matches, it is just deleted from
5232 * the argument list, otherwise zsh gives an error message and doesn't
5233 * expand any other pattern.
5235 if (shell_style
== STYLE_PRINT
)
5236 extra_shell_arg
= (char_u
*)"-G"; /* Use zsh NULL_GLOB option */
5239 * If we use -f then shell variables set in .cshrc won't get expanded.
5240 * vi can do it, so we will too, but it is only necessary if there is a "$"
5241 * in one of the patterns, otherwise we can still use the fast option.
5243 else if (shell_style
== STYLE_GLOB
&& !have_dollars(num_pat
, pat
))
5244 extra_shell_arg
= (char_u
*)"-f"; /* Use csh fast option */
5247 * execute the shell command
5249 i
= call_shell(command
, SHELL_EXPAND
| SHELL_SILENT
);
5251 /* When running in the background, give it some time to create the temp
5252 * file, but don't wait for it to finish. */
5254 mch_delay(10L, TRUE
);
5256 extra_shell_arg
= NULL
; /* cleanup */
5257 show_shell_mess
= TRUE
;
5260 if (i
) /* mch_call_shell() failed */
5262 mch_remove(tempname
);
5265 * With interactive completion, the error message is not printed.
5266 * However with USE_SYSTEM, I don't know how to turn off error messages
5267 * from the shell, so screen may still get messed up -- webb.
5270 if (!(flags
& EW_SILENT
))
5273 redraw_later_clear(); /* probably messed up screen */
5274 msg_putchar('\n'); /* clear bottom line quickly */
5275 cmdline_row
= Rows
- 1; /* continue on last line */
5277 if (!(flags
& EW_SILENT
))
5280 MSG(_(e_wildexpand
));
5281 msg_start(); /* don't overwrite this message */
5284 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
5285 * EW_NOTFOUND is given */
5286 if (shell_style
== STYLE_BT
)
5292 * read the names from the file into memory
5294 fd
= fopen((char *)tempname
, READBIN
);
5297 /* Something went wrong, perhaps a file name with a special char. */
5298 if (!(flags
& EW_SILENT
))
5300 MSG(_(e_wildexpand
));
5301 msg_start(); /* don't overwrite this message */
5306 fseek(fd
, 0L, SEEK_END
);
5307 len
= ftell(fd
); /* get size of temp file */
5308 fseek(fd
, 0L, SEEK_SET
);
5309 buffer
= alloc(len
+ 1);
5313 mch_remove(tempname
);
5318 i
= fread((char *)buffer
, 1, len
, fd
);
5320 mch_remove(tempname
);
5323 /* unexpected read error */
5324 EMSG2(_(e_notread
), tempname
);
5331 #if defined(__CYGWIN__) || defined(__CYGWIN32__)
5332 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
5334 for (i
= 0; i
< len
; ++i
)
5335 if (!(buffer
[i
] == CAR
&& buffer
[i
+ 1] == NL
))
5341 /* file names are separated with Space */
5342 if (shell_style
== STYLE_ECHO
)
5344 buffer
[len
] = '\n'; /* make sure the buffer ends in NL */
5346 for (i
= 0; *p
!= '\n'; ++i
) /* count number of entries */
5348 while (*p
!= ' ' && *p
!= '\n')
5350 p
= skipwhite(p
); /* skip to next entry */
5353 /* file names are separated with NL */
5354 else if (shell_style
== STYLE_BT
)
5356 buffer
[len
] = NUL
; /* make sure the buffer ends in NUL */
5358 for (i
= 0; *p
!= NUL
; ++i
) /* count number of entries */
5360 while (*p
!= '\n' && *p
!= NUL
)
5364 p
= skipwhite(p
); /* skip leading white space */
5367 /* file names are separated with NUL */
5371 * Some versions of zsh use spaces instead of NULs to separate
5372 * results. Only do this when there is no NUL before the end of the
5373 * buffer, otherwise we would never be able to use file names with
5374 * embedded spaces when zsh does use NULs.
5375 * When we found a NUL once, we know zsh is OK, set did_find_nul and
5376 * don't check for spaces again.
5378 check_spaces
= FALSE
;
5379 if (shell_style
== STYLE_PRINT
&& !did_find_nul
)
5381 /* If there is a NUL, set did_find_nul, else set check_spaces */
5382 if (len
&& (int)STRLEN(buffer
) < len
- 1)
5383 did_find_nul
= TRUE
;
5385 check_spaces
= TRUE
;
5389 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
5390 * already is one, for STYLE_GLOB it needs to be added.
5392 if (len
&& buffer
[len
- 1] == NUL
)
5397 for (p
= buffer
; p
< buffer
+ len
; ++p
)
5398 if (*p
== NUL
|| (*p
== ' ' && check_spaces
)) /* count entry */
5404 ++i
; /* count last entry */
5409 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
5410 * /bin/sh will happily expand it to nothing rather than returning an
5411 * error; and hey, it's good to check anyway -- webb.
5417 *file
= (char_u
**)alloc(sizeof(char_u
*) * i
);
5426 * Isolate the individual file names.
5429 for (i
= 0; i
< *num_file
; ++i
)
5432 /* Space or NL separates */
5433 if (shell_style
== STYLE_ECHO
|| shell_style
== STYLE_BT
)
5435 while (!(shell_style
== STYLE_ECHO
&& *p
== ' ')
5436 && *p
!= '\n' && *p
!= NUL
)
5438 if (p
== buffer
+ len
) /* last entry */
5443 p
= skipwhite(p
); /* skip to next entry */
5446 else /* NUL separates */
5448 while (*p
&& p
< buffer
+ len
) /* skip entry */
5455 * Move the file names to allocated memory.
5457 for (j
= 0, i
= 0; i
< *num_file
; ++i
)
5459 /* Require the files to exist. Helps when using /bin/sh */
5460 if (!(flags
& EW_NOTFOUND
) && mch_getperm((*file
)[i
]) < 0)
5463 /* check if this entry should be included */
5464 dir
= (mch_isdir((*file
)[i
]));
5465 if ((dir
&& !(flags
& EW_DIR
)) || (!dir
&& !(flags
& EW_FILE
)))
5468 /* Skip files that are not executable if we check for that. */
5469 if (!dir
&& (flags
& EW_EXEC
) && !mch_can_exe((*file
)[i
]))
5472 p
= alloc((unsigned)(STRLEN((*file
)[i
]) + 1 + dir
));
5475 STRCPY(p
, (*file
)[i
]);
5477 STRCAT(p
, "/"); /* add '/' to a directory name */
5484 if (*num_file
== 0) /* rejected all entries */
5494 if (flags
& EW_NOTFOUND
)
5495 return save_patterns(num_pat
, pat
, num_file
, file
);
5498 #endif /* __EMX__ */
5505 save_patterns(num_pat
, pat
, num_file
, file
)
5514 *file
= (char_u
**)alloc(num_pat
* sizeof(char_u
*));
5517 for (i
= 0; i
< num_pat
; i
++)
5519 s
= vim_strsave(pat
[i
]);
5521 /* Be compatible with expand_filename(): halve the number of
5526 *num_file
= num_pat
;
5533 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
5537 mch_has_exp_wildcard(p
)
5540 for ( ; *p
; mb_ptr_adv(p
))
5543 if (*p
== '\\' && p
[1] != NUL
)
5547 if (vim_strchr((char_u
*)
5564 * Return TRUE if the string "p" contains a wildcard.
5565 * Don't recognize '~' at the end as a wildcard.
5571 for ( ; *p
; mb_ptr_adv(p
))
5574 if (*p
== '\\' && p
[1] != NUL
)
5578 if (vim_strchr((char_u
*)
5583 # ifdef VIM_BACKTICK
5593 || (*p
== '~' && p
[1] != NUL
))
5601 have_wildcard(num
, file
)
5607 for (i
= 0; i
< num
; i
++)
5608 if (mch_has_wildcard(file
[i
]))
5614 have_dollars(num
, file
)
5620 for (i
= 0; i
< num
; i
++)
5621 if (vim_strchr(file
[i
], '$') != NULL
)
5625 #endif /* ifndef __EMX__ */
5629 * Scaled-down version of rename(), which is missing in Xenix.
5630 * This version can only move regular files and will fail if the
5631 * destination exists.
5634 mch_rename(src
, dest
)
5635 const char *src
, *dest
;
5639 if (stat(dest
, &st
) >= 0) /* fail if destination exists */
5641 if (link(src
, dest
) != 0) /* link file to new name */
5643 if (mch_remove(src
) == 0) /* delete link to old name */
5647 #endif /* !HAVE_RENAME */
5649 #ifdef FEAT_MOUSE_GPM
5651 * Initializes connection with gpm (if it isn't already opened)
5652 * Return 1 if succeeded (or connection already opened), 0 if failed
5657 static Gpm_Connect gpm_connect
; /* Must it be kept till closing ? */
5661 gpm_connect
.eventMask
= (GPM_UP
| GPM_DRAG
| GPM_DOWN
);
5662 gpm_connect
.defaultMask
= ~GPM_HARD
;
5663 /* Default handling for mouse move*/
5664 gpm_connect
.minMod
= 0; /* Handle any modifier keys */
5665 gpm_connect
.maxMod
= 0xffff;
5666 if (Gpm_Open(&gpm_connect
, 0) > 0)
5668 /* gpm library tries to handling TSTP causes
5669 * problems. Anyways, we close connection to Gpm whenever
5670 * we are going to suspend or starting an external process
5671 * so we should'nt have problem with this
5673 signal(SIGTSTP
, restricted
? SIG_IGN
: SIG_DFL
);
5674 return 1; /* succeed */
5677 Gpm_Close(); /* We don't want to talk to xterm via gpm */
5680 return 1; /* already open */
5684 * Closes connection to gpm
5685 * returns non-zero if connection succesfully closed
5690 if (gpm_flag
&& gpm_fd
>= 0) /* if Open */
5694 /* Reads gpm event and adds special keys to input buf. Returns length of
5695 * generated key sequence.
5696 * This function is made after gui_send_mouse_event
5702 static Gpm_Event gpm_event
;
5704 int_u vim_modifiers
;
5706 unsigned char buttons_mask
;
5707 unsigned char gpm_modifiers
;
5708 static unsigned char old_buttons
= 0;
5710 Gpm_GetEvent(&gpm_event
);
5713 /* Don't put events in the input queue now. */
5714 if (hold_gui_events
)
5718 row
= gpm_event
.y
- 1;
5719 col
= gpm_event
.x
- 1;
5721 string
[0] = ESC
; /* Our termcode */
5724 switch (GPM_BARE_EVENTS(gpm_event
.type
))
5727 string
[3] = MOUSE_DRAG
;
5730 buttons_mask
= gpm_event
.buttons
& ~old_buttons
;
5731 old_buttons
= gpm_event
.buttons
;
5732 switch (buttons_mask
)
5735 button
= MOUSE_LEFT
;
5738 button
= MOUSE_MIDDLE
;
5741 button
= MOUSE_RIGHT
;
5745 /*Don't know what to do. Can more than one button be
5746 * reported in one event? */
5748 string
[3] = (char_u
)(button
| 0x20);
5749 SET_NUM_MOUSE_CLICKS(string
[3], gpm_event
.clicks
+ 1);
5752 string
[3] = MOUSE_RELEASE
;
5753 old_buttons
&= ~gpm_event
.buttons
;
5758 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
5759 gpm_modifiers
= gpm_event
.modifiers
;
5760 vim_modifiers
= 0x0;
5761 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
5762 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
5763 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
5765 if (gpm_modifiers
& ((1 << KG_SHIFT
) | (1 << KG_SHIFTR
) | (1 << KG_SHIFTL
)))
5766 vim_modifiers
|= MOUSE_SHIFT
;
5768 if (gpm_modifiers
& ((1 << KG_CTRL
) | (1 << KG_CTRLR
) | (1 << KG_CTRLL
)))
5769 vim_modifiers
|= MOUSE_CTRL
;
5770 if (gpm_modifiers
& ((1 << KG_ALT
) | (1 << KG_ALTGR
)))
5771 vim_modifiers
|= MOUSE_ALT
;
5772 string
[3] |= vim_modifiers
;
5773 string
[4] = (char_u
)(col
+ ' ' + 1);
5774 string
[5] = (char_u
)(row
+ ' ' + 1);
5775 add_to_input_buf(string
, 6);
5778 #endif /* FEAT_MOUSE_GPM */
5780 #if defined(FEAT_LIBCALL) || defined(PROTO)
5781 typedef char_u
* (*STRPROCSTR
)__ARGS((char_u
*));
5782 typedef char_u
* (*INTPROCSTR
)__ARGS((int));
5783 typedef int (*STRPROCINT
)__ARGS((char_u
*));
5784 typedef int (*INTPROCINT
)__ARGS((int));
5787 * Call a DLL routine which takes either a string or int param
5788 * and returns an allocated string.
5791 mch_libcall(libname
, funcname
, argstring
, argint
, string_result
, number_result
)
5794 char_u
*argstring
; /* NULL when using a argint */
5796 char_u
**string_result
;/* NULL when using number_result */
5799 # if defined(USE_DLOPEN)
5806 INTPROCSTR ProcAddI
;
5807 char_u
*retval_str
= NULL
;
5809 int success
= FALSE
;
5812 * Get a handle to the DLL module.
5814 # if defined(USE_DLOPEN)
5815 /* First clear any error, it's not cleared by the dlopen() call. */
5818 hinstLib
= dlopen((char *)libname
, RTLD_LAZY
5823 if (hinstLib
== NULL
)
5825 /* "dlerr" must be used before dlclose() */
5826 dlerr
= (char *)dlerror();
5828 EMSG2(_("dlerror = \"%s\""), dlerr
);
5831 hinstLib
= shl_load((const char*)libname
, BIND_IMMEDIATE
|BIND_VERBOSE
, 0L);
5834 /* If the handle is valid, try to get the function address. */
5835 if (hinstLib
!= NULL
)
5837 # ifdef HAVE_SETJMP_H
5839 * Catch a crash when calling the library function. For example when
5840 * using a number where a string pointer is expected.
5843 if (SETJMP(lc_jump_env
) != 0)
5846 # if defined(USE_DLOPEN)
5857 if (argstring
!= NULL
)
5859 # if defined(USE_DLOPEN)
5860 ProcAdd
= (STRPROCSTR
)dlsym(hinstLib
, (const char *)funcname
);
5861 dlerr
= (char *)dlerror();
5863 if (shl_findsym(&hinstLib
, (const char *)funcname
,
5864 TYPE_PROCEDURE
, (void *)&ProcAdd
) < 0)
5867 if ((success
= (ProcAdd
!= NULL
5868 # if defined(USE_DLOPEN)
5873 if (string_result
== NULL
)
5874 retval_int
= ((STRPROCINT
)ProcAdd
)(argstring
);
5876 retval_str
= (ProcAdd
)(argstring
);
5881 # if defined(USE_DLOPEN)
5882 ProcAddI
= (INTPROCSTR
)dlsym(hinstLib
, (const char *)funcname
);
5883 dlerr
= (char *)dlerror();
5885 if (shl_findsym(&hinstLib
, (const char *)funcname
,
5886 TYPE_PROCEDURE
, (void *)&ProcAddI
) < 0)
5889 if ((success
= (ProcAddI
!= NULL
5890 # if defined(USE_DLOPEN)
5895 if (string_result
== NULL
)
5896 retval_int
= ((INTPROCINT
)ProcAddI
)(argint
);
5898 retval_str
= (ProcAddI
)(argint
);
5902 /* Save the string before we free the library. */
5903 /* Assume that a "1" or "-1" result is an illegal pointer. */
5904 if (string_result
== NULL
)
5905 *number_result
= retval_int
;
5906 else if (retval_str
!= NULL
5907 && retval_str
!= (char_u
*)1
5908 && retval_str
!= (char_u
*)-1)
5909 *string_result
= vim_strsave(retval_str
);
5912 # ifdef HAVE_SETJMP_H
5919 /* try to find the name of this signal */
5920 for (i
= 0; signal_info
[i
].sig
!= -1; i
++)
5921 if (lc_signal
== signal_info
[i
].sig
)
5923 EMSG2("E368: got SIG%s in libcall()", signal_info
[i
].name
);
5928 # if defined(USE_DLOPEN)
5929 /* "dlerr" must be used before dlclose() */
5931 EMSG2(_("dlerror = \"%s\""), dlerr
);
5933 /* Free the DLL module. */
5934 (void)dlclose(hinstLib
);
5936 (void)shl_unload(hinstLib
);
5942 EMSG2(_(e_libcall
), funcname
);
5950 #if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
5951 static int xterm_trace
= -1; /* default: disabled */
5952 static int xterm_button
;
5955 * Setup a dummy window for X selections in a terminal.
5964 if (!x_connect_to_server())
5968 if (app_context
!= NULL
&& xterm_Shell
== (Widget
)0)
5970 int (*oldhandler
)();
5971 #if defined(HAVE_SETJMP_H)
5972 int (*oldIOhandler
)();
5974 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
5975 struct timeval start_tv
;
5978 gettimeofday(&start_tv
, NULL
);
5981 /* Ignore X errors while opening the display */
5982 oldhandler
= XSetErrorHandler(x_error_check
);
5984 #if defined(HAVE_SETJMP_H)
5985 /* Ignore X IO errors while opening the display */
5986 oldIOhandler
= XSetIOErrorHandler(x_IOerror_check
);
5988 if (SETJMP(lc_jump_env
) != 0)
5996 xterm_dpy
= XtOpenDisplay(app_context
, xterm_display
,
5997 "vim_xterm", "Vim_xterm", NULL
, 0, &z
, &strp
);
5998 #if defined(HAVE_SETJMP_H)
6003 #if defined(HAVE_SETJMP_H)
6004 /* Now handle X IO errors normally. */
6005 (void)XSetIOErrorHandler(oldIOhandler
);
6007 /* Now handle X errors normally. */
6008 (void)XSetErrorHandler(oldhandler
);
6010 if (xterm_dpy
== NULL
)
6013 verb_msg((char_u
*)_("Opening the X display failed"));
6017 /* Catch terminating error of the X server connection. */
6018 (void)XSetIOErrorHandler(x_IOerror_handler
);
6020 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
6024 xopen_message(&start_tv
);
6029 /* Create a Shell to make converters work. */
6030 AppShell
= XtVaAppCreateShell("vim_xterm", "Vim_xterm",
6031 applicationShellWidgetClass
, xterm_dpy
,
6033 if (AppShell
== (Widget
)0)
6035 xterm_Shell
= XtVaCreatePopupShell("VIM",
6036 topLevelShellWidgetClass
, AppShell
,
6037 XtNmappedWhenManaged
, 0,
6041 if (xterm_Shell
== (Widget
)0)
6044 x11_setup_atoms(xterm_dpy
);
6045 if (x11_display
== NULL
)
6046 x11_display
= xterm_dpy
;
6048 XtRealizeWidget(xterm_Shell
);
6049 XSync(xterm_dpy
, False
);
6052 if (xterm_Shell
!= (Widget
)0)
6055 if (x11_window
== 0 && (strp
= getenv("WINDOWID")) != NULL
)
6056 x11_window
= (Window
)atol(strp
);
6057 /* Check if $WINDOWID is valid. */
6058 if (test_x11_window(xterm_dpy
) == FAIL
)
6060 if (x11_window
!= 0)
6066 start_xterm_trace(button
)
6069 if (x11_window
== 0 || xterm_trace
< 0 || xterm_Shell
== (Widget
)0)
6072 xterm_button
= button
;
6080 if (xterm_trace
< 0)
6086 * Query the xterm pointer and generate mouse termcodes if necessary
6087 * return TRUE if dragging is active, else FALSE
6100 static char_u
*mouse_code
;
6101 static char_u mouse_name
[2] = {KS_MOUSE
, KE_FILLER
};
6102 static int prev_row
= 0, prev_col
= 0;
6103 static XSizeHints xterm_hints
;
6105 if (xterm_trace
<= 0)
6108 if (xterm_trace
== 1)
6110 /* Get the hints just before tracking starts. The font size might
6111 * have changed recently */
6112 XGetWMNormalHints(xterm_dpy
, x11_window
, &xterm_hints
, &got_hints
);
6113 if (!(got_hints
& PResizeInc
)
6114 || xterm_hints
.width_inc
<= 1
6115 || xterm_hints
.height_inc
<= 1)
6117 xterm_trace
= -1; /* Not enough data -- disable tracing */
6121 /* Rely on the same mouse code for the duration of this */
6122 mouse_code
= find_termcode(mouse_name
);
6123 prev_row
= mouse_row
;
6124 prev_row
= mouse_col
;
6127 /* Find the offset of the chars, there might be a scrollbar on the
6128 * left of the window and/or a menu on the top (eterm etc.) */
6129 XQueryPointer(xterm_dpy
, x11_window
, &root
, &child
, &root_x
, &root_y
,
6130 &win_x
, &win_y
, &mask_return
);
6131 xterm_hints
.y
= win_y
- (xterm_hints
.height_inc
* mouse_row
)
6132 - (xterm_hints
.height_inc
/ 2);
6133 if (xterm_hints
.y
<= xterm_hints
.height_inc
/ 2)
6135 xterm_hints
.x
= win_x
- (xterm_hints
.width_inc
* mouse_col
)
6136 - (xterm_hints
.width_inc
/ 2);
6137 if (xterm_hints
.x
<= xterm_hints
.width_inc
/ 2)
6141 if (mouse_code
== NULL
)
6147 XQueryPointer(xterm_dpy
, x11_window
, &root
, &child
, &root_x
, &root_y
,
6148 &win_x
, &win_y
, &mask_return
);
6150 row
= check_row((win_y
- xterm_hints
.y
) / xterm_hints
.height_inc
);
6151 col
= check_col((win_x
- xterm_hints
.x
) / xterm_hints
.width_inc
);
6152 if (row
== prev_row
&& col
== prev_col
)
6155 STRCPY(buf
, mouse_code
);
6156 strp
= buf
+ STRLEN(buf
);
6157 *strp
++ = (xterm_button
| MOUSE_DRAG
) & ~0x20;
6158 *strp
++ = (char_u
)(col
+ ' ' + 1);
6159 *strp
++ = (char_u
)(row
+ ' ' + 1);
6161 add_to_input_buf(buf
, STRLEN(buf
));
6168 # if defined(FEAT_GUI) || defined(PROTO)
6170 * Destroy the display, window and app_context. Required for GTK.
6175 if (xterm_Shell
!= (Widget
)0)
6177 XtDestroyWidget(xterm_Shell
);
6178 xterm_Shell
= (Widget
)0;
6180 if (xterm_dpy
!= NULL
)
6183 /* Lesstif and Solaris crash here, lose some memory */
6184 XtCloseDisplay(xterm_dpy
);
6186 if (x11_display
== xterm_dpy
)
6191 if (app_context
!= (XtAppContext
)NULL
)
6193 /* Lesstif and Solaris crash here, lose some memory */
6194 XtDestroyApplicationContext(app_context
);
6195 app_context
= (XtAppContext
)NULL
;
6202 * Catch up with any queued X events. This may put keyboard input into the
6203 * input buffer, call resize call-backs, trigger timers etc. If there is
6204 * nothing in the X event queue (& no timers pending), then we return
6212 while (XtAppPending(app_context
) && !vim_is_input_buf_full())
6214 XtAppNextEvent(app_context
, &event
);
6215 #ifdef FEAT_CLIENTSERVER
6217 XPropertyEvent
*e
= (XPropertyEvent
*)&event
;
6219 if (e
->type
== PropertyNotify
&& e
->window
== commWindow
6220 && e
->atom
== commProperty
&& e
->state
== PropertyNewValue
)
6221 serverEventProc(xterm_dpy
, &event
);
6224 XtDispatchEvent(&event
);
6229 clip_xterm_own_selection(cbd
)
6232 if (xterm_Shell
!= (Widget
)0)
6233 return clip_x11_own_selection(xterm_Shell
, cbd
);
6238 clip_xterm_lose_selection(cbd
)
6241 if (xterm_Shell
!= (Widget
)0)
6242 clip_x11_lose_selection(xterm_Shell
, cbd
);
6246 clip_xterm_request_selection(cbd
)
6249 if (xterm_Shell
!= (Widget
)0)
6250 clip_x11_request_selection(xterm_Shell
, xterm_dpy
, cbd
);
6254 clip_xterm_set_selection(cbd
)
6257 clip_x11_set_selection(cbd
);
6262 #if defined(USE_XSMP) || defined(PROTO)
6264 * Code for X Session Management Protocol.
6266 static void xsmp_handle_save_yourself
__ARGS((SmcConn smc_conn
, SmPointer client_data
, int save_type
, Bool shutdown
, int interact_style
, Bool fast
));
6267 static void xsmp_die
__ARGS((SmcConn smc_conn
, SmPointer client_data
));
6268 static void xsmp_save_complete
__ARGS((SmcConn smc_conn
, SmPointer client_data
));
6269 static void xsmp_shutdown_cancelled
__ARGS((SmcConn smc_conn
, SmPointer client_data
));
6270 static void xsmp_ice_connection
__ARGS((IceConn iceConn
, IcePointer clientData
, Bool opening
, IcePointer
*watchData
));
6273 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6274 static void xsmp_handle_interaction
__ARGS((SmcConn smc_conn
, SmPointer client_data
));
6277 * This is our chance to ask the user if they want to save,
6278 * or abort the logout
6282 xsmp_handle_interaction(smc_conn
, client_data
)
6284 SmPointer client_data
;
6286 cmdmod_T save_cmdmod
;
6287 int cancel_shutdown
= False
;
6289 save_cmdmod
= cmdmod
;
6290 cmdmod
.confirm
= TRUE
;
6291 if (check_changed_any(FALSE
))
6292 /* Mustn't logout */
6293 cancel_shutdown
= True
;
6294 cmdmod
= save_cmdmod
;
6295 setcursor(); /* position cursor */
6298 /* Done interaction */
6299 SmcInteractDone(smc_conn
, cancel_shutdown
);
6302 * Only end save-yourself here if we're not cancelling shutdown;
6303 * we'll get a cancelled callback later in which we'll end it.
6304 * Hopefully get around glitchy SMs (like GNOME-1)
6306 if (!cancel_shutdown
)
6308 xsmp
.save_yourself
= False
;
6309 SmcSaveYourselfDone(smc_conn
, True
);
6315 * Callback that starts save-yourself.
6319 xsmp_handle_save_yourself(smc_conn
, client_data
, save_type
,
6320 shutdown
, interact_style
, fast
)
6322 SmPointer client_data
;
6328 /* Handle already being in saveyourself */
6329 if (xsmp
.save_yourself
)
6330 SmcSaveYourselfDone(smc_conn
, True
);
6331 xsmp
.save_yourself
= True
;
6332 xsmp
.shutdown
= shutdown
;
6334 /* First up, preserve all files */
6336 ml_sync_all(FALSE
, FALSE
); /* preserve all swap files */
6339 verb_msg((char_u
*)_("XSMP handling save-yourself request"));
6341 # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
6342 /* Now see if we can ask about unsaved files */
6343 if (shutdown
&& !fast
&& gui
.in_use
)
6344 /* Need to interact with user, but need SM's permission */
6345 SmcInteractRequest(smc_conn
, SmDialogError
,
6346 xsmp_handle_interaction
, client_data
);
6350 /* Can stop the cycle here */
6351 SmcSaveYourselfDone(smc_conn
, True
);
6352 xsmp
.save_yourself
= False
;
6358 * Callback to warn us of imminent death.
6362 xsmp_die(smc_conn
, client_data
)
6364 SmPointer client_data
;
6368 /* quit quickly leaving swapfiles for modified buffers behind */
6369 getout_preserve_modified(0);
6374 * Callback to tell us that save-yourself has completed.
6378 xsmp_save_complete(smc_conn
, client_data
)
6380 SmPointer client_data
;
6382 xsmp
.save_yourself
= False
;
6387 * Callback to tell us that an instigated shutdown was cancelled
6388 * (maybe even by us)
6392 xsmp_shutdown_cancelled(smc_conn
, client_data
)
6394 SmPointer client_data
;
6396 if (xsmp
.save_yourself
)
6397 SmcSaveYourselfDone(smc_conn
, True
);
6398 xsmp
.save_yourself
= False
;
6399 xsmp
.shutdown
= False
;
6404 * Callback to tell us that a new ICE connection has been established.
6408 xsmp_ice_connection(iceConn
, clientData
, opening
, watchData
)
6410 IcePointer clientData
;
6412 IcePointer
*watchData
;
6414 /* Intercept creation of ICE connection fd */
6417 xsmp_icefd
= IceConnectionNumber(iceConn
);
6418 IceRemoveConnectionWatch(xsmp_ice_connection
, NULL
);
6423 /* Handle any ICE processing that's required; return FAIL if SM lost */
6425 xsmp_handle_requests()
6429 if (IceProcessMessages(xsmp
.iceconn
, NULL
, &rep
)
6430 == IceProcessMessagesIOError
)
6434 verb_msg((char_u
*)_("XSMP lost ICE connection"));
6444 /* Set up X Session Management Protocol */
6448 char errorstring
[80];
6450 SmcCallbacks smcallbacks
;
6458 verb_msg((char_u
*)_("XSMP opening connection"));
6460 xsmp
.save_yourself
= xsmp
.shutdown
= False
;
6462 /* Set up SM callbacks - must have all, even if they're not used */
6463 smcallbacks
.save_yourself
.callback
= xsmp_handle_save_yourself
;
6464 smcallbacks
.save_yourself
.client_data
= NULL
;
6465 smcallbacks
.die
.callback
= xsmp_die
;
6466 smcallbacks
.die
.client_data
= NULL
;
6467 smcallbacks
.save_complete
.callback
= xsmp_save_complete
;
6468 smcallbacks
.save_complete
.client_data
= NULL
;
6469 smcallbacks
.shutdown_cancelled
.callback
= xsmp_shutdown_cancelled
;
6470 smcallbacks
.shutdown_cancelled
.client_data
= NULL
;
6472 /* Set up a watch on ICE connection creations. The "dummy" argument is
6473 * apparently required for FreeBSD (we get a BUS error when using NULL). */
6474 if (IceAddConnectionWatch(xsmp_ice_connection
, &dummy
) == 0)
6477 verb_msg((char_u
*)_("XSMP ICE connection watch failed"));
6481 /* Create an SM connection */
6482 xsmp
.smcconn
= SmcOpenConnection(
6487 SmcSaveYourselfProcMask
| SmcDieProcMask
6488 | SmcSaveCompleteProcMask
| SmcShutdownCancelledProcMask
,
6492 sizeof(errorstring
),
6494 if (xsmp
.smcconn
== NULL
)
6496 char errorreport
[132];
6500 vim_snprintf(errorreport
, sizeof(errorreport
),
6501 _("XSMP SmcOpenConnection failed: %s"), errorstring
);
6502 verb_msg((char_u
*)errorreport
);
6506 xsmp
.iceconn
= SmcGetIceConnection(xsmp
.smcconn
);
6510 smname
.value
= "vim";
6512 smnameprop
.name
= "SmProgram";
6513 smnameprop
.type
= "SmARRAY8";
6514 smnameprop
.num_vals
= 1;
6515 smnameprop
.vals
= &smname
;
6517 smprops
[0] = &smnameprop
;
6518 SmcSetProperties(xsmp
.smcconn
, 1, smprops
);
6523 /* Shut down XSMP comms. */
6527 if (xsmp_icefd
!= -1)
6529 SmcCloseConnection(xsmp
.smcconn
, 0, NULL
);
6533 #endif /* USE_XSMP */
6537 /* Translate character to its CTRL- value */
6541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6544 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6545 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6546 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6550 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, 0, 0, 0,
6564 0, 0, 0, 0, 0, 0, 0,
6575 0, 0, 0, 0, 0, 0, 0, 0,
6588 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6590 /* BE - C0 */ 0, 0, 0,
6600 /* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
6610 /* DA - DF */ 0, 0, 0, 0, 0, 0,
6621 /* EA - FF*/ 0, 0, 0, 0, 0, 0,
6622 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6625 char MetaCharTable
[]=
6626 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6627 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
6628 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
6629 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
6630 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
6634 /* TODO: Use characters NOT numbers!!! */
6635 char CtrlCharTable
[]=
6636 {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
6637 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
6638 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
6639 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
6640 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,