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