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