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