blob: 0067b1c2f76d0cd48569b184f27a25703f1cf63f [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));
119#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
120static 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
204 time_fd = fopen(STARTUPTIME, "a");
205 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 Moolenaar843ee412004-06-30 16:16:41 +0000352# if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)
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 Moolenaar843ee412004-06-30 16:16:41 +0000436#if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)
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 Moolenaar90cfdbe2005-08-12 19:59:19 +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, "");
1239
1240# ifdef FEAT_GETTEXT
1241 {
1242 int mustfree = FALSE;
1243 char_u *p;
1244
1245# ifdef DYNAMIC_GETTEXT
1246 /* Initialize the gettext library */
1247 dyn_libintl_init(NULL);
1248# endif
1249 /* expand_env() doesn't work yet, because chartab[] is not initialized
1250 * yet, call vim_getenv() directly */
1251 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1252 if (p != NULL && *p != NUL)
1253 {
1254 STRCPY(NameBuff, p);
1255 STRCAT(NameBuff, "/lang");
1256 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1257 }
1258 if (mustfree)
1259 vim_free(p);
1260 textdomain(VIMPACKAGE);
1261 }
1262# endif
1263}
1264#endif
1265
1266/*
1267 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1268 * If the executable name starts with "r" we disable shell commands.
1269 * If the next character is "e" we run in Easy mode.
1270 * If the next character is "g" we run the GUI version.
1271 * If the next characters are "view" we start in readonly mode.
1272 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1273 * If the next characters are "ex" we start in Ex mode. If it's followed
1274 * by "im" use improved Ex mode.
1275 */
1276 static void
1277parse_command_name(parmp)
1278 mparm_T *parmp;
1279{
1280 char_u *initstr;
1281
1282 initstr = gettail((char_u *)parmp->argv[0]);
1283
1284#ifdef MACOS_X_UNIX
1285 /* An issue has been seen when launching Vim in such a way that
1286 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1287 * executable or a symbolic link of it. Until this issue is resolved
1288 * we prohibit the GUI from being used.
1289 */
1290 if (STRCMP(initstr, parmp->argv[0]) == 0)
1291 disallow_gui = TRUE;
1292
1293 /* TODO: On MacOS X default to gui if argv[0] ends in:
1294 * /vim.app/Contents/MacOS/Vim */
1295#endif
1296
1297#ifdef FEAT_EVAL
1298 set_vim_var_string(VV_PROGNAME, initstr, -1);
1299#endif
1300
1301 if (TOLOWER_ASC(initstr[0]) == 'r')
1302 {
1303 restricted = TRUE;
1304 ++initstr;
1305 }
1306
1307 /* Avoid using evim mode for "editor". */
1308 if (TOLOWER_ASC(initstr[0]) == 'e'
1309 && (TOLOWER_ASC(initstr[1]) == 'v'
1310 || TOLOWER_ASC(initstr[1]) == 'g'))
1311 {
1312#ifdef FEAT_GUI
1313 gui.starting = TRUE;
1314#endif
1315 parmp->evim_mode = TRUE;
1316 ++initstr;
1317 }
1318
1319 if (TOLOWER_ASC(initstr[0]) == 'g' || initstr[0] == 'k')
1320 {
1321 main_start_gui();
1322#ifdef FEAT_GUI
1323 ++initstr;
1324#endif
1325 }
1326
1327 if (STRNICMP(initstr, "view", 4) == 0)
1328 {
1329 readonlymode = TRUE;
1330 curbuf->b_p_ro = TRUE;
1331 p_uc = 10000; /* don't update very often */
1332 initstr += 4;
1333 }
1334 else if (STRNICMP(initstr, "vim", 3) == 0)
1335 initstr += 3;
1336
1337 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1338 if (STRICMP(initstr, "diff") == 0)
1339 {
1340#ifdef FEAT_DIFF
1341 parmp->diff_mode = TRUE;
1342#else
1343 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1344 mch_errmsg("\n");
1345 mch_exit(2);
1346#endif
1347 }
1348
1349 if (STRNICMP(initstr, "ex", 2) == 0)
1350 {
1351 if (STRNICMP(initstr + 2, "im", 2) == 0)
1352 exmode_active = EXMODE_VIM;
1353 else
1354 exmode_active = EXMODE_NORMAL;
1355 change_compatible(TRUE); /* set 'compatible' */
1356 }
1357}
1358
Bram Moolenaarb4210b32004-06-13 14:51:16 +00001359/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00001360 * Get the name of the display, before gui_prepare() removes it from
1361 * argv[]. Used for the xterm-clipboard display.
1362 *
1363 * Also find the --server... arguments and --socketid
1364 */
1365/*ARGSUSED*/
1366 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001367early_arg_scan(parmp)
Bram Moolenaar58d98232005-07-23 22:25:46 +00001368 mparm_T *parmp;
1369{
1370#if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER)
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001371 int argc = parmp->argc;
1372 char **argv = parmp->argv;
Bram Moolenaar58d98232005-07-23 22:25:46 +00001373 int i;
1374
1375 for (i = 1; i < argc; i++)
1376 {
1377 if (STRCMP(argv[i], "--") == 0)
1378 break;
1379# ifdef FEAT_XCLIPBOARD
1380 else if (STRICMP(argv[i], "-display") == 0
1381# if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)
1382 || STRICMP(argv[i], "--display") == 0
1383# endif
1384 )
1385 {
1386 if (i == argc - 1)
1387 mainerr_arg_missing((char_u *)argv[i]);
1388 xterm_display = argv[++i];
1389 }
1390# endif
1391# ifdef FEAT_CLIENTSERVER
1392 else if (STRICMP(argv[i], "--servername") == 0)
1393 {
1394 if (i == argc - 1)
1395 mainerr_arg_missing((char_u *)argv[i]);
1396 parmp->serverName_arg = (char_u *)argv[++i];
1397 }
1398 else if (STRICMP(argv[i], "--serverlist") == 0
1399 || STRICMP(argv[i], "--remote-send") == 0
1400 || STRICMP(argv[i], "--remote-expr") == 0
1401 || STRICMP(argv[i], "--remote") == 0
1402 || STRICMP(argv[i], "--remote-silent") == 0)
1403 parmp->serverArg = TRUE;
1404 else if (STRICMP(argv[i], "--remote-wait") == 0
1405 || STRICMP(argv[i], "--remote-wait-silent") == 0)
1406 {
1407 parmp->serverArg = TRUE;
1408#ifdef FEAT_GUI
1409 /* don't fork() when starting the GUI to edit the files ourself */
1410 gui.dofork = FALSE;
1411#endif
1412 }
1413# endif
1414# ifdef FEAT_GUI_GTK
1415 else if (STRICMP(argv[i], "--socketid") == 0)
1416 {
1417 unsigned int socket_id;
1418 int count;
1419
1420 if (i == argc - 1)
1421 mainerr_arg_missing((char_u *)argv[i]);
1422 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1423 count = sscanf(&(argv[i + 1][2]), "%x", &socket_id);
1424 else
1425 count = sscanf(argv[i+1], "%u", &socket_id);
1426 if (count != 1)
1427 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1428 else
1429 gtk_socket_id = socket_id;
1430 i++;
1431 }
1432 else if (STRICMP(argv[i], "--echo-wid") == 0)
1433 echo_wid_arg = TRUE;
1434# endif
1435 }
1436#endif
1437}
1438
1439/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001440 * Scan the command line arguments.
1441 */
1442 static void
1443command_line_scan(parmp)
1444 mparm_T *parmp;
1445{
1446 int argc = parmp->argc;
1447 char **argv = parmp->argv;
1448 int argv_idx; /* index in argv[n][] */
1449 int had_minmin = FALSE; /* found "--" argument */
1450 int want_argument; /* option argument with argument */
1451 int c;
Bram Moolenaar231334e2005-07-25 20:46:57 +00001452 char_u *p = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001453 long n;
1454
1455 --argc;
1456 ++argv;
1457 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1458 while (argc > 0)
1459 {
1460 /*
1461 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1462 */
1463 if (argv[0][0] == '+' && !had_minmin)
1464 {
1465 if (parmp->n_commands >= MAX_ARG_CMDS)
1466 mainerr(ME_EXTRA_CMD, NULL);
1467 argv_idx = -1; /* skip to next argument */
1468 if (argv[0][1] == NUL)
1469 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1470 else
1471 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1472 }
1473
1474 /*
1475 * Optional argument.
1476 */
1477 else if (argv[0][0] == '-' && !had_minmin)
1478 {
1479 want_argument = FALSE;
1480 c = argv[0][argv_idx++];
1481#ifdef VMS
1482 /*
1483 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1484 * and "-/X" as "-X".
1485 */
1486 if (c == '/')
1487 {
1488 c = argv[0][argv_idx++];
1489 c = TOUPPER_ASC(c);
1490 }
1491 else
1492 c = TOLOWER_ASC(c);
1493#endif
1494 switch (c)
1495 {
1496 case NUL: /* "vim -" read from stdin */
1497 /* "ex -" silent mode */
1498 if (exmode_active)
1499 silent_mode = TRUE;
1500 else
1501 {
1502 if (parmp->edit_type != EDIT_NONE)
1503 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1504 parmp->edit_type = EDIT_STDIN;
1505 read_cmd_fd = 2; /* read from stderr instead of stdin */
1506 }
1507 argv_idx = -1; /* skip to next argument */
1508 break;
1509
1510 case '-': /* "--" don't take any more option arguments */
1511 /* "--help" give help message */
1512 /* "--version" give version message */
1513 /* "--literal" take files literally */
1514 /* "--nofork" don't fork */
1515 /* "--noplugin[s]" skip plugins */
1516 /* "--cmd <cmd>" execute cmd before vimrc */
1517 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1518 usage();
1519 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1520 {
1521 Columns = 80; /* need to init Columns */
1522 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1523 list_version();
1524 msg_putchar('\n');
1525 msg_didout = FALSE;
1526 mch_exit(0);
1527 }
1528 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1529 {
1530#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1531 parmp->literal = TRUE;
1532#endif
1533 }
1534 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1535 {
1536#ifdef FEAT_GUI
1537 gui.dofork = FALSE; /* don't fork() when starting GUI */
1538#endif
1539 }
1540 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1541 p_lpl = FALSE;
1542 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1543 {
1544 want_argument = TRUE;
1545 argv_idx += 3;
1546 }
1547#ifdef FEAT_CLIENTSERVER
1548 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1549 ; /* already processed -- no arg */
1550 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1551 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1552 {
1553 /* already processed -- snatch the following arg */
1554 if (argc > 1)
1555 {
1556 --argc;
1557 ++argv;
1558 }
1559 }
1560#endif
1561#ifdef FEAT_GUI_GTK
1562 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1563 {
1564 /* already processed -- snatch the following arg */
1565 if (argc > 1)
1566 {
1567 --argc;
1568 ++argv;
1569 }
1570 }
1571 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1572 {
1573 /* already processed, skip */
1574 }
1575#endif
1576 else
1577 {
1578 if (argv[0][argv_idx])
1579 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1580 had_minmin = TRUE;
1581 }
1582 if (!want_argument)
1583 argv_idx = -1; /* skip to next argument */
1584 break;
1585
1586 case 'A': /* "-A" start in Arabic mode */
1587#ifdef FEAT_ARABIC
1588 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1589#else
1590 mch_errmsg(_(e_noarabic));
1591 mch_exit(2);
1592#endif
1593 break;
1594
1595 case 'b': /* "-b" binary mode */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001596 /* Needs to be effective before expanding file names, because
1597 * for Win32 this makes us edit a shortcut file itself,
1598 * instead of the file it links to. */
1599 set_options_bin(curbuf->b_p_bin, 1, 0);
1600 curbuf->b_p_bin = 1; /* binary file I/O */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001601 break;
1602
1603 case 'C': /* "-C" Compatible */
1604 change_compatible(TRUE);
1605 break;
1606
1607 case 'e': /* "-e" Ex mode */
1608 exmode_active = EXMODE_NORMAL;
1609 break;
1610
1611 case 'E': /* "-E" Improved Ex mode */
1612 exmode_active = EXMODE_VIM;
1613 break;
1614
1615 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1616 window directly, not with newcli */
1617#ifdef FEAT_GUI
1618 gui.dofork = FALSE; /* don't fork() when starting GUI */
1619#endif
1620 break;
1621
1622 case 'g': /* "-g" start GUI */
1623 main_start_gui();
1624 break;
1625
1626 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1627#ifdef FEAT_FKMAP
1628 curwin->w_p_rl = p_fkmap = TRUE;
1629#else
1630 mch_errmsg(_(e_nofarsi));
1631 mch_exit(2);
1632#endif
1633 break;
1634
1635 case 'h': /* "-h" give help message */
1636#ifdef FEAT_GUI_GNOME
1637 /* Tell usage() to exit for "gvim". */
1638 gui.starting = FALSE;
1639#endif
1640 usage();
1641 break;
1642
1643 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1644#ifdef FEAT_RIGHTLEFT
1645 curwin->w_p_rl = p_hkmap = TRUE;
1646#else
1647 mch_errmsg(_(e_nohebrew));
1648 mch_exit(2);
1649#endif
1650 break;
1651
1652 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1653#ifdef FEAT_LISP
1654 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1655 p_sm = TRUE;
1656#endif
1657 break;
1658
1659#ifdef TARGET_API_MAC_OSX
1660 /* For some reason on MacOS X, an argument like:
1661 -psn_0_10223617 is passed in when invoke from Finder
1662 or with the 'open' command */
1663 case 'p':
1664 argv_idx = -1; /* bypass full -psn */
1665 main_start_gui();
1666 break;
1667#endif
1668 case 'M': /* "-M" no changes or writing of files */
1669 reset_modifiable();
1670 /* FALLTHROUGH */
1671
1672 case 'm': /* "-m" no writing of files */
1673 p_write = FALSE;
1674 break;
1675
1676 case 'y': /* "-y" easy mode */
1677#ifdef FEAT_GUI
1678 gui.starting = TRUE; /* start GUI a bit later */
1679#endif
1680 parmp->evim_mode = TRUE;
1681 break;
1682
1683 case 'N': /* "-N" Nocompatible */
1684 change_compatible(FALSE);
1685 break;
1686
1687 case 'n': /* "-n" no swap file */
1688 parmp->no_swap_file = TRUE;
1689 break;
1690
1691 case 'o': /* "-o[N]" open N horizontal split windows */
1692#ifdef FEAT_WINDOWS
1693 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001694 parmp->window_count = get_number_arg((char_u *)argv[0],
1695 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001696 parmp->vert_windows = FALSE;
1697#endif
1698 break;
1699
1700 case 'O': /* "-O[N]" open N vertical split windows */
1701#if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1702 /* default is 0: open window for each file */
Bram Moolenaar231334e2005-07-25 20:46:57 +00001703 parmp->window_count = get_number_arg((char_u *)argv[0],
1704 &argv_idx, 0);
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001705 parmp->vert_windows = TRUE;
1706#endif
1707 break;
1708
1709#ifdef FEAT_QUICKFIX
1710 case 'q': /* "-q" QuickFix mode */
1711 if (parmp->edit_type != EDIT_NONE)
1712 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1713 parmp->edit_type = EDIT_QF;
1714 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1715 {
1716 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1717 argv_idx = -1;
1718 }
1719 else if (argc > 1) /* "-q {errorfile}" */
1720 want_argument = TRUE;
1721 break;
1722#endif
1723
1724 case 'R': /* "-R" readonly mode */
1725 readonlymode = TRUE;
1726 curbuf->b_p_ro = TRUE;
1727 p_uc = 10000; /* don't update very often */
1728 break;
1729
1730 case 'r': /* "-r" recovery mode */
1731 case 'L': /* "-L" recovery mode */
1732 recoverymode = 1;
1733 break;
1734
1735 case 's':
1736 if (exmode_active) /* "-s" silent (batch) mode */
1737 silent_mode = TRUE;
1738 else /* "-s {scriptin}" read from script file */
1739 want_argument = TRUE;
1740 break;
1741
1742 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1743 if (parmp->edit_type != EDIT_NONE)
1744 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1745 parmp->edit_type = EDIT_TAG;
1746 if (argv[0][argv_idx]) /* "-t{tag}" */
1747 {
1748 parmp->tagname = (char_u *)argv[0] + argv_idx;
1749 argv_idx = -1;
1750 }
1751 else /* "-t {tag}" */
1752 want_argument = TRUE;
1753 break;
1754
1755#ifdef FEAT_EVAL
1756 case 'D': /* "-D" Debugging */
1757 parmp->use_debug_break_level = 9999;
1758 break;
1759#endif
1760#ifdef FEAT_DIFF
1761 case 'd': /* "-d" 'diff' */
1762# ifdef AMIGA
1763 /* check for "-dev {device}" */
1764 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1765 want_argument = TRUE;
1766 else
1767# endif
1768 parmp->diff_mode = TRUE;
1769 break;
1770#endif
1771 case 'V': /* "-V{N}" Verbose level */
1772 /* default is 10: a little bit verbose */
1773 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1774 if (argv[0][argv_idx] != NUL)
1775 {
1776 set_option_value((char_u *)"verbosefile", 0L,
1777 (char_u *)argv[0] + argv_idx, 0);
1778 argv_idx = STRLEN(argv[0]);
1779 }
1780 break;
1781
1782 case 'v': /* "-v" Vi-mode (as if called "vi") */
1783 exmode_active = 0;
1784#ifdef FEAT_GUI
1785 gui.starting = FALSE; /* don't start GUI */
1786#endif
1787 break;
1788
1789 case 'w': /* "-w{number}" set window height */
1790 /* "-w {scriptout}" write to script */
1791 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
1792 {
1793 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1794 set_option_value((char_u *)"window", n, NULL, 0);
1795 break;
1796 }
1797 want_argument = TRUE;
1798 break;
1799
1800#ifdef FEAT_CRYPT
1801 case 'x': /* "-x" encrypted reading/writing of files */
1802 parmp->ask_for_key = TRUE;
1803 break;
1804#endif
1805
1806 case 'X': /* "-X" don't connect to X server */
1807#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
1808 x_no_connect = TRUE;
1809#endif
1810 break;
1811
1812 case 'Z': /* "-Z" restricted mode */
1813 restricted = TRUE;
1814 break;
1815
1816 case 'c': /* "-c{command}" or "-c {command}" execute
1817 command */
1818 if (argv[0][argv_idx] != NUL)
1819 {
1820 if (parmp->n_commands >= MAX_ARG_CMDS)
1821 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001822 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
1823 + argv_idx;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001824 argv_idx = -1;
1825 break;
1826 }
1827 /*FALLTHROUGH*/
1828 case 'S': /* "-S {file}" execute Vim script */
1829 case 'i': /* "-i {viminfo}" use for viminfo */
1830#ifndef FEAT_DIFF
1831 case 'd': /* "-d {device}" device (for Amiga) */
1832#endif
1833 case 'T': /* "-T {terminal}" terminal name */
1834 case 'u': /* "-u {vimrc}" vim inits file */
1835 case 'U': /* "-U {gvimrc}" gvim inits file */
1836 case 'W': /* "-W {scriptout}" overwrite */
1837#ifdef FEAT_GUI_W32
1838 case 'P': /* "-P {parent title}" MDI parent */
1839#endif
1840 want_argument = TRUE;
1841 break;
1842
1843 default:
1844 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1845 }
1846
1847 /*
1848 * Handle option arguments with argument.
1849 */
1850 if (want_argument)
1851 {
1852 /*
1853 * Check for garbage immediately after the option letter.
1854 */
1855 if (argv[0][argv_idx] != NUL)
1856 mainerr(ME_GARBAGE, (char_u *)argv[0]);
1857
1858 --argc;
1859 if (argc < 1 && c != 'S')
1860 mainerr_arg_missing((char_u *)argv[0]);
1861 ++argv;
1862 argv_idx = -1;
1863
1864 switch (c)
1865 {
1866 case 'c': /* "-c {command}" execute command */
1867 case 'S': /* "-S {file}" execute Vim script */
1868 if (parmp->n_commands >= MAX_ARG_CMDS)
1869 mainerr(ME_EXTRA_CMD, NULL);
1870 if (c == 'S')
1871 {
1872 char *a;
1873
1874 if (argc < 1)
1875 /* "-S" without argument: use default session file
1876 * name. */
1877 a = SESSION_FILE;
1878 else if (argv[0][0] == '-')
1879 {
1880 /* "-S" followed by another option: use default
1881 * session file name. */
1882 a = SESSION_FILE;
1883 ++argc;
1884 --argv;
1885 }
1886 else
1887 a = argv[0];
1888 p = alloc((unsigned)(STRLEN(a) + 4));
1889 if (p == NULL)
1890 mch_exit(2);
1891 sprintf((char *)p, "so %s", a);
1892 parmp->cmds_tofree[parmp->n_commands] = TRUE;
1893 parmp->commands[parmp->n_commands++] = p;
1894 }
1895 else
Bram Moolenaar231334e2005-07-25 20:46:57 +00001896 parmp->commands[parmp->n_commands++] =
1897 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001898 break;
1899
1900 case '-': /* "--cmd {command}" execute command */
1901 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
1902 mainerr(ME_EXTRA_CMD, NULL);
Bram Moolenaar231334e2005-07-25 20:46:57 +00001903 parmp->pre_commands[parmp->n_pre_commands++] =
1904 (char_u *)argv[0];
Bram Moolenaarc013cb62005-07-24 21:18:31 +00001905 break;
1906
1907 /* case 'd': -d {device} is handled in mch_check_win() for the
1908 * Amiga */
1909
1910#ifdef FEAT_QUICKFIX
1911 case 'q': /* "-q {errorfile}" QuickFix mode */
1912 parmp->use_ef = (char_u *)argv[0];
1913 break;
1914#endif
1915
1916 case 'i': /* "-i {viminfo}" use for viminfo */
1917 use_viminfo = (char_u *)argv[0];
1918 break;
1919
1920 case 's': /* "-s {scriptin}" read from script file */
1921 if (scriptin[0] != NULL)
1922 {
1923scripterror:
1924 mch_errmsg(_("Attempt to open script file again: \""));
1925 mch_errmsg(argv[-1]);
1926 mch_errmsg(" ");
1927 mch_errmsg(argv[0]);
1928 mch_errmsg("\"\n");
1929 mch_exit(2);
1930 }
1931 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
1932 {
1933 mch_errmsg(_("Cannot open for reading: \""));
1934 mch_errmsg(argv[0]);
1935 mch_errmsg("\"\n");
1936 mch_exit(2);
1937 }
1938 if (save_typebuf() == FAIL)
1939 mch_exit(2); /* out of memory */
1940 break;
1941
1942 case 't': /* "-t {tag}" */
1943 parmp->tagname = (char_u *)argv[0];
1944 break;
1945
1946 case 'T': /* "-T {terminal}" terminal name */
1947 /*
1948 * The -T term argument is always available and when
1949 * HAVE_TERMLIB is supported it overrides the environment
1950 * variable TERM.
1951 */
1952#ifdef FEAT_GUI
1953 if (term_is_gui((char_u *)argv[0]))
1954 gui.starting = TRUE; /* start GUI a bit later */
1955 else
1956#endif
1957 parmp->term = (char_u *)argv[0];
1958 break;
1959
1960 case 'u': /* "-u {vimrc}" vim inits file */
1961 parmp->use_vimrc = (char_u *)argv[0];
1962 break;
1963
1964 case 'U': /* "-U {gvimrc}" gvim inits file */
1965#ifdef FEAT_GUI
1966 use_gvimrc = (char_u *)argv[0];
1967#endif
1968 break;
1969
1970 case 'w': /* "-w {nr}" 'window' value */
1971 /* "-w {scriptout}" append to script file */
1972 if (vim_isdigit(*((char_u *)argv[0])))
1973 {
1974 argv_idx = 0;
1975 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1976 set_option_value((char_u *)"window", n, NULL, 0);
1977 argv_idx = -1;
1978 break;
1979 }
1980 /*FALLTHROUGH*/
1981 case 'W': /* "-W {scriptout}" overwrite script file */
1982 if (scriptout != NULL)
1983 goto scripterror;
1984 if ((scriptout = mch_fopen(argv[0],
1985 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
1986 {
1987 mch_errmsg(_("Cannot open for script output: \""));
1988 mch_errmsg(argv[0]);
1989 mch_errmsg("\"\n");
1990 mch_exit(2);
1991 }
1992 break;
1993
1994#ifdef FEAT_GUI_W32
1995 case 'P': /* "-P {parent title}" MDI parent */
1996 gui_mch_set_parent(argv[0]);
1997 break;
1998#endif
1999 }
2000 }
2001 }
2002
2003 /*
2004 * File name argument.
2005 */
2006 else
2007 {
2008 argv_idx = -1; /* skip to next argument */
2009
2010 /* Check for only one type of editing. */
2011 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2012 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2013 parmp->edit_type = EDIT_FILE;
2014
2015#ifdef MSWIN
2016 /* Remember if the argument was a full path before changing
2017 * slashes to backslashes. */
2018 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2019 parmp->full_path = TRUE;
2020#endif
2021
2022 /* Add the file to the global argument list. */
2023 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2024 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2025 mch_exit(2);
2026#ifdef FEAT_DIFF
2027 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2028 && !mch_isdir(alist_name(&GARGLIST[0])))
2029 {
2030 char_u *r;
2031
2032 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2033 if (r != NULL)
2034 {
2035 vim_free(p);
2036 p = r;
2037 }
2038 }
2039#endif
2040#if defined(__CYGWIN32__) && !defined(WIN32)
2041 /*
2042 * If vim is invoked by non-Cygwin tools, convert away any
2043 * DOS paths, so things like .swp files are created correctly.
2044 * Look for evidence of non-Cygwin paths before we bother.
2045 * This is only for when using the Unix files.
2046 */
2047 if (strpbrk(p, "\\:") != NULL)
2048 {
2049 char posix_path[PATH_MAX];
2050
2051 cygwin_conv_to_posix_path(p, posix_path);
2052 vim_free(p);
2053 p = vim_strsave(posix_path);
2054 if (p == NULL)
2055 mch_exit(2);
2056 }
2057#endif
2058 alist_add(&global_alist, p,
2059#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
Bram Moolenaar231334e2005-07-25 20:46:57 +00002060 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002061#else
2062 2 /* add buffer number now and use curbuf */
2063#endif
2064 );
2065
2066#if defined(FEAT_MBYTE) && defined(WIN32)
2067 {
2068 extern void used_file_arg(char *, int, int);
2069
2070 /* Remember this argument has been added to the argument list.
2071 * Needed when 'encoding' is changed. */
2072 used_file_arg(argv[0], parmp->literal, parmp->full_path);
2073 }
2074#endif
2075 }
2076
2077 /*
2078 * If there are no more letters after the current "-", go to next
2079 * argument. argv_idx is set to -1 when the current argument is to be
2080 * skipped.
2081 */
2082 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2083 {
2084 --argc;
2085 ++argv;
2086 argv_idx = 1;
2087 }
2088 }
2089}
2090
2091/*
2092 * Print a warning if stdout is not a terminal.
2093 * When starting in Ex mode and commands come from a file, set Silent mode.
2094 */
2095 static void
2096check_tty(parmp)
2097 mparm_T *parmp;
2098{
2099 int input_isatty; /* is active input a terminal? */
2100
2101 input_isatty = mch_input_isatty();
2102 if (exmode_active)
2103 {
2104 if (!input_isatty)
2105 silent_mode = TRUE;
2106 }
2107 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2108#ifdef FEAT_GUI
2109 /* don't want the delay when started from the desktop */
2110 && !gui.starting
2111#endif
2112 )
2113 {
2114#ifdef NBDEBUG
2115 /*
2116 * This shouldn't be necessary. But if I run netbeans with the log
2117 * output coming to the console and XOpenDisplay fails, I get vim
2118 * trying to start with input/output to my console tty. This fills my
2119 * input buffer so fast I can't even kill the process in under 2
2120 * minutes (and it beeps continuosly the whole time :-)
2121 */
2122 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2123 {
2124 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2125 exit(1);
2126 }
2127#endif
2128 if (!parmp->stdout_isatty)
2129 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2130 if (!input_isatty)
2131 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2132 out_flush();
2133 if (scriptin[0] == NULL)
2134 ui_delay(2000L, TRUE);
2135 TIME_MSG("Warning delay");
2136 }
2137}
2138
2139/*
2140 * Read text from stdin.
2141 */
2142 static void
2143read_stdin()
2144{
2145 int i;
2146
2147#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2148 /* When getting the ATTENTION prompt here, use a dialog */
2149 swap_exists_action = SEA_DIALOG;
2150#endif
2151 no_wait_return = TRUE;
2152 i = msg_didany;
2153 set_buflisted(TRUE);
2154 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2155 no_wait_return = FALSE;
2156 msg_didany = i;
2157 TIME_MSG("reading stdin");
2158#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2159 check_swap_exists_action();
2160#endif
2161#if !(defined(AMIGA) || defined(MACOS))
2162 /*
2163 * Close stdin and dup it from stderr. Required for GPM to work
2164 * properly, and for running external commands.
2165 * Is there any other system that cannot do this?
2166 */
2167 close(0);
2168 dup(2);
2169#endif
2170}
2171
2172/*
2173 * Create the requested number of windows and edit buffers in them.
2174 * Also does recovery if "recoverymode" set.
2175 */
2176/*ARGSUSED*/
2177 static void
2178create_windows(parmp)
2179 mparm_T *parmp;
2180{
2181#ifdef FEAT_WINDOWS
2182 /*
2183 * Create the number of windows that was requested.
2184 */
2185 if (parmp->window_count == -1) /* was not set */
2186 parmp->window_count = 1;
2187 if (parmp->window_count == 0)
2188 parmp->window_count = GARGCOUNT;
2189 if (parmp->window_count > 1)
2190 {
2191 /* Don't change the windows if there was a command in .vimrc that
2192 * already split some windows */
2193 if (parmp->vert_windows == MAYBE)
2194 parmp->vert_windows = FALSE;
2195 if (firstwin->w_next == NULL)
2196 {
2197 parmp->window_count = make_windows(parmp->window_count,
2198 parmp->vert_windows);
2199 TIME_MSG("making windows");
2200 }
2201 else
2202 parmp->window_count = win_count();
2203 }
2204 else
2205 parmp->window_count = 1;
2206#endif
2207
2208 if (recoverymode) /* do recover */
2209 {
2210 msg_scroll = TRUE; /* scroll message up */
2211 ml_recover();
2212 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2213 getout(1);
2214 do_modelines(FALSE); /* do modelines */
2215 }
2216 else
2217 {
2218 /*
2219 * Open a buffer for windows that don't have one yet.
2220 * Commands in the .vimrc might have loaded a file or split the window.
2221 * Watch out for autocommands that delete a window.
2222 */
2223#ifdef FEAT_AUTOCMD
2224 /*
2225 * Don't execute Win/Buf Enter/Leave autocommands here
2226 */
2227 ++autocmd_no_enter;
2228 ++autocmd_no_leave;
2229#endif
2230#ifdef FEAT_WINDOWS
2231 for (curwin = firstwin; curwin != NULL; curwin = W_NEXT(curwin))
2232#endif
2233 {
2234 curbuf = curwin->w_buffer;
2235 if (curbuf->b_ml.ml_mfp == NULL)
2236 {
2237#ifdef FEAT_FOLDING
2238 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2239 if (p_fdls >= 0)
2240 curwin->w_p_fdl = p_fdls;
2241#endif
2242#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2243 /* When getting the ATTENTION prompt here, use a dialog */
2244 swap_exists_action = SEA_DIALOG;
2245#endif
2246 set_buflisted(TRUE);
2247 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2248
2249#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2250 check_swap_exists_action();
2251#endif
2252#ifdef FEAT_AUTOCMD
2253 curwin = firstwin; /* start again */
2254#endif
2255 }
2256#ifdef FEAT_WINDOWS
2257 ui_breakcheck();
2258 if (got_int)
2259 {
2260 (void)vgetc(); /* only break the file loading, not the rest */
2261 break;
2262 }
2263#endif
2264 }
2265#ifdef FEAT_AUTOCMD
2266 --autocmd_no_enter;
2267 --autocmd_no_leave;
2268#endif
2269#ifdef FEAT_WINDOWS
2270 curwin = firstwin;
2271 curbuf = curwin->w_buffer;
2272#endif
2273 }
2274}
2275
2276#ifdef FEAT_WINDOWS
2277 /*
2278 * If opened more than one window, start editing files in the other
2279 * windows. make_windows() has already opened the windows.
2280 */
2281 static void
2282edit_buffers(parmp)
2283 mparm_T *parmp;
2284{
2285 int arg_idx; /* index in argument list */
2286 int i;
2287
2288# ifdef FEAT_AUTOCMD
2289 /*
2290 * Don't execute Win/Buf Enter/Leave autocommands here
2291 */
2292 ++autocmd_no_enter;
2293 ++autocmd_no_leave;
2294# endif
2295 arg_idx = 1;
2296 for (i = 1; i < parmp->window_count; ++i)
2297 {
2298 if (curwin->w_next == NULL) /* just checking */
2299 break;
2300 win_enter(curwin->w_next, FALSE);
2301
2302 /* Only open the file if there is no file in this window yet (that can
2303 * happen when .vimrc contains ":sall") */
2304 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2305 {
2306 curwin->w_arg_idx = arg_idx;
2307 /* edit file from arg list, if there is one */
2308 (void)do_ecmd(0, arg_idx < GARGCOUNT
2309 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2310 NULL, NULL, ECMD_LASTL, ECMD_HIDE);
2311 if (arg_idx == GARGCOUNT - 1)
2312 arg_had_last = TRUE;
2313 ++arg_idx;
2314 }
2315 ui_breakcheck();
2316 if (got_int)
2317 {
2318 (void)vgetc(); /* only break the file loading, not the rest */
2319 break;
2320 }
2321 }
2322# ifdef FEAT_AUTOCMD
2323 --autocmd_no_enter;
2324# endif
2325 win_enter(firstwin, FALSE); /* back to first window */
2326# ifdef FEAT_AUTOCMD
2327 --autocmd_no_leave;
2328# endif
2329 TIME_MSG("editing files in windows");
2330 if (parmp->window_count > 1)
2331 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2332}
2333#endif /* FEAT_WINDOWS */
2334
2335/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002336 * Execute the commands from --cmd arguments "cmds[cnt]".
2337 */
2338 static void
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002339exe_pre_commands(parmp)
2340 mparm_T *parmp;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002341{
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002342 char_u **cmds = parmp->pre_commands;
2343 int cnt = parmp->n_pre_commands;
Bram Moolenaar58d98232005-07-23 22:25:46 +00002344 int i;
2345
2346 if (cnt > 0)
2347 {
2348 curwin->w_cursor.lnum = 0; /* just in case.. */
2349 sourcing_name = (char_u *)_("pre-vimrc command line");
2350# ifdef FEAT_EVAL
2351 current_SID = SID_CMDARG;
2352# endif
2353 for (i = 0; i < cnt; ++i)
2354 do_cmdline_cmd(cmds[i]);
2355 sourcing_name = NULL;
2356# ifdef FEAT_EVAL
2357 current_SID = 0;
2358# endif
2359 TIME_MSG("--cmd commands");
2360 }
2361}
2362
2363/*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002364 * Execute "+", "-c" and "-S" arguments.
2365 */
2366 static void
2367exe_commands(parmp)
2368 mparm_T *parmp;
2369{
2370 int i;
2371
2372 /*
2373 * We start commands on line 0, make "vim +/pat file" match a
2374 * pattern on line 1. But don't move the cursor when an autocommand
2375 * with g`" was used.
2376 */
2377 msg_scroll = TRUE;
2378 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2379 curwin->w_cursor.lnum = 0;
2380 sourcing_name = (char_u *)"command line";
2381#ifdef FEAT_EVAL
2382 current_SID = SID_CARG;
2383#endif
2384 for (i = 0; i < parmp->n_commands; ++i)
2385 {
2386 do_cmdline_cmd(parmp->commands[i]);
2387 if (parmp->cmds_tofree[i])
2388 vim_free(parmp->commands[i]);
2389 }
2390 sourcing_name = NULL;
2391#ifdef FEAT_EVAL
2392 current_SID = 0;
2393#endif
2394 if (curwin->w_cursor.lnum == 0)
2395 curwin->w_cursor.lnum = 1;
2396
2397 if (!exmode_active)
2398 msg_scroll = FALSE;
2399
2400#ifdef FEAT_QUICKFIX
2401 /* When started with "-q errorfile" jump to first error again. */
2402 if (parmp->edit_type == EDIT_QF)
2403 qf_jump(0, 0, FALSE);
2404#endif
2405 TIME_MSG("executing command arguments");
2406}
2407
2408/*
Bram Moolenaar58d98232005-07-23 22:25:46 +00002409 * Source startup scripts.
2410 */
2411 static void
2412source_startup_scripts(parmp)
2413 mparm_T *parmp;
2414{
2415 int i;
2416
2417 /*
2418 * For "evim" source evim.vim first of all, so that the user can overrule
2419 * any things he doesn't like.
2420 */
2421 if (parmp->evim_mode)
2422 {
2423 (void)do_source((char_u *)EVIM_FILE, FALSE, FALSE);
2424 TIME_MSG("source evim file");
2425 }
2426
2427 /*
Bram Moolenaarc013cb62005-07-24 21:18:31 +00002428 * If -u argument given, use only the initializations from that file and
Bram Moolenaar58d98232005-07-23 22:25:46 +00002429 * nothing else.
2430 */
2431 if (parmp->use_vimrc != NULL)
2432 {
Bram Moolenaar231334e2005-07-25 20:46:57 +00002433 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2434 || STRCMP(parmp->use_vimrc, "NORC") == 0)
Bram Moolenaar58d98232005-07-23 22:25:46 +00002435 {
2436#ifdef FEAT_GUI
2437 if (use_gvimrc == NULL) /* don't load gvimrc either */
2438 use_gvimrc = parmp->use_vimrc;
2439#endif
2440 if (parmp->use_vimrc[2] == 'N')
2441 p_lpl = FALSE; /* don't load plugins either */
2442 }
2443 else
2444 {
2445 if (do_source(parmp->use_vimrc, FALSE, FALSE) != OK)
2446 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2447 }
2448 }
2449 else if (!silent_mode)
2450 {
2451#ifdef AMIGA
2452 struct Process *proc = (struct Process *)FindTask(0L);
2453 APTR save_winptr = proc->pr_WindowPtr;
2454
2455 /* Avoid a requester here for a volume that doesn't exist. */
2456 proc->pr_WindowPtr = (APTR)-1L;
2457#endif
2458
2459 /*
2460 * Get system wide defaults, if the file name is defined.
2461 */
2462#ifdef SYS_VIMRC_FILE
2463 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, FALSE);
2464#endif
2465
2466 /*
2467 * Try to read initialization commands from the following places:
2468 * - environment variable VIMINIT
2469 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2470 * - second user vimrc file ($VIM/.vimrc for Dos)
2471 * - environment variable EXINIT
2472 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2473 * - second user exrc file ($VIM/.exrc for Dos)
2474 * The first that exists is used, the rest is ignored.
2475 */
2476 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2477 {
2478 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, TRUE) == FAIL
2479#ifdef USR_VIMRC_FILE2
2480 && do_source((char_u *)USR_VIMRC_FILE2, TRUE, TRUE) == FAIL
2481#endif
2482#ifdef USR_VIMRC_FILE3
2483 && do_source((char_u *)USR_VIMRC_FILE3, TRUE, TRUE) == FAIL
2484#endif
2485 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2486 && do_source((char_u *)USR_EXRC_FILE, FALSE, FALSE) == FAIL)
2487 {
2488#ifdef USR_EXRC_FILE2
2489 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, FALSE);
2490#endif
2491 }
2492 }
2493
2494 /*
2495 * Read initialization commands from ".vimrc" or ".exrc" in current
2496 * directory. This is only done if the 'exrc' option is set.
2497 * Because of security reasons we disallow shell and write commands
2498 * now, except for unix if the file is owned by the user or 'secure'
2499 * option has been reset in environment of global ".exrc" or ".vimrc".
2500 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2501 * SYS_VIMRC_FILE.
2502 */
2503 if (p_exrc)
2504 {
2505#if defined(UNIX) || defined(VMS)
2506 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2507 if (!file_owned(VIMRC_FILE))
2508#endif
2509 secure = p_secure;
2510
2511 i = FAIL;
2512 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2513 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2514#ifdef USR_VIMRC_FILE2
2515 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2516 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2517#endif
2518#ifdef USR_VIMRC_FILE3
2519 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2520 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2521#endif
2522#ifdef SYS_VIMRC_FILE
2523 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2524 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2525#endif
2526 )
2527 i = do_source((char_u *)VIMRC_FILE, TRUE, TRUE);
2528
2529 if (i == FAIL)
2530 {
2531#if defined(UNIX) || defined(VMS)
2532 /* if ".exrc" is not owned by user set 'secure' mode */
2533 if (!file_owned(EXRC_FILE))
2534 secure = p_secure;
2535 else
2536 secure = 0;
2537#endif
2538 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2539 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2540#ifdef USR_EXRC_FILE2
2541 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2542 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2543#endif
2544 )
2545 (void)do_source((char_u *)EXRC_FILE, FALSE, FALSE);
2546 }
2547 }
2548 if (secure == 2)
2549 need_wait_return = TRUE;
2550 secure = 0;
2551#ifdef AMIGA
2552 proc->pr_WindowPtr = save_winptr;
2553#endif
2554 }
2555 TIME_MSG("sourcing vimrc file(s)");
2556}
2557
2558/*
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002559 * Setup to start using the GUI. Exit with an error when not available.
2560 */
2561 static void
2562main_start_gui()
2563{
2564#ifdef FEAT_GUI
2565 gui.starting = TRUE; /* start GUI a bit later */
2566#else
2567 mch_errmsg(_(e_nogvim));
2568 mch_errmsg("\n");
2569 mch_exit(2);
2570#endif
2571}
2572
2573/*
2574 * Get an evironment variable, and execute it as Ex commands.
2575 * Returns FAIL if the environment variable was not executed, OK otherwise.
2576 */
2577 int
2578process_env(env, is_viminit)
2579 char_u *env;
2580 int is_viminit; /* when TRUE, called for VIMINIT */
2581{
2582 char_u *initstr;
2583 char_u *save_sourcing_name;
2584 linenr_T save_sourcing_lnum;
2585#ifdef FEAT_EVAL
2586 scid_T save_sid;
2587#endif
2588
2589 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2590 {
2591 if (is_viminit)
2592 vimrc_found();
2593 save_sourcing_name = sourcing_name;
2594 save_sourcing_lnum = sourcing_lnum;
2595 sourcing_name = env;
2596 sourcing_lnum = 0;
2597#ifdef FEAT_EVAL
2598 save_sid = current_SID;
2599 current_SID = SID_ENV;
2600#endif
2601 do_cmdline_cmd(initstr);
2602 sourcing_name = save_sourcing_name;
2603 sourcing_lnum = save_sourcing_lnum;
2604#ifdef FEAT_EVAL
2605 current_SID = save_sid;;
2606#endif
2607 return OK;
2608 }
2609 return FAIL;
2610}
2611
2612#if defined(UNIX) || defined(VMS)
2613/*
2614 * Return TRUE if we are certain the user owns the file "fname".
2615 * Used for ".vimrc" and ".exrc".
2616 * Use both stat() and lstat() for extra security.
2617 */
2618 static int
2619file_owned(fname)
2620 char *fname;
2621{
2622 struct stat s;
2623# ifdef UNIX
2624 uid_t uid = getuid();
2625# else /* VMS */
2626 uid_t uid = ((getgid() << 16) | getuid());
2627# endif
2628
2629 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2630# ifdef HAVE_LSTAT
2631 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2632# endif
2633 );
2634}
2635#endif
2636
2637/*
2638 * Give an error message main_errors["n"] and exit.
2639 */
2640 static void
2641mainerr(n, str)
2642 int n; /* one of the ME_ defines */
2643 char_u *str; /* extra argument or NULL */
2644{
2645#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2646 reset_signals(); /* kill us with CTRL-C here, if you like */
2647#endif
2648
2649 mch_errmsg(longVersion);
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002650 mch_errmsg("\n");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002651 mch_errmsg(_(main_errors[n]));
2652 if (str != NULL)
2653 {
2654 mch_errmsg(": \"");
2655 mch_errmsg((char *)str);
2656 mch_errmsg("\"");
2657 }
Bram Moolenaar2a8d1f82005-02-05 21:43:56 +00002658 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002659
2660 mch_exit(1);
2661}
2662
2663 void
2664mainerr_arg_missing(str)
2665 char_u *str;
2666{
2667 mainerr(ME_ARG_MISSING, str);
2668}
2669
2670/*
2671 * print a message with three spaces prepended and '\n' appended.
2672 */
2673 static void
2674main_msg(s)
2675 char *s;
2676{
2677 mch_msg(" ");
2678 mch_msg(s);
2679 mch_msg("\n");
2680}
2681
2682/*
2683 * Print messages for "vim -h" or "vim --help" and exit.
2684 */
2685 static void
2686usage()
2687{
2688 int i;
2689 static char *(use[]) =
2690 {
2691 N_("[file ..] edit specified file(s)"),
2692 N_("- read text from stdin"),
2693 N_("-t tag edit file where tag is defined"),
2694#ifdef FEAT_QUICKFIX
2695 N_("-q [errorfile] edit file with first error")
2696#endif
2697 };
2698
2699#if defined(UNIX) || defined(__EMX__) || defined(VMS)
2700 reset_signals(); /* kill us with CTRL-C here, if you like */
2701#endif
2702
2703 mch_msg(longVersion);
2704 mch_msg(_("\n\nusage:"));
2705 for (i = 0; ; ++i)
2706 {
2707 mch_msg(_(" vim [arguments] "));
2708 mch_msg(_(use[i]));
2709 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
2710 break;
2711 mch_msg(_("\n or:"));
2712 }
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002713#ifdef VMS
2714 mch_msg(_("where case is ignored prepend / to make flag upper case"));
2715#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002716
2717 mch_msg(_("\n\nArguments:\n"));
2718 main_msg(_("--\t\t\tOnly file names after this"));
2719#if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2720 main_msg(_("--literal\t\tDon't expand wildcards"));
2721#endif
2722#ifdef FEAT_OLE
2723 main_msg(_("-register\t\tRegister this gvim for OLE"));
2724 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
2725#endif
2726#ifdef FEAT_GUI
2727 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
2728 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
2729#endif
2730 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
2731 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
2732 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
2733#ifdef FEAT_DIFF
2734 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
2735#endif
2736 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
2737 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
2738 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
2739 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
2740 main_msg(_("-M\t\t\tModifications in text not allowed"));
2741 main_msg(_("-b\t\t\tBinary mode"));
2742#ifdef FEAT_LISP
2743 main_msg(_("-l\t\t\tLisp mode"));
2744#endif
2745 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
2746 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
2747 main_msg(_("-V[N]\t\tVerbose level"));
2748 main_msg(_("-D\t\t\tDebugging mode"));
2749 main_msg(_("-n\t\t\tNo swap file, use memory only"));
2750 main_msg(_("-r\t\t\tList swap files and exit"));
2751 main_msg(_("-r (with file name)\tRecover crashed session"));
2752 main_msg(_("-L\t\t\tSame as -r"));
2753#ifdef AMIGA
2754 main_msg(_("-f\t\t\tDon't use newcli to open window"));
2755 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
2756#endif
2757#ifdef FEAT_ARABIC
2758 main_msg(_("-A\t\t\tstart in Arabic mode"));
2759#endif
2760#ifdef FEAT_RIGHTLEFT
2761 main_msg(_("-H\t\t\tStart in Hebrew mode"));
2762#endif
2763#ifdef FEAT_FKMAP
2764 main_msg(_("-F\t\t\tStart in Farsi mode"));
2765#endif
2766 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
2767 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
2768#ifdef FEAT_GUI
2769 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
2770#endif
2771 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
2772 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
2773 main_msg(_("-O[N]\t\tLike -o but split vertically"));
2774 main_msg(_("+\t\t\tStart at end of file"));
2775 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002776 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002777 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
2778 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
2779 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
2780 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
2781 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
2782#ifdef FEAT_CRYPT
2783 main_msg(_("-x\t\t\tEdit encrypted files"));
2784#endif
2785#if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
2786# if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
2787 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
2788# endif
2789 main_msg(_("-X\t\t\tDo not connect to X server"));
2790#endif
2791#ifdef FEAT_CLIENTSERVER
2792 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
2793 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
2794 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
2795 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
2796 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
2797 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
2798 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
2799 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
2800#endif
2801#ifdef FEAT_VIMINFO
2802 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
2803#endif
2804 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
2805 main_msg(_("--version\t\tPrint version information and exit"));
2806
2807#ifdef FEAT_GUI_X11
2808# ifdef FEAT_GUI_MOTIF
2809 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
2810# else
2811# ifdef FEAT_GUI_ATHENA
2812# ifdef FEAT_GUI_NEXTAW
2813 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
2814# else
2815 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
2816# endif
2817# endif
2818# endif
2819 main_msg(_("-display <display>\tRun vim on <display>"));
2820 main_msg(_("-iconic\t\tStart vim iconified"));
2821# if 0
2822 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
2823 mch_msg(_("\t\t\t (Unimplemented)\n"));
2824# endif
2825 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
2826 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
2827 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2828 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
2829 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
2830 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2831 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
2832 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
2833# ifdef FEAT_GUI_ATHENA
2834 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
2835# endif
2836 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2837 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
2838 main_msg(_("-xrm <resource>\tSet the specified resource"));
2839#endif /* FEAT_GUI_X11 */
2840#if defined(FEAT_GUI) && defined(RISCOS)
2841 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
2842 main_msg(_("--columns <number>\tInitial width of window in columns"));
2843 main_msg(_("--rows <number>\tInitial height of window in rows"));
2844#endif
2845#ifdef FEAT_GUI_GTK
2846 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
2847 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2848 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2849 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
2850 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
2851# ifdef HAVE_GTK2
2852 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
2853# endif
2854 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
2855#endif
Bram Moolenaar843ee412004-06-30 16:16:41 +00002856#ifdef FEAT_GUI_KDE
2857 mch_msg(_("\nArguments recognised by kvim (KDE version):\n"));
2858 main_msg(_("-black\t\tUse reverse video"));
2859#if QT_VERSION>=300
2860 main_msg(_("-tip\t\t\tDisplay the tip dialog on startup"));
2861 main_msg(_("-notip\t\tDisable the tip dialog"));
2862#endif
2863 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
2864 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
2865 main_msg(_("--display <display>\tRun vim on <display>"));
2866#endif
Bram Moolenaarb4210b32004-06-13 14:51:16 +00002867#ifdef FEAT_GUI_W32
2868 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
2869#endif
2870
2871#ifdef FEAT_GUI_GNOME
2872 /* Gnome gives extra messages for --help if we continue, but not for -h. */
2873 if (gui.starting)
2874 mch_msg("\n");
2875 else
2876#endif
2877 mch_exit(0);
2878}
2879
2880#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2881/*
2882 * Check the result of the ATTENTION dialog:
2883 * When "Quit" selected, exit Vim.
2884 * When "Recover" selected, recover the file.
2885 */
2886 static void
2887check_swap_exists_action()
2888{
2889 if (swap_exists_action == SEA_QUIT)
2890 getout(1);
2891 handle_swap_exists(NULL);
2892}
2893#endif
2894
2895#if defined(STARTUPTIME) || defined(PROTO)
2896static void time_diff __ARGS((struct timeval *then, struct timeval *now));
2897
2898static struct timeval prev_timeval;
2899
2900/*
2901 * Save the previous time before doing something that could nest.
2902 * set "*tv_rel" to the time elapsed so far.
2903 */
2904 void
2905time_push(tv_rel, tv_start)
2906 void *tv_rel, *tv_start;
2907{
2908 *((struct timeval *)tv_rel) = prev_timeval;
2909 gettimeofday(&prev_timeval, NULL);
2910 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
2911 - ((struct timeval *)tv_rel)->tv_usec;
2912 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
2913 - ((struct timeval *)tv_rel)->tv_sec;
2914 if (((struct timeval *)tv_rel)->tv_usec < 0)
2915 {
2916 ((struct timeval *)tv_rel)->tv_usec += 1000000;
2917 --((struct timeval *)tv_rel)->tv_sec;
2918 }
2919 *(struct timeval *)tv_start = prev_timeval;
2920}
2921
2922/*
2923 * Compute the previous time after doing something that could nest.
2924 * Subtract "*tp" from prev_timeval;
2925 * Note: The arguments are (void *) to avoid trouble with systems that don't
2926 * have struct timeval.
2927 */
2928 void
2929time_pop(tp)
2930 void *tp; /* actually (struct timeval *) */
2931{
2932 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
2933 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
2934 if (prev_timeval.tv_usec < 0)
2935 {
2936 prev_timeval.tv_usec += 1000000;
2937 --prev_timeval.tv_sec;
2938 }
2939}
2940
2941 static void
2942time_diff(then, now)
2943 struct timeval *then;
2944 struct timeval *now;
2945{
2946 long usec;
2947 long msec;
2948
2949 usec = now->tv_usec - then->tv_usec;
2950 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
2951 usec = usec % 1000L;
2952 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
2953}
2954
2955 void
2956time_msg(msg, tv_start)
2957 char *msg;
2958 void *tv_start; /* only for do_source: start time; actually
2959 (struct timeval *) */
2960{
2961 static struct timeval start;
2962 struct timeval now;
2963
2964 if (time_fd != NULL)
2965 {
2966 if (strstr(msg, "STARTING") != NULL)
2967 {
2968 gettimeofday(&start, NULL);
2969 prev_timeval = start;
2970 fprintf(time_fd, "\n\ntimes in msec\n");
2971 fprintf(time_fd, " clock self+sourced self: sourced script\n");
2972 fprintf(time_fd, " clock elapsed: other lines\n\n");
2973 }
2974 gettimeofday(&now, NULL);
2975 time_diff(&start, &now);
2976 if (((struct timeval *)tv_start) != NULL)
2977 {
2978 fprintf(time_fd, " ");
2979 time_diff(((struct timeval *)tv_start), &now);
2980 }
2981 fprintf(time_fd, " ");
2982 time_diff(&prev_timeval, &now);
2983 prev_timeval = now;
2984 fprintf(time_fd, ": %s\n", msg);
2985 }
2986}
2987
2988# ifdef WIN3264
2989/*
2990 * Windows doesn't have gettimeofday(), although it does have struct timeval.
2991 */
2992 int
2993gettimeofday(struct timeval *tv, char *dummy)
2994{
2995 long t = clock();
2996 tv->tv_sec = t / CLOCKS_PER_SEC;
2997 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
2998 return 0;
2999}
3000# endif
3001
3002#endif
3003
3004#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3005
3006/*
3007 * Common code for the X command server and the Win32 command server.
3008 */
3009
3010static char_u *build_drop_cmd __ARGS((int filec, char **filev, int sendReply));
3011
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003012/*
3013 * Do the client-server stuff, unless "--servername ''" was used.
3014 */
3015 static void
3016exec_on_server(parmp)
3017 mparm_T *parmp;
3018{
3019 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3020 {
3021# ifdef WIN32
3022 /* Initialise the client/server messaging infrastructure. */
3023 serverInitMessaging();
3024# endif
3025
3026 /*
3027 * When a command server argument was found, execute it. This may
3028 * exit Vim when it was successful. Otherwise it's executed further
3029 * on. Remember the encoding used here in "serverStrEnc".
3030 */
3031 if (parmp->serverArg)
3032 {
3033 cmdsrv_main(&parmp->argc, parmp->argv,
3034 parmp->serverName_arg, &parmp->serverStr);
3035# ifdef FEAT_MBYTE
3036 parmp->serverStrEnc = vim_strsave(p_enc);
3037# endif
3038 }
3039
3040 /* If we're still running, get the name to register ourselves.
3041 * On Win32 can register right now, for X11 need to setup the
3042 * clipboard first, it's further down. */
3043 parmp->servername = serverMakeName(parmp->serverName_arg,
3044 parmp->argv[0]);
3045# ifdef WIN32
3046 if (parmp->servername != NULL)
3047 {
3048 serverSetName(parmp->servername);
3049 vim_free(parmp->servername);
3050 }
3051# endif
3052 }
3053}
3054
3055/*
3056 * Prepare for running as a Vim server.
3057 */
3058 static void
3059prepare_server(parmp)
3060 mparm_T *parmp;
3061{
3062# if defined(FEAT_X11)
3063 /*
3064 * Register for remote command execution with :serversend and --remote
3065 * unless there was a -X or a --servername '' on the command line.
3066 * Only register nongui-vim's with an explicit --servername argument.
3067 */
3068 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3069# ifdef FEAT_GUI
3070 gui.in_use ||
3071# endif
3072 parmp->serverName_arg != NULL))
3073 {
3074 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3075 vim_free(parmp->servername);
3076 TIME_MSG("register server name");
3077 }
3078 else
3079 serverDelayedStartName = parmp->servername;
3080# endif
3081
3082 /*
3083 * Execute command ourselves if we're here because the send failed (or
3084 * else we would have exited above).
3085 */
3086 if (parmp->serverStr != NULL)
3087 {
3088 char_u *p;
3089
3090 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3091 parmp->serverStr, &p));
3092 vim_free(p);
3093 }
3094}
3095
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003096 static void
3097cmdsrv_main(argc, argv, serverName_arg, serverStr)
3098 int *argc;
3099 char **argv;
3100 char_u *serverName_arg;
3101 char_u **serverStr;
3102{
3103 char_u *res;
3104 int i;
3105 char_u *sname;
3106 int ret;
3107 int didone = FALSE;
3108 int exiterr = 0;
3109 char **newArgV = argv + 1;
3110 int newArgC = 1,
3111 Argc = *argc;
3112 int argtype;
3113#define ARGTYPE_OTHER 0
3114#define ARGTYPE_EDIT 1
3115#define ARGTYPE_EDIT_WAIT 2
3116#define ARGTYPE_SEND 3
3117 int silent = FALSE;
3118# ifndef FEAT_X11
3119 HWND srv;
3120# else
3121 Window srv;
3122
3123 setup_term_clip();
3124# endif
3125
3126 sname = serverMakeName(serverName_arg, argv[0]);
3127 if (sname == NULL)
3128 return;
3129
3130 /*
3131 * Execute the command server related arguments and remove them
3132 * from the argc/argv array; We may have to return into main()
3133 */
3134 for (i = 1; i < Argc; i++)
3135 {
3136 res = NULL;
Bram Moolenaarc013cb62005-07-24 21:18:31 +00003137 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003138 {
3139 for (; i < *argc; i++)
3140 {
3141 *newArgV++ = argv[i];
3142 newArgC++;
3143 }
3144 break;
3145 }
3146
3147 if (STRICMP(argv[i], "--remote") == 0)
3148 argtype = ARGTYPE_EDIT;
3149 else if (STRICMP(argv[i], "--remote-silent") == 0)
3150 {
3151 argtype = ARGTYPE_EDIT;
3152 silent = TRUE;
3153 }
3154 else if (STRICMP(argv[i], "--remote-wait") == 0)
3155 argtype = ARGTYPE_EDIT_WAIT;
3156 else if (STRICMP(argv[i], "--remote-wait-silent") == 0)
3157 {
3158 argtype = ARGTYPE_EDIT_WAIT;
3159 silent = TRUE;
3160 }
3161 else if (STRICMP(argv[i], "--remote-send") == 0)
3162 argtype = ARGTYPE_SEND;
3163 else
3164 argtype = ARGTYPE_OTHER;
3165 if (argtype != ARGTYPE_OTHER)
3166 {
3167 if (i == *argc - 1)
3168 mainerr_arg_missing((char_u *)argv[i]);
3169 if (argtype == ARGTYPE_SEND)
3170 {
3171 *serverStr = (char_u *)argv[i + 1];
3172 i++;
3173 }
3174 else
3175 {
3176 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3177 argtype == ARGTYPE_EDIT_WAIT);
3178 if (*serverStr == NULL)
3179 {
3180 /* Probably out of memory, exit. */
3181 didone = TRUE;
3182 exiterr = 1;
3183 break;
3184 }
3185 Argc = i;
3186 }
3187# ifdef FEAT_X11
3188 if (xterm_dpy == NULL)
3189 {
3190 mch_errmsg(_("No display"));
3191 ret = -1;
3192 }
3193 else
3194 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3195 NULL, &srv, 0, 0, silent);
3196# else
3197 /* Win32 always works? */
3198 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3199# endif
3200 if (ret < 0)
3201 {
3202 if (argtype == ARGTYPE_SEND)
3203 {
3204 /* Failed to send, abort. */
3205 mch_errmsg(_(": Send failed.\n"));
3206 didone = TRUE;
3207 exiterr = 1;
3208 }
3209 else if (!silent)
3210 /* Let vim start normally. */
3211 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3212 break;
3213 }
3214
3215# ifdef FEAT_GUI_W32
3216 /* Guess that when the server name starts with "g" it's a GUI
3217 * server, which we can bring to the foreground here.
3218 * Foreground() in the server doesn't work very well. */
3219 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3220 SetForegroundWindow(srv);
3221# endif
3222
3223 /*
3224 * For --remote-wait: Wait until the server did edit each
3225 * file. Also detect that the server no longer runs.
3226 */
3227 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3228 {
3229 int numFiles = *argc - i - 1;
3230 int j;
3231 char_u *done = alloc(numFiles);
3232 char_u *p;
3233# ifdef FEAT_GUI_W32
3234 NOTIFYICONDATA ni;
3235 int count = 0;
3236 extern HWND message_window;
3237# endif
3238
3239 if (numFiles > 0 && argv[i + 1][0] == '+')
3240 /* Skip "+cmd" argument, don't wait for it to be edited. */
3241 --numFiles;
3242
3243# ifdef FEAT_GUI_W32
3244 ni.cbSize = sizeof(ni);
3245 ni.hWnd = message_window;
3246 ni.uID = 0;
3247 ni.uFlags = NIF_ICON|NIF_TIP;
3248 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3249 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3250 Shell_NotifyIcon(NIM_ADD, &ni);
3251# endif
3252
3253 /* Wait for all files to unload in remote */
3254 memset(done, 0, numFiles);
3255 while (memchr(done, 0, numFiles) != NULL)
3256 {
3257# ifdef WIN32
3258 p = serverGetReply(srv, NULL, TRUE, TRUE);
3259 if (p == NULL)
3260 break;
3261# else
3262 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3263 break;
3264# endif
3265 j = atoi((char *)p);
3266 if (j >= 0 && j < numFiles)
3267 {
3268# ifdef FEAT_GUI_W32
3269 ++count;
3270 sprintf(ni.szTip, _("%d of %d edited"),
3271 count, numFiles);
3272 Shell_NotifyIcon(NIM_MODIFY, &ni);
3273# endif
3274 done[j] = 1;
3275 }
3276 }
3277# ifdef FEAT_GUI_W32
3278 Shell_NotifyIcon(NIM_DELETE, &ni);
3279# endif
3280 }
3281 }
3282 else if (STRICMP(argv[i], "--remote-expr") == 0)
3283 {
3284 if (i == *argc - 1)
3285 mainerr_arg_missing((char_u *)argv[i]);
3286# ifdef WIN32
3287 /* Win32 always works? */
3288 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3289 &res, NULL, 1, FALSE) < 0)
3290# else
3291 if (xterm_dpy == NULL)
3292 mch_errmsg(_("No display: Send expression failed.\n"));
3293 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3294 &res, NULL, 1, 1, FALSE) < 0)
3295# endif
3296 {
3297 if (res != NULL && *res != NUL)
3298 {
3299 /* Output error from remote */
3300 mch_errmsg((char *)res);
3301 vim_free(res);
3302 res = NULL;
3303 }
3304 mch_errmsg(_(": Send expression failed.\n"));
3305 }
3306 }
3307 else if (STRICMP(argv[i], "--serverlist") == 0)
3308 {
3309# ifdef WIN32
3310 /* Win32 always works? */
3311 res = serverGetVimNames();
3312# else
3313 if (xterm_dpy != NULL)
3314 res = serverGetVimNames(xterm_dpy);
3315# endif
3316 if (called_emsg)
3317 mch_errmsg("\n");
3318 }
3319 else if (STRICMP(argv[i], "--servername") == 0)
3320 {
3321 /* Alredy processed. Take it out of the command line */
3322 i++;
3323 continue;
3324 }
3325 else
3326 {
3327 *newArgV++ = argv[i];
3328 newArgC++;
3329 continue;
3330 }
3331 didone = TRUE;
3332 if (res != NULL && *res != NUL)
3333 {
3334 mch_msg((char *)res);
3335 if (res[STRLEN(res) - 1] != '\n')
3336 mch_msg("\n");
3337 }
3338 vim_free(res);
3339 }
3340
3341 if (didone)
3342 {
3343 display_errors(); /* display any collected messages */
3344 exit(exiterr); /* Mission accomplished - get out */
3345 }
3346
3347 /* Return back into main() */
3348 *argc = newArgC;
3349 vim_free(sname);
3350}
3351
3352/*
3353 * Build a ":drop" command to send to a Vim server.
3354 */
3355 static char_u *
3356build_drop_cmd(filec, filev, sendReply)
3357 int filec;
3358 char **filev;
3359 int sendReply;
3360{
3361 garray_T ga;
3362 int i;
3363 char_u *inicmd = NULL;
3364 char_u *p;
3365 char_u cwd[MAXPATHL];
3366
3367 if (filec > 0 && filev[0][0] == '+')
3368 {
3369 inicmd = (char_u *)filev[0] + 1;
3370 filev++;
3371 filec--;
3372 }
3373 /* Check if we have at least one argument. */
3374 if (filec <= 0)
3375 mainerr_arg_missing((char_u *)filev[-1]);
3376 if (mch_dirname(cwd, MAXPATHL) != OK)
3377 return NULL;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003378 if ((p = vim_strsave_escaped_ext(cwd, PATH_ESC_CHARS, '\\', TRUE)) == NULL)
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003379 return NULL;
3380 ga_init2(&ga, 1, 100);
3381 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3382 ga_concat(&ga, p);
3383 /* Call inputsave() so that a prompt for an encryption key works. */
3384 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|drop");
3385 vim_free(p);
3386 for (i = 0; i < filec; i++)
3387 {
3388 /* On Unix the shell has already expanded the wildcards, don't want to
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003389 * do it again in the Vim server. On MS-Windows only escape
3390 * non-wildcard characters. */
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003391 p = vim_strsave_escaped((char_u *)filev[i],
3392#ifdef UNIX
3393 PATH_ESC_CHARS
3394#else
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00003395 (char_u *)" \t%#"
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003396#endif
3397 );
3398 if (p == NULL)
3399 {
3400 vim_free(ga.ga_data);
3401 return NULL;
3402 }
3403 ga_concat(&ga, (char_u *)" ");
3404 ga_concat(&ga, p);
3405 vim_free(p);
3406 }
3407 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3408 * CTRL-\ CTRL-N again. */
3409 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3410 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3411 if (sendReply)
3412 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3413 ga_concat(&ga, (char_u *)"<CR>:");
3414 if (inicmd != NULL)
3415 {
3416 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3417 * the following commands to be inserted as text. Use a "|",
3418 * hopefully "inicmd" does allow this... */
3419 ga_concat(&ga, inicmd);
3420 ga_concat(&ga, (char_u *)"|");
3421 }
3422 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3423 * clear command line. */
Bram Moolenaar567e4de2004-12-31 21:01:02 +00003424 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003425 ga_append(&ga, NUL);
3426 return ga.ga_data;
3427}
3428
3429/*
3430 * Replace termcodes such as <CR> and insert as key presses if there is room.
3431 */
3432 void
3433server_to_input_buf(str)
3434 char_u *str;
3435{
3436 char_u *ptr = NULL;
3437 char_u *cpo_save = p_cpo;
3438
3439 /* Set 'cpoptions' the way we want it.
3440 * B set - backslashes are *not* treated specially
3441 * k set - keycodes are *not* reverse-engineered
3442 * < unset - <Key> sequences *are* interpreted
3443 * The last parameter of replace_termcodes() is TRUE so that the <lt>
3444 * sequence is recognised - needed for a real backslash.
3445 */
3446 p_cpo = (char_u *)"Bk";
3447 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE);
3448 p_cpo = cpo_save;
3449
3450 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3451 {
3452 /*
3453 * Add the string to the input stream.
3454 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3455 *
3456 * First clear typed characters from the typeahead buffer, there could
3457 * be half a mapping there. Then append to the existing string, so
3458 * that multiple commands from a client are concatenated.
3459 */
3460 if (typebuf.tb_maplen < typebuf.tb_len)
3461 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3462 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3463
3464 /* Let input_available() know we inserted text in the typeahead
3465 * buffer. */
3466 received_from_client = TRUE;
3467 }
3468 vim_free((char_u *)ptr);
3469}
3470
3471/*
3472 * Evaluate an expression that the client sent to a string.
3473 * Handles disabling error messages and disables debugging, otherwise Vim
3474 * hangs, waiting for "cont" to be typed.
3475 */
3476 char_u *
3477eval_client_expr_to_string(expr)
3478 char_u *expr;
3479{
3480 char_u *res;
3481 int save_dbl = debug_break_level;
3482 int save_ro = redir_off;
3483
3484 debug_break_level = -1;
3485 redir_off = 0;
3486 ++emsg_skip;
3487
3488 res = eval_to_string(expr, NULL);
3489
3490 debug_break_level = save_dbl;
3491 redir_off = save_ro;
3492 --emsg_skip;
3493
3494 return res;
3495}
3496
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003497/*
3498 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3499 * return an allocated string. Otherwise return "data".
3500 * "*tofree" is set to the result when it needs to be freed later.
3501 */
3502/*ARGSUSED*/
3503 char_u *
3504serverConvert(client_enc, data, tofree)
3505 char_u *client_enc;
3506 char_u *data;
3507 char_u **tofree;
3508{
3509 char_u *res = data;
3510
3511 *tofree = NULL;
3512# ifdef FEAT_MBYTE
3513 if (client_enc != NULL && p_enc != NULL)
3514 {
3515 vimconv_T vimconv;
3516
3517 vimconv.vc_type = CONV_NONE;
3518 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3519 && vimconv.vc_type != CONV_NONE)
3520 {
3521 res = string_convert(&vimconv, data, NULL);
3522 if (res == NULL)
3523 res = data;
3524 else
3525 *tofree = res;
3526 }
3527 convert_setup(&vimconv, NULL, NULL);
3528 }
3529# endif
3530 return res;
3531}
3532
Bram Moolenaarb4210b32004-06-13 14:51:16 +00003533
3534/*
3535 * Make our basic server name: use the specified "arg" if given, otherwise use
3536 * the tail of the command "cmd" we were started with.
3537 * Return the name in allocated memory. This doesn't include a serial number.
3538 */
3539 static char_u *
3540serverMakeName(arg, cmd)
3541 char_u *arg;
3542 char *cmd;
3543{
3544 char_u *p;
3545
3546 if (arg != NULL && *arg != NUL)
3547 p = vim_strsave_up(arg);
3548 else
3549 {
3550 p = vim_strsave_up(gettail((char_u *)cmd));
3551 /* Remove .exe or .bat from the name. */
3552 if (p != NULL && vim_strchr(p, '.') != NULL)
3553 *vim_strchr(p, '.') = NUL;
3554 }
3555 return p;
3556}
3557#endif /* FEAT_CLIENTSERVER */
3558
3559/*
3560 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3561 */
3562#if defined(FEAT_FKMAP) || defined(PROTO)
3563# include "farsi.c"
3564#endif
3565
3566/*
3567 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3568 */
3569#if defined(FEAT_ARABIC) || defined(PROTO)
3570# include "arabic.c"
3571#endif