blob: 551e980f9a410bfbd42d448ff22c1beea117469f [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
847 /* start in insert mode */
848 if (p_im)
849 need_start_insertmode = TRUE;
850
851#ifdef FEAT_AUTOCMD
852 apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
853 TIME_MSG("VimEnter autocommands");
854#endif
855
856#if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
857 /* When a startup script or session file setup for diff'ing and
858 * scrollbind, sync the scrollbind now. */
859 if (curwin->w_p_diff && curwin->w_p_scb)
860 {
861 update_topline();
862 check_scrollbind((linenr_T)0, 0L);
863 TIME_MSG("diff scrollbinding");
864 }
865#endif
866
867#if defined(WIN3264) && !defined(FEAT_GUI_W32)
868 mch_set_winsize_now(); /* Allow winsize changes from now on */
869#endif
870
871 /* If ":startinsert" command used, stuff a dummy command to be able to
872 * call normal_cmd(), which will then start Insert mode. */
873 if (restart_edit != 0)
Bram Moolenaarebefac62005-12-28 22:39:57 +0000874 stuffcharReadbuff(K_NOP);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000875
876#ifdef FEAT_NETBEANS_INTG
877 if (usingNetbeans)
878 /* Tell the client that it can start sending commands. */
879 netbeans_startup_done();
880#endif
881
882 TIME_MSG("before starting main loop");
883
884 /*
885 * Call the main command loop. This never returns.
886 */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000887 main_loop(FALSE, FALSE);
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000888
889 return 0;
890}
891#endif /* PROTO */
892
893/*
894 * Main loop: Execute Normal mode commands until exiting Vim.
895 * Also used to handle commands in the command-line window, until the window
896 * is closed.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000897 * Also used to handle ":visual" command after ":global": execute Normal mode
898 * commands, return when entering Ex mode. "noexmode" is TRUE then.
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000899 */
900 void
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000901main_loop(cmdwin, noexmode)
902 int cmdwin; /* TRUE when working in the command-line window */
903 int noexmode; /* TRUE when return on entering Ex mode */
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000904{
905 oparg_T oa; /* operator arguments */
906
907#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
908 /* Setup to catch a terminating error from the X server. Just ignore
909 * it, restore the state and continue. This might not always work
910 * properly, but at least we don't exit unexpectedly when the X server
911 * exists while Vim is running in a console. */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +0000912 if (!cmdwin && !noexmode && SETJMP(x_jump_env))
Bram Moolenaarb4210b32004-06-13 14:51:16 +0000913 {
914 State = NORMAL;
915# ifdef FEAT_VISUAL
916 VIsual_active = FALSE;
917# endif
918 got_int = TRUE;
919 need_wait_return = FALSE;
920 global_busy = FALSE;
921 exmode_active = 0;
922 skip_redraw = FALSE;
923 RedrawingDisabled = 0;
924 no_wait_return = 0;
925# ifdef FEAT_EVAL
926 emsg_skip = 0;
927# endif
928 emsg_off = 0;
929# ifdef FEAT_MOUSE
930 setmouse();
931# endif
932 settmode(TMODE_RAW);
933 starttermcap();
934 scroll_start();
935 redraw_later_clear();
936 }
937#endif
938
939 clear_oparg(&oa);
940 while (!cmdwin
941#ifdef FEAT_CMDWIN
942 || cmdwin_result == 0
943#endif
944 )
945 {
946 if (stuff_empty())
947 {
948 did_check_timestamps = FALSE;
949 if (need_check_timestamps)
950 check_timestamps(FALSE);
951 if (need_wait_return) /* if wait_return still needed ... */
952 wait_return(FALSE); /* ... call it now */
953 if (need_start_insertmode && goto_im()
954#ifdef FEAT_VISUAL
955 && !VIsual_active
956#endif
957 )
958 {
959 need_start_insertmode = FALSE;
960 stuffReadbuff((char_u *)"i"); /* start insert mode next */
961 /* skip the fileinfo message now, because it would be shown
962 * after insert mode finishes! */
963 need_fileinfo = FALSE;
964 }
965 }
966 if (got_int && !global_busy)
967 {
968 if (!quit_more)
969 (void)vgetc(); /* flush all buffers */
970 got_int = FALSE;
971 }
972 if (!exmode_active)
973 msg_scroll = FALSE;
974 quit_more = FALSE;
975
976 /*
977 * If skip redraw is set (for ":" in wait_return()), don't redraw now.
978 * If there is nothing in the stuff_buffer or do_redraw is TRUE,
979 * update cursor and redraw.
980 */
981 if (skip_redraw || exmode_active)
982 skip_redraw = FALSE;
983 else if (do_redraw || stuff_empty())
984 {
985#if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
986 /* Include a closed fold completely in the Visual area. */
987 foldAdjustVisual();
988#endif
989#ifdef FEAT_FOLDING
990 /*
991 * When 'foldclose' is set, apply 'foldlevel' to folds that don't
992 * contain the cursor.
993 * When 'foldopen' is "all", open the fold(s) under the cursor.
994 * This may mark the window for redrawing.
995 */
996 if (hasAnyFolding(curwin) && !char_avail())
997 {
998 foldCheckClose();
999 if (fdo_flags & FDO_ALL)
1000 foldOpenCursor();
1001 }
1002#endif
1003
1004 /*
1005 * Before redrawing, make sure w_topline is correct, and w_leftcol
1006 * if lines don't wrap, and w_skipcol if lines wrap.
1007 */
1008 update_topline();
1009 validate_cursor();
1010
1011#ifdef FEAT_VISUAL
1012 if (VIsual_active)
1013 update_curbuf(INVERTED);/* update inverted part */
1014 else
1015#endif
1016 if (must_redraw)
1017 update_screen(0);
1018 else if (redraw_cmdline || clear_cmdline)
1019 showmode();
1020#ifdef FEAT_WINDOWS
1021 redraw_statuslines();
1022#endif
1023#ifdef FEAT_TITLE
1024 if (need_maketitle)
1025 maketitle();
1026#endif
1027 /* display message after redraw */
1028 if (keep_msg != NULL)
1029 {
1030 char_u *p;
1031
1032 /* msg_attr_keep() will set keep_msg to NULL, must free the
1033 * string here. */
1034 p = keep_msg;
1035 msg_attr(p, keep_msg_attr);
1036 vim_free(p);
1037 }
1038 if (need_fileinfo) /* show file info after redraw */
1039 {
1040 fileinfo(FALSE, TRUE, FALSE);
1041 need_fileinfo = FALSE;
1042 }
1043
1044 emsg_on_display = FALSE; /* can delete error message now */
1045 did_emsg = FALSE;
1046 msg_didany = FALSE; /* reset lines_left in msg_start() */
Bram Moolenaar661b1822005-07-28 22:36:45 +00001047 may_clear_sb_text(); /* clear scroll-back text on next msg */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001048 showruler(FALSE);
1049
1050 setcursor();
1051 cursor_on();
1052
1053 do_redraw = FALSE;
1054 }
1055#ifdef FEAT_GUI
1056 if (need_mouse_correct)
1057 gui_mouse_correct();
1058#endif
1059
1060 /*
1061 * Update w_curswant if w_set_curswant has been set.
1062 * Postponed until here to avoid computing w_virtcol too often.
1063 */
1064 update_curswant();
1065
1066 /*
1067 * If we're invoked as ex, do a round of ex commands.
1068 * Otherwise, get and execute a normal mode command.
1069 */
1070 if (exmode_active)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001071 {
1072 if (noexmode) /* End of ":global/path/visual" commands */
1073 return;
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001074 do_exmode(exmode_active == EXMODE_VIM);
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001075 }
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001076 else
1077 normal_cmd(&oa, TRUE);
1078 }
1079}
1080
1081
1082#if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO)
1083/*
1084 * Exit, but leave behind swap files for modified buffers.
1085 */
1086 void
1087getout_preserve_modified(exitval)
1088 int exitval;
1089{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001090# if defined(SIGHUP) && defined(SIG_IGN)
1091 /* Ignore SIGHUP, because a dropped connection causes a read error, which
1092 * makes Vim exit and then handling SIGHUP causes various reentrance
1093 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001094 signal(SIGHUP, SIG_IGN);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001095# endif
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001096
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001097 ml_close_notmod(); /* close all not-modified buffers */
1098 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
1099 ml_close_all(FALSE); /* close all memfiles, without deleting */
1100 getout(exitval); /* exit Vim properly */
1101}
1102#endif
1103
1104
1105/* Exit properly */
1106 void
1107getout(exitval)
1108 int exitval;
1109{
1110#ifdef FEAT_AUTOCMD
1111 buf_T *buf;
1112 win_T *wp;
1113#endif
1114
1115 exiting = TRUE;
1116
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00001117 /* When running in Ex mode an error causes us to exit with a non-zero exit
1118 * code. POSIX requires this, although it's not 100% clear from the
1119 * standard. */
1120 if (exmode_active)
1121 exitval += ex_exitval;
1122
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001123 /* Position the cursor on the last screen line, below all the text */
1124#ifdef FEAT_GUI
1125 if (!gui.in_use)
1126#endif
1127 windgoto((int)Rows - 1, 0);
1128
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +00001129#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
1130 /* Optionally print hashtable efficiency. */
1131 hash_debug_results();
1132#endif
1133
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001134#ifdef FEAT_GUI
1135 msg_didany = FALSE;
1136#endif
1137
1138#ifdef FEAT_AUTOCMD
1139 /* Trigger BufWinLeave for all windows, but only once per buffer. */
1140 for (wp = firstwin; wp != NULL; )
1141 {
1142 buf = wp->w_buffer;
1143 if (buf->b_changedtick != -1)
1144 {
1145 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
1146 FALSE, buf);
1147 buf->b_changedtick = -1; /* note that we did it already */
1148 wp = firstwin; /* restart, window may be closed */
1149 }
1150 else
1151 wp = wp->w_next;
1152 }
1153 /* Trigger BufUnload for buffers that are loaded */
1154 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1155 if (buf->b_ml.ml_mfp != NULL)
1156 {
1157 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
1158 FALSE, buf);
1159 if (!buf_valid(buf)) /* autocmd may delete the buffer */
1160 break;
1161 }
1162 apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
1163#endif
1164
1165#ifdef FEAT_VIMINFO
1166 if (*p_viminfo != NUL)
1167 /* Write out the registers, history, marks etc, to the viminfo file */
1168 write_viminfo(NULL, FALSE);
1169#endif
1170
1171#ifdef FEAT_AUTOCMD
1172 apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
1173#endif
1174
Bram Moolenaar05159a02005-02-26 23:04:13 +00001175#ifdef FEAT_PROFILE
1176 profile_dump();
1177#endif
1178
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001179 if (did_emsg
1180#ifdef FEAT_GUI
1181 || (gui.in_use && msg_didany && p_verbose > 0)
1182#endif
1183 )
1184 {
1185 /* give the user a chance to read the (error) message */
1186 no_wait_return = FALSE;
1187 wait_return(FALSE);
1188 }
1189
1190#ifdef FEAT_AUTOCMD
1191 /* Position the cursor again, the autocommands may have moved it */
1192# ifdef FEAT_GUI
1193 if (!gui.in_use)
1194# endif
1195 windgoto((int)Rows - 1, 0);
1196#endif
1197
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001198#ifdef FEAT_MZSCHEME
1199 mzscheme_end();
1200#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001201#ifdef FEAT_TCL
1202 tcl_end();
1203#endif
1204#ifdef FEAT_RUBY
1205 ruby_end();
1206#endif
1207#ifdef FEAT_PYTHON
1208 python_end();
1209#endif
1210#ifdef FEAT_PERL
1211 perl_end();
1212#endif
1213#if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
1214 iconv_end();
1215#endif
1216#ifdef FEAT_NETBEANS_INTG
1217 netbeans_end();
1218#endif
1219
1220 mch_exit(exitval);
1221}
1222
1223/*
1224 * Get a (optional) count for a Vim argument.
1225 */
1226 static int
1227get_number_arg(p, idx, def)
1228 char_u *p; /* pointer to argument */
1229 int *idx; /* index in argument, is incremented */
1230 int def; /* default value */
1231{
1232 if (vim_isdigit(p[*idx]))
1233 {
1234 def = atoi((char *)&(p[*idx]));
1235 while (vim_isdigit(p[*idx]))
1236 *idx = *idx + 1;
1237 }
1238 return def;
1239}
1240
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001241#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1242/*
1243 * Setup to use the current locale (for ctype() and many other things).
1244 */
1245 static void
1246init_locale()
1247{
1248 setlocale(LC_ALL, "");
Bram Moolenaar482aaeb2005-09-29 18:26:07 +00001249# ifdef WIN32
1250 /* Apparently MS-Windows printf() may cause a crash when we give it 8-bit
1251 * text while it's expecting text in the current locale. This call avoids
1252 * that. */
1253 setlocale(LC_CTYPE, "C");
1254# endif
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001255
1256# ifdef FEAT_GETTEXT
1257 {
1258 int mustfree = FALSE;
1259 char_u *p;
1260
1261# ifdef DYNAMIC_GETTEXT
1262 /* Initialize the gettext library */
1263 dyn_libintl_init(NULL);
1264# endif
1265 /* expand_env() doesn't work yet, because chartab[] is not initialized
1266 * yet, call vim_getenv() directly */
1267 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1268 if (p != NULL && *p != NUL)
1269 {
1270 STRCPY(NameBuff, p);
1271 STRCAT(NameBuff, "/lang");
1272 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1273 }
1274 if (mustfree)
1275 vim_free(p);
1276 textdomain(VIMPACKAGE);
1277 }
1278# endif
1279}
1280#endif
1281
1282/*
1283 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1284 * If the executable name starts with "r" we disable shell commands.
1285 * If the next character is "e" we run in Easy mode.
1286 * If the next character is "g" we run the GUI version.
1287 * If the next characters are "view" we start in readonly mode.
1288 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1289 * If the next characters are "ex" we start in Ex mode. If it's followed
1290 * by "im" use improved Ex mode.
1291 */
1292 static void
1293parse_command_name(parmp)
1294 mparm_T *parmp;
1295{
1296 char_u *initstr;
1297
1298 initstr = gettail((char_u *)parmp->argv[0]);
1299
1300#ifdef MACOS_X_UNIX
1301 /* An issue has been seen when launching Vim in such a way that
1302 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1303 * executable or a symbolic link of it. Until this issue is resolved
1304 * we prohibit the GUI from being used.
1305 */
1306 if (STRCMP(initstr, parmp->argv[0]) == 0)
1307 disallow_gui = TRUE;
1308
1309 /* TODO: On MacOS X default to gui if argv[0] ends in:
1310 * /vim.app/Contents/MacOS/Vim */
1311#endif
1312
1313#ifdef FEAT_EVAL
1314 set_vim_var_string(VV_PROGNAME, initstr, -1);
1315#endif
1316
1317 if (TOLOWER_ASC(initstr[0]) == 'r')
1318 {
1319 restricted = TRUE;
1320 ++initstr;
1321 }
1322
1323 /* Avoid using evim mode for "editor". */
1324 if (TOLOWER_ASC(initstr[0]) == 'e'
1325 && (TOLOWER_ASC(initstr[1]) == 'v'
1326 || TOLOWER_ASC(initstr[1]) == 'g'))
1327 {
1328#ifdef FEAT_GUI
1329 gui.starting = TRUE;
1330#endif
1331 parmp->evim_mode = TRUE;
1332 ++initstr;
1333 }
1334
1335 if (TOLOWER_ASC(initstr[0]) == 'g' || initstr[0] == 'k')
1336 {
1337 main_start_gui();
1338#ifdef FEAT_GUI
1339 ++initstr;
1340#endif
1341 }
1342
1343 if (STRNICMP(initstr, "view", 4) == 0)
1344 {
1345 readonlymode = TRUE;
1346 curbuf->b_p_ro = TRUE;
1347 p_uc = 10000; /* don't update very often */
1348 initstr += 4;
1349 }
1350 else if (STRNICMP(initstr, "vim", 3) == 0)
1351 initstr += 3;
1352
1353 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1354 if (STRICMP(initstr, "diff") == 0)
1355 {
1356#ifdef FEAT_DIFF
1357 parmp->diff_mode = TRUE;
1358#else
1359 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1360 mch_errmsg("\n");
1361 mch_exit(2);
1362#endif
1363 }
1364
1365 if (STRNICMP(initstr, "ex", 2) == 0)
1366 {
1367 if (STRNICMP(initstr + 2, "im", 2) == 0)
1368 exmode_active = EXMODE_VIM;
1369 else
1370 exmode_active = EXMODE_NORMAL;
1371 change_compatible(TRUE); /* set 'compatible' */
1372 }
1373}
1374
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001375/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00001376 * Get the name of the display, before gui_prepare() removes it from
1377 * argv[]. Used for the xterm-clipboard display.
1378 *
1379 * Also find the --server... arguments and --socketid
1380 */
1381/*ARGSUSED*/
1382 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001383early_arg_scan(parmp)
Bram Moolenaar58d98232005-07-23 22:25:46 +00001384 mparm_T *parmp;
1385{
1386#if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001387 int argc = parmp->argc;
1388 char **argv = parmp->argv;
Bram Moolenaar58d98232005-07-23 22:25:46 +00001389 int i;
1390
1391 for (i = 1; i < argc; i++)
1392 {
1393 if (STRCMP(argv[i], "--") == 0)
1394 break;
1395# ifdef FEAT_XCLIPBOARD
1396 else if (STRICMP(argv[i], "-display") == 0
Bram Moolenaar241a8aa2005-12-06 20:04:44 +00001397# if defined(FEAT_GUI_GTK)
Bram Moolenaar58d98232005-07-23 22:25:46 +00001398 || STRICMP(argv[i], "--display") == 0
1399# endif
1400 )
1401 {
1402 if (i == argc - 1)
1403 mainerr_arg_missing((char_u *)argv[i]);
1404 xterm_display = argv[++i];
1405 }
1406# endif
1407# ifdef FEAT_CLIENTSERVER
1408 else if (STRICMP(argv[i], "--servername") == 0)
1409 {
1410 if (i == argc - 1)
1411 mainerr_arg_missing((char_u *)argv[i]);
1412 parmp->serverName_arg = (char_u *)argv[++i];
1413 }
1414 else if (STRICMP(argv[i], "--serverlist") == 0
1415 || STRICMP(argv[i], "--remote-send") == 0
1416 || STRICMP(argv[i], "--remote-expr") == 0
1417 || STRICMP(argv[i], "--remote") == 0
1418 || STRICMP(argv[i], "--remote-silent") == 0)
1419 parmp->serverArg = TRUE;
1420 else if (STRICMP(argv[i], "--remote-wait") == 0
1421 || STRICMP(argv[i], "--remote-wait-silent") == 0)
1422 {
1423 parmp->serverArg = TRUE;
1424#ifdef FEAT_GUI
1425 /* don't fork() when starting the GUI to edit the files ourself */
1426 gui.dofork = FALSE;
1427#endif
1428 }
1429# endif
1430# ifdef FEAT_GUI_GTK
1431 else if (STRICMP(argv[i], "--socketid") == 0)
1432 {
1433 unsigned int socket_id;
1434 int count;
1435
1436 if (i == argc - 1)
1437 mainerr_arg_missing((char_u *)argv[i]);
1438 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1439 count = sscanf(&(argv[i + 1][2]), "%x", &socket_id);
1440 else
1441 count = sscanf(argv[i+1], "%u", &socket_id);
1442 if (count != 1)
1443 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1444 else
1445 gtk_socket_id = socket_id;
1446 i++;
1447 }
1448 else if (STRICMP(argv[i], "--echo-wid") == 0)
1449 echo_wid_arg = TRUE;
1450# endif
1451 }
1452#endif
1453}
1454
1455/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001456 * Scan the command line arguments.
1457 */
1458 static void
1459command_line_scan(parmp)
1460 mparm_T *parmp;
1461{
1462 int argc = parmp->argc;
1463 char **argv = parmp->argv;
1464 int argv_idx; /* index in argv[n][] */
1465 int had_minmin = FALSE; /* found "--" argument */
1466 int want_argument; /* option argument with argument */
1467 int c;
Bram Moolenaar231334e2005-07-25 20:46:57 +00001468 char_u *p = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001469 long n;
1470
1471 --argc;
1472 ++argv;
1473 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1474 while (argc > 0)
1475 {
1476 /*
1477 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1478 */
1479 if (argv[0][0] == '+' && !had_minmin)
1480 {
1481 if (parmp->n_commands >= MAX_ARG_CMDS)
1482 mainerr(ME_EXTRA_CMD, NULL);
1483 argv_idx = -1; /* skip to next argument */
1484 if (argv[0][1] == NUL)
1485 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1486 else
1487 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1488 }
1489
1490 /*
1491 * Optional argument.
1492 */
1493 else if (argv[0][0] == '-' && !had_minmin)
1494 {
1495 want_argument = FALSE;
1496 c = argv[0][argv_idx++];
1497#ifdef VMS
1498 /*
1499 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1500 * and "-/X" as "-X".
1501 */
1502 if (c == '/')
1503 {
1504 c = argv[0][argv_idx++];
1505 c = TOUPPER_ASC(c);
1506 }
1507 else
1508 c = TOLOWER_ASC(c);
1509#endif
1510 switch (c)
1511 {
1512 case NUL: /* "vim -" read from stdin */
1513 /* "ex -" silent mode */
1514 if (exmode_active)
1515 silent_mode = TRUE;
1516 else
1517 {
1518 if (parmp->edit_type != EDIT_NONE)
1519 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1520 parmp->edit_type = EDIT_STDIN;
1521 read_cmd_fd = 2; /* read from stderr instead of stdin */
1522 }
1523 argv_idx = -1; /* skip to next argument */
1524 break;
1525
1526 case '-': /* "--" don't take any more option arguments */
1527 /* "--help" give help message */
1528 /* "--version" give version message */
1529 /* "--literal" take files literally */
1530 /* "--nofork" don't fork */
1531 /* "--noplugin[s]" skip plugins */
1532 /* "--cmd <cmd>" execute cmd before vimrc */
1533 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1534 usage();
1535 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1536 {
1537 Columns = 80; /* need to init Columns */
1538 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1539 list_version();
1540 msg_putchar('\n');
1541 msg_didout = FALSE;
1542 mch_exit(0);
1543 }
1544 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1545 {
1546#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1547 parmp->literal = TRUE;
1548#endif
1549 }
1550 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1551 {
1552#ifdef FEAT_GUI
1553 gui.dofork = FALSE; /* don't fork() when starting GUI */
1554#endif
1555 }
1556 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1557 p_lpl = FALSE;
1558 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1559 {
1560 want_argument = TRUE;
1561 argv_idx += 3;
1562 }
1563#ifdef FEAT_CLIENTSERVER
1564 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1565 ; /* already processed -- no arg */
1566 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1567 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1568 {
1569 /* already processed -- snatch the following arg */
1570 if (argc > 1)
1571 {
1572 --argc;
1573 ++argv;
1574 }
1575 }
1576#endif
1577#ifdef FEAT_GUI_GTK
1578 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1579 {
1580 /* already processed -- snatch the following arg */
1581 if (argc > 1)
1582 {
1583 --argc;
1584 ++argv;
1585 }
1586 }
1587 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1588 {
1589 /* already processed, skip */
1590 }
1591#endif
1592 else
1593 {
1594 if (argv[0][argv_idx])
1595 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1596 had_minmin = TRUE;
1597 }
1598 if (!want_argument)
1599 argv_idx = -1; /* skip to next argument */
1600 break;
1601
1602 case 'A': /* "-A" start in Arabic mode */
1603#ifdef FEAT_ARABIC
1604 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1605#else
1606 mch_errmsg(_(e_noarabic));
1607 mch_exit(2);
1608#endif
1609 break;
1610
1611 case 'b': /* "-b" binary mode */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001612 /* Needs to be effective before expanding file names, because
1613 * for Win32 this makes us edit a shortcut file itself,
1614 * instead of the file it links to. */
1615 set_options_bin(curbuf->b_p_bin, 1, 0);
1616 curbuf->b_p_bin = 1; /* binary file I/O */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001617 break;
1618
1619 case 'C': /* "-C" Compatible */
1620 change_compatible(TRUE);
1621 break;
1622
1623 case 'e': /* "-e" Ex mode */
1624 exmode_active = EXMODE_NORMAL;
1625 break;
1626
1627 case 'E': /* "-E" Improved Ex mode */
1628 exmode_active = EXMODE_VIM;
1629 break;
1630
1631 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1632 window directly, not with newcli */
1633#ifdef FEAT_GUI
1634 gui.dofork = FALSE; /* don't fork() when starting GUI */
1635#endif
1636 break;
1637
1638 case 'g': /* "-g" start GUI */
1639 main_start_gui();
1640 break;
1641
1642 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1643#ifdef FEAT_FKMAP
1644 curwin->w_p_rl = p_fkmap = TRUE;
1645#else
1646 mch_errmsg(_(e_nofarsi));
1647 mch_exit(2);
1648#endif
1649 break;
1650
1651 case 'h': /* "-h" give help message */
1652#ifdef FEAT_GUI_GNOME
1653 /* Tell usage() to exit for "gvim". */
1654 gui.starting = FALSE;
1655#endif
1656 usage();
1657 break;
1658
1659 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1660#ifdef FEAT_RIGHTLEFT
1661 curwin->w_p_rl = p_hkmap = TRUE;
1662#else
1663 mch_errmsg(_(e_nohebrew));
1664 mch_exit(2);
1665#endif
1666 break;
1667
1668 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1669#ifdef FEAT_LISP
1670 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1671 p_sm = TRUE;
1672#endif
1673 break;
1674
1675#ifdef TARGET_API_MAC_OSX
1676 /* For some reason on MacOS X, an argument like:
1677 -psn_0_10223617 is passed in when invoke from Finder
1678 or with the 'open' command */
1679 case 'p':
1680 argv_idx = -1; /* bypass full -psn */
1681 main_start_gui();
1682 break;
1683#endif
1684 case 'M': /* "-M" no changes or writing of files */
1685 reset_modifiable();
1686 /* FALLTHROUGH */
1687
1688 case 'm': /* "-m" no writing of files */
1689 p_write = FALSE;
1690 break;
1691
1692 case 'y': /* "-y" easy mode */
1693#ifdef FEAT_GUI
1694 gui.starting = TRUE; /* start GUI a bit later */
1695#endif
1696 parmp->evim_mode = TRUE;
1697 break;
1698
1699 case 'N': /* "-N" Nocompatible */
1700 change_compatible(FALSE);
1701 break;
1702
1703 case 'n': /* "-n" no swap file */
1704 parmp->no_swap_file = TRUE;
1705 break;
1706
1707 case 'o': /* "-o[N]" open N horizontal split windows */
1708#ifdef FEAT_WINDOWS
1709 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001710 parmp->window_count = get_number_arg((char_u *)argv[0],
1711 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001712 parmp->vert_windows = FALSE;
1713#endif
1714 break;
1715
1716 case 'O': /* "-O[N]" open N vertical split windows */
1717#if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1718 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001719 parmp->window_count = get_number_arg((char_u *)argv[0],
1720 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001721 parmp->vert_windows = TRUE;
1722#endif
1723 break;
1724
1725#ifdef FEAT_QUICKFIX
1726 case 'q': /* "-q" QuickFix mode */
1727 if (parmp->edit_type != EDIT_NONE)
1728 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1729 parmp->edit_type = EDIT_QF;
1730 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1731 {
1732 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1733 argv_idx = -1;
1734 }
1735 else if (argc > 1) /* "-q {errorfile}" */
1736 want_argument = TRUE;
1737 break;
1738#endif
1739
1740 case 'R': /* "-R" readonly mode */
1741 readonlymode = TRUE;
1742 curbuf->b_p_ro = TRUE;
1743 p_uc = 10000; /* don't update very often */
1744 break;
1745
1746 case 'r': /* "-r" recovery mode */
1747 case 'L': /* "-L" recovery mode */
1748 recoverymode = 1;
1749 break;
1750
1751 case 's':
1752 if (exmode_active) /* "-s" silent (batch) mode */
1753 silent_mode = TRUE;
1754 else /* "-s {scriptin}" read from script file */
1755 want_argument = TRUE;
1756 break;
1757
1758 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1759 if (parmp->edit_type != EDIT_NONE)
1760 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1761 parmp->edit_type = EDIT_TAG;
1762 if (argv[0][argv_idx]) /* "-t{tag}" */
1763 {
1764 parmp->tagname = (char_u *)argv[0] + argv_idx;
1765 argv_idx = -1;
1766 }
1767 else /* "-t {tag}" */
1768 want_argument = TRUE;
1769 break;
1770
1771#ifdef FEAT_EVAL
1772 case 'D': /* "-D" Debugging */
1773 parmp->use_debug_break_level = 9999;
1774 break;
1775#endif
1776#ifdef FEAT_DIFF
1777 case 'd': /* "-d" 'diff' */
1778# ifdef AMIGA
1779 /* check for "-dev {device}" */
1780 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1781 want_argument = TRUE;
1782 else
1783# endif
1784 parmp->diff_mode = TRUE;
1785 break;
1786#endif
1787 case 'V': /* "-V{N}" Verbose level */
1788 /* default is 10: a little bit verbose */
1789 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1790 if (argv[0][argv_idx] != NUL)
1791 {
1792 set_option_value((char_u *)"verbosefile", 0L,
1793 (char_u *)argv[0] + argv_idx, 0);
1794 argv_idx = STRLEN(argv[0]);
1795 }
1796 break;
1797
1798 case 'v': /* "-v" Vi-mode (as if called "vi") */
1799 exmode_active = 0;
1800#ifdef FEAT_GUI
1801 gui.starting = FALSE; /* don't start GUI */
1802#endif
1803 break;
1804
1805 case 'w': /* "-w{number}" set window height */
1806 /* "-w {scriptout}" write to script */
1807 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
1808 {
1809 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1810 set_option_value((char_u *)"window", n, NULL, 0);
1811 break;
1812 }
1813 want_argument = TRUE;
1814 break;
1815
1816#ifdef FEAT_CRYPT
1817 case 'x': /* "-x" encrypted reading/writing of files */
1818 parmp->ask_for_key = TRUE;
1819 break;
1820#endif
1821
1822 case 'X': /* "-X" don't connect to X server */
1823#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
1824 x_no_connect = TRUE;
1825#endif
1826 break;
1827
1828 case 'Z': /* "-Z" restricted mode */
1829 restricted = TRUE;
1830 break;
1831
1832 case 'c': /* "-c{command}" or "-c {command}" execute
1833 command */
1834 if (argv[0][argv_idx] != NUL)
1835 {
1836 if (parmp->n_commands >= MAX_ARG_CMDS)
1837 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001838 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
1839 + argv_idx;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001840 argv_idx = -1;
1841 break;
1842 }
1843 /*FALLTHROUGH*/
1844 case 'S': /* "-S {file}" execute Vim script */
1845 case 'i': /* "-i {viminfo}" use for viminfo */
1846#ifndef FEAT_DIFF
1847 case 'd': /* "-d {device}" device (for Amiga) */
1848#endif
1849 case 'T': /* "-T {terminal}" terminal name */
1850 case 'u': /* "-u {vimrc}" vim inits file */
1851 case 'U': /* "-U {gvimrc}" gvim inits file */
1852 case 'W': /* "-W {scriptout}" overwrite */
1853#ifdef FEAT_GUI_W32
1854 case 'P': /* "-P {parent title}" MDI parent */
1855#endif
1856 want_argument = TRUE;
1857 break;
1858
1859 default:
1860 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1861 }
1862
1863 /*
1864 * Handle option arguments with argument.
1865 */
1866 if (want_argument)
1867 {
1868 /*
1869 * Check for garbage immediately after the option letter.
1870 */
1871 if (argv[0][argv_idx] != NUL)
1872 mainerr(ME_GARBAGE, (char_u *)argv[0]);
1873
1874 --argc;
1875 if (argc < 1 && c != 'S')
1876 mainerr_arg_missing((char_u *)argv[0]);
1877 ++argv;
1878 argv_idx = -1;
1879
1880 switch (c)
1881 {
1882 case 'c': /* "-c {command}" execute command */
1883 case 'S': /* "-S {file}" execute Vim script */
1884 if (parmp->n_commands >= MAX_ARG_CMDS)
1885 mainerr(ME_EXTRA_CMD, NULL);
1886 if (c == 'S')
1887 {
1888 char *a;
1889
1890 if (argc < 1)
1891 /* "-S" without argument: use default session file
1892 * name. */
1893 a = SESSION_FILE;
1894 else if (argv[0][0] == '-')
1895 {
1896 /* "-S" followed by another option: use default
1897 * session file name. */
1898 a = SESSION_FILE;
1899 ++argc;
1900 --argv;
1901 }
1902 else
1903 a = argv[0];
1904 p = alloc((unsigned)(STRLEN(a) + 4));
1905 if (p == NULL)
1906 mch_exit(2);
1907 sprintf((char *)p, "so %s", a);
1908 parmp->cmds_tofree[parmp->n_commands] = TRUE;
1909 parmp->commands[parmp->n_commands++] = p;
1910 }
1911 else
Bram Moolenaar231334e2005-07-25 20:46:57 +00001912 parmp->commands[parmp->n_commands++] =
1913 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001914 break;
1915
1916 case '-': /* "--cmd {command}" execute command */
1917 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
1918 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001919 parmp->pre_commands[parmp->n_pre_commands++] =
1920 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001921 break;
1922
1923 /* case 'd': -d {device} is handled in mch_check_win() for the
1924 * Amiga */
1925
1926#ifdef FEAT_QUICKFIX
1927 case 'q': /* "-q {errorfile}" QuickFix mode */
1928 parmp->use_ef = (char_u *)argv[0];
1929 break;
1930#endif
1931
1932 case 'i': /* "-i {viminfo}" use for viminfo */
1933 use_viminfo = (char_u *)argv[0];
1934 break;
1935
1936 case 's': /* "-s {scriptin}" read from script file */
1937 if (scriptin[0] != NULL)
1938 {
1939scripterror:
1940 mch_errmsg(_("Attempt to open script file again: \""));
1941 mch_errmsg(argv[-1]);
1942 mch_errmsg(" ");
1943 mch_errmsg(argv[0]);
1944 mch_errmsg("\"\n");
1945 mch_exit(2);
1946 }
1947 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
1948 {
1949 mch_errmsg(_("Cannot open for reading: \""));
1950 mch_errmsg(argv[0]);
1951 mch_errmsg("\"\n");
1952 mch_exit(2);
1953 }
1954 if (save_typebuf() == FAIL)
1955 mch_exit(2); /* out of memory */
1956 break;
1957
1958 case 't': /* "-t {tag}" */
1959 parmp->tagname = (char_u *)argv[0];
1960 break;
1961
1962 case 'T': /* "-T {terminal}" terminal name */
1963 /*
1964 * The -T term argument is always available and when
1965 * HAVE_TERMLIB is supported it overrides the environment
1966 * variable TERM.
1967 */
1968#ifdef FEAT_GUI
1969 if (term_is_gui((char_u *)argv[0]))
1970 gui.starting = TRUE; /* start GUI a bit later */
1971 else
1972#endif
1973 parmp->term = (char_u *)argv[0];
1974 break;
1975
1976 case 'u': /* "-u {vimrc}" vim inits file */
1977 parmp->use_vimrc = (char_u *)argv[0];
1978 break;
1979
1980 case 'U': /* "-U {gvimrc}" gvim inits file */
1981#ifdef FEAT_GUI
1982 use_gvimrc = (char_u *)argv[0];
1983#endif
1984 break;
1985
1986 case 'w': /* "-w {nr}" 'window' value */
1987 /* "-w {scriptout}" append to script file */
1988 if (vim_isdigit(*((char_u *)argv[0])))
1989 {
1990 argv_idx = 0;
1991 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1992 set_option_value((char_u *)"window", n, NULL, 0);
1993 argv_idx = -1;
1994 break;
1995 }
1996 /*FALLTHROUGH*/
1997 case 'W': /* "-W {scriptout}" overwrite script file */
1998 if (scriptout != NULL)
1999 goto scripterror;
2000 if ((scriptout = mch_fopen(argv[0],
2001 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
2002 {
2003 mch_errmsg(_("Cannot open for script output: \""));
2004 mch_errmsg(argv[0]);
2005 mch_errmsg("\"\n");
2006 mch_exit(2);
2007 }
2008 break;
2009
2010#ifdef FEAT_GUI_W32
2011 case 'P': /* "-P {parent title}" MDI parent */
2012 gui_mch_set_parent(argv[0]);
2013 break;
2014#endif
2015 }
2016 }
2017 }
2018
2019 /*
2020 * File name argument.
2021 */
2022 else
2023 {
2024 argv_idx = -1; /* skip to next argument */
2025
2026 /* Check for only one type of editing. */
2027 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2028 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2029 parmp->edit_type = EDIT_FILE;
2030
2031#ifdef MSWIN
2032 /* Remember if the argument was a full path before changing
2033 * slashes to backslashes. */
2034 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2035 parmp->full_path = TRUE;
2036#endif
2037
2038 /* Add the file to the global argument list. */
2039 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2040 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2041 mch_exit(2);
2042#ifdef FEAT_DIFF
2043 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2044 && !mch_isdir(alist_name(&GARGLIST[0])))
2045 {
2046 char_u *r;
2047
2048 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2049 if (r != NULL)
2050 {
2051 vim_free(p);
2052 p = r;
2053 }
2054 }
2055#endif
2056#if defined(__CYGWIN32__) && !defined(WIN32)
2057 /*
2058 * If vim is invoked by non-Cygwin tools, convert away any
2059 * DOS paths, so things like .swp files are created correctly.
2060 * Look for evidence of non-Cygwin paths before we bother.
2061 * This is only for when using the Unix files.
2062 */
2063 if (strpbrk(p, "\\:") != NULL)
2064 {
2065 char posix_path[PATH_MAX];
2066
2067 cygwin_conv_to_posix_path(p, posix_path);
2068 vim_free(p);
2069 p = vim_strsave(posix_path);
2070 if (p == NULL)
2071 mch_exit(2);
2072 }
2073#endif
Bram Moolenaarcc016f52005-12-10 20:23:46 +00002074
2075#ifdef USE_FNAME_CASE
2076 /* Make the case of the file name match the actual file. */
2077 fname_case(p, 0);
2078#endif
2079
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002080 alist_add(&global_alist, p,
2081#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
Bram Moolenaar231334e2005-07-25 20:46:57 +00002082 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002083#else
2084 2 /* add buffer number now and use curbuf */
2085#endif
2086 );
2087
2088#if defined(FEAT_MBYTE) && defined(WIN32)
2089 {
2090 extern void used_file_arg(char *, int, int);
2091
2092 /* Remember this argument has been added to the argument list.
2093 * Needed when 'encoding' is changed. */
2094 used_file_arg(argv[0], parmp->literal, parmp->full_path);
2095 }
2096#endif
2097 }
2098
2099 /*
2100 * If there are no more letters after the current "-", go to next
2101 * argument. argv_idx is set to -1 when the current argument is to be
2102 * skipped.
2103 */
2104 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2105 {
2106 --argc;
2107 ++argv;
2108 argv_idx = 1;
2109 }
2110 }
2111}
2112
2113/*
2114 * Print a warning if stdout is not a terminal.
2115 * When starting in Ex mode and commands come from a file, set Silent mode.
2116 */
2117 static void
2118check_tty(parmp)
2119 mparm_T *parmp;
2120{
2121 int input_isatty; /* is active input a terminal? */
2122
2123 input_isatty = mch_input_isatty();
2124 if (exmode_active)
2125 {
2126 if (!input_isatty)
2127 silent_mode = TRUE;
2128 }
2129 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2130#ifdef FEAT_GUI
2131 /* don't want the delay when started from the desktop */
2132 && !gui.starting
2133#endif
2134 )
2135 {
2136#ifdef NBDEBUG
2137 /*
2138 * This shouldn't be necessary. But if I run netbeans with the log
2139 * output coming to the console and XOpenDisplay fails, I get vim
2140 * trying to start with input/output to my console tty. This fills my
2141 * input buffer so fast I can't even kill the process in under 2
2142 * minutes (and it beeps continuosly the whole time :-)
2143 */
2144 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2145 {
2146 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2147 exit(1);
2148 }
2149#endif
2150 if (!parmp->stdout_isatty)
2151 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2152 if (!input_isatty)
2153 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2154 out_flush();
2155 if (scriptin[0] == NULL)
2156 ui_delay(2000L, TRUE);
2157 TIME_MSG("Warning delay");
2158 }
2159}
2160
2161/*
2162 * Read text from stdin.
2163 */
2164 static void
2165read_stdin()
2166{
2167 int i;
2168
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002169#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002170 /* When getting the ATTENTION prompt here, use a dialog */
2171 swap_exists_action = SEA_DIALOG;
2172#endif
2173 no_wait_return = TRUE;
2174 i = msg_didany;
2175 set_buflisted(TRUE);
2176 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2177 no_wait_return = FALSE;
2178 msg_didany = i;
2179 TIME_MSG("reading stdin");
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002180#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002181 check_swap_exists_action();
2182#endif
2183#if !(defined(AMIGA) || defined(MACOS))
2184 /*
2185 * Close stdin and dup it from stderr. Required for GPM to work
2186 * properly, and for running external commands.
2187 * Is there any other system that cannot do this?
2188 */
2189 close(0);
2190 dup(2);
2191#endif
2192}
2193
2194/*
2195 * Create the requested number of windows and edit buffers in them.
2196 * Also does recovery if "recoverymode" set.
2197 */
2198/*ARGSUSED*/
2199 static void
2200create_windows(parmp)
2201 mparm_T *parmp;
2202{
2203#ifdef FEAT_WINDOWS
2204 /*
2205 * Create the number of windows that was requested.
2206 */
2207 if (parmp->window_count == -1) /* was not set */
2208 parmp->window_count = 1;
2209 if (parmp->window_count == 0)
2210 parmp->window_count = GARGCOUNT;
2211 if (parmp->window_count > 1)
2212 {
2213 /* Don't change the windows if there was a command in .vimrc that
2214 * already split some windows */
2215 if (parmp->vert_windows == MAYBE)
2216 parmp->vert_windows = FALSE;
2217 if (firstwin->w_next == NULL)
2218 {
2219 parmp->window_count = make_windows(parmp->window_count,
2220 parmp->vert_windows);
2221 TIME_MSG("making windows");
2222 }
2223 else
2224 parmp->window_count = win_count();
2225 }
2226 else
2227 parmp->window_count = 1;
2228#endif
2229
2230 if (recoverymode) /* do recover */
2231 {
2232 msg_scroll = TRUE; /* scroll message up */
2233 ml_recover();
2234 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2235 getout(1);
2236 do_modelines(FALSE); /* do modelines */
2237 }
2238 else
2239 {
2240 /*
2241 * Open a buffer for windows that don't have one yet.
2242 * Commands in the .vimrc might have loaded a file or split the window.
2243 * Watch out for autocommands that delete a window.
2244 */
2245#ifdef FEAT_AUTOCMD
2246 /*
2247 * Don't execute Win/Buf Enter/Leave autocommands here
2248 */
2249 ++autocmd_no_enter;
2250 ++autocmd_no_leave;
2251#endif
2252#ifdef FEAT_WINDOWS
2253 for (curwin = firstwin; curwin != NULL; curwin = W_NEXT(curwin))
2254#endif
2255 {
2256 curbuf = curwin->w_buffer;
2257 if (curbuf->b_ml.ml_mfp == NULL)
2258 {
2259#ifdef FEAT_FOLDING
2260 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2261 if (p_fdls >= 0)
2262 curwin->w_p_fdl = p_fdls;
2263#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002264#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002265 /* When getting the ATTENTION prompt here, use a dialog */
2266 swap_exists_action = SEA_DIALOG;
2267#endif
2268 set_buflisted(TRUE);
2269 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2270
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002271#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002272 check_swap_exists_action();
2273#endif
2274#ifdef FEAT_AUTOCMD
2275 curwin = firstwin; /* start again */
2276#endif
2277 }
2278#ifdef FEAT_WINDOWS
2279 ui_breakcheck();
2280 if (got_int)
2281 {
2282 (void)vgetc(); /* only break the file loading, not the rest */
2283 break;
2284 }
2285#endif
2286 }
2287#ifdef FEAT_AUTOCMD
2288 --autocmd_no_enter;
2289 --autocmd_no_leave;
2290#endif
2291#ifdef FEAT_WINDOWS
2292 curwin = firstwin;
2293 curbuf = curwin->w_buffer;
2294#endif
2295 }
2296}
2297
2298#ifdef FEAT_WINDOWS
2299 /*
2300 * If opened more than one window, start editing files in the other
2301 * windows. make_windows() has already opened the windows.
2302 */
2303 static void
2304edit_buffers(parmp)
2305 mparm_T *parmp;
2306{
2307 int arg_idx; /* index in argument list */
2308 int i;
2309
2310# ifdef FEAT_AUTOCMD
2311 /*
2312 * Don't execute Win/Buf Enter/Leave autocommands here
2313 */
2314 ++autocmd_no_enter;
2315 ++autocmd_no_leave;
2316# endif
2317 arg_idx = 1;
2318 for (i = 1; i < parmp->window_count; ++i)
2319 {
2320 if (curwin->w_next == NULL) /* just checking */
2321 break;
2322 win_enter(curwin->w_next, FALSE);
2323
2324 /* Only open the file if there is no file in this window yet (that can
2325 * happen when .vimrc contains ":sall") */
2326 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2327 {
2328 curwin->w_arg_idx = arg_idx;
2329 /* edit file from arg list, if there is one */
2330 (void)do_ecmd(0, arg_idx < GARGCOUNT
2331 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2332 NULL, NULL, ECMD_LASTL, ECMD_HIDE);
2333 if (arg_idx == GARGCOUNT - 1)
2334 arg_had_last = TRUE;
2335 ++arg_idx;
2336 }
2337 ui_breakcheck();
2338 if (got_int)
2339 {
2340 (void)vgetc(); /* only break the file loading, not the rest */
2341 break;
2342 }
2343 }
2344# ifdef FEAT_AUTOCMD
2345 --autocmd_no_enter;
2346# endif
2347 win_enter(firstwin, FALSE); /* back to first window */
2348# ifdef FEAT_AUTOCMD
2349 --autocmd_no_leave;
2350# endif
2351 TIME_MSG("editing files in windows");
2352 if (parmp->window_count > 1)
2353 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2354}
2355#endif /* FEAT_WINDOWS */
2356
2357/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002358 * Execute the commands from --cmd arguments "cmds[cnt]".
2359 */
2360 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002361exe_pre_commands(parmp)
2362 mparm_T *parmp;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002363{
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002364 char_u **cmds = parmp->pre_commands;
2365 int cnt = parmp->n_pre_commands;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002366 int i;
2367
2368 if (cnt > 0)
2369 {
2370 curwin->w_cursor.lnum = 0; /* just in case.. */
2371 sourcing_name = (char_u *)_("pre-vimrc command line");
2372# ifdef FEAT_EVAL
2373 current_SID = SID_CMDARG;
2374# endif
2375 for (i = 0; i < cnt; ++i)
2376 do_cmdline_cmd(cmds[i]);
2377 sourcing_name = NULL;
2378# ifdef FEAT_EVAL
2379 current_SID = 0;
2380# endif
2381 TIME_MSG("--cmd commands");
2382 }
2383}
2384
2385/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002386 * Execute "+", "-c" and "-S" arguments.
2387 */
2388 static void
2389exe_commands(parmp)
2390 mparm_T *parmp;
2391{
2392 int i;
2393
2394 /*
2395 * We start commands on line 0, make "vim +/pat file" match a
2396 * pattern on line 1. But don't move the cursor when an autocommand
2397 * with g`" was used.
2398 */
2399 msg_scroll = TRUE;
2400 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2401 curwin->w_cursor.lnum = 0;
2402 sourcing_name = (char_u *)"command line";
2403#ifdef FEAT_EVAL
2404 current_SID = SID_CARG;
2405#endif
2406 for (i = 0; i < parmp->n_commands; ++i)
2407 {
2408 do_cmdline_cmd(parmp->commands[i]);
2409 if (parmp->cmds_tofree[i])
2410 vim_free(parmp->commands[i]);
2411 }
2412 sourcing_name = NULL;
2413#ifdef FEAT_EVAL
2414 current_SID = 0;
2415#endif
2416 if (curwin->w_cursor.lnum == 0)
2417 curwin->w_cursor.lnum = 1;
2418
2419 if (!exmode_active)
2420 msg_scroll = FALSE;
2421
2422#ifdef FEAT_QUICKFIX
2423 /* When started with "-q errorfile" jump to first error again. */
2424 if (parmp->edit_type == EDIT_QF)
2425 qf_jump(0, 0, FALSE);
2426#endif
2427 TIME_MSG("executing command arguments");
2428}
2429
2430/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002431 * Source startup scripts.
2432 */
2433 static void
2434source_startup_scripts(parmp)
2435 mparm_T *parmp;
2436{
2437 int i;
2438
2439 /*
2440 * For "evim" source evim.vim first of all, so that the user can overrule
2441 * any things he doesn't like.
2442 */
2443 if (parmp->evim_mode)
2444 {
2445 (void)do_source((char_u *)EVIM_FILE, FALSE, FALSE);
2446 TIME_MSG("source evim file");
2447 }
2448
2449 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002450 * If -u argument given, use only the initializations from that file and
Bram Moolenaar58d98232005-07-23 22:25:46 +00002451 * nothing else.
2452 */
2453 if (parmp->use_vimrc != NULL)
2454 {
Bram Moolenaar231334e2005-07-25 20:46:57 +00002455 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2456 || STRCMP(parmp->use_vimrc, "NORC") == 0)
Bram Moolenaar58d98232005-07-23 22:25:46 +00002457 {
2458#ifdef FEAT_GUI
2459 if (use_gvimrc == NULL) /* don't load gvimrc either */
2460 use_gvimrc = parmp->use_vimrc;
2461#endif
2462 if (parmp->use_vimrc[2] == 'N')
2463 p_lpl = FALSE; /* don't load plugins either */
2464 }
2465 else
2466 {
2467 if (do_source(parmp->use_vimrc, FALSE, FALSE) != OK)
2468 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2469 }
2470 }
2471 else if (!silent_mode)
2472 {
2473#ifdef AMIGA
2474 struct Process *proc = (struct Process *)FindTask(0L);
2475 APTR save_winptr = proc->pr_WindowPtr;
2476
2477 /* Avoid a requester here for a volume that doesn't exist. */
2478 proc->pr_WindowPtr = (APTR)-1L;
2479#endif
2480
2481 /*
2482 * Get system wide defaults, if the file name is defined.
2483 */
2484#ifdef SYS_VIMRC_FILE
2485 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, FALSE);
2486#endif
2487
2488 /*
2489 * Try to read initialization commands from the following places:
2490 * - environment variable VIMINIT
2491 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2492 * - second user vimrc file ($VIM/.vimrc for Dos)
2493 * - environment variable EXINIT
2494 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2495 * - second user exrc file ($VIM/.exrc for Dos)
2496 * The first that exists is used, the rest is ignored.
2497 */
2498 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2499 {
2500 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, TRUE) == FAIL
2501#ifdef USR_VIMRC_FILE2
2502 && do_source((char_u *)USR_VIMRC_FILE2, TRUE, TRUE) == FAIL
2503#endif
2504#ifdef USR_VIMRC_FILE3
2505 && do_source((char_u *)USR_VIMRC_FILE3, TRUE, TRUE) == FAIL
2506#endif
2507 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2508 && do_source((char_u *)USR_EXRC_FILE, FALSE, FALSE) == FAIL)
2509 {
2510#ifdef USR_EXRC_FILE2
2511 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, FALSE);
2512#endif
2513 }
2514 }
2515
2516 /*
2517 * Read initialization commands from ".vimrc" or ".exrc" in current
2518 * directory. This is only done if the 'exrc' option is set.
2519 * Because of security reasons we disallow shell and write commands
2520 * now, except for unix if the file is owned by the user or 'secure'
2521 * option has been reset in environment of global ".exrc" or ".vimrc".
2522 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2523 * SYS_VIMRC_FILE.
2524 */
2525 if (p_exrc)
2526 {
2527#if defined(UNIX) || defined(VMS)
2528 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2529 if (!file_owned(VIMRC_FILE))
2530#endif
2531 secure = p_secure;
2532
2533 i = FAIL;
2534 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2535 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2536#ifdef USR_VIMRC_FILE2
2537 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2538 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2539#endif
2540#ifdef USR_VIMRC_FILE3
2541 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2542 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2543#endif
2544#ifdef SYS_VIMRC_FILE
2545 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2546 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2547#endif
2548 )
2549 i = do_source((char_u *)VIMRC_FILE, TRUE, TRUE);
2550
2551 if (i == FAIL)
2552 {
2553#if defined(UNIX) || defined(VMS)
2554 /* if ".exrc" is not owned by user set 'secure' mode */
2555 if (!file_owned(EXRC_FILE))
2556 secure = p_secure;
2557 else
2558 secure = 0;
2559#endif
2560 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2561 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2562#ifdef USR_EXRC_FILE2
2563 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2564 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2565#endif
2566 )
2567 (void)do_source((char_u *)EXRC_FILE, FALSE, FALSE);
2568 }
2569 }
2570 if (secure == 2)
2571 need_wait_return = TRUE;
2572 secure = 0;
2573#ifdef AMIGA
2574 proc->pr_WindowPtr = save_winptr;
2575#endif
2576 }
2577 TIME_MSG("sourcing vimrc file(s)");
2578}
2579
2580/*
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002581 * Setup to start using the GUI. Exit with an error when not available.
2582 */
2583 static void
2584main_start_gui()
2585{
2586#ifdef FEAT_GUI
2587 gui.starting = TRUE; /* start GUI a bit later */
2588#else
2589 mch_errmsg(_(e_nogvim));
2590 mch_errmsg("\n");
2591 mch_exit(2);
2592#endif
2593}
2594
2595/*
2596 * Get an evironment variable, and execute it as Ex commands.
2597 * Returns FAIL if the environment variable was not executed, OK otherwise.
2598 */
2599 int
2600process_env(env, is_viminit)
2601 char_u *env;
2602 int is_viminit; /* when TRUE, called for VIMINIT */
2603{
2604 char_u *initstr;
2605 char_u *save_sourcing_name;
2606 linenr_T save_sourcing_lnum;
2607#ifdef FEAT_EVAL
2608 scid_T save_sid;
2609#endif
2610
2611 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2612 {
2613 if (is_viminit)
2614 vimrc_found();
2615 save_sourcing_name = sourcing_name;
2616 save_sourcing_lnum = sourcing_lnum;
2617 sourcing_name = env;
2618 sourcing_lnum = 0;
2619#ifdef FEAT_EVAL
2620 save_sid = current_SID;
2621 current_SID = SID_ENV;
2622#endif
2623 do_cmdline_cmd(initstr);
2624 sourcing_name = save_sourcing_name;
2625 sourcing_lnum = save_sourcing_lnum;
2626#ifdef FEAT_EVAL
2627 current_SID = save_sid;;
2628#endif
2629 return OK;
2630 }
2631 return FAIL;
2632}
2633
2634#if defined(UNIX) || defined(VMS)
2635/*
2636 * Return TRUE if we are certain the user owns the file "fname".
2637 * Used for ".vimrc" and ".exrc".
2638 * Use both stat() and lstat() for extra security.
2639 */
2640 static int
2641file_owned(fname)
2642 char *fname;
2643{
2644 struct stat s;
2645# ifdef UNIX
2646 uid_t uid = getuid();
2647# else /* VMS */
2648 uid_t uid = ((getgid() << 16) | getuid());
2649# endif
2650
2651 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2652# ifdef HAVE_LSTAT
2653 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2654# endif
2655 );
2656}
2657#endif
2658
2659/*
2660 * Give an error message main_errors["n"] and exit.
2661 */
2662 static void
2663mainerr(n, str)
2664 int n; /* one of the ME_ defines */
2665 char_u *str; /* extra argument or NULL */
2666{
2667#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2668 reset_signals(); /* kill us with CTRL-C here, if you like */
2669#endif
2670
2671 mch_errmsg(longVersion);
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002672 mch_errmsg("\n");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002673 mch_errmsg(_(main_errors[n]));
2674 if (str != NULL)
2675 {
2676 mch_errmsg(": \"");
2677 mch_errmsg((char *)str);
2678 mch_errmsg("\"");
2679 }
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002680 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002681
2682 mch_exit(1);
2683}
2684
2685 void
2686mainerr_arg_missing(str)
2687 char_u *str;
2688{
2689 mainerr(ME_ARG_MISSING, str);
2690}
2691
2692/*
2693 * print a message with three spaces prepended and '\n' appended.
2694 */
2695 static void
2696main_msg(s)
2697 char *s;
2698{
2699 mch_msg(" ");
2700 mch_msg(s);
2701 mch_msg("\n");
2702}
2703
2704/*
2705 * Print messages for "vim -h" or "vim --help" and exit.
2706 */
2707 static void
2708usage()
2709{
2710 int i;
2711 static char *(use[]) =
2712 {
2713 N_("[file ..] edit specified file(s)"),
2714 N_("- read text from stdin"),
2715 N_("-t tag edit file where tag is defined"),
2716#ifdef FEAT_QUICKFIX
2717 N_("-q [errorfile] edit file with first error")
2718#endif
2719 };
2720
2721#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2722 reset_signals(); /* kill us with CTRL-C here, if you like */
2723#endif
2724
2725 mch_msg(longVersion);
2726 mch_msg(_("\n\nusage:"));
2727 for (i = 0; ; ++i)
2728 {
2729 mch_msg(_(" vim [arguments] "));
2730 mch_msg(_(use[i]));
2731 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
2732 break;
2733 mch_msg(_("\n or:"));
2734 }
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002735#ifdef VMS
2736 mch_msg(_("where case is ignored prepend / to make flag upper case"));
2737#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002738
2739 mch_msg(_("\n\nArguments:\n"));
2740 main_msg(_("--\t\t\tOnly file names after this"));
2741#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2742 main_msg(_("--literal\t\tDon't expand wildcards"));
2743#endif
2744#ifdef FEAT_OLE
2745 main_msg(_("-register\t\tRegister this gvim for OLE"));
2746 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
2747#endif
2748#ifdef FEAT_GUI
2749 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
2750 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
2751#endif
2752 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
2753 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
2754 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
2755#ifdef FEAT_DIFF
2756 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
2757#endif
2758 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
2759 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
2760 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
2761 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
2762 main_msg(_("-M\t\t\tModifications in text not allowed"));
2763 main_msg(_("-b\t\t\tBinary mode"));
2764#ifdef FEAT_LISP
2765 main_msg(_("-l\t\t\tLisp mode"));
2766#endif
2767 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
2768 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
2769 main_msg(_("-V[N]\t\tVerbose level"));
2770 main_msg(_("-D\t\t\tDebugging mode"));
2771 main_msg(_("-n\t\t\tNo swap file, use memory only"));
2772 main_msg(_("-r\t\t\tList swap files and exit"));
2773 main_msg(_("-r (with file name)\tRecover crashed session"));
2774 main_msg(_("-L\t\t\tSame as -r"));
2775#ifdef AMIGA
2776 main_msg(_("-f\t\t\tDon't use newcli to open window"));
2777 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
2778#endif
2779#ifdef FEAT_ARABIC
2780 main_msg(_("-A\t\t\tstart in Arabic mode"));
2781#endif
2782#ifdef FEAT_RIGHTLEFT
2783 main_msg(_("-H\t\t\tStart in Hebrew mode"));
2784#endif
2785#ifdef FEAT_FKMAP
2786 main_msg(_("-F\t\t\tStart in Farsi mode"));
2787#endif
2788 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
2789 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
2790#ifdef FEAT_GUI
2791 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
2792#endif
2793 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
2794 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
2795 main_msg(_("-O[N]\t\tLike -o but split vertically"));
2796 main_msg(_("+\t\t\tStart at end of file"));
2797 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002798 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002799 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
2800 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
2801 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
2802 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
2803 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
2804#ifdef FEAT_CRYPT
2805 main_msg(_("-x\t\t\tEdit encrypted files"));
2806#endif
2807#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
2808# if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
2809 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
2810# endif
2811 main_msg(_("-X\t\t\tDo not connect to X server"));
2812#endif
2813#ifdef FEAT_CLIENTSERVER
2814 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
2815 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
2816 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
2817 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
2818 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
2819 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
2820 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
2821 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
2822#endif
2823#ifdef FEAT_VIMINFO
2824 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
2825#endif
2826 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
2827 main_msg(_("--version\t\tPrint version information and exit"));
2828
2829#ifdef FEAT_GUI_X11
2830# ifdef FEAT_GUI_MOTIF
2831 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
2832# else
2833# ifdef FEAT_GUI_ATHENA
2834# ifdef FEAT_GUI_NEXTAW
2835 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
2836# else
2837 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
2838# endif
2839# endif
2840# endif
2841 main_msg(_("-display <display>\tRun vim on <display>"));
2842 main_msg(_("-iconic\t\tStart vim iconified"));
2843# if 0
2844 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
2845 mch_msg(_("\t\t\t (Unimplemented)\n"));
2846# endif
2847 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
2848 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
2849 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2850 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
2851 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
2852 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2853 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
2854 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
2855# ifdef FEAT_GUI_ATHENA
2856 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
2857# endif
2858 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2859 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
2860 main_msg(_("-xrm <resource>\tSet the specified resource"));
2861#endif /* FEAT_GUI_X11 */
2862#if defined(FEAT_GUI) && defined(RISCOS)
2863 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
2864 main_msg(_("--columns <number>\tInitial width of window in columns"));
2865 main_msg(_("--rows <number>\tInitial height of window in rows"));
2866#endif
2867#ifdef FEAT_GUI_GTK
2868 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
2869 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2870 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2871 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2872 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
2873# ifdef HAVE_GTK2
2874 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
2875# endif
2876 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
2877#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002878#ifdef FEAT_GUI_W32
2879 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
2880#endif
2881
2882#ifdef FEAT_GUI_GNOME
2883 /* Gnome gives extra messages for --help if we continue, but not for -h. */
2884 if (gui.starting)
2885 mch_msg("\n");
2886 else
2887#endif
2888 mch_exit(0);
2889}
2890
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002891#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002892/*
2893 * Check the result of the ATTENTION dialog:
2894 * When "Quit" selected, exit Vim.
2895 * When "Recover" selected, recover the file.
2896 */
2897 static void
2898check_swap_exists_action()
2899{
2900 if (swap_exists_action == SEA_QUIT)
2901 getout(1);
2902 handle_swap_exists(NULL);
2903}
2904#endif
2905
2906#if defined(STARTUPTIME) || defined(PROTO)
2907static void time_diff __ARGS((struct timeval *then, struct timeval *now));
2908
2909static struct timeval prev_timeval;
2910
2911/*
2912 * Save the previous time before doing something that could nest.
2913 * set "*tv_rel" to the time elapsed so far.
2914 */
2915 void
2916time_push(tv_rel, tv_start)
2917 void *tv_rel, *tv_start;
2918{
2919 *((struct timeval *)tv_rel) = prev_timeval;
2920 gettimeofday(&prev_timeval, NULL);
2921 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
2922 - ((struct timeval *)tv_rel)->tv_usec;
2923 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
2924 - ((struct timeval *)tv_rel)->tv_sec;
2925 if (((struct timeval *)tv_rel)->tv_usec < 0)
2926 {
2927 ((struct timeval *)tv_rel)->tv_usec += 1000000;
2928 --((struct timeval *)tv_rel)->tv_sec;
2929 }
2930 *(struct timeval *)tv_start = prev_timeval;
2931}
2932
2933/*
2934 * Compute the previous time after doing something that could nest.
2935 * Subtract "*tp" from prev_timeval;
2936 * Note: The arguments are (void *) to avoid trouble with systems that don't
2937 * have struct timeval.
2938 */
2939 void
2940time_pop(tp)
2941 void *tp; /* actually (struct timeval *) */
2942{
2943 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
2944 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
2945 if (prev_timeval.tv_usec < 0)
2946 {
2947 prev_timeval.tv_usec += 1000000;
2948 --prev_timeval.tv_sec;
2949 }
2950}
2951
2952 static void
2953time_diff(then, now)
2954 struct timeval *then;
2955 struct timeval *now;
2956{
2957 long usec;
2958 long msec;
2959
2960 usec = now->tv_usec - then->tv_usec;
2961 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
2962 usec = usec % 1000L;
2963 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
2964}
2965
2966 void
2967time_msg(msg, tv_start)
2968 char *msg;
2969 void *tv_start; /* only for do_source: start time; actually
2970 (struct timeval *) */
2971{
2972 static struct timeval start;
2973 struct timeval now;
2974
2975 if (time_fd != NULL)
2976 {
2977 if (strstr(msg, "STARTING") != NULL)
2978 {
2979 gettimeofday(&start, NULL);
2980 prev_timeval = start;
2981 fprintf(time_fd, "\n\ntimes in msec\n");
2982 fprintf(time_fd, " clock self+sourced self: sourced script\n");
2983 fprintf(time_fd, " clock elapsed: other lines\n\n");
2984 }
2985 gettimeofday(&now, NULL);
2986 time_diff(&start, &now);
2987 if (((struct timeval *)tv_start) != NULL)
2988 {
2989 fprintf(time_fd, " ");
2990 time_diff(((struct timeval *)tv_start), &now);
2991 }
2992 fprintf(time_fd, " ");
2993 time_diff(&prev_timeval, &now);
2994 prev_timeval = now;
2995 fprintf(time_fd, ": %s\n", msg);
2996 }
2997}
2998
2999# ifdef WIN3264
3000/*
3001 * Windows doesn't have gettimeofday(), although it does have struct timeval.
3002 */
3003 int
3004gettimeofday(struct timeval *tv, char *dummy)
3005{
3006 long t = clock();
3007 tv->tv_sec = t / CLOCKS_PER_SEC;
3008 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
3009 return 0;
3010}
3011# endif
3012
3013#endif
3014
3015#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3016
3017/*
3018 * Common code for the X command server and the Win32 command server.
3019 */
3020
3021static char_u *build_drop_cmd __ARGS((int filec, char **filev, int sendReply));
3022
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003023/*
3024 * Do the client-server stuff, unless "--servername ''" was used.
3025 */
3026 static void
3027exec_on_server(parmp)
3028 mparm_T *parmp;
3029{
3030 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3031 {
3032# ifdef WIN32
3033 /* Initialise the client/server messaging infrastructure. */
3034 serverInitMessaging();
3035# endif
3036
3037 /*
3038 * When a command server argument was found, execute it. This may
3039 * exit Vim when it was successful. Otherwise it's executed further
3040 * on. Remember the encoding used here in "serverStrEnc".
3041 */
3042 if (parmp->serverArg)
3043 {
3044 cmdsrv_main(&parmp->argc, parmp->argv,
3045 parmp->serverName_arg, &parmp->serverStr);
3046# ifdef FEAT_MBYTE
3047 parmp->serverStrEnc = vim_strsave(p_enc);
3048# endif
3049 }
3050
3051 /* If we're still running, get the name to register ourselves.
3052 * On Win32 can register right now, for X11 need to setup the
3053 * clipboard first, it's further down. */
3054 parmp->servername = serverMakeName(parmp->serverName_arg,
3055 parmp->argv[0]);
3056# ifdef WIN32
3057 if (parmp->servername != NULL)
3058 {
3059 serverSetName(parmp->servername);
3060 vim_free(parmp->servername);
3061 }
3062# endif
3063 }
3064}
3065
3066/*
3067 * Prepare for running as a Vim server.
3068 */
3069 static void
3070prepare_server(parmp)
3071 mparm_T *parmp;
3072{
3073# if defined(FEAT_X11)
3074 /*
3075 * Register for remote command execution with :serversend and --remote
3076 * unless there was a -X or a --servername '' on the command line.
3077 * Only register nongui-vim's with an explicit --servername argument.
3078 */
3079 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3080# ifdef FEAT_GUI
3081 gui.in_use ||
3082# endif
3083 parmp->serverName_arg != NULL))
3084 {
3085 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3086 vim_free(parmp->servername);
3087 TIME_MSG("register server name");
3088 }
3089 else
3090 serverDelayedStartName = parmp->servername;
3091# endif
3092
3093 /*
3094 * Execute command ourselves if we're here because the send failed (or
3095 * else we would have exited above).
3096 */
3097 if (parmp->serverStr != NULL)
3098 {
3099 char_u *p;
3100
3101 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3102 parmp->serverStr, &p));
3103 vim_free(p);
3104 }
3105}
3106
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003107 static void
3108cmdsrv_main(argc, argv, serverName_arg, serverStr)
3109 int *argc;
3110 char **argv;
3111 char_u *serverName_arg;
3112 char_u **serverStr;
3113{
3114 char_u *res;
3115 int i;
3116 char_u *sname;
3117 int ret;
3118 int didone = FALSE;
3119 int exiterr = 0;
3120 char **newArgV = argv + 1;
3121 int newArgC = 1,
3122 Argc = *argc;
3123 int argtype;
3124#define ARGTYPE_OTHER 0
3125#define ARGTYPE_EDIT 1
3126#define ARGTYPE_EDIT_WAIT 2
3127#define ARGTYPE_SEND 3
3128 int silent = FALSE;
3129# ifndef FEAT_X11
3130 HWND srv;
3131# else
3132 Window srv;
3133
3134 setup_term_clip();
3135# endif
3136
3137 sname = serverMakeName(serverName_arg, argv[0]);
3138 if (sname == NULL)
3139 return;
3140
3141 /*
3142 * Execute the command server related arguments and remove them
3143 * from the argc/argv array; We may have to return into main()
3144 */
3145 for (i = 1; i < Argc; i++)
3146 {
3147 res = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003148 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003149 {
3150 for (; i < *argc; i++)
3151 {
3152 *newArgV++ = argv[i];
3153 newArgC++;
3154 }
3155 break;
3156 }
3157
3158 if (STRICMP(argv[i], "--remote") == 0)
3159 argtype = ARGTYPE_EDIT;
3160 else if (STRICMP(argv[i], "--remote-silent") == 0)
3161 {
3162 argtype = ARGTYPE_EDIT;
3163 silent = TRUE;
3164 }
3165 else if (STRICMP(argv[i], "--remote-wait") == 0)
3166 argtype = ARGTYPE_EDIT_WAIT;
3167 else if (STRICMP(argv[i], "--remote-wait-silent") == 0)
3168 {
3169 argtype = ARGTYPE_EDIT_WAIT;
3170 silent = TRUE;
3171 }
3172 else if (STRICMP(argv[i], "--remote-send") == 0)
3173 argtype = ARGTYPE_SEND;
3174 else
3175 argtype = ARGTYPE_OTHER;
3176 if (argtype != ARGTYPE_OTHER)
3177 {
3178 if (i == *argc - 1)
3179 mainerr_arg_missing((char_u *)argv[i]);
3180 if (argtype == ARGTYPE_SEND)
3181 {
3182 *serverStr = (char_u *)argv[i + 1];
3183 i++;
3184 }
3185 else
3186 {
3187 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3188 argtype == ARGTYPE_EDIT_WAIT);
3189 if (*serverStr == NULL)
3190 {
3191 /* Probably out of memory, exit. */
3192 didone = TRUE;
3193 exiterr = 1;
3194 break;
3195 }
3196 Argc = i;
3197 }
3198# ifdef FEAT_X11
3199 if (xterm_dpy == NULL)
3200 {
3201 mch_errmsg(_("No display"));
3202 ret = -1;
3203 }
3204 else
3205 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3206 NULL, &srv, 0, 0, silent);
3207# else
3208 /* Win32 always works? */
3209 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3210# endif
3211 if (ret < 0)
3212 {
3213 if (argtype == ARGTYPE_SEND)
3214 {
3215 /* Failed to send, abort. */
3216 mch_errmsg(_(": Send failed.\n"));
3217 didone = TRUE;
3218 exiterr = 1;
3219 }
3220 else if (!silent)
3221 /* Let vim start normally. */
3222 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3223 break;
3224 }
3225
3226# ifdef FEAT_GUI_W32
3227 /* Guess that when the server name starts with "g" it's a GUI
3228 * server, which we can bring to the foreground here.
3229 * Foreground() in the server doesn't work very well. */
3230 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3231 SetForegroundWindow(srv);
3232# endif
3233
3234 /*
3235 * For --remote-wait: Wait until the server did edit each
3236 * file. Also detect that the server no longer runs.
3237 */
3238 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3239 {
3240 int numFiles = *argc - i - 1;
3241 int j;
3242 char_u *done = alloc(numFiles);
3243 char_u *p;
3244# ifdef FEAT_GUI_W32
3245 NOTIFYICONDATA ni;
3246 int count = 0;
3247 extern HWND message_window;
3248# endif
3249
3250 if (numFiles > 0 && argv[i + 1][0] == '+')
3251 /* Skip "+cmd" argument, don't wait for it to be edited. */
3252 --numFiles;
3253
3254# ifdef FEAT_GUI_W32
3255 ni.cbSize = sizeof(ni);
3256 ni.hWnd = message_window;
3257 ni.uID = 0;
3258 ni.uFlags = NIF_ICON|NIF_TIP;
3259 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3260 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3261 Shell_NotifyIcon(NIM_ADD, &ni);
3262# endif
3263
3264 /* Wait for all files to unload in remote */
3265 memset(done, 0, numFiles);
3266 while (memchr(done, 0, numFiles) != NULL)
3267 {
3268# ifdef WIN32
3269 p = serverGetReply(srv, NULL, TRUE, TRUE);
3270 if (p == NULL)
3271 break;
3272# else
3273 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3274 break;
3275# endif
3276 j = atoi((char *)p);
3277 if (j >= 0 && j < numFiles)
3278 {
3279# ifdef FEAT_GUI_W32
3280 ++count;
3281 sprintf(ni.szTip, _("%d of %d edited"),
3282 count, numFiles);
3283 Shell_NotifyIcon(NIM_MODIFY, &ni);
3284# endif
3285 done[j] = 1;
3286 }
3287 }
3288# ifdef FEAT_GUI_W32
3289 Shell_NotifyIcon(NIM_DELETE, &ni);
3290# endif
3291 }
3292 }
3293 else if (STRICMP(argv[i], "--remote-expr") == 0)
3294 {
3295 if (i == *argc - 1)
3296 mainerr_arg_missing((char_u *)argv[i]);
3297# ifdef WIN32
3298 /* Win32 always works? */
3299 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3300 &res, NULL, 1, FALSE) < 0)
3301# else
3302 if (xterm_dpy == NULL)
3303 mch_errmsg(_("No display: Send expression failed.\n"));
3304 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3305 &res, NULL, 1, 1, FALSE) < 0)
3306# endif
3307 {
3308 if (res != NULL && *res != NUL)
3309 {
3310 /* Output error from remote */
3311 mch_errmsg((char *)res);
3312 vim_free(res);
3313 res = NULL;
3314 }
3315 mch_errmsg(_(": Send expression failed.\n"));
3316 }
3317 }
3318 else if (STRICMP(argv[i], "--serverlist") == 0)
3319 {
3320# ifdef WIN32
3321 /* Win32 always works? */
3322 res = serverGetVimNames();
3323# else
3324 if (xterm_dpy != NULL)
3325 res = serverGetVimNames(xterm_dpy);
3326# endif
3327 if (called_emsg)
3328 mch_errmsg("\n");
3329 }
3330 else if (STRICMP(argv[i], "--servername") == 0)
3331 {
3332 /* Alredy processed. Take it out of the command line */
3333 i++;
3334 continue;
3335 }
3336 else
3337 {
3338 *newArgV++ = argv[i];
3339 newArgC++;
3340 continue;
3341 }
3342 didone = TRUE;
3343 if (res != NULL && *res != NUL)
3344 {
3345 mch_msg((char *)res);
3346 if (res[STRLEN(res) - 1] != '\n')
3347 mch_msg("\n");
3348 }
3349 vim_free(res);
3350 }
3351
3352 if (didone)
3353 {
3354 display_errors(); /* display any collected messages */
3355 exit(exiterr); /* Mission accomplished - get out */
3356 }
3357
3358 /* Return back into main() */
3359 *argc = newArgC;
3360 vim_free(sname);
3361}
3362
3363/*
3364 * Build a ":drop" command to send to a Vim server.
3365 */
3366 static char_u *
3367build_drop_cmd(filec, filev, sendReply)
3368 int filec;
3369 char **filev;
3370 int sendReply;
3371{
3372 garray_T ga;
3373 int i;
3374 char_u *inicmd = NULL;
3375 char_u *p;
3376 char_u cwd[MAXPATHL];
3377
3378 if (filec > 0 && filev[0][0] == '+')
3379 {
3380 inicmd = (char_u *)filev[0] + 1;
3381 filev++;
3382 filec--;
3383 }
3384 /* Check if we have at least one argument. */
3385 if (filec <= 0)
3386 mainerr_arg_missing((char_u *)filev[-1]);
3387 if (mch_dirname(cwd, MAXPATHL) != OK)
3388 return NULL;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003389 if ((p = vim_strsave_escaped_ext(cwd, PATH_ESC_CHARS, '\\', TRUE)) == NULL)
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003390 return NULL;
3391 ga_init2(&ga, 1, 100);
3392 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3393 ga_concat(&ga, p);
3394 /* Call inputsave() so that a prompt for an encryption key works. */
3395 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|drop");
3396 vim_free(p);
3397 for (i = 0; i < filec; i++)
3398 {
3399 /* On Unix the shell has already expanded the wildcards, don't want to
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003400 * do it again in the Vim server. On MS-Windows only escape
3401 * non-wildcard characters. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003402 p = vim_strsave_escaped((char_u *)filev[i],
3403#ifdef UNIX
3404 PATH_ESC_CHARS
3405#else
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003406 (char_u *)" \t%#"
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003407#endif
3408 );
3409 if (p == NULL)
3410 {
3411 vim_free(ga.ga_data);
3412 return NULL;
3413 }
3414 ga_concat(&ga, (char_u *)" ");
3415 ga_concat(&ga, p);
3416 vim_free(p);
3417 }
3418 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3419 * CTRL-\ CTRL-N again. */
3420 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3421 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3422 if (sendReply)
3423 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3424 ga_concat(&ga, (char_u *)"<CR>:");
3425 if (inicmd != NULL)
3426 {
3427 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3428 * the following commands to be inserted as text. Use a "|",
3429 * hopefully "inicmd" does allow this... */
3430 ga_concat(&ga, inicmd);
3431 ga_concat(&ga, (char_u *)"|");
3432 }
3433 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3434 * clear command line. */
Bram Moolenaar567e4de2004-12-31 21:01:02 +00003435 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003436 ga_append(&ga, NUL);
3437 return ga.ga_data;
3438}
3439
3440/*
3441 * Replace termcodes such as <CR> and insert as key presses if there is room.
3442 */
3443 void
3444server_to_input_buf(str)
3445 char_u *str;
3446{
3447 char_u *ptr = NULL;
3448 char_u *cpo_save = p_cpo;
3449
3450 /* Set 'cpoptions' the way we want it.
3451 * B set - backslashes are *not* treated specially
3452 * k set - keycodes are *not* reverse-engineered
3453 * < unset - <Key> sequences *are* interpreted
3454 * The last parameter of replace_termcodes() is TRUE so that the <lt>
3455 * sequence is recognised - needed for a real backslash.
3456 */
3457 p_cpo = (char_u *)"Bk";
3458 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE);
3459 p_cpo = cpo_save;
3460
3461 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3462 {
3463 /*
3464 * Add the string to the input stream.
3465 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3466 *
3467 * First clear typed characters from the typeahead buffer, there could
3468 * be half a mapping there. Then append to the existing string, so
3469 * that multiple commands from a client are concatenated.
3470 */
3471 if (typebuf.tb_maplen < typebuf.tb_len)
3472 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3473 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3474
3475 /* Let input_available() know we inserted text in the typeahead
3476 * buffer. */
3477 received_from_client = TRUE;
3478 }
3479 vim_free((char_u *)ptr);
3480}
3481
3482/*
3483 * Evaluate an expression that the client sent to a string.
3484 * Handles disabling error messages and disables debugging, otherwise Vim
3485 * hangs, waiting for "cont" to be typed.
3486 */
3487 char_u *
3488eval_client_expr_to_string(expr)
3489 char_u *expr;
3490{
3491 char_u *res;
3492 int save_dbl = debug_break_level;
3493 int save_ro = redir_off;
3494
3495 debug_break_level = -1;
3496 redir_off = 0;
3497 ++emsg_skip;
3498
3499 res = eval_to_string(expr, NULL);
3500
3501 debug_break_level = save_dbl;
3502 redir_off = save_ro;
3503 --emsg_skip;
3504
Bram Moolenaar63a121b2005-12-11 21:36:39 +00003505 /* A client can tell us to redraw, but not to display the cursor, so do
3506 * that here. */
3507 setcursor();
3508 out_flush();
3509#ifdef FEAT_GUI
3510 if (gui.in_use)
3511 gui_update_cursor(FALSE, FALSE);
3512#endif
3513
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003514 return res;
3515}
3516
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003517/*
3518 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3519 * return an allocated string. Otherwise return "data".
3520 * "*tofree" is set to the result when it needs to be freed later.
3521 */
3522/*ARGSUSED*/
3523 char_u *
3524serverConvert(client_enc, data, tofree)
3525 char_u *client_enc;
3526 char_u *data;
3527 char_u **tofree;
3528{
3529 char_u *res = data;
3530
3531 *tofree = NULL;
3532# ifdef FEAT_MBYTE
3533 if (client_enc != NULL && p_enc != NULL)
3534 {
3535 vimconv_T vimconv;
3536
3537 vimconv.vc_type = CONV_NONE;
3538 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3539 && vimconv.vc_type != CONV_NONE)
3540 {
3541 res = string_convert(&vimconv, data, NULL);
3542 if (res == NULL)
3543 res = data;
3544 else
3545 *tofree = res;
3546 }
3547 convert_setup(&vimconv, NULL, NULL);
3548 }
3549# endif
3550 return res;
3551}
3552
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003553
3554/*
3555 * Make our basic server name: use the specified "arg" if given, otherwise use
3556 * the tail of the command "cmd" we were started with.
3557 * Return the name in allocated memory. This doesn't include a serial number.
3558 */
3559 static char_u *
3560serverMakeName(arg, cmd)
3561 char_u *arg;
3562 char *cmd;
3563{
3564 char_u *p;
3565
3566 if (arg != NULL && *arg != NUL)
3567 p = vim_strsave_up(arg);
3568 else
3569 {
3570 p = vim_strsave_up(gettail((char_u *)cmd));
3571 /* Remove .exe or .bat from the name. */
3572 if (p != NULL && vim_strchr(p, '.') != NULL)
3573 *vim_strchr(p, '.') = NUL;
3574 }
3575 return p;
3576}
3577#endif /* FEAT_CLIENTSERVER */
3578
3579/*
3580 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3581 */
3582#if defined(FEAT_FKMAP) || defined(PROTO)
3583# include "farsi.c"
3584#endif
3585
3586/*
3587 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3588 */
3589#if defined(FEAT_ARABIC) || defined(PROTO)
3590# include "arabic.c"
3591#endif