blob: fd85ea89d75da0e72ae6318ca3411527705c6d81 [file] [log] [blame]
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10#if defined(MSDOS) || defined(WIN32) || defined(_WIN64)
11# include <io.h> /* for close() and dup() */
12#endif
13
14#define EXTERN
15#include "vim.h"
16
17#ifdef SPAWNO
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +000018# include <spawno.h> /* special MS-DOS swapping library */
Bram Moolenaarb4210b32004-06-13 14:51:16 +000019#endif
20
21#ifdef HAVE_FCNTL_H
22# include <fcntl.h>
23#endif
24
25#ifdef __CYGWIN__
26# ifndef WIN32
27# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() */
28# endif
29# include <limits.h>
30#endif
31
Bram Moolenaarc013cb62005-07-24 21:18:31 +000032/* Maximum number of commands from + or -c arguments. */
33#define MAX_ARG_CMDS 10
34
Bram Moolenaar58d98232005-07-23 22:25:46 +000035/* Struct for various parameters passed between main() and other functions. */
36typedef struct
37{
Bram Moolenaarc013cb62005-07-24 21:18:31 +000038 int argc;
39 char **argv;
40
41 int evim_mode; /* started as "evim" */
Bram Moolenaarc013cb62005-07-24 21:18:31 +000042 char_u *use_vimrc; /* vimrc from -u argument */
43
44 int n_commands; /* no. of commands from + or -c */
45 char_u *commands[MAX_ARG_CMDS]; /* commands from + or -c arg. */
46 char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
47 int n_pre_commands; /* no. of commands from --cmd */
48 char_u *pre_commands[MAX_ARG_CMDS]; /* commands from --cmd argument */
49
50 int edit_type; /* type of editing to do */
51 char_u *tagname; /* tag from -t argument */
52#ifdef FEAT_QUICKFIX
53 char_u *use_ef; /* 'errorfile' from -q argument */
54#endif
55
56 int want_full_screen;
57 int stdout_isatty; /* is stdout a terminal? */
58 char_u *term; /* specified terminal name */
59#ifdef FEAT_CRYPT
60 int ask_for_key; /* -x argument */
61#endif
62 int no_swap_file; /* "-n" argument used */
63#ifdef FEAT_EVAL
64 int use_debug_break_level;
65#endif
66#ifdef FEAT_WINDOWS
67 int window_count; /* number of windows to use */
68 int vert_windows; /* "-O" used instead of "-o" */
69#endif
70
71#ifdef FEAT_CLIENTSERVER
Bram Moolenaar58d98232005-07-23 22:25:46 +000072 int serverArg; /* TRUE when argument for a server */
73 char_u *serverName_arg; /* cmdline arg for server name */
Bram Moolenaarc013cb62005-07-24 21:18:31 +000074 char_u *serverStr; /* remote server command */
75 char_u *serverStrEnc; /* encoding of serverStr */
76 char_u *servername; /* allocated name for our server */
77#endif
78#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
79 int literal; /* don't expand file names */
80#endif
81#ifdef MSWIN
82 int full_path; /* file name argument was full path */
83#endif
84#ifdef FEAT_DIFF
85 int diff_mode; /* start with 'diff' set */
86#endif
Bram Moolenaar58d98232005-07-23 22:25:46 +000087} mparm_T;
88
Bram Moolenaarc013cb62005-07-24 21:18:31 +000089/* Values for edit_type. */
90#define EDIT_NONE 0 /* no edit type yet */
91#define EDIT_FILE 1 /* file name argument[s] given, use argument list */
92#define EDIT_STDIN 2 /* read file from stdin */
93#define EDIT_TAG 3 /* tag name argument given, use tagname */
94#define EDIT_QF 4 /* start in quickfix mode */
95
Bram Moolenaarb4210b32004-06-13 14:51:16 +000096#if defined(UNIX) || defined(VMS)
97static int file_owned __ARGS((char *fname));
98#endif
99static void mainerr __ARGS((int, char_u *));
100static void main_msg __ARGS((char *s));
101static void usage __ARGS((void));
102static int get_number_arg __ARGS((char_u *p, int *idx, int def));
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000103#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
104static void init_locale __ARGS((void));
105#endif
106static void parse_command_name __ARGS((mparm_T *parmp));
107static void early_arg_scan __ARGS((mparm_T *parmp));
108static void command_line_scan __ARGS((mparm_T *parmp));
109static void check_tty __ARGS((mparm_T *parmp));
110static void read_stdin __ARGS((void));
111static void create_windows __ARGS((mparm_T *parmp));
112#ifdef FEAT_WINDOWS
113static void edit_buffers __ARGS((mparm_T *parmp));
114#endif
115static void exe_pre_commands __ARGS((mparm_T *parmp));
116static void exe_commands __ARGS((mparm_T *parmp));
Bram Moolenaar58d98232005-07-23 22:25:46 +0000117static void source_startup_scripts __ARGS((mparm_T *parmp));
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000118static void main_start_gui __ARGS((void));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +0000119#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000120static void check_swap_exists_action __ARGS((void));
121#endif
122#ifdef FEAT_CLIENTSERVER
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000123static void exec_on_server __ARGS((mparm_T *parmp));
124static void prepare_server __ARGS((mparm_T *parmp));
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000125static void cmdsrv_main __ARGS((int *argc, char **argv, char_u *serverName_arg, char_u **serverStr));
126static char_u *serverMakeName __ARGS((char_u *arg, char *cmd));
127#endif
128
129
130#ifdef STARTUPTIME
131static FILE *time_fd = NULL;
132#endif
133
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000134/*
135 * Different types of error messages.
136 */
137static char *(main_errors[]) =
138{
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000139 N_("Unknown option argument"),
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000140#define ME_UNKNOWN_OPTION 0
141 N_("Too many edit arguments"),
142#define ME_TOO_MANY_ARGS 1
143 N_("Argument missing after"),
144#define ME_ARG_MISSING 2
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000145 N_("Garbage after option argument"),
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000146#define ME_GARBAGE 3
147 N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments"),
148#define ME_EXTRA_CMD 4
149 N_("Invalid argument for"),
150#define ME_INVALID_ARG 5
151};
152
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000153#ifndef PROTO /* don't want a prototype for main() */
154 int
155# ifdef VIMDLL
156_export
157# endif
158# ifdef FEAT_GUI_MSWIN
159# ifdef __BORLANDC__
160_cdecl
161# endif
162VimMain
163# else
164main
165# endif
166(argc, argv)
167 int argc;
168 char **argv;
169{
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000170 char_u *fname = NULL; /* file name from command line */
Bram Moolenaar58d98232005-07-23 22:25:46 +0000171 mparm_T params; /* various parameters passed between
172 * main() and other functions. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000173
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000174 /*
175 * Do any system-specific initialisations. These can NOT use IObuff or
176 * NameBuff. Thus emsg2() cannot be called!
177 */
178 mch_early_init();
179
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000180 /* Many variables are in "params" so that we can pass them to invoked
181 * functions without a lot of arguments. "argc" and "argv" are also
182 * copied, so that they can be changed. */
Bram Moolenaar58d98232005-07-23 22:25:46 +0000183 vim_memset(&params, 0, sizeof(params));
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000184 params.argc = argc;
185 params.argv = argv;
186 params.want_full_screen = TRUE;
187#ifdef FEAT_EVAL
188 params.use_debug_break_level = -1;
189#endif
190#ifdef FEAT_WINDOWS
191 params.window_count = -1;
192 params.vert_windows = MAYBE;
193#endif
Bram Moolenaar58d98232005-07-23 22:25:46 +0000194
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000195#ifdef FEAT_TCL
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000196 vim_tcl_init(params.argv[0]);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000197#endif
198
199#ifdef MEM_PROFILE
200 atexit(vim_mem_profile_dump);
201#endif
202
203#ifdef STARTUPTIME
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +0000204 time_fd = mch_fopen(STARTUPTIME, "a");
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000205 TIME_MSG("--- VIM STARTING ---");
206#endif
207
208#ifdef __EMX__
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000209 _wildcard(&params.argc, &params.argv);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000210#endif
211
212#ifdef FEAT_MBYTE
213 (void)mb_init(); /* init mb_bytelen_tab[] to ones */
214#endif
Bram Moolenaardcaf10e2005-01-21 11:55:25 +0000215#ifdef FEAT_EVAL
216 eval_init(); /* init global variables */
217#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000218
219#ifdef __QNXNTO__
220 qnx_init(); /* PhAttach() for clipboard, (and gui) */
221#endif
222
223#ifdef MAC_OS_CLASSIC
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000224 /* Prepare for possibly starting GUI sometime */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000225 /* Macintosh needs this before any memory is allocated. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000226 gui_prepare(&params.argc, params.argv);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000227 TIME_MSG("GUI prepared");
228#endif
229
230 /* Init the table of Normal mode commands. */
231 init_normal_cmds();
232
233#if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC)
Bram Moolenaar58d98232005-07-23 22:25:46 +0000234 make_version(); /* Construct the long version string. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000235#endif
236
237 /*
238 * Allocate space for the generic buffers (needed for set_init_1() and
239 * EMSG2()).
240 */
241 if ((IObuff = alloc(IOSIZE)) == NULL
242 || (NameBuff = alloc(MAXPATHL)) == NULL)
243 mch_exit(0);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000244 TIME_MSG("Allocated generic buffers");
245
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000246#ifdef NBDEBUG
247 /* Wait a moment for debugging NetBeans. Must be after allocating
248 * NameBuff. */
249 nbdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL");
250 nbdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20);
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000251 TIME_MSG("NetBeans debug wait");
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000252#endif
253
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000254#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
255 /*
256 * Setup to use the current locale (for ctype() and many other things).
257 * NOTE: Translated messages with encodings other than latin1 will not
258 * work until set_init_1() has been called!
259 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000260 init_locale();
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000261 TIME_MSG("locale set");
262#endif
263
264#ifdef FEAT_GUI
265 gui.dofork = TRUE; /* default is to use fork() */
266#endif
267
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000268 /*
Bram Moolenaar58d98232005-07-23 22:25:46 +0000269 * Do a first scan of the arguments in "argv[]":
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000270 * -display or --display
Bram Moolenaar58d98232005-07-23 22:25:46 +0000271 * --server...
272 * --socketid
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000273 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000274 early_arg_scan(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000275
276#ifdef FEAT_SUN_WORKSHOP
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000277 findYourself(params.argv[0]);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000278#endif
279#if defined(FEAT_GUI) && !defined(MAC_OS_CLASSIC)
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000280 /* Prepare for possibly starting GUI sometime */
281 gui_prepare(&params.argc, params.argv);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000282 TIME_MSG("GUI prepared");
283#endif
284
285#ifdef FEAT_CLIPBOARD
286 clip_init(FALSE); /* Initialise clipboard stuff */
287 TIME_MSG("clipboard setup");
288#endif
289
290 /*
291 * Check if we have an interactive window.
292 * On the Amiga: If there is no window, we open one with a newcli command
293 * (needed for :! to * work). mch_check_win() will also handle the -d or
294 * -dev argument.
295 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000296 params.stdout_isatty = (mch_check_win(params.argc, params.argv) != FAIL);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000297 TIME_MSG("window checked");
298
299 /*
300 * Allocate the first window and buffer. Can't do much without it.
301 */
302 win_alloc_first();
303
304 init_yank(); /* init yank buffers */
305
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000306 alist_init(&global_alist); /* Init the argument list to empty. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000307
308 /*
309 * Set the default values for the options.
310 * NOTE: Non-latin1 translated messages are working only after this,
311 * because this is where "has_mbyte" will be set, which is used by
312 * msg_outtrans_len_attr().
313 * First find out the home directory, needed to expand "~" in options.
314 */
315 init_homedir(); /* find real value of $HOME */
316 set_init_1();
317 TIME_MSG("inits 1");
318
319#ifdef FEAT_EVAL
320 set_lang_var(); /* set v:lang and v:ctype */
321#endif
322
323#ifdef FEAT_CLIENTSERVER
324 /*
325 * Do the client-server stuff, unless "--servername ''" was used.
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000326 * This may exit Vim if the command was sent to the server.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000327 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000328 exec_on_server(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000329#endif
330
331 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000332 * Figure out the way to work from the command name argv[0].
333 * "vimdiff" starts diff mode, "rvim" sets "restricted", etc.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000334 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000335 parse_command_name(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000336
337 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000338 * Process the command line arguments. File names are put in the global
339 * argument list "global_alist".
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000340 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000341 command_line_scan(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000342 TIME_MSG("parsing arguments");
343
344 /*
345 * On some systems, when we compile with the GUI, we always use it. On Mac
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000346 * there is no terminal version, and on Windows we can't fork one off with
347 * :gui.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000348 */
349#ifdef ALWAYS_USE_GUI
350 gui.starting = TRUE;
351#else
Bram Moolenaar241a8aa2005-12-06 20:04:44 +0000352# if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000353 /*
354 * Check if the GUI can be started. Reset gui.starting if not.
355 * Don't know about other systems, stay on the safe side and don't check.
356 */
357 if (gui.starting && gui_init_check() == FAIL)
358 {
359 gui.starting = FALSE;
360
361 /* When running "evim" or "gvim -y" we need the menus, exit if we
362 * don't have them. */
Bram Moolenaar58d98232005-07-23 22:25:46 +0000363 if (params.evim_mode)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000364 mch_exit(1);
365 }
366# endif
367#endif
368
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000369 if (GARGCOUNT > 0)
370 {
371#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
372 /*
373 * Expand wildcards in file names.
374 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000375 if (!params.literal)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000376 {
377 /* Temporarily add '(' and ')' to 'isfname'. These are valid
378 * filename characters but are excluded from 'isfname' to make
379 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
380 do_cmdline_cmd((char_u *)":set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +0000381 alist_expand(NULL, 0);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000382 do_cmdline_cmd((char_u *)":set isf&");
383 }
384#endif
385 fname = alist_name(&GARGLIST[0]);
386 }
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000387
388#if defined(WIN32) && defined(FEAT_MBYTE)
389 {
390 extern void set_alist_count(void);
391
392 /* Remember the number of entries in the argument list. If it changes
393 * we don't react on setting 'encoding'. */
394 set_alist_count();
395 }
396#endif
397
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000398#ifdef MSWIN
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000399 if (GARGCOUNT == 1 && params.full_path)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000400 {
401 /*
402 * If there is one filename, fully qualified, we have very probably
403 * been invoked from explorer, so change to the file's directory.
404 * Hint: to avoid this when typing a command use a forward slash.
405 * If the cd fails, it doesn't matter.
406 */
407 (void)vim_chdirfile(fname);
408 }
409#endif
410 TIME_MSG("expanding arguments");
411
412#ifdef FEAT_DIFF
Bram Moolenaar231334e2005-07-25 20:46:57 +0000413 if (params.diff_mode)
414 {
415 if (params.window_count == -1)
416 params.window_count = 0; /* open up to 3 windows */
417 if (params.vert_windows == MAYBE)
418 params.vert_windows = TRUE; /* use vertical split */
419 }
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000420#endif
421
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000422 /* Don't redraw until much later. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000423 ++RedrawingDisabled;
424
425 /*
426 * When listing swap file names, don't do cursor positioning et. al.
427 */
428 if (recoverymode && fname == NULL)
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000429 params.want_full_screen = FALSE;
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000430
431 /*
432 * When certain to start the GUI, don't check capabilities of terminal.
433 * For GTK we can't be sure, but when started from the desktop it doesn't
434 * make sense to try using a terminal.
435 */
Bram Moolenaar241a8aa2005-12-06 20:04:44 +0000436#if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000437 if (gui.starting
438# ifdef FEAT_GUI_GTK
439 && !isatty(2)
440# endif
441 )
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000442 params.want_full_screen = FALSE;
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000443#endif
444
445#if defined(FEAT_GUI_MAC) && defined(MACOS_X_UNIX)
446 /* When the GUI is started from Finder, need to display messages in a
447 * message box. isatty(2) returns TRUE anyway, thus we need to check the
448 * name to know we're not started from a terminal. */
449 if (gui.starting && (!isatty(2) || strcmp("/dev/console", ttyname(2)) == 0))
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000450 params.want_full_screen = FALSE;
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000451#endif
452
453 /*
454 * mch_init() sets up the terminal (window) for use. This must be
455 * done after resetting full_screen, otherwise it may move the cursor
456 * (MSDOS).
457 * Note that we may use mch_exit() before mch_init()!
458 */
459 mch_init();
460 TIME_MSG("shell init");
461
462#ifdef USE_XSMP
463 /*
464 * For want of anywhere else to do it, try to connect to xsmp here.
465 * Fitting it in after gui_mch_init, but before gui_init (via termcapinit).
466 * Hijacking -X 'no X connection' to also disable XSMP connection as that
467 * has a similar delay upon failure.
468 * Only try if SESSION_MANAGER is set to something non-null.
469 */
470 if (!x_no_connect)
471 {
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000472 char *p = getenv("SESSION_MANAGER");
473
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000474 if (p != NULL && *p != NUL)
475 {
476 xsmp_init();
477 TIME_MSG("xsmp init");
478 }
479 }
480#endif
481
482 /*
483 * Print a warning if stdout is not a terminal.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000484 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000485 check_tty(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000486
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000487 /* This message comes before term inits, but after setting "silent_mode"
488 * when the input is not a tty. */
489 if (GARGCOUNT > 1 && !silent_mode)
490 printf(_("%d files to edit\n"), GARGCOUNT);
491
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000492 if (params.want_full_screen && !silent_mode)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000493 {
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000494 termcapinit(params.term); /* set terminal name and get terminal
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000495 capabilities (will set full_screen) */
496 screen_start(); /* don't know where cursor is now */
497 TIME_MSG("Termcap init");
498 }
499
500 /*
501 * Set the default values for the options that use Rows and Columns.
502 */
503 ui_get_shellsize(); /* inits Rows and Columns */
504#ifdef FEAT_NETBEANS_INTG
505 if (usingNetbeans)
506 Columns += 2; /* leave room for glyph gutter */
507#endif
508 firstwin->w_height = Rows - p_ch;
509 topframe->fr_height = Rows - p_ch;
510#ifdef FEAT_VERTSPLIT
511 firstwin->w_width = Columns;
512 topframe->fr_width = Columns;
513#endif
514#ifdef FEAT_DIFF
515 /* Set the 'diff' option now, so that it can be checked for in a .vimrc
516 * file. There is no buffer yet though. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000517 if (params.diff_mode)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000518 diff_win_options(firstwin, FALSE);
519#endif
520
521 cmdline_row = Rows - p_ch;
522 msg_row = cmdline_row;
523 screenalloc(FALSE); /* allocate screen buffers */
524 set_init_2();
525 TIME_MSG("inits 2");
526
527 msg_scroll = TRUE;
528 no_wait_return = TRUE;
529
530 init_mappings(); /* set up initial mappings */
531
532 init_highlight(TRUE, FALSE); /* set the default highlight groups */
533 TIME_MSG("init highlight");
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000534
535#ifdef FEAT_EVAL
536 /* Set the break level after the terminal is initialized. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000537 debug_break_level = params.use_debug_break_level;
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000538#endif
539
Bram Moolenaar58d98232005-07-23 22:25:46 +0000540 /* Execute --cmd arguments. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000541 exe_pre_commands(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000542
Bram Moolenaar58d98232005-07-23 22:25:46 +0000543 /* Source startup scripts. */
544 source_startup_scripts(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000545
546#ifdef FEAT_EVAL
547 /*
548 * Read all the plugin files.
549 * Only when compiled with +eval, since most plugins need it.
550 */
551 if (p_lpl)
552 {
Bram Moolenaar07d4d732005-10-03 22:04:08 +0000553 source_runtime((char_u *)"plugin/**/*.vim", TRUE);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000554 TIME_MSG("loading plugins");
555 }
556#endif
557
558 /*
559 * Recovery mode without a file name: List swap files.
560 * This uses the 'dir' option, therefore it must be after the
561 * initializations.
562 */
563 if (recoverymode && fname == NULL)
564 {
565 recover_names(NULL, TRUE, 0);
566 mch_exit(0);
567 }
568
569 /*
570 * Set a few option defaults after reading .vimrc files:
571 * 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
572 */
573 set_init_3();
574 TIME_MSG("inits 3");
575
576 /*
577 * "-n" argument: Disable swap file by setting 'updatecount' to 0.
578 * Note that this overrides anything from a vimrc file.
579 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000580 if (params.no_swap_file)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000581 p_uc = 0;
582
583#ifdef FEAT_FKMAP
584 if (curwin->w_p_rl && p_altkeymap)
585 {
586 p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
587# ifdef FEAT_ARABIC
588 curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
589# endif
590 p_fkmap = TRUE; /* Set the Farsi keymap mode */
591 }
592#endif
593
594#ifdef FEAT_GUI
595 if (gui.starting)
596 {
597#if defined(UNIX) || defined(VMS)
598 /* When something caused a message from a vimrc script, need to output
599 * an extra newline before the shell prompt. */
600 if (did_emsg || msg_didout)
601 putchar('\n');
602#endif
603
604 gui_start(); /* will set full_screen to TRUE */
605 TIME_MSG("starting GUI");
606
607 /* When running "evim" or "gvim -y" we need the menus, exit if we
608 * don't have them. */
Bram Moolenaar58d98232005-07-23 22:25:46 +0000609 if (!gui.in_use && params.evim_mode)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000610 mch_exit(1);
611 }
612#endif
613
614#ifdef SPAWNO /* special MSDOS swapping library */
615 init_SPAWNO("", SWAP_ANY);
616#endif
617
618#ifdef FEAT_VIMINFO
619 /*
620 * Read in registers, history etc, but not marks, from the viminfo file
621 */
622 if (*p_viminfo != NUL)
623 {
624 read_viminfo(NULL, TRUE, FALSE, FALSE);
625 TIME_MSG("reading viminfo");
626 }
627#endif
628
629#ifdef FEAT_QUICKFIX
630 /*
631 * "-q errorfile": Load the error file now.
632 * If the error file can't be read, exit before doing anything else.
633 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000634 if (params.edit_type == EDIT_QF)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000635 {
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000636 if (params.use_ef != NULL)
637 set_string_option_direct((char_u *)"ef", -1,
638 params.use_ef, OPT_FREE);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000639 if (qf_init(p_ef, p_efm, TRUE) < 0)
640 {
641 out_char('\n');
642 mch_exit(3);
643 }
644 TIME_MSG("reading errorfile");
645 }
646#endif
647
648 /*
649 * Start putting things on the screen.
650 * Scroll screen down before drawing over it
651 * Clear screen now, so file message will not be cleared.
652 */
653 starting = NO_BUFFERS;
654 no_wait_return = FALSE;
655 if (!exmode_active)
656 msg_scroll = FALSE;
657
658#ifdef FEAT_GUI
659 /*
660 * This seems to be required to make callbacks to be called now, instead
661 * of after things have been put on the screen, which then may be deleted
662 * when getting a resize callback.
663 * For the Mac this handles putting files dropped on the Vim icon to
664 * global_alist.
665 */
666 if (gui.in_use)
667 {
668# ifdef FEAT_SUN_WORKSHOP
669 if (!usingSunWorkShop)
670# endif
671 gui_wait_for_chars(50L);
672 TIME_MSG("GUI delay");
673 }
674#endif
675
676#if defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)
677 qnx_clip_init();
678#endif
679
680#ifdef FEAT_XCLIPBOARD
681 /* Start using the X clipboard, unless the GUI was started. */
682# ifdef FEAT_GUI
683 if (!gui.in_use)
684# endif
685 {
686 setup_term_clip();
687 TIME_MSG("setup clipboard");
688 }
689#endif
690
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000691#ifdef FEAT_CLIENTSERVER
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000692 /* Prepare for being a Vim server. */
693 prepare_server(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000694#endif
695
696 /*
697 * If "-" argument given: Read file from stdin.
698 * Do this before starting Raw mode, because it may change things that the
699 * writing end of the pipe doesn't like, e.g., in case stdin and stderr
700 * are the same terminal: "cat | vim -".
701 * Using autocommands here may cause trouble...
702 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000703 if (params.edit_type == EDIT_STDIN && !recoverymode)
704 read_stdin();
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000705
706#if defined(UNIX) || defined(VMS)
707 /* When switching screens and something caused a message from a vimrc
708 * script, need to output an extra newline on exit. */
709 if ((did_emsg || msg_didout) && *T_TI != NUL)
710 newline_on_exit = TRUE;
711#endif
712
713 /*
714 * When done something that is not allowed or error message call
715 * wait_return. This must be done before starttermcap(), because it may
716 * switch to another screen. It must be done after settmode(TMODE_RAW),
717 * because we want to react on a single key stroke.
718 * Call settmode and starttermcap here, so the T_KS and T_TI may be
719 * defined by termcapinit and redifined in .exrc.
720 */
721 settmode(TMODE_RAW);
722 TIME_MSG("setting raw mode");
723
724 if (need_wait_return || msg_didany)
725 {
726 wait_return(TRUE);
727 TIME_MSG("waiting for return");
728 }
729
730 starttermcap(); /* start termcap if not done by wait_return() */
731 TIME_MSG("start termcap");
732
733#ifdef FEAT_MOUSE
734 setmouse(); /* may start using the mouse */
735#endif
736 if (scroll_region)
737 scroll_region_reset(); /* In case Rows changed */
Bram Moolenaar58d98232005-07-23 22:25:46 +0000738 scroll_start(); /* may scroll the screen to the right position */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000739
740 /*
741 * Don't clear the screen when starting in Ex mode, unless using the GUI.
742 */
743 if (exmode_active
744#ifdef FEAT_GUI
745 && !gui.in_use
746#endif
747 )
748 must_redraw = CLEAR;
749 else
750 {
751 screenclear(); /* clear screen */
752 TIME_MSG("clearing screen");
753 }
754
755#ifdef FEAT_CRYPT
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000756 if (params.ask_for_key)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000757 {
758 (void)get_crypt_key(TRUE, TRUE);
759 TIME_MSG("getting crypt key");
760 }
761#endif
762
763 no_wait_return = TRUE;
764
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000765 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000766 * Create the requested number of windows and edit buffers in them.
767 * Also does recovery if "recoverymode" set.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000768 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000769 create_windows(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000770 TIME_MSG("opening buffers");
771
772 /* Ex starts at last line of the file */
773 if (exmode_active)
774 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
775
776#ifdef FEAT_AUTOCMD
777 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
778 TIME_MSG("BufEnter autocommands");
779#endif
780 setpcmark();
781
782#ifdef FEAT_QUICKFIX
783 /*
784 * When started with "-q errorfile" jump to first error now.
785 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000786 if (params.edit_type == EDIT_QF)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000787 {
788 qf_jump(0, 0, FALSE);
789 TIME_MSG("jump to first error");
790 }
791#endif
792
793#ifdef FEAT_WINDOWS
794 /*
795 * If opened more than one window, start editing files in the other
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000796 * windows.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000797 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000798 edit_buffers(&params);
799#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000800
801#ifdef FEAT_DIFF
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000802 if (params.diff_mode)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000803 {
804 win_T *wp;
805
806 /* set options in each window for "vimdiff". */
807 for (wp = firstwin; wp != NULL; wp = wp->w_next)
808 diff_win_options(wp, TRUE);
809 }
810#endif
811
812 /*
813 * Shorten any of the filenames, but only when absolute.
814 */
815 shorten_fnames(FALSE);
816
817 /*
818 * Need to jump to the tag before executing the '-c command'.
819 * Makes "vim -c '/return' -t main" work.
820 */
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000821 if (params.tagname != NULL)
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000822 {
Bram Moolenaar146522e2005-12-16 21:55:46 +0000823#if defined(HAS_SWAP_EXISTS_ACTION)
824 swap_exists_did_quit = FALSE;
825#endif
826
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000827 vim_snprintf((char *)IObuff, IOSIZE, "ta %s", params.tagname);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000828 do_cmdline_cmd(IObuff);
829 TIME_MSG("jumping to tag");
Bram Moolenaar146522e2005-12-16 21:55:46 +0000830
831#if defined(HAS_SWAP_EXISTS_ACTION)
832 /* If the user doesn't want to edit the file then we quit here. */
833 if (swap_exists_did_quit)
834 getout(1);
835#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000836 }
837
Bram Moolenaarc013cb62005-07-24 21:18:31 +0000838 /* Execute any "+", "-c" and "-S" arguments. */
839 if (params.n_commands > 0)
840 exe_commands(&params);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000841
842 RedrawingDisabled = 0;
843 redraw_all_later(NOT_VALID);
844 no_wait_return = FALSE;
845 starting = 0;
846
Bram Moolenaara40ceaf2006-01-13 22:35:40 +0000847#ifdef FEAT_TERMRESPONSE
848 /* Requesting the termresponse is postponed until here, so that a "-c q"
849 * argument doesn't make it appear in the shell Vim was started from. */
850 may_req_termresponse();
851#endif
852
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000853 /* start in insert mode */
854 if (p_im)
855 need_start_insertmode = TRUE;
856
857#ifdef FEAT_AUTOCMD
858 apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
859 TIME_MSG("VimEnter autocommands");
860#endif
861
862#if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
863 /* When a startup script or session file setup for diff'ing and
864 * scrollbind, sync the scrollbind now. */
865 if (curwin->w_p_diff && curwin->w_p_scb)
866 {
867 update_topline();
868 check_scrollbind((linenr_T)0, 0L);
869 TIME_MSG("diff scrollbinding");
870 }
871#endif
872
873#if defined(WIN3264) && !defined(FEAT_GUI_W32)
874 mch_set_winsize_now(); /* Allow winsize changes from now on */
875#endif
876
877 /* If ":startinsert" command used, stuff a dummy command to be able to
878 * call normal_cmd(), which will then start Insert mode. */
879 if (restart_edit != 0)
Bram Moolenaarebefac62005-12-28 22:39:57 +0000880 stuffcharReadbuff(K_NOP);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000881
882#ifdef FEAT_NETBEANS_INTG
883 if (usingNetbeans)
884 /* Tell the client that it can start sending commands. */
885 netbeans_startup_done();
886#endif
887
888 TIME_MSG("before starting main loop");
889
890 /*
891 * Call the main command loop. This never returns.
892 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000893 main_loop(FALSE, FALSE);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000894
895 return 0;
896}
897#endif /* PROTO */
898
899/*
900 * Main loop: Execute Normal mode commands until exiting Vim.
901 * Also used to handle commands in the command-line window, until the window
902 * is closed.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000903 * Also used to handle ":visual" command after ":global": execute Normal mode
904 * commands, return when entering Ex mode. "noexmode" is TRUE then.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000905 */
906 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000907main_loop(cmdwin, noexmode)
908 int cmdwin; /* TRUE when working in the command-line window */
909 int noexmode; /* TRUE when return on entering Ex mode */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000910{
911 oparg_T oa; /* operator arguments */
912
913#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
914 /* Setup to catch a terminating error from the X server. Just ignore
915 * it, restore the state and continue. This might not always work
916 * properly, but at least we don't exit unexpectedly when the X server
917 * exists while Vim is running in a console. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000918 if (!cmdwin && !noexmode && SETJMP(x_jump_env))
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000919 {
920 State = NORMAL;
921# ifdef FEAT_VISUAL
922 VIsual_active = FALSE;
923# endif
924 got_int = TRUE;
925 need_wait_return = FALSE;
926 global_busy = FALSE;
927 exmode_active = 0;
928 skip_redraw = FALSE;
929 RedrawingDisabled = 0;
930 no_wait_return = 0;
931# ifdef FEAT_EVAL
932 emsg_skip = 0;
933# endif
934 emsg_off = 0;
935# ifdef FEAT_MOUSE
936 setmouse();
937# endif
938 settmode(TMODE_RAW);
939 starttermcap();
940 scroll_start();
941 redraw_later_clear();
942 }
943#endif
944
945 clear_oparg(&oa);
946 while (!cmdwin
947#ifdef FEAT_CMDWIN
948 || cmdwin_result == 0
949#endif
950 )
951 {
952 if (stuff_empty())
953 {
954 did_check_timestamps = FALSE;
955 if (need_check_timestamps)
956 check_timestamps(FALSE);
957 if (need_wait_return) /* if wait_return still needed ... */
958 wait_return(FALSE); /* ... call it now */
959 if (need_start_insertmode && goto_im()
960#ifdef FEAT_VISUAL
961 && !VIsual_active
962#endif
963 )
964 {
965 need_start_insertmode = FALSE;
966 stuffReadbuff((char_u *)"i"); /* start insert mode next */
967 /* skip the fileinfo message now, because it would be shown
968 * after insert mode finishes! */
969 need_fileinfo = FALSE;
970 }
971 }
972 if (got_int && !global_busy)
973 {
974 if (!quit_more)
975 (void)vgetc(); /* flush all buffers */
976 got_int = FALSE;
977 }
978 if (!exmode_active)
979 msg_scroll = FALSE;
980 quit_more = FALSE;
981
982 /*
983 * If skip redraw is set (for ":" in wait_return()), don't redraw now.
984 * If there is nothing in the stuff_buffer or do_redraw is TRUE,
985 * update cursor and redraw.
986 */
987 if (skip_redraw || exmode_active)
988 skip_redraw = FALSE;
989 else if (do_redraw || stuff_empty())
990 {
991#if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
992 /* Include a closed fold completely in the Visual area. */
993 foldAdjustVisual();
994#endif
995#ifdef FEAT_FOLDING
996 /*
997 * When 'foldclose' is set, apply 'foldlevel' to folds that don't
998 * contain the cursor.
999 * When 'foldopen' is "all", open the fold(s) under the cursor.
1000 * This may mark the window for redrawing.
1001 */
1002 if (hasAnyFolding(curwin) && !char_avail())
1003 {
1004 foldCheckClose();
1005 if (fdo_flags & FDO_ALL)
1006 foldOpenCursor();
1007 }
1008#endif
1009
1010 /*
1011 * Before redrawing, make sure w_topline is correct, and w_leftcol
1012 * if lines don't wrap, and w_skipcol if lines wrap.
1013 */
1014 update_topline();
1015 validate_cursor();
1016
1017#ifdef FEAT_VISUAL
1018 if (VIsual_active)
1019 update_curbuf(INVERTED);/* update inverted part */
1020 else
1021#endif
1022 if (must_redraw)
1023 update_screen(0);
1024 else if (redraw_cmdline || clear_cmdline)
1025 showmode();
1026#ifdef FEAT_WINDOWS
1027 redraw_statuslines();
1028#endif
1029#ifdef FEAT_TITLE
1030 if (need_maketitle)
1031 maketitle();
1032#endif
1033 /* display message after redraw */
1034 if (keep_msg != NULL)
1035 {
1036 char_u *p;
1037
1038 /* msg_attr_keep() will set keep_msg to NULL, must free the
1039 * string here. */
1040 p = keep_msg;
1041 msg_attr(p, keep_msg_attr);
1042 vim_free(p);
1043 }
1044 if (need_fileinfo) /* show file info after redraw */
1045 {
1046 fileinfo(FALSE, TRUE, FALSE);
1047 need_fileinfo = FALSE;
1048 }
1049
1050 emsg_on_display = FALSE; /* can delete error message now */
1051 did_emsg = FALSE;
1052 msg_didany = FALSE; /* reset lines_left in msg_start() */
Bram Moolenaar661b1822005-07-28 22:36:45 +00001053 may_clear_sb_text(); /* clear scroll-back text on next msg */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001054 showruler(FALSE);
1055
1056 setcursor();
1057 cursor_on();
1058
1059 do_redraw = FALSE;
1060 }
1061#ifdef FEAT_GUI
1062 if (need_mouse_correct)
1063 gui_mouse_correct();
1064#endif
1065
1066 /*
1067 * Update w_curswant if w_set_curswant has been set.
1068 * Postponed until here to avoid computing w_virtcol too often.
1069 */
1070 update_curswant();
1071
1072 /*
1073 * If we're invoked as ex, do a round of ex commands.
1074 * Otherwise, get and execute a normal mode command.
1075 */
1076 if (exmode_active)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001077 {
1078 if (noexmode) /* End of ":global/path/visual" commands */
1079 return;
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001080 do_exmode(exmode_active == EXMODE_VIM);
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001081 }
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001082 else
1083 normal_cmd(&oa, TRUE);
1084 }
1085}
1086
1087
1088#if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO)
1089/*
1090 * Exit, but leave behind swap files for modified buffers.
1091 */
1092 void
1093getout_preserve_modified(exitval)
1094 int exitval;
1095{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001096# if defined(SIGHUP) && defined(SIG_IGN)
1097 /* Ignore SIGHUP, because a dropped connection causes a read error, which
1098 * makes Vim exit and then handling SIGHUP causes various reentrance
1099 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001100 signal(SIGHUP, SIG_IGN);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001101# endif
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001102
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001103 ml_close_notmod(); /* close all not-modified buffers */
1104 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
1105 ml_close_all(FALSE); /* close all memfiles, without deleting */
1106 getout(exitval); /* exit Vim properly */
1107}
1108#endif
1109
1110
1111/* Exit properly */
1112 void
1113getout(exitval)
1114 int exitval;
1115{
1116#ifdef FEAT_AUTOCMD
1117 buf_T *buf;
1118 win_T *wp;
1119#endif
1120
1121 exiting = TRUE;
1122
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001123 /* When running in Ex mode an error causes us to exit with a non-zero exit
1124 * code. POSIX requires this, although it's not 100% clear from the
1125 * standard. */
1126 if (exmode_active)
1127 exitval += ex_exitval;
1128
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001129 /* Position the cursor on the last screen line, below all the text */
1130#ifdef FEAT_GUI
1131 if (!gui.in_use)
1132#endif
1133 windgoto((int)Rows - 1, 0);
1134
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +00001135#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
1136 /* Optionally print hashtable efficiency. */
1137 hash_debug_results();
1138#endif
1139
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001140#ifdef FEAT_GUI
1141 msg_didany = FALSE;
1142#endif
1143
1144#ifdef FEAT_AUTOCMD
1145 /* Trigger BufWinLeave for all windows, but only once per buffer. */
1146 for (wp = firstwin; wp != NULL; )
1147 {
1148 buf = wp->w_buffer;
1149 if (buf->b_changedtick != -1)
1150 {
1151 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
1152 FALSE, buf);
1153 buf->b_changedtick = -1; /* note that we did it already */
1154 wp = firstwin; /* restart, window may be closed */
1155 }
1156 else
1157 wp = wp->w_next;
1158 }
1159 /* Trigger BufUnload for buffers that are loaded */
1160 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1161 if (buf->b_ml.ml_mfp != NULL)
1162 {
1163 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
1164 FALSE, buf);
1165 if (!buf_valid(buf)) /* autocmd may delete the buffer */
1166 break;
1167 }
1168 apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
1169#endif
1170
1171#ifdef FEAT_VIMINFO
1172 if (*p_viminfo != NUL)
1173 /* Write out the registers, history, marks etc, to the viminfo file */
1174 write_viminfo(NULL, FALSE);
1175#endif
1176
1177#ifdef FEAT_AUTOCMD
1178 apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
1179#endif
1180
Bram Moolenaar05159a02005-02-26 23:04:13 +00001181#ifdef FEAT_PROFILE
1182 profile_dump();
1183#endif
1184
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001185 if (did_emsg
1186#ifdef FEAT_GUI
1187 || (gui.in_use && msg_didany && p_verbose > 0)
1188#endif
1189 )
1190 {
1191 /* give the user a chance to read the (error) message */
1192 no_wait_return = FALSE;
1193 wait_return(FALSE);
1194 }
1195
1196#ifdef FEAT_AUTOCMD
1197 /* Position the cursor again, the autocommands may have moved it */
1198# ifdef FEAT_GUI
1199 if (!gui.in_use)
1200# endif
1201 windgoto((int)Rows - 1, 0);
1202#endif
1203
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001204#ifdef FEAT_MZSCHEME
1205 mzscheme_end();
1206#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001207#ifdef FEAT_TCL
1208 tcl_end();
1209#endif
1210#ifdef FEAT_RUBY
1211 ruby_end();
1212#endif
1213#ifdef FEAT_PYTHON
1214 python_end();
1215#endif
1216#ifdef FEAT_PERL
1217 perl_end();
1218#endif
1219#if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
1220 iconv_end();
1221#endif
1222#ifdef FEAT_NETBEANS_INTG
1223 netbeans_end();
1224#endif
1225
1226 mch_exit(exitval);
1227}
1228
1229/*
1230 * Get a (optional) count for a Vim argument.
1231 */
1232 static int
1233get_number_arg(p, idx, def)
1234 char_u *p; /* pointer to argument */
1235 int *idx; /* index in argument, is incremented */
1236 int def; /* default value */
1237{
1238 if (vim_isdigit(p[*idx]))
1239 {
1240 def = atoi((char *)&(p[*idx]));
1241 while (vim_isdigit(p[*idx]))
1242 *idx = *idx + 1;
1243 }
1244 return def;
1245}
1246
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001247#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1248/*
1249 * Setup to use the current locale (for ctype() and many other things).
1250 */
1251 static void
1252init_locale()
1253{
1254 setlocale(LC_ALL, "");
Bram Moolenaar482aaeb2005-09-29 18:26:07 +00001255# ifdef WIN32
1256 /* Apparently MS-Windows printf() may cause a crash when we give it 8-bit
1257 * text while it's expecting text in the current locale. This call avoids
1258 * that. */
1259 setlocale(LC_CTYPE, "C");
1260# endif
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001261
1262# ifdef FEAT_GETTEXT
1263 {
1264 int mustfree = FALSE;
1265 char_u *p;
1266
1267# ifdef DYNAMIC_GETTEXT
1268 /* Initialize the gettext library */
1269 dyn_libintl_init(NULL);
1270# endif
1271 /* expand_env() doesn't work yet, because chartab[] is not initialized
1272 * yet, call vim_getenv() directly */
1273 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1274 if (p != NULL && *p != NUL)
1275 {
1276 STRCPY(NameBuff, p);
1277 STRCAT(NameBuff, "/lang");
1278 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1279 }
1280 if (mustfree)
1281 vim_free(p);
1282 textdomain(VIMPACKAGE);
1283 }
1284# endif
1285}
1286#endif
1287
1288/*
1289 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1290 * If the executable name starts with "r" we disable shell commands.
1291 * If the next character is "e" we run in Easy mode.
1292 * If the next character is "g" we run the GUI version.
1293 * If the next characters are "view" we start in readonly mode.
1294 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1295 * If the next characters are "ex" we start in Ex mode. If it's followed
1296 * by "im" use improved Ex mode.
1297 */
1298 static void
1299parse_command_name(parmp)
1300 mparm_T *parmp;
1301{
1302 char_u *initstr;
1303
1304 initstr = gettail((char_u *)parmp->argv[0]);
1305
1306#ifdef MACOS_X_UNIX
1307 /* An issue has been seen when launching Vim in such a way that
1308 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1309 * executable or a symbolic link of it. Until this issue is resolved
1310 * we prohibit the GUI from being used.
1311 */
1312 if (STRCMP(initstr, parmp->argv[0]) == 0)
1313 disallow_gui = TRUE;
1314
1315 /* TODO: On MacOS X default to gui if argv[0] ends in:
1316 * /vim.app/Contents/MacOS/Vim */
1317#endif
1318
1319#ifdef FEAT_EVAL
1320 set_vim_var_string(VV_PROGNAME, initstr, -1);
1321#endif
1322
1323 if (TOLOWER_ASC(initstr[0]) == 'r')
1324 {
1325 restricted = TRUE;
1326 ++initstr;
1327 }
1328
1329 /* Avoid using evim mode for "editor". */
1330 if (TOLOWER_ASC(initstr[0]) == 'e'
1331 && (TOLOWER_ASC(initstr[1]) == 'v'
1332 || TOLOWER_ASC(initstr[1]) == 'g'))
1333 {
1334#ifdef FEAT_GUI
1335 gui.starting = TRUE;
1336#endif
1337 parmp->evim_mode = TRUE;
1338 ++initstr;
1339 }
1340
1341 if (TOLOWER_ASC(initstr[0]) == 'g' || initstr[0] == 'k')
1342 {
1343 main_start_gui();
1344#ifdef FEAT_GUI
1345 ++initstr;
1346#endif
1347 }
1348
1349 if (STRNICMP(initstr, "view", 4) == 0)
1350 {
1351 readonlymode = TRUE;
1352 curbuf->b_p_ro = TRUE;
1353 p_uc = 10000; /* don't update very often */
1354 initstr += 4;
1355 }
1356 else if (STRNICMP(initstr, "vim", 3) == 0)
1357 initstr += 3;
1358
1359 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1360 if (STRICMP(initstr, "diff") == 0)
1361 {
1362#ifdef FEAT_DIFF
1363 parmp->diff_mode = TRUE;
1364#else
1365 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1366 mch_errmsg("\n");
1367 mch_exit(2);
1368#endif
1369 }
1370
1371 if (STRNICMP(initstr, "ex", 2) == 0)
1372 {
1373 if (STRNICMP(initstr + 2, "im", 2) == 0)
1374 exmode_active = EXMODE_VIM;
1375 else
1376 exmode_active = EXMODE_NORMAL;
1377 change_compatible(TRUE); /* set 'compatible' */
1378 }
1379}
1380
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001381/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00001382 * Get the name of the display, before gui_prepare() removes it from
1383 * argv[]. Used for the xterm-clipboard display.
1384 *
1385 * Also find the --server... arguments and --socketid
1386 */
1387/*ARGSUSED*/
1388 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001389early_arg_scan(parmp)
Bram Moolenaar58d98232005-07-23 22:25:46 +00001390 mparm_T *parmp;
1391{
1392#if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001393 int argc = parmp->argc;
1394 char **argv = parmp->argv;
Bram Moolenaar58d98232005-07-23 22:25:46 +00001395 int i;
1396
1397 for (i = 1; i < argc; i++)
1398 {
1399 if (STRCMP(argv[i], "--") == 0)
1400 break;
1401# ifdef FEAT_XCLIPBOARD
1402 else if (STRICMP(argv[i], "-display") == 0
Bram Moolenaar241a8aa2005-12-06 20:04:44 +00001403# if defined(FEAT_GUI_GTK)
Bram Moolenaar58d98232005-07-23 22:25:46 +00001404 || STRICMP(argv[i], "--display") == 0
1405# endif
1406 )
1407 {
1408 if (i == argc - 1)
1409 mainerr_arg_missing((char_u *)argv[i]);
1410 xterm_display = argv[++i];
1411 }
1412# endif
1413# ifdef FEAT_CLIENTSERVER
1414 else if (STRICMP(argv[i], "--servername") == 0)
1415 {
1416 if (i == argc - 1)
1417 mainerr_arg_missing((char_u *)argv[i]);
1418 parmp->serverName_arg = (char_u *)argv[++i];
1419 }
1420 else if (STRICMP(argv[i], "--serverlist") == 0
1421 || STRICMP(argv[i], "--remote-send") == 0
1422 || STRICMP(argv[i], "--remote-expr") == 0
1423 || STRICMP(argv[i], "--remote") == 0
1424 || STRICMP(argv[i], "--remote-silent") == 0)
1425 parmp->serverArg = TRUE;
1426 else if (STRICMP(argv[i], "--remote-wait") == 0
1427 || STRICMP(argv[i], "--remote-wait-silent") == 0)
1428 {
1429 parmp->serverArg = TRUE;
1430#ifdef FEAT_GUI
1431 /* don't fork() when starting the GUI to edit the files ourself */
1432 gui.dofork = FALSE;
1433#endif
1434 }
1435# endif
1436# ifdef FEAT_GUI_GTK
1437 else if (STRICMP(argv[i], "--socketid") == 0)
1438 {
1439 unsigned int socket_id;
1440 int count;
1441
1442 if (i == argc - 1)
1443 mainerr_arg_missing((char_u *)argv[i]);
1444 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1445 count = sscanf(&(argv[i + 1][2]), "%x", &socket_id);
1446 else
1447 count = sscanf(argv[i+1], "%u", &socket_id);
1448 if (count != 1)
1449 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1450 else
1451 gtk_socket_id = socket_id;
1452 i++;
1453 }
1454 else if (STRICMP(argv[i], "--echo-wid") == 0)
1455 echo_wid_arg = TRUE;
1456# endif
1457 }
1458#endif
1459}
1460
1461/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001462 * Scan the command line arguments.
1463 */
1464 static void
1465command_line_scan(parmp)
1466 mparm_T *parmp;
1467{
1468 int argc = parmp->argc;
1469 char **argv = parmp->argv;
1470 int argv_idx; /* index in argv[n][] */
1471 int had_minmin = FALSE; /* found "--" argument */
1472 int want_argument; /* option argument with argument */
1473 int c;
Bram Moolenaar231334e2005-07-25 20:46:57 +00001474 char_u *p = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001475 long n;
1476
1477 --argc;
1478 ++argv;
1479 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1480 while (argc > 0)
1481 {
1482 /*
1483 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1484 */
1485 if (argv[0][0] == '+' && !had_minmin)
1486 {
1487 if (parmp->n_commands >= MAX_ARG_CMDS)
1488 mainerr(ME_EXTRA_CMD, NULL);
1489 argv_idx = -1; /* skip to next argument */
1490 if (argv[0][1] == NUL)
1491 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1492 else
1493 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1494 }
1495
1496 /*
1497 * Optional argument.
1498 */
1499 else if (argv[0][0] == '-' && !had_minmin)
1500 {
1501 want_argument = FALSE;
1502 c = argv[0][argv_idx++];
1503#ifdef VMS
1504 /*
1505 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1506 * and "-/X" as "-X".
1507 */
1508 if (c == '/')
1509 {
1510 c = argv[0][argv_idx++];
1511 c = TOUPPER_ASC(c);
1512 }
1513 else
1514 c = TOLOWER_ASC(c);
1515#endif
1516 switch (c)
1517 {
1518 case NUL: /* "vim -" read from stdin */
1519 /* "ex -" silent mode */
1520 if (exmode_active)
1521 silent_mode = TRUE;
1522 else
1523 {
1524 if (parmp->edit_type != EDIT_NONE)
1525 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1526 parmp->edit_type = EDIT_STDIN;
1527 read_cmd_fd = 2; /* read from stderr instead of stdin */
1528 }
1529 argv_idx = -1; /* skip to next argument */
1530 break;
1531
1532 case '-': /* "--" don't take any more option arguments */
1533 /* "--help" give help message */
1534 /* "--version" give version message */
1535 /* "--literal" take files literally */
1536 /* "--nofork" don't fork */
1537 /* "--noplugin[s]" skip plugins */
1538 /* "--cmd <cmd>" execute cmd before vimrc */
1539 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1540 usage();
1541 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1542 {
1543 Columns = 80; /* need to init Columns */
1544 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1545 list_version();
1546 msg_putchar('\n');
1547 msg_didout = FALSE;
1548 mch_exit(0);
1549 }
1550 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1551 {
1552#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1553 parmp->literal = TRUE;
1554#endif
1555 }
1556 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1557 {
1558#ifdef FEAT_GUI
1559 gui.dofork = FALSE; /* don't fork() when starting GUI */
1560#endif
1561 }
1562 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1563 p_lpl = FALSE;
1564 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1565 {
1566 want_argument = TRUE;
1567 argv_idx += 3;
1568 }
1569#ifdef FEAT_CLIENTSERVER
1570 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1571 ; /* already processed -- no arg */
1572 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1573 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1574 {
1575 /* already processed -- snatch the following arg */
1576 if (argc > 1)
1577 {
1578 --argc;
1579 ++argv;
1580 }
1581 }
1582#endif
1583#ifdef FEAT_GUI_GTK
1584 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1585 {
1586 /* already processed -- snatch the following arg */
1587 if (argc > 1)
1588 {
1589 --argc;
1590 ++argv;
1591 }
1592 }
1593 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1594 {
1595 /* already processed, skip */
1596 }
1597#endif
1598 else
1599 {
1600 if (argv[0][argv_idx])
1601 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1602 had_minmin = TRUE;
1603 }
1604 if (!want_argument)
1605 argv_idx = -1; /* skip to next argument */
1606 break;
1607
1608 case 'A': /* "-A" start in Arabic mode */
1609#ifdef FEAT_ARABIC
1610 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1611#else
1612 mch_errmsg(_(e_noarabic));
1613 mch_exit(2);
1614#endif
1615 break;
1616
1617 case 'b': /* "-b" binary mode */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001618 /* Needs to be effective before expanding file names, because
1619 * for Win32 this makes us edit a shortcut file itself,
1620 * instead of the file it links to. */
1621 set_options_bin(curbuf->b_p_bin, 1, 0);
1622 curbuf->b_p_bin = 1; /* binary file I/O */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001623 break;
1624
1625 case 'C': /* "-C" Compatible */
1626 change_compatible(TRUE);
1627 break;
1628
1629 case 'e': /* "-e" Ex mode */
1630 exmode_active = EXMODE_NORMAL;
1631 break;
1632
1633 case 'E': /* "-E" Improved Ex mode */
1634 exmode_active = EXMODE_VIM;
1635 break;
1636
1637 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1638 window directly, not with newcli */
1639#ifdef FEAT_GUI
1640 gui.dofork = FALSE; /* don't fork() when starting GUI */
1641#endif
1642 break;
1643
1644 case 'g': /* "-g" start GUI */
1645 main_start_gui();
1646 break;
1647
1648 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1649#ifdef FEAT_FKMAP
1650 curwin->w_p_rl = p_fkmap = TRUE;
1651#else
1652 mch_errmsg(_(e_nofarsi));
1653 mch_exit(2);
1654#endif
1655 break;
1656
1657 case 'h': /* "-h" give help message */
1658#ifdef FEAT_GUI_GNOME
1659 /* Tell usage() to exit for "gvim". */
1660 gui.starting = FALSE;
1661#endif
1662 usage();
1663 break;
1664
1665 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1666#ifdef FEAT_RIGHTLEFT
1667 curwin->w_p_rl = p_hkmap = TRUE;
1668#else
1669 mch_errmsg(_(e_nohebrew));
1670 mch_exit(2);
1671#endif
1672 break;
1673
1674 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1675#ifdef FEAT_LISP
1676 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1677 p_sm = TRUE;
1678#endif
1679 break;
1680
1681#ifdef TARGET_API_MAC_OSX
1682 /* For some reason on MacOS X, an argument like:
1683 -psn_0_10223617 is passed in when invoke from Finder
1684 or with the 'open' command */
1685 case 'p':
1686 argv_idx = -1; /* bypass full -psn */
1687 main_start_gui();
1688 break;
1689#endif
1690 case 'M': /* "-M" no changes or writing of files */
1691 reset_modifiable();
1692 /* FALLTHROUGH */
1693
1694 case 'm': /* "-m" no writing of files */
1695 p_write = FALSE;
1696 break;
1697
1698 case 'y': /* "-y" easy mode */
1699#ifdef FEAT_GUI
1700 gui.starting = TRUE; /* start GUI a bit later */
1701#endif
1702 parmp->evim_mode = TRUE;
1703 break;
1704
1705 case 'N': /* "-N" Nocompatible */
1706 change_compatible(FALSE);
1707 break;
1708
1709 case 'n': /* "-n" no swap file */
1710 parmp->no_swap_file = TRUE;
1711 break;
1712
1713 case 'o': /* "-o[N]" open N horizontal split windows */
1714#ifdef FEAT_WINDOWS
1715 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001716 parmp->window_count = get_number_arg((char_u *)argv[0],
1717 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001718 parmp->vert_windows = FALSE;
1719#endif
1720 break;
1721
1722 case 'O': /* "-O[N]" open N vertical split windows */
1723#if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1724 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001725 parmp->window_count = get_number_arg((char_u *)argv[0],
1726 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001727 parmp->vert_windows = TRUE;
1728#endif
1729 break;
1730
1731#ifdef FEAT_QUICKFIX
1732 case 'q': /* "-q" QuickFix mode */
1733 if (parmp->edit_type != EDIT_NONE)
1734 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1735 parmp->edit_type = EDIT_QF;
1736 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1737 {
1738 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1739 argv_idx = -1;
1740 }
1741 else if (argc > 1) /* "-q {errorfile}" */
1742 want_argument = TRUE;
1743 break;
1744#endif
1745
1746 case 'R': /* "-R" readonly mode */
1747 readonlymode = TRUE;
1748 curbuf->b_p_ro = TRUE;
1749 p_uc = 10000; /* don't update very often */
1750 break;
1751
1752 case 'r': /* "-r" recovery mode */
1753 case 'L': /* "-L" recovery mode */
1754 recoverymode = 1;
1755 break;
1756
1757 case 's':
1758 if (exmode_active) /* "-s" silent (batch) mode */
1759 silent_mode = TRUE;
1760 else /* "-s {scriptin}" read from script file */
1761 want_argument = TRUE;
1762 break;
1763
1764 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1765 if (parmp->edit_type != EDIT_NONE)
1766 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1767 parmp->edit_type = EDIT_TAG;
1768 if (argv[0][argv_idx]) /* "-t{tag}" */
1769 {
1770 parmp->tagname = (char_u *)argv[0] + argv_idx;
1771 argv_idx = -1;
1772 }
1773 else /* "-t {tag}" */
1774 want_argument = TRUE;
1775 break;
1776
1777#ifdef FEAT_EVAL
1778 case 'D': /* "-D" Debugging */
1779 parmp->use_debug_break_level = 9999;
1780 break;
1781#endif
1782#ifdef FEAT_DIFF
1783 case 'd': /* "-d" 'diff' */
1784# ifdef AMIGA
1785 /* check for "-dev {device}" */
1786 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1787 want_argument = TRUE;
1788 else
1789# endif
1790 parmp->diff_mode = TRUE;
1791 break;
1792#endif
1793 case 'V': /* "-V{N}" Verbose level */
1794 /* default is 10: a little bit verbose */
1795 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1796 if (argv[0][argv_idx] != NUL)
1797 {
1798 set_option_value((char_u *)"verbosefile", 0L,
1799 (char_u *)argv[0] + argv_idx, 0);
1800 argv_idx = STRLEN(argv[0]);
1801 }
1802 break;
1803
1804 case 'v': /* "-v" Vi-mode (as if called "vi") */
1805 exmode_active = 0;
1806#ifdef FEAT_GUI
1807 gui.starting = FALSE; /* don't start GUI */
1808#endif
1809 break;
1810
1811 case 'w': /* "-w{number}" set window height */
1812 /* "-w {scriptout}" write to script */
1813 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
1814 {
1815 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1816 set_option_value((char_u *)"window", n, NULL, 0);
1817 break;
1818 }
1819 want_argument = TRUE;
1820 break;
1821
1822#ifdef FEAT_CRYPT
1823 case 'x': /* "-x" encrypted reading/writing of files */
1824 parmp->ask_for_key = TRUE;
1825 break;
1826#endif
1827
1828 case 'X': /* "-X" don't connect to X server */
1829#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
1830 x_no_connect = TRUE;
1831#endif
1832 break;
1833
1834 case 'Z': /* "-Z" restricted mode */
1835 restricted = TRUE;
1836 break;
1837
1838 case 'c': /* "-c{command}" or "-c {command}" execute
1839 command */
1840 if (argv[0][argv_idx] != NUL)
1841 {
1842 if (parmp->n_commands >= MAX_ARG_CMDS)
1843 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001844 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
1845 + argv_idx;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001846 argv_idx = -1;
1847 break;
1848 }
1849 /*FALLTHROUGH*/
1850 case 'S': /* "-S {file}" execute Vim script */
1851 case 'i': /* "-i {viminfo}" use for viminfo */
1852#ifndef FEAT_DIFF
1853 case 'd': /* "-d {device}" device (for Amiga) */
1854#endif
1855 case 'T': /* "-T {terminal}" terminal name */
1856 case 'u': /* "-u {vimrc}" vim inits file */
1857 case 'U': /* "-U {gvimrc}" gvim inits file */
1858 case 'W': /* "-W {scriptout}" overwrite */
1859#ifdef FEAT_GUI_W32
1860 case 'P': /* "-P {parent title}" MDI parent */
1861#endif
1862 want_argument = TRUE;
1863 break;
1864
1865 default:
1866 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1867 }
1868
1869 /*
1870 * Handle option arguments with argument.
1871 */
1872 if (want_argument)
1873 {
1874 /*
1875 * Check for garbage immediately after the option letter.
1876 */
1877 if (argv[0][argv_idx] != NUL)
1878 mainerr(ME_GARBAGE, (char_u *)argv[0]);
1879
1880 --argc;
1881 if (argc < 1 && c != 'S')
1882 mainerr_arg_missing((char_u *)argv[0]);
1883 ++argv;
1884 argv_idx = -1;
1885
1886 switch (c)
1887 {
1888 case 'c': /* "-c {command}" execute command */
1889 case 'S': /* "-S {file}" execute Vim script */
1890 if (parmp->n_commands >= MAX_ARG_CMDS)
1891 mainerr(ME_EXTRA_CMD, NULL);
1892 if (c == 'S')
1893 {
1894 char *a;
1895
1896 if (argc < 1)
1897 /* "-S" without argument: use default session file
1898 * name. */
1899 a = SESSION_FILE;
1900 else if (argv[0][0] == '-')
1901 {
1902 /* "-S" followed by another option: use default
1903 * session file name. */
1904 a = SESSION_FILE;
1905 ++argc;
1906 --argv;
1907 }
1908 else
1909 a = argv[0];
1910 p = alloc((unsigned)(STRLEN(a) + 4));
1911 if (p == NULL)
1912 mch_exit(2);
1913 sprintf((char *)p, "so %s", a);
1914 parmp->cmds_tofree[parmp->n_commands] = TRUE;
1915 parmp->commands[parmp->n_commands++] = p;
1916 }
1917 else
Bram Moolenaar231334e2005-07-25 20:46:57 +00001918 parmp->commands[parmp->n_commands++] =
1919 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001920 break;
1921
1922 case '-': /* "--cmd {command}" execute command */
1923 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
1924 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001925 parmp->pre_commands[parmp->n_pre_commands++] =
1926 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001927 break;
1928
1929 /* case 'd': -d {device} is handled in mch_check_win() for the
1930 * Amiga */
1931
1932#ifdef FEAT_QUICKFIX
1933 case 'q': /* "-q {errorfile}" QuickFix mode */
1934 parmp->use_ef = (char_u *)argv[0];
1935 break;
1936#endif
1937
1938 case 'i': /* "-i {viminfo}" use for viminfo */
1939 use_viminfo = (char_u *)argv[0];
1940 break;
1941
1942 case 's': /* "-s {scriptin}" read from script file */
1943 if (scriptin[0] != NULL)
1944 {
1945scripterror:
1946 mch_errmsg(_("Attempt to open script file again: \""));
1947 mch_errmsg(argv[-1]);
1948 mch_errmsg(" ");
1949 mch_errmsg(argv[0]);
1950 mch_errmsg("\"\n");
1951 mch_exit(2);
1952 }
1953 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
1954 {
1955 mch_errmsg(_("Cannot open for reading: \""));
1956 mch_errmsg(argv[0]);
1957 mch_errmsg("\"\n");
1958 mch_exit(2);
1959 }
1960 if (save_typebuf() == FAIL)
1961 mch_exit(2); /* out of memory */
1962 break;
1963
1964 case 't': /* "-t {tag}" */
1965 parmp->tagname = (char_u *)argv[0];
1966 break;
1967
1968 case 'T': /* "-T {terminal}" terminal name */
1969 /*
1970 * The -T term argument is always available and when
1971 * HAVE_TERMLIB is supported it overrides the environment
1972 * variable TERM.
1973 */
1974#ifdef FEAT_GUI
1975 if (term_is_gui((char_u *)argv[0]))
1976 gui.starting = TRUE; /* start GUI a bit later */
1977 else
1978#endif
1979 parmp->term = (char_u *)argv[0];
1980 break;
1981
1982 case 'u': /* "-u {vimrc}" vim inits file */
1983 parmp->use_vimrc = (char_u *)argv[0];
1984 break;
1985
1986 case 'U': /* "-U {gvimrc}" gvim inits file */
1987#ifdef FEAT_GUI
1988 use_gvimrc = (char_u *)argv[0];
1989#endif
1990 break;
1991
1992 case 'w': /* "-w {nr}" 'window' value */
1993 /* "-w {scriptout}" append to script file */
1994 if (vim_isdigit(*((char_u *)argv[0])))
1995 {
1996 argv_idx = 0;
1997 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1998 set_option_value((char_u *)"window", n, NULL, 0);
1999 argv_idx = -1;
2000 break;
2001 }
2002 /*FALLTHROUGH*/
2003 case 'W': /* "-W {scriptout}" overwrite script file */
2004 if (scriptout != NULL)
2005 goto scripterror;
2006 if ((scriptout = mch_fopen(argv[0],
2007 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
2008 {
2009 mch_errmsg(_("Cannot open for script output: \""));
2010 mch_errmsg(argv[0]);
2011 mch_errmsg("\"\n");
2012 mch_exit(2);
2013 }
2014 break;
2015
2016#ifdef FEAT_GUI_W32
2017 case 'P': /* "-P {parent title}" MDI parent */
2018 gui_mch_set_parent(argv[0]);
2019 break;
2020#endif
2021 }
2022 }
2023 }
2024
2025 /*
2026 * File name argument.
2027 */
2028 else
2029 {
2030 argv_idx = -1; /* skip to next argument */
2031
2032 /* Check for only one type of editing. */
2033 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2034 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2035 parmp->edit_type = EDIT_FILE;
2036
2037#ifdef MSWIN
2038 /* Remember if the argument was a full path before changing
2039 * slashes to backslashes. */
2040 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2041 parmp->full_path = TRUE;
2042#endif
2043
2044 /* Add the file to the global argument list. */
2045 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2046 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2047 mch_exit(2);
2048#ifdef FEAT_DIFF
2049 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2050 && !mch_isdir(alist_name(&GARGLIST[0])))
2051 {
2052 char_u *r;
2053
2054 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2055 if (r != NULL)
2056 {
2057 vim_free(p);
2058 p = r;
2059 }
2060 }
2061#endif
2062#if defined(__CYGWIN32__) && !defined(WIN32)
2063 /*
2064 * If vim is invoked by non-Cygwin tools, convert away any
2065 * DOS paths, so things like .swp files are created correctly.
2066 * Look for evidence of non-Cygwin paths before we bother.
2067 * This is only for when using the Unix files.
2068 */
2069 if (strpbrk(p, "\\:") != NULL)
2070 {
2071 char posix_path[PATH_MAX];
2072
2073 cygwin_conv_to_posix_path(p, posix_path);
2074 vim_free(p);
2075 p = vim_strsave(posix_path);
2076 if (p == NULL)
2077 mch_exit(2);
2078 }
2079#endif
Bram Moolenaarcc016f52005-12-10 20:23:46 +00002080
2081#ifdef USE_FNAME_CASE
2082 /* Make the case of the file name match the actual file. */
2083 fname_case(p, 0);
2084#endif
2085
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002086 alist_add(&global_alist, p,
2087#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
Bram Moolenaar231334e2005-07-25 20:46:57 +00002088 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002089#else
2090 2 /* add buffer number now and use curbuf */
2091#endif
2092 );
2093
2094#if defined(FEAT_MBYTE) && defined(WIN32)
2095 {
2096 extern void used_file_arg(char *, int, int);
2097
2098 /* Remember this argument has been added to the argument list.
2099 * Needed when 'encoding' is changed. */
2100 used_file_arg(argv[0], parmp->literal, parmp->full_path);
2101 }
2102#endif
2103 }
2104
2105 /*
2106 * If there are no more letters after the current "-", go to next
2107 * argument. argv_idx is set to -1 when the current argument is to be
2108 * skipped.
2109 */
2110 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2111 {
2112 --argc;
2113 ++argv;
2114 argv_idx = 1;
2115 }
2116 }
2117}
2118
2119/*
2120 * Print a warning if stdout is not a terminal.
2121 * When starting in Ex mode and commands come from a file, set Silent mode.
2122 */
2123 static void
2124check_tty(parmp)
2125 mparm_T *parmp;
2126{
2127 int input_isatty; /* is active input a terminal? */
2128
2129 input_isatty = mch_input_isatty();
2130 if (exmode_active)
2131 {
2132 if (!input_isatty)
2133 silent_mode = TRUE;
2134 }
2135 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2136#ifdef FEAT_GUI
2137 /* don't want the delay when started from the desktop */
2138 && !gui.starting
2139#endif
2140 )
2141 {
2142#ifdef NBDEBUG
2143 /*
2144 * This shouldn't be necessary. But if I run netbeans with the log
2145 * output coming to the console and XOpenDisplay fails, I get vim
2146 * trying to start with input/output to my console tty. This fills my
2147 * input buffer so fast I can't even kill the process in under 2
2148 * minutes (and it beeps continuosly the whole time :-)
2149 */
2150 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2151 {
2152 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2153 exit(1);
2154 }
2155#endif
2156 if (!parmp->stdout_isatty)
2157 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2158 if (!input_isatty)
2159 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2160 out_flush();
2161 if (scriptin[0] == NULL)
2162 ui_delay(2000L, TRUE);
2163 TIME_MSG("Warning delay");
2164 }
2165}
2166
2167/*
2168 * Read text from stdin.
2169 */
2170 static void
2171read_stdin()
2172{
2173 int i;
2174
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002175#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002176 /* When getting the ATTENTION prompt here, use a dialog */
2177 swap_exists_action = SEA_DIALOG;
2178#endif
2179 no_wait_return = TRUE;
2180 i = msg_didany;
2181 set_buflisted(TRUE);
2182 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2183 no_wait_return = FALSE;
2184 msg_didany = i;
2185 TIME_MSG("reading stdin");
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002186#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002187 check_swap_exists_action();
2188#endif
2189#if !(defined(AMIGA) || defined(MACOS))
2190 /*
2191 * Close stdin and dup it from stderr. Required for GPM to work
2192 * properly, and for running external commands.
2193 * Is there any other system that cannot do this?
2194 */
2195 close(0);
2196 dup(2);
2197#endif
2198}
2199
2200/*
2201 * Create the requested number of windows and edit buffers in them.
2202 * Also does recovery if "recoverymode" set.
2203 */
2204/*ARGSUSED*/
2205 static void
2206create_windows(parmp)
2207 mparm_T *parmp;
2208{
2209#ifdef FEAT_WINDOWS
2210 /*
2211 * Create the number of windows that was requested.
2212 */
2213 if (parmp->window_count == -1) /* was not set */
2214 parmp->window_count = 1;
2215 if (parmp->window_count == 0)
2216 parmp->window_count = GARGCOUNT;
2217 if (parmp->window_count > 1)
2218 {
2219 /* Don't change the windows if there was a command in .vimrc that
2220 * already split some windows */
2221 if (parmp->vert_windows == MAYBE)
2222 parmp->vert_windows = FALSE;
2223 if (firstwin->w_next == NULL)
2224 {
2225 parmp->window_count = make_windows(parmp->window_count,
2226 parmp->vert_windows);
2227 TIME_MSG("making windows");
2228 }
2229 else
2230 parmp->window_count = win_count();
2231 }
2232 else
2233 parmp->window_count = 1;
2234#endif
2235
2236 if (recoverymode) /* do recover */
2237 {
2238 msg_scroll = TRUE; /* scroll message up */
2239 ml_recover();
2240 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2241 getout(1);
2242 do_modelines(FALSE); /* do modelines */
2243 }
2244 else
2245 {
2246 /*
2247 * Open a buffer for windows that don't have one yet.
2248 * Commands in the .vimrc might have loaded a file or split the window.
2249 * Watch out for autocommands that delete a window.
2250 */
2251#ifdef FEAT_AUTOCMD
2252 /*
2253 * Don't execute Win/Buf Enter/Leave autocommands here
2254 */
2255 ++autocmd_no_enter;
2256 ++autocmd_no_leave;
2257#endif
2258#ifdef FEAT_WINDOWS
2259 for (curwin = firstwin; curwin != NULL; curwin = W_NEXT(curwin))
2260#endif
2261 {
2262 curbuf = curwin->w_buffer;
2263 if (curbuf->b_ml.ml_mfp == NULL)
2264 {
2265#ifdef FEAT_FOLDING
2266 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2267 if (p_fdls >= 0)
2268 curwin->w_p_fdl = p_fdls;
2269#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002270#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002271 /* When getting the ATTENTION prompt here, use a dialog */
2272 swap_exists_action = SEA_DIALOG;
2273#endif
2274 set_buflisted(TRUE);
2275 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2276
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002277#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002278 check_swap_exists_action();
2279#endif
2280#ifdef FEAT_AUTOCMD
2281 curwin = firstwin; /* start again */
2282#endif
2283 }
2284#ifdef FEAT_WINDOWS
2285 ui_breakcheck();
2286 if (got_int)
2287 {
2288 (void)vgetc(); /* only break the file loading, not the rest */
2289 break;
2290 }
2291#endif
2292 }
2293#ifdef FEAT_AUTOCMD
2294 --autocmd_no_enter;
2295 --autocmd_no_leave;
2296#endif
2297#ifdef FEAT_WINDOWS
2298 curwin = firstwin;
2299 curbuf = curwin->w_buffer;
2300#endif
2301 }
2302}
2303
2304#ifdef FEAT_WINDOWS
2305 /*
2306 * If opened more than one window, start editing files in the other
2307 * windows. make_windows() has already opened the windows.
2308 */
2309 static void
2310edit_buffers(parmp)
2311 mparm_T *parmp;
2312{
2313 int arg_idx; /* index in argument list */
2314 int i;
2315
2316# ifdef FEAT_AUTOCMD
2317 /*
2318 * Don't execute Win/Buf Enter/Leave autocommands here
2319 */
2320 ++autocmd_no_enter;
2321 ++autocmd_no_leave;
2322# endif
2323 arg_idx = 1;
2324 for (i = 1; i < parmp->window_count; ++i)
2325 {
2326 if (curwin->w_next == NULL) /* just checking */
2327 break;
2328 win_enter(curwin->w_next, FALSE);
2329
2330 /* Only open the file if there is no file in this window yet (that can
2331 * happen when .vimrc contains ":sall") */
2332 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2333 {
2334 curwin->w_arg_idx = arg_idx;
2335 /* edit file from arg list, if there is one */
2336 (void)do_ecmd(0, arg_idx < GARGCOUNT
2337 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2338 NULL, NULL, ECMD_LASTL, ECMD_HIDE);
2339 if (arg_idx == GARGCOUNT - 1)
2340 arg_had_last = TRUE;
2341 ++arg_idx;
2342 }
2343 ui_breakcheck();
2344 if (got_int)
2345 {
2346 (void)vgetc(); /* only break the file loading, not the rest */
2347 break;
2348 }
2349 }
2350# ifdef FEAT_AUTOCMD
2351 --autocmd_no_enter;
2352# endif
2353 win_enter(firstwin, FALSE); /* back to first window */
2354# ifdef FEAT_AUTOCMD
2355 --autocmd_no_leave;
2356# endif
2357 TIME_MSG("editing files in windows");
2358 if (parmp->window_count > 1)
2359 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2360}
2361#endif /* FEAT_WINDOWS */
2362
2363/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002364 * Execute the commands from --cmd arguments "cmds[cnt]".
2365 */
2366 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002367exe_pre_commands(parmp)
2368 mparm_T *parmp;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002369{
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002370 char_u **cmds = parmp->pre_commands;
2371 int cnt = parmp->n_pre_commands;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002372 int i;
2373
2374 if (cnt > 0)
2375 {
2376 curwin->w_cursor.lnum = 0; /* just in case.. */
2377 sourcing_name = (char_u *)_("pre-vimrc command line");
2378# ifdef FEAT_EVAL
2379 current_SID = SID_CMDARG;
2380# endif
2381 for (i = 0; i < cnt; ++i)
2382 do_cmdline_cmd(cmds[i]);
2383 sourcing_name = NULL;
2384# ifdef FEAT_EVAL
2385 current_SID = 0;
2386# endif
2387 TIME_MSG("--cmd commands");
2388 }
2389}
2390
2391/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002392 * Execute "+", "-c" and "-S" arguments.
2393 */
2394 static void
2395exe_commands(parmp)
2396 mparm_T *parmp;
2397{
2398 int i;
2399
2400 /*
2401 * We start commands on line 0, make "vim +/pat file" match a
2402 * pattern on line 1. But don't move the cursor when an autocommand
2403 * with g`" was used.
2404 */
2405 msg_scroll = TRUE;
2406 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2407 curwin->w_cursor.lnum = 0;
2408 sourcing_name = (char_u *)"command line";
2409#ifdef FEAT_EVAL
2410 current_SID = SID_CARG;
2411#endif
2412 for (i = 0; i < parmp->n_commands; ++i)
2413 {
2414 do_cmdline_cmd(parmp->commands[i]);
2415 if (parmp->cmds_tofree[i])
2416 vim_free(parmp->commands[i]);
2417 }
2418 sourcing_name = NULL;
2419#ifdef FEAT_EVAL
2420 current_SID = 0;
2421#endif
2422 if (curwin->w_cursor.lnum == 0)
2423 curwin->w_cursor.lnum = 1;
2424
2425 if (!exmode_active)
2426 msg_scroll = FALSE;
2427
2428#ifdef FEAT_QUICKFIX
2429 /* When started with "-q errorfile" jump to first error again. */
2430 if (parmp->edit_type == EDIT_QF)
2431 qf_jump(0, 0, FALSE);
2432#endif
2433 TIME_MSG("executing command arguments");
2434}
2435
2436/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002437 * Source startup scripts.
2438 */
2439 static void
2440source_startup_scripts(parmp)
2441 mparm_T *parmp;
2442{
2443 int i;
2444
2445 /*
2446 * For "evim" source evim.vim first of all, so that the user can overrule
2447 * any things he doesn't like.
2448 */
2449 if (parmp->evim_mode)
2450 {
2451 (void)do_source((char_u *)EVIM_FILE, FALSE, FALSE);
2452 TIME_MSG("source evim file");
2453 }
2454
2455 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002456 * If -u argument given, use only the initializations from that file and
Bram Moolenaar58d98232005-07-23 22:25:46 +00002457 * nothing else.
2458 */
2459 if (parmp->use_vimrc != NULL)
2460 {
Bram Moolenaar231334e2005-07-25 20:46:57 +00002461 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2462 || STRCMP(parmp->use_vimrc, "NORC") == 0)
Bram Moolenaar58d98232005-07-23 22:25:46 +00002463 {
2464#ifdef FEAT_GUI
2465 if (use_gvimrc == NULL) /* don't load gvimrc either */
2466 use_gvimrc = parmp->use_vimrc;
2467#endif
2468 if (parmp->use_vimrc[2] == 'N')
2469 p_lpl = FALSE; /* don't load plugins either */
2470 }
2471 else
2472 {
2473 if (do_source(parmp->use_vimrc, FALSE, FALSE) != OK)
2474 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2475 }
2476 }
2477 else if (!silent_mode)
2478 {
2479#ifdef AMIGA
2480 struct Process *proc = (struct Process *)FindTask(0L);
2481 APTR save_winptr = proc->pr_WindowPtr;
2482
2483 /* Avoid a requester here for a volume that doesn't exist. */
2484 proc->pr_WindowPtr = (APTR)-1L;
2485#endif
2486
2487 /*
2488 * Get system wide defaults, if the file name is defined.
2489 */
2490#ifdef SYS_VIMRC_FILE
2491 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, FALSE);
2492#endif
2493
2494 /*
2495 * Try to read initialization commands from the following places:
2496 * - environment variable VIMINIT
2497 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2498 * - second user vimrc file ($VIM/.vimrc for Dos)
2499 * - environment variable EXINIT
2500 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2501 * - second user exrc file ($VIM/.exrc for Dos)
2502 * The first that exists is used, the rest is ignored.
2503 */
2504 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2505 {
2506 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, TRUE) == FAIL
2507#ifdef USR_VIMRC_FILE2
2508 && do_source((char_u *)USR_VIMRC_FILE2, TRUE, TRUE) == FAIL
2509#endif
2510#ifdef USR_VIMRC_FILE3
2511 && do_source((char_u *)USR_VIMRC_FILE3, TRUE, TRUE) == FAIL
2512#endif
2513 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2514 && do_source((char_u *)USR_EXRC_FILE, FALSE, FALSE) == FAIL)
2515 {
2516#ifdef USR_EXRC_FILE2
2517 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, FALSE);
2518#endif
2519 }
2520 }
2521
2522 /*
2523 * Read initialization commands from ".vimrc" or ".exrc" in current
2524 * directory. This is only done if the 'exrc' option is set.
2525 * Because of security reasons we disallow shell and write commands
2526 * now, except for unix if the file is owned by the user or 'secure'
2527 * option has been reset in environment of global ".exrc" or ".vimrc".
2528 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2529 * SYS_VIMRC_FILE.
2530 */
2531 if (p_exrc)
2532 {
2533#if defined(UNIX) || defined(VMS)
2534 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2535 if (!file_owned(VIMRC_FILE))
2536#endif
2537 secure = p_secure;
2538
2539 i = FAIL;
2540 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2541 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2542#ifdef USR_VIMRC_FILE2
2543 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2544 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2545#endif
2546#ifdef USR_VIMRC_FILE3
2547 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2548 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2549#endif
2550#ifdef SYS_VIMRC_FILE
2551 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2552 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2553#endif
2554 )
2555 i = do_source((char_u *)VIMRC_FILE, TRUE, TRUE);
2556
2557 if (i == FAIL)
2558 {
2559#if defined(UNIX) || defined(VMS)
2560 /* if ".exrc" is not owned by user set 'secure' mode */
2561 if (!file_owned(EXRC_FILE))
2562 secure = p_secure;
2563 else
2564 secure = 0;
2565#endif
2566 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2567 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2568#ifdef USR_EXRC_FILE2
2569 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2570 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2571#endif
2572 )
2573 (void)do_source((char_u *)EXRC_FILE, FALSE, FALSE);
2574 }
2575 }
2576 if (secure == 2)
2577 need_wait_return = TRUE;
2578 secure = 0;
2579#ifdef AMIGA
2580 proc->pr_WindowPtr = save_winptr;
2581#endif
2582 }
2583 TIME_MSG("sourcing vimrc file(s)");
2584}
2585
2586/*
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002587 * Setup to start using the GUI. Exit with an error when not available.
2588 */
2589 static void
2590main_start_gui()
2591{
2592#ifdef FEAT_GUI
2593 gui.starting = TRUE; /* start GUI a bit later */
2594#else
2595 mch_errmsg(_(e_nogvim));
2596 mch_errmsg("\n");
2597 mch_exit(2);
2598#endif
2599}
2600
2601/*
2602 * Get an evironment variable, and execute it as Ex commands.
2603 * Returns FAIL if the environment variable was not executed, OK otherwise.
2604 */
2605 int
2606process_env(env, is_viminit)
2607 char_u *env;
2608 int is_viminit; /* when TRUE, called for VIMINIT */
2609{
2610 char_u *initstr;
2611 char_u *save_sourcing_name;
2612 linenr_T save_sourcing_lnum;
2613#ifdef FEAT_EVAL
2614 scid_T save_sid;
2615#endif
2616
2617 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2618 {
2619 if (is_viminit)
2620 vimrc_found();
2621 save_sourcing_name = sourcing_name;
2622 save_sourcing_lnum = sourcing_lnum;
2623 sourcing_name = env;
2624 sourcing_lnum = 0;
2625#ifdef FEAT_EVAL
2626 save_sid = current_SID;
2627 current_SID = SID_ENV;
2628#endif
2629 do_cmdline_cmd(initstr);
2630 sourcing_name = save_sourcing_name;
2631 sourcing_lnum = save_sourcing_lnum;
2632#ifdef FEAT_EVAL
2633 current_SID = save_sid;;
2634#endif
2635 return OK;
2636 }
2637 return FAIL;
2638}
2639
2640#if defined(UNIX) || defined(VMS)
2641/*
2642 * Return TRUE if we are certain the user owns the file "fname".
2643 * Used for ".vimrc" and ".exrc".
2644 * Use both stat() and lstat() for extra security.
2645 */
2646 static int
2647file_owned(fname)
2648 char *fname;
2649{
2650 struct stat s;
2651# ifdef UNIX
2652 uid_t uid = getuid();
2653# else /* VMS */
2654 uid_t uid = ((getgid() << 16) | getuid());
2655# endif
2656
2657 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2658# ifdef HAVE_LSTAT
2659 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2660# endif
2661 );
2662}
2663#endif
2664
2665/*
2666 * Give an error message main_errors["n"] and exit.
2667 */
2668 static void
2669mainerr(n, str)
2670 int n; /* one of the ME_ defines */
2671 char_u *str; /* extra argument or NULL */
2672{
2673#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2674 reset_signals(); /* kill us with CTRL-C here, if you like */
2675#endif
2676
2677 mch_errmsg(longVersion);
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002678 mch_errmsg("\n");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002679 mch_errmsg(_(main_errors[n]));
2680 if (str != NULL)
2681 {
2682 mch_errmsg(": \"");
2683 mch_errmsg((char *)str);
2684 mch_errmsg("\"");
2685 }
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002686 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002687
2688 mch_exit(1);
2689}
2690
2691 void
2692mainerr_arg_missing(str)
2693 char_u *str;
2694{
2695 mainerr(ME_ARG_MISSING, str);
2696}
2697
2698/*
2699 * print a message with three spaces prepended and '\n' appended.
2700 */
2701 static void
2702main_msg(s)
2703 char *s;
2704{
2705 mch_msg(" ");
2706 mch_msg(s);
2707 mch_msg("\n");
2708}
2709
2710/*
2711 * Print messages for "vim -h" or "vim --help" and exit.
2712 */
2713 static void
2714usage()
2715{
2716 int i;
2717 static char *(use[]) =
2718 {
2719 N_("[file ..] edit specified file(s)"),
2720 N_("- read text from stdin"),
2721 N_("-t tag edit file where tag is defined"),
2722#ifdef FEAT_QUICKFIX
2723 N_("-q [errorfile] edit file with first error")
2724#endif
2725 };
2726
2727#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2728 reset_signals(); /* kill us with CTRL-C here, if you like */
2729#endif
2730
2731 mch_msg(longVersion);
2732 mch_msg(_("\n\nusage:"));
2733 for (i = 0; ; ++i)
2734 {
2735 mch_msg(_(" vim [arguments] "));
2736 mch_msg(_(use[i]));
2737 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
2738 break;
2739 mch_msg(_("\n or:"));
2740 }
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002741#ifdef VMS
2742 mch_msg(_("where case is ignored prepend / to make flag upper case"));
2743#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002744
2745 mch_msg(_("\n\nArguments:\n"));
2746 main_msg(_("--\t\t\tOnly file names after this"));
2747#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2748 main_msg(_("--literal\t\tDon't expand wildcards"));
2749#endif
2750#ifdef FEAT_OLE
2751 main_msg(_("-register\t\tRegister this gvim for OLE"));
2752 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
2753#endif
2754#ifdef FEAT_GUI
2755 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
2756 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
2757#endif
2758 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
2759 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
2760 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
2761#ifdef FEAT_DIFF
2762 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
2763#endif
2764 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
2765 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
2766 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
2767 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
2768 main_msg(_("-M\t\t\tModifications in text not allowed"));
2769 main_msg(_("-b\t\t\tBinary mode"));
2770#ifdef FEAT_LISP
2771 main_msg(_("-l\t\t\tLisp mode"));
2772#endif
2773 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
2774 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
2775 main_msg(_("-V[N]\t\tVerbose level"));
2776 main_msg(_("-D\t\t\tDebugging mode"));
2777 main_msg(_("-n\t\t\tNo swap file, use memory only"));
2778 main_msg(_("-r\t\t\tList swap files and exit"));
2779 main_msg(_("-r (with file name)\tRecover crashed session"));
2780 main_msg(_("-L\t\t\tSame as -r"));
2781#ifdef AMIGA
2782 main_msg(_("-f\t\t\tDon't use newcli to open window"));
2783 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
2784#endif
2785#ifdef FEAT_ARABIC
2786 main_msg(_("-A\t\t\tstart in Arabic mode"));
2787#endif
2788#ifdef FEAT_RIGHTLEFT
2789 main_msg(_("-H\t\t\tStart in Hebrew mode"));
2790#endif
2791#ifdef FEAT_FKMAP
2792 main_msg(_("-F\t\t\tStart in Farsi mode"));
2793#endif
2794 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
2795 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
2796#ifdef FEAT_GUI
2797 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
2798#endif
2799 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
2800 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
2801 main_msg(_("-O[N]\t\tLike -o but split vertically"));
2802 main_msg(_("+\t\t\tStart at end of file"));
2803 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002804 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002805 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
2806 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
2807 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
2808 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
2809 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
2810#ifdef FEAT_CRYPT
2811 main_msg(_("-x\t\t\tEdit encrypted files"));
2812#endif
2813#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
2814# if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
2815 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
2816# endif
2817 main_msg(_("-X\t\t\tDo not connect to X server"));
2818#endif
2819#ifdef FEAT_CLIENTSERVER
2820 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
2821 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
2822 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
2823 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
2824 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
2825 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
2826 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
2827 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
2828#endif
2829#ifdef FEAT_VIMINFO
2830 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
2831#endif
2832 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
2833 main_msg(_("--version\t\tPrint version information and exit"));
2834
2835#ifdef FEAT_GUI_X11
2836# ifdef FEAT_GUI_MOTIF
2837 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
2838# else
2839# ifdef FEAT_GUI_ATHENA
2840# ifdef FEAT_GUI_NEXTAW
2841 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
2842# else
2843 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
2844# endif
2845# endif
2846# endif
2847 main_msg(_("-display <display>\tRun vim on <display>"));
2848 main_msg(_("-iconic\t\tStart vim iconified"));
2849# if 0
2850 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
2851 mch_msg(_("\t\t\t (Unimplemented)\n"));
2852# endif
2853 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
2854 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
2855 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2856 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
2857 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
2858 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2859 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
2860 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
2861# ifdef FEAT_GUI_ATHENA
2862 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
2863# endif
2864 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2865 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
2866 main_msg(_("-xrm <resource>\tSet the specified resource"));
2867#endif /* FEAT_GUI_X11 */
2868#if defined(FEAT_GUI) && defined(RISCOS)
2869 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
2870 main_msg(_("--columns <number>\tInitial width of window in columns"));
2871 main_msg(_("--rows <number>\tInitial height of window in rows"));
2872#endif
2873#ifdef FEAT_GUI_GTK
2874 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
2875 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2876 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2877 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2878 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
2879# ifdef HAVE_GTK2
2880 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
2881# endif
2882 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
2883#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002884#ifdef FEAT_GUI_W32
2885 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
2886#endif
2887
2888#ifdef FEAT_GUI_GNOME
2889 /* Gnome gives extra messages for --help if we continue, but not for -h. */
2890 if (gui.starting)
2891 mch_msg("\n");
2892 else
2893#endif
2894 mch_exit(0);
2895}
2896
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002897#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002898/*
2899 * Check the result of the ATTENTION dialog:
2900 * When "Quit" selected, exit Vim.
2901 * When "Recover" selected, recover the file.
2902 */
2903 static void
2904check_swap_exists_action()
2905{
2906 if (swap_exists_action == SEA_QUIT)
2907 getout(1);
2908 handle_swap_exists(NULL);
2909}
2910#endif
2911
2912#if defined(STARTUPTIME) || defined(PROTO)
2913static void time_diff __ARGS((struct timeval *then, struct timeval *now));
2914
2915static struct timeval prev_timeval;
2916
2917/*
2918 * Save the previous time before doing something that could nest.
2919 * set "*tv_rel" to the time elapsed so far.
2920 */
2921 void
2922time_push(tv_rel, tv_start)
2923 void *tv_rel, *tv_start;
2924{
2925 *((struct timeval *)tv_rel) = prev_timeval;
2926 gettimeofday(&prev_timeval, NULL);
2927 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
2928 - ((struct timeval *)tv_rel)->tv_usec;
2929 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
2930 - ((struct timeval *)tv_rel)->tv_sec;
2931 if (((struct timeval *)tv_rel)->tv_usec < 0)
2932 {
2933 ((struct timeval *)tv_rel)->tv_usec += 1000000;
2934 --((struct timeval *)tv_rel)->tv_sec;
2935 }
2936 *(struct timeval *)tv_start = prev_timeval;
2937}
2938
2939/*
2940 * Compute the previous time after doing something that could nest.
2941 * Subtract "*tp" from prev_timeval;
2942 * Note: The arguments are (void *) to avoid trouble with systems that don't
2943 * have struct timeval.
2944 */
2945 void
2946time_pop(tp)
2947 void *tp; /* actually (struct timeval *) */
2948{
2949 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
2950 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
2951 if (prev_timeval.tv_usec < 0)
2952 {
2953 prev_timeval.tv_usec += 1000000;
2954 --prev_timeval.tv_sec;
2955 }
2956}
2957
2958 static void
2959time_diff(then, now)
2960 struct timeval *then;
2961 struct timeval *now;
2962{
2963 long usec;
2964 long msec;
2965
2966 usec = now->tv_usec - then->tv_usec;
2967 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
2968 usec = usec % 1000L;
2969 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
2970}
2971
2972 void
2973time_msg(msg, tv_start)
2974 char *msg;
2975 void *tv_start; /* only for do_source: start time; actually
2976 (struct timeval *) */
2977{
2978 static struct timeval start;
2979 struct timeval now;
2980
2981 if (time_fd != NULL)
2982 {
2983 if (strstr(msg, "STARTING") != NULL)
2984 {
2985 gettimeofday(&start, NULL);
2986 prev_timeval = start;
2987 fprintf(time_fd, "\n\ntimes in msec\n");
2988 fprintf(time_fd, " clock self+sourced self: sourced script\n");
2989 fprintf(time_fd, " clock elapsed: other lines\n\n");
2990 }
2991 gettimeofday(&now, NULL);
2992 time_diff(&start, &now);
2993 if (((struct timeval *)tv_start) != NULL)
2994 {
2995 fprintf(time_fd, " ");
2996 time_diff(((struct timeval *)tv_start), &now);
2997 }
2998 fprintf(time_fd, " ");
2999 time_diff(&prev_timeval, &now);
3000 prev_timeval = now;
3001 fprintf(time_fd, ": %s\n", msg);
3002 }
3003}
3004
3005# ifdef WIN3264
3006/*
3007 * Windows doesn't have gettimeofday(), although it does have struct timeval.
3008 */
3009 int
3010gettimeofday(struct timeval *tv, char *dummy)
3011{
3012 long t = clock();
3013 tv->tv_sec = t / CLOCKS_PER_SEC;
3014 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
3015 return 0;
3016}
3017# endif
3018
3019#endif
3020
3021#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3022
3023/*
3024 * Common code for the X command server and the Win32 command server.
3025 */
3026
3027static char_u *build_drop_cmd __ARGS((int filec, char **filev, int sendReply));
3028
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003029/*
3030 * Do the client-server stuff, unless "--servername ''" was used.
3031 */
3032 static void
3033exec_on_server(parmp)
3034 mparm_T *parmp;
3035{
3036 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3037 {
3038# ifdef WIN32
3039 /* Initialise the client/server messaging infrastructure. */
3040 serverInitMessaging();
3041# endif
3042
3043 /*
3044 * When a command server argument was found, execute it. This may
3045 * exit Vim when it was successful. Otherwise it's executed further
3046 * on. Remember the encoding used here in "serverStrEnc".
3047 */
3048 if (parmp->serverArg)
3049 {
3050 cmdsrv_main(&parmp->argc, parmp->argv,
3051 parmp->serverName_arg, &parmp->serverStr);
3052# ifdef FEAT_MBYTE
3053 parmp->serverStrEnc = vim_strsave(p_enc);
3054# endif
3055 }
3056
3057 /* If we're still running, get the name to register ourselves.
3058 * On Win32 can register right now, for X11 need to setup the
3059 * clipboard first, it's further down. */
3060 parmp->servername = serverMakeName(parmp->serverName_arg,
3061 parmp->argv[0]);
3062# ifdef WIN32
3063 if (parmp->servername != NULL)
3064 {
3065 serverSetName(parmp->servername);
3066 vim_free(parmp->servername);
3067 }
3068# endif
3069 }
3070}
3071
3072/*
3073 * Prepare for running as a Vim server.
3074 */
3075 static void
3076prepare_server(parmp)
3077 mparm_T *parmp;
3078{
3079# if defined(FEAT_X11)
3080 /*
3081 * Register for remote command execution with :serversend and --remote
3082 * unless there was a -X or a --servername '' on the command line.
3083 * Only register nongui-vim's with an explicit --servername argument.
3084 */
3085 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3086# ifdef FEAT_GUI
3087 gui.in_use ||
3088# endif
3089 parmp->serverName_arg != NULL))
3090 {
3091 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3092 vim_free(parmp->servername);
3093 TIME_MSG("register server name");
3094 }
3095 else
3096 serverDelayedStartName = parmp->servername;
3097# endif
3098
3099 /*
3100 * Execute command ourselves if we're here because the send failed (or
3101 * else we would have exited above).
3102 */
3103 if (parmp->serverStr != NULL)
3104 {
3105 char_u *p;
3106
3107 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3108 parmp->serverStr, &p));
3109 vim_free(p);
3110 }
3111}
3112
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003113 static void
3114cmdsrv_main(argc, argv, serverName_arg, serverStr)
3115 int *argc;
3116 char **argv;
3117 char_u *serverName_arg;
3118 char_u **serverStr;
3119{
3120 char_u *res;
3121 int i;
3122 char_u *sname;
3123 int ret;
3124 int didone = FALSE;
3125 int exiterr = 0;
3126 char **newArgV = argv + 1;
3127 int newArgC = 1,
3128 Argc = *argc;
3129 int argtype;
3130#define ARGTYPE_OTHER 0
3131#define ARGTYPE_EDIT 1
3132#define ARGTYPE_EDIT_WAIT 2
3133#define ARGTYPE_SEND 3
3134 int silent = FALSE;
3135# ifndef FEAT_X11
3136 HWND srv;
3137# else
3138 Window srv;
3139
3140 setup_term_clip();
3141# endif
3142
3143 sname = serverMakeName(serverName_arg, argv[0]);
3144 if (sname == NULL)
3145 return;
3146
3147 /*
3148 * Execute the command server related arguments and remove them
3149 * from the argc/argv array; We may have to return into main()
3150 */
3151 for (i = 1; i < Argc; i++)
3152 {
3153 res = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003154 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003155 {
3156 for (; i < *argc; i++)
3157 {
3158 *newArgV++ = argv[i];
3159 newArgC++;
3160 }
3161 break;
3162 }
3163
3164 if (STRICMP(argv[i], "--remote") == 0)
3165 argtype = ARGTYPE_EDIT;
3166 else if (STRICMP(argv[i], "--remote-silent") == 0)
3167 {
3168 argtype = ARGTYPE_EDIT;
3169 silent = TRUE;
3170 }
3171 else if (STRICMP(argv[i], "--remote-wait") == 0)
3172 argtype = ARGTYPE_EDIT_WAIT;
3173 else if (STRICMP(argv[i], "--remote-wait-silent") == 0)
3174 {
3175 argtype = ARGTYPE_EDIT_WAIT;
3176 silent = TRUE;
3177 }
3178 else if (STRICMP(argv[i], "--remote-send") == 0)
3179 argtype = ARGTYPE_SEND;
3180 else
3181 argtype = ARGTYPE_OTHER;
3182 if (argtype != ARGTYPE_OTHER)
3183 {
3184 if (i == *argc - 1)
3185 mainerr_arg_missing((char_u *)argv[i]);
3186 if (argtype == ARGTYPE_SEND)
3187 {
3188 *serverStr = (char_u *)argv[i + 1];
3189 i++;
3190 }
3191 else
3192 {
3193 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3194 argtype == ARGTYPE_EDIT_WAIT);
3195 if (*serverStr == NULL)
3196 {
3197 /* Probably out of memory, exit. */
3198 didone = TRUE;
3199 exiterr = 1;
3200 break;
3201 }
3202 Argc = i;
3203 }
3204# ifdef FEAT_X11
3205 if (xterm_dpy == NULL)
3206 {
3207 mch_errmsg(_("No display"));
3208 ret = -1;
3209 }
3210 else
3211 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3212 NULL, &srv, 0, 0, silent);
3213# else
3214 /* Win32 always works? */
3215 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3216# endif
3217 if (ret < 0)
3218 {
3219 if (argtype == ARGTYPE_SEND)
3220 {
3221 /* Failed to send, abort. */
3222 mch_errmsg(_(": Send failed.\n"));
3223 didone = TRUE;
3224 exiterr = 1;
3225 }
3226 else if (!silent)
3227 /* Let vim start normally. */
3228 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3229 break;
3230 }
3231
3232# ifdef FEAT_GUI_W32
3233 /* Guess that when the server name starts with "g" it's a GUI
3234 * server, which we can bring to the foreground here.
3235 * Foreground() in the server doesn't work very well. */
3236 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3237 SetForegroundWindow(srv);
3238# endif
3239
3240 /*
3241 * For --remote-wait: Wait until the server did edit each
3242 * file. Also detect that the server no longer runs.
3243 */
3244 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3245 {
3246 int numFiles = *argc - i - 1;
3247 int j;
3248 char_u *done = alloc(numFiles);
3249 char_u *p;
3250# ifdef FEAT_GUI_W32
3251 NOTIFYICONDATA ni;
3252 int count = 0;
3253 extern HWND message_window;
3254# endif
3255
3256 if (numFiles > 0 && argv[i + 1][0] == '+')
3257 /* Skip "+cmd" argument, don't wait for it to be edited. */
3258 --numFiles;
3259
3260# ifdef FEAT_GUI_W32
3261 ni.cbSize = sizeof(ni);
3262 ni.hWnd = message_window;
3263 ni.uID = 0;
3264 ni.uFlags = NIF_ICON|NIF_TIP;
3265 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3266 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3267 Shell_NotifyIcon(NIM_ADD, &ni);
3268# endif
3269
3270 /* Wait for all files to unload in remote */
3271 memset(done, 0, numFiles);
3272 while (memchr(done, 0, numFiles) != NULL)
3273 {
3274# ifdef WIN32
3275 p = serverGetReply(srv, NULL, TRUE, TRUE);
3276 if (p == NULL)
3277 break;
3278# else
3279 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3280 break;
3281# endif
3282 j = atoi((char *)p);
3283 if (j >= 0 && j < numFiles)
3284 {
3285# ifdef FEAT_GUI_W32
3286 ++count;
3287 sprintf(ni.szTip, _("%d of %d edited"),
3288 count, numFiles);
3289 Shell_NotifyIcon(NIM_MODIFY, &ni);
3290# endif
3291 done[j] = 1;
3292 }
3293 }
3294# ifdef FEAT_GUI_W32
3295 Shell_NotifyIcon(NIM_DELETE, &ni);
3296# endif
3297 }
3298 }
3299 else if (STRICMP(argv[i], "--remote-expr") == 0)
3300 {
3301 if (i == *argc - 1)
3302 mainerr_arg_missing((char_u *)argv[i]);
3303# ifdef WIN32
3304 /* Win32 always works? */
3305 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3306 &res, NULL, 1, FALSE) < 0)
3307# else
3308 if (xterm_dpy == NULL)
3309 mch_errmsg(_("No display: Send expression failed.\n"));
3310 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3311 &res, NULL, 1, 1, FALSE) < 0)
3312# endif
3313 {
3314 if (res != NULL && *res != NUL)
3315 {
3316 /* Output error from remote */
3317 mch_errmsg((char *)res);
3318 vim_free(res);
3319 res = NULL;
3320 }
3321 mch_errmsg(_(": Send expression failed.\n"));
3322 }
3323 }
3324 else if (STRICMP(argv[i], "--serverlist") == 0)
3325 {
3326# ifdef WIN32
3327 /* Win32 always works? */
3328 res = serverGetVimNames();
3329# else
3330 if (xterm_dpy != NULL)
3331 res = serverGetVimNames(xterm_dpy);
3332# endif
3333 if (called_emsg)
3334 mch_errmsg("\n");
3335 }
3336 else if (STRICMP(argv[i], "--servername") == 0)
3337 {
3338 /* Alredy processed. Take it out of the command line */
3339 i++;
3340 continue;
3341 }
3342 else
3343 {
3344 *newArgV++ = argv[i];
3345 newArgC++;
3346 continue;
3347 }
3348 didone = TRUE;
3349 if (res != NULL && *res != NUL)
3350 {
3351 mch_msg((char *)res);
3352 if (res[STRLEN(res) - 1] != '\n')
3353 mch_msg("\n");
3354 }
3355 vim_free(res);
3356 }
3357
3358 if (didone)
3359 {
3360 display_errors(); /* display any collected messages */
3361 exit(exiterr); /* Mission accomplished - get out */
3362 }
3363
3364 /* Return back into main() */
3365 *argc = newArgC;
3366 vim_free(sname);
3367}
3368
3369/*
3370 * Build a ":drop" command to send to a Vim server.
3371 */
3372 static char_u *
3373build_drop_cmd(filec, filev, sendReply)
3374 int filec;
3375 char **filev;
3376 int sendReply;
3377{
3378 garray_T ga;
3379 int i;
3380 char_u *inicmd = NULL;
3381 char_u *p;
3382 char_u cwd[MAXPATHL];
3383
3384 if (filec > 0 && filev[0][0] == '+')
3385 {
3386 inicmd = (char_u *)filev[0] + 1;
3387 filev++;
3388 filec--;
3389 }
3390 /* Check if we have at least one argument. */
3391 if (filec <= 0)
3392 mainerr_arg_missing((char_u *)filev[-1]);
3393 if (mch_dirname(cwd, MAXPATHL) != OK)
3394 return NULL;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003395 if ((p = vim_strsave_escaped_ext(cwd, PATH_ESC_CHARS, '\\', TRUE)) == NULL)
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003396 return NULL;
3397 ga_init2(&ga, 1, 100);
3398 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3399 ga_concat(&ga, p);
3400 /* Call inputsave() so that a prompt for an encryption key works. */
3401 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|drop");
3402 vim_free(p);
3403 for (i = 0; i < filec; i++)
3404 {
3405 /* On Unix the shell has already expanded the wildcards, don't want to
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003406 * do it again in the Vim server. On MS-Windows only escape
3407 * non-wildcard characters. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003408 p = vim_strsave_escaped((char_u *)filev[i],
3409#ifdef UNIX
3410 PATH_ESC_CHARS
3411#else
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003412 (char_u *)" \t%#"
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003413#endif
3414 );
3415 if (p == NULL)
3416 {
3417 vim_free(ga.ga_data);
3418 return NULL;
3419 }
3420 ga_concat(&ga, (char_u *)" ");
3421 ga_concat(&ga, p);
3422 vim_free(p);
3423 }
3424 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3425 * CTRL-\ CTRL-N again. */
3426 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3427 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3428 if (sendReply)
3429 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3430 ga_concat(&ga, (char_u *)"<CR>:");
3431 if (inicmd != NULL)
3432 {
3433 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3434 * the following commands to be inserted as text. Use a "|",
3435 * hopefully "inicmd" does allow this... */
3436 ga_concat(&ga, inicmd);
3437 ga_concat(&ga, (char_u *)"|");
3438 }
3439 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3440 * clear command line. */
Bram Moolenaar567e4de2004-12-31 21:01:02 +00003441 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003442 ga_append(&ga, NUL);
3443 return ga.ga_data;
3444}
3445
3446/*
3447 * Replace termcodes such as <CR> and insert as key presses if there is room.
3448 */
3449 void
3450server_to_input_buf(str)
3451 char_u *str;
3452{
3453 char_u *ptr = NULL;
3454 char_u *cpo_save = p_cpo;
3455
3456 /* Set 'cpoptions' the way we want it.
3457 * B set - backslashes are *not* treated specially
3458 * k set - keycodes are *not* reverse-engineered
3459 * < unset - <Key> sequences *are* interpreted
3460 * The last parameter of replace_termcodes() is TRUE so that the <lt>
3461 * sequence is recognised - needed for a real backslash.
3462 */
3463 p_cpo = (char_u *)"Bk";
3464 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE);
3465 p_cpo = cpo_save;
3466
3467 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3468 {
3469 /*
3470 * Add the string to the input stream.
3471 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3472 *
3473 * First clear typed characters from the typeahead buffer, there could
3474 * be half a mapping there. Then append to the existing string, so
3475 * that multiple commands from a client are concatenated.
3476 */
3477 if (typebuf.tb_maplen < typebuf.tb_len)
3478 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3479 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3480
3481 /* Let input_available() know we inserted text in the typeahead
3482 * buffer. */
3483 received_from_client = TRUE;
3484 }
3485 vim_free((char_u *)ptr);
3486}
3487
3488/*
3489 * Evaluate an expression that the client sent to a string.
3490 * Handles disabling error messages and disables debugging, otherwise Vim
3491 * hangs, waiting for "cont" to be typed.
3492 */
3493 char_u *
3494eval_client_expr_to_string(expr)
3495 char_u *expr;
3496{
3497 char_u *res;
3498 int save_dbl = debug_break_level;
3499 int save_ro = redir_off;
3500
3501 debug_break_level = -1;
3502 redir_off = 0;
3503 ++emsg_skip;
3504
3505 res = eval_to_string(expr, NULL);
3506
3507 debug_break_level = save_dbl;
3508 redir_off = save_ro;
3509 --emsg_skip;
3510
Bram Moolenaar63a121b2005-12-11 21:36:39 +00003511 /* A client can tell us to redraw, but not to display the cursor, so do
3512 * that here. */
3513 setcursor();
3514 out_flush();
3515#ifdef FEAT_GUI
3516 if (gui.in_use)
3517 gui_update_cursor(FALSE, FALSE);
3518#endif
3519
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003520 return res;
3521}
3522
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003523/*
3524 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3525 * return an allocated string. Otherwise return "data".
3526 * "*tofree" is set to the result when it needs to be freed later.
3527 */
3528/*ARGSUSED*/
3529 char_u *
3530serverConvert(client_enc, data, tofree)
3531 char_u *client_enc;
3532 char_u *data;
3533 char_u **tofree;
3534{
3535 char_u *res = data;
3536
3537 *tofree = NULL;
3538# ifdef FEAT_MBYTE
3539 if (client_enc != NULL && p_enc != NULL)
3540 {
3541 vimconv_T vimconv;
3542
3543 vimconv.vc_type = CONV_NONE;
3544 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3545 && vimconv.vc_type != CONV_NONE)
3546 {
3547 res = string_convert(&vimconv, data, NULL);
3548 if (res == NULL)
3549 res = data;
3550 else
3551 *tofree = res;
3552 }
3553 convert_setup(&vimconv, NULL, NULL);
3554 }
3555# endif
3556 return res;
3557}
3558
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003559
3560/*
3561 * Make our basic server name: use the specified "arg" if given, otherwise use
3562 * the tail of the command "cmd" we were started with.
3563 * Return the name in allocated memory. This doesn't include a serial number.
3564 */
3565 static char_u *
3566serverMakeName(arg, cmd)
3567 char_u *arg;
3568 char *cmd;
3569{
3570 char_u *p;
3571
3572 if (arg != NULL && *arg != NUL)
3573 p = vim_strsave_up(arg);
3574 else
3575 {
3576 p = vim_strsave_up(gettail((char_u *)cmd));
3577 /* Remove .exe or .bat from the name. */
3578 if (p != NULL && vim_strchr(p, '.') != NULL)
3579 *vim_strchr(p, '.') = NUL;
3580 }
3581 return p;
3582}
3583#endif /* FEAT_CLIENTSERVER */
3584
3585/*
3586 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3587 */
3588#if defined(FEAT_FKMAP) || defined(PROTO)
3589# include "farsi.c"
3590#endif
3591
3592/*
3593 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3594 */
3595#if defined(FEAT_ARABIC) || defined(PROTO)
3596# include "arabic.c"
3597#endif