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