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