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