Merged from the latest developing branch.
[MacVim.git] / src / main.c
blob13707ce11096dfc803e91913510526398815a9db
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
10 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
11 # include "vimio.h" /* for close() and dup() */
12 #endif
14 #define EXTERN
15 #include "vim.h"
17 #ifdef SPAWNO
18 # include <spawno.h> /* special MS-DOS swapping library */
19 #endif
21 #ifdef __CYGWIN__
22 # ifndef WIN32
23 # include <cygwin/version.h>
24 # include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
25 * cygwin_conv_path() */
26 # endif
27 # include <limits.h>
28 #endif
30 /* Maximum number of commands from + or -c arguments. */
31 #define MAX_ARG_CMDS 10
33 /* values for "window_layout" */
34 #define WIN_HOR 1 /* "-o" horizontally split windows */
35 #define WIN_VER 2 /* "-O" vertically split windows */
36 #define WIN_TABS 3 /* "-p" windows on tab pages */
38 /* Struct for various parameters passed between main() and other functions. */
39 typedef struct
41 int argc;
42 char **argv;
44 int evim_mode; /* started as "evim" */
45 char_u *use_vimrc; /* vimrc from -u argument */
47 int n_commands; /* no. of commands from + or -c */
48 char_u *commands[MAX_ARG_CMDS]; /* commands from + or -c arg. */
49 char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
50 int n_pre_commands; /* no. of commands from --cmd */
51 char_u *pre_commands[MAX_ARG_CMDS]; /* commands from --cmd argument */
53 int edit_type; /* type of editing to do */
54 char_u *tagname; /* tag from -t argument */
55 #ifdef FEAT_QUICKFIX
56 char_u *use_ef; /* 'errorfile' from -q argument */
57 #endif
59 int want_full_screen;
60 int stdout_isatty; /* is stdout a terminal? */
61 char_u *term; /* specified terminal name */
62 #ifdef FEAT_CRYPT
63 int ask_for_key; /* -x argument */
64 #endif
65 int no_swap_file; /* "-n" argument used */
66 #ifdef FEAT_EVAL
67 int use_debug_break_level;
68 #endif
69 #ifdef FEAT_WINDOWS
70 int window_count; /* number of windows to use */
71 int window_layout; /* 0, WIN_HOR, WIN_VER or WIN_TABS */
72 #endif
74 #ifdef FEAT_CLIENTSERVER
75 int serverArg; /* TRUE when argument for a server */
76 char_u *serverName_arg; /* cmdline arg for server name */
77 char_u *serverStr; /* remote server command */
78 char_u *serverStrEnc; /* encoding of serverStr */
79 char_u *servername; /* allocated name for our server */
80 #endif
81 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
82 int literal; /* don't expand file names */
83 #endif
84 #ifdef MSWIN
85 int full_path; /* file name argument was full path */
86 #endif
87 #ifdef FEAT_DIFF
88 int diff_mode; /* start with 'diff' set */
89 #endif
90 } mparm_T;
92 /* Values for edit_type. */
93 #define EDIT_NONE 0 /* no edit type yet */
94 #define EDIT_FILE 1 /* file name argument[s] given, use argument list */
95 #define EDIT_STDIN 2 /* read file from stdin */
96 #define EDIT_TAG 3 /* tag name argument given, use tagname */
97 #define EDIT_QF 4 /* start in quickfix mode */
99 #if defined(UNIX) || defined(VMS)
100 static int file_owned __ARGS((char *fname));
101 #endif
102 static void mainerr __ARGS((int, char_u *));
103 static void main_msg __ARGS((char *s));
104 static void usage __ARGS((void));
105 static int get_number_arg __ARGS((char_u *p, int *idx, int def));
106 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
107 static void init_locale __ARGS((void));
108 #endif
109 static void parse_command_name __ARGS((mparm_T *parmp));
110 static void early_arg_scan __ARGS((mparm_T *parmp));
111 static void command_line_scan __ARGS((mparm_T *parmp));
112 static void check_tty __ARGS((mparm_T *parmp));
113 static void read_stdin __ARGS((void));
114 static void create_windows __ARGS((mparm_T *parmp));
115 #ifdef FEAT_WINDOWS
116 static void edit_buffers __ARGS((mparm_T *parmp));
117 #endif
118 static void exe_pre_commands __ARGS((mparm_T *parmp));
119 static void exe_commands __ARGS((mparm_T *parmp));
120 static void source_startup_scripts __ARGS((mparm_T *parmp));
121 static void main_start_gui __ARGS((void));
122 #if defined(HAS_SWAP_EXISTS_ACTION)
123 static void check_swap_exists_action __ARGS((void));
124 #endif
125 #ifdef FEAT_CLIENTSERVER
126 static void exec_on_server __ARGS((mparm_T *parmp));
127 static void prepare_server __ARGS((mparm_T *parmp));
128 static void cmdsrv_main __ARGS((int *argc, char **argv, char_u *serverName_arg, char_u **serverStr));
129 static char_u *serverMakeName __ARGS((char_u *arg, char *cmd));
130 #endif
134 * Different types of error messages.
136 static char *(main_errors[]) =
138 N_("Unknown option argument"),
139 #define ME_UNKNOWN_OPTION 0
140 N_("Too many edit arguments"),
141 #define ME_TOO_MANY_ARGS 1
142 N_("Argument missing after"),
143 #define ME_ARG_MISSING 2
144 N_("Garbage after option argument"),
145 #define ME_GARBAGE 3
146 N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments"),
147 #define ME_EXTRA_CMD 4
148 N_("Invalid argument for"),
149 #define ME_INVALID_ARG 5
152 #ifndef PROTO /* don't want a prototype for main() */
154 # ifdef VIMDLL
155 _export
156 # endif
157 # ifdef FEAT_GUI_MSWIN
158 # ifdef __BORLANDC__
159 _cdecl
160 # endif
161 VimMain
162 # else
163 main
164 # endif
165 (argc, argv)
166 int argc;
167 char **argv;
169 char_u *fname = NULL; /* file name from command line */
170 mparm_T params; /* various parameters passed between
171 * main() and other functions. */
172 #ifdef STARTUPTIME
173 int i;
174 #endif
177 * Do any system-specific initialisations. These can NOT use IObuff or
178 * NameBuff. Thus emsg2() cannot be called!
180 mch_early_init();
182 /* Many variables are in "params" so that we can pass them to invoked
183 * functions without a lot of arguments. "argc" and "argv" are also
184 * copied, so that they can be changed. */
185 vim_memset(&params, 0, sizeof(params));
186 params.argc = argc;
187 params.argv = argv;
188 params.want_full_screen = TRUE;
189 #ifdef FEAT_EVAL
190 params.use_debug_break_level = -1;
191 #endif
192 #ifdef FEAT_WINDOWS
193 params.window_count = -1;
194 #endif
196 #ifdef FEAT_TCL
197 vim_tcl_init(params.argv[0]);
198 #endif
200 #ifdef MEM_PROFILE
201 atexit(vim_mem_profile_dump);
202 #endif
204 #ifdef STARTUPTIME
205 for (i = 1; i < argc; ++i)
207 if (STRICMP(argv[i], "--startuptime") == 0 && i + 1 < argc)
209 time_fd = mch_fopen(argv[i + 1], "a");
210 TIME_MSG("--- VIM STARTING ---");
211 break;
214 #endif
215 starttime = time(NULL);
217 #ifdef __EMX__
218 _wildcard(&params.argc, &params.argv);
219 #endif
221 #ifdef FEAT_MBYTE
222 (void)mb_init(); /* init mb_bytelen_tab[] to ones */
223 #endif
224 #ifdef FEAT_EVAL
225 eval_init(); /* init global variables */
226 #endif
228 #ifdef __QNXNTO__
229 qnx_init(); /* PhAttach() for clipboard, (and gui) */
230 #endif
232 #ifdef MAC_OS_CLASSIC
233 /* Prepare for possibly starting GUI sometime */
234 /* Macintosh needs this before any memory is allocated. */
235 gui_prepare(&params.argc, params.argv);
236 TIME_MSG("GUI prepared");
237 #endif
239 /* Init the table of Normal mode commands. */
240 init_normal_cmds();
242 #if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC)
243 make_version(); /* Construct the long version string. */
244 #endif
247 * Allocate space for the generic buffers (needed for set_init_1() and
248 * EMSG2()).
250 if ((IObuff = alloc(IOSIZE)) == NULL
251 || (NameBuff = alloc(MAXPATHL)) == NULL)
252 mch_exit(0);
253 TIME_MSG("Allocated generic buffers");
255 #ifdef NBDEBUG
256 /* Wait a moment for debugging NetBeans. Must be after allocating
257 * NameBuff. */
258 nbdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL");
259 nbdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20);
260 TIME_MSG("NetBeans debug wait");
261 #endif
263 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
265 * Setup to use the current locale (for ctype() and many other things).
266 * NOTE: Translated messages with encodings other than latin1 will not
267 * work until set_init_1() has been called!
269 init_locale();
270 TIME_MSG("locale set");
271 #endif
273 #ifdef FEAT_GUI
274 gui.dofork = TRUE; /* default is to use fork() */
275 #endif
278 * Do a first scan of the arguments in "argv[]":
279 * -display or --display
280 * --server...
281 * --socketid
282 * --windowid
284 early_arg_scan(&params);
286 #ifdef FEAT_SUN_WORKSHOP
287 findYourself(params.argv[0]);
288 #endif
289 #if defined(FEAT_GUI) && !defined(MAC_OS_CLASSIC)
290 /* Prepare for possibly starting GUI sometime */
291 gui_prepare(&params.argc, params.argv);
292 TIME_MSG("GUI prepared");
293 #endif
295 #ifdef FEAT_CLIPBOARD
296 clip_init(FALSE); /* Initialise clipboard stuff */
297 TIME_MSG("clipboard setup");
298 #endif
301 * Check if we have an interactive window.
302 * On the Amiga: If there is no window, we open one with a newcli command
303 * (needed for :! to * work). mch_check_win() will also handle the -d or
304 * -dev argument.
306 params.stdout_isatty = (mch_check_win(params.argc, params.argv) != FAIL);
307 TIME_MSG("window checked");
310 * Allocate the first window and buffer.
311 * Can't do anything without it, exit when it fails.
313 if (win_alloc_first() == FAIL)
314 mch_exit(0);
316 init_yank(); /* init yank buffers */
318 alist_init(&global_alist); /* Init the argument list to empty. */
321 * Set the default values for the options.
322 * NOTE: Non-latin1 translated messages are working only after this,
323 * because this is where "has_mbyte" will be set, which is used by
324 * msg_outtrans_len_attr().
325 * First find out the home directory, needed to expand "~" in options.
327 init_homedir(); /* find real value of $HOME */
328 set_init_1();
329 TIME_MSG("inits 1");
331 #ifdef FEAT_EVAL
332 set_lang_var(); /* set v:lang and v:ctype */
333 #endif
335 #ifdef FEAT_CLIENTSERVER
337 * Do the client-server stuff, unless "--servername ''" was used.
338 * This may exit Vim if the command was sent to the server.
340 exec_on_server(&params);
341 #endif
344 * Figure out the way to work from the command name argv[0].
345 * "vimdiff" starts diff mode, "rvim" sets "restricted", etc.
347 parse_command_name(&params);
350 * Process the command line arguments. File names are put in the global
351 * argument list "global_alist".
353 command_line_scan(&params);
354 TIME_MSG("parsing arguments");
357 * On some systems, when we compile with the GUI, we always use it. On Mac
358 * there is no terminal version, and on Windows we can't fork one off with
359 * :gui.
361 #ifdef ALWAYS_USE_GUI
362 gui.starting = TRUE;
363 #else
364 # if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
366 * Check if the GUI can be started. Reset gui.starting if not.
367 * Don't know about other systems, stay on the safe side and don't check.
369 if (gui.starting && gui_init_check() == FAIL)
371 gui.starting = FALSE;
373 /* When running "evim" or "gvim -y" we need the menus, exit if we
374 * don't have them. */
375 if (params.evim_mode)
376 mch_exit(1);
378 # endif
379 #endif
381 if (GARGCOUNT > 0)
383 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
385 * Expand wildcards in file names.
387 if (!params.literal)
389 /* Temporarily add '(' and ')' to 'isfname'. These are valid
390 * filename characters but are excluded from 'isfname' to make
391 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
392 do_cmdline_cmd((char_u *)":set isf+=(,)");
393 alist_expand(NULL, 0);
394 do_cmdline_cmd((char_u *)":set isf&");
396 #endif
397 fname = alist_name(&GARGLIST[0]);
400 #if defined(WIN32) && defined(FEAT_MBYTE)
402 extern void set_alist_count(void);
404 /* Remember the number of entries in the argument list. If it changes
405 * we don't react on setting 'encoding'. */
406 set_alist_count();
408 #endif
410 #ifdef MSWIN
411 if (GARGCOUNT == 1 && params.full_path)
414 * If there is one filename, fully qualified, we have very probably
415 * been invoked from explorer, so change to the file's directory.
416 * Hint: to avoid this when typing a command use a forward slash.
417 * If the cd fails, it doesn't matter.
419 (void)vim_chdirfile(fname);
421 #endif
422 TIME_MSG("expanding arguments");
424 #ifdef FEAT_DIFF
425 if (params.diff_mode && params.window_count == -1)
426 params.window_count = 0; /* open up to 3 windows */
427 #endif
429 /* Don't redraw until much later. */
430 ++RedrawingDisabled;
433 * When listing swap file names, don't do cursor positioning et. al.
435 if (recoverymode && fname == NULL)
436 params.want_full_screen = FALSE;
439 * When certain to start the GUI, don't check capabilities of terminal.
440 * For GTK we can't be sure, but when started from the desktop it doesn't
441 * make sense to try using a terminal.
443 #if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
444 if (gui.starting
445 # ifdef FEAT_GUI_GTK
446 && !isatty(2)
447 # endif
449 params.want_full_screen = FALSE;
450 #endif
452 #if defined(FEAT_GUI_MAC) && defined(MACOS_X_UNIX)
453 /* When the GUI is started from Finder, need to display messages in a
454 * message box. isatty(2) returns TRUE anyway, thus we need to check the
455 * name to know we're not started from a terminal. */
456 if (gui.starting && (!isatty(2) || strcmp("/dev/console", ttyname(2)) == 0))
458 params.want_full_screen = FALSE;
460 /* Avoid always using "/" as the current directory. Note that when
461 * started from Finder the arglist will be filled later in
462 * HandleODocAE() and "fname" will be NULL. */
463 if (getcwd((char *)NameBuff, MAXPATHL) != NULL
464 && STRCMP(NameBuff, "/") == 0)
466 if (fname != NULL)
467 (void)vim_chdirfile(fname);
468 else
470 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
471 vim_chdir(NameBuff);
475 #endif
478 * mch_init() sets up the terminal (window) for use. This must be
479 * done after resetting full_screen, otherwise it may move the cursor
480 * (MSDOS).
481 * Note that we may use mch_exit() before mch_init()!
483 mch_init();
484 TIME_MSG("shell init");
486 #ifdef USE_XSMP
488 * For want of anywhere else to do it, try to connect to xsmp here.
489 * Fitting it in after gui_mch_init, but before gui_init (via termcapinit).
490 * Hijacking -X 'no X connection' to also disable XSMP connection as that
491 * has a similar delay upon failure.
492 * Only try if SESSION_MANAGER is set to something non-null.
494 if (!x_no_connect)
496 char *p = getenv("SESSION_MANAGER");
498 if (p != NULL && *p != NUL)
500 xsmp_init();
501 TIME_MSG("xsmp init");
504 #endif
507 * Print a warning if stdout is not a terminal.
509 check_tty(&params);
511 /* This message comes before term inits, but after setting "silent_mode"
512 * when the input is not a tty. */
513 if (GARGCOUNT > 1 && !silent_mode)
514 printf(_("%d files to edit\n"), GARGCOUNT);
516 if (params.want_full_screen && !silent_mode)
518 termcapinit(params.term); /* set terminal name and get terminal
519 capabilities (will set full_screen) */
520 screen_start(); /* don't know where cursor is now */
521 TIME_MSG("Termcap init");
525 * Set the default values for the options that use Rows and Columns.
527 ui_get_shellsize(); /* inits Rows and Columns */
528 #ifdef FEAT_NETBEANS_INTG
529 if (usingNetbeans)
530 Columns += 2; /* leave room for glyph gutter */
531 #endif
532 win_init_size();
533 #ifdef FEAT_DIFF
534 /* Set the 'diff' option now, so that it can be checked for in a .vimrc
535 * file. There is no buffer yet though. */
536 if (params.diff_mode)
537 diff_win_options(firstwin, FALSE);
538 #endif
540 cmdline_row = Rows - p_ch;
541 msg_row = cmdline_row;
542 screenalloc(FALSE); /* allocate screen buffers */
543 set_init_2();
544 TIME_MSG("inits 2");
546 msg_scroll = TRUE;
547 no_wait_return = TRUE;
549 init_mappings(); /* set up initial mappings */
551 init_highlight(TRUE, FALSE); /* set the default highlight groups */
552 TIME_MSG("init highlight");
554 #ifdef FEAT_EVAL
555 /* Set the break level after the terminal is initialized. */
556 debug_break_level = params.use_debug_break_level;
557 #endif
559 /* Execute --cmd arguments. */
560 exe_pre_commands(&params);
562 /* Source startup scripts. */
563 source_startup_scripts(&params);
565 #ifdef FEAT_EVAL
567 * Read all the plugin files.
568 * Only when compiled with +eval, since most plugins need it.
570 if (p_lpl)
572 # ifdef VMS /* Somehow VMS doesn't handle the "**". */
573 source_runtime((char_u *)"plugin/*.vim", TRUE);
574 # else
575 source_runtime((char_u *)"plugin/**/*.vim", TRUE);
576 # endif
577 TIME_MSG("loading plugins");
579 #endif
581 #ifdef FEAT_DIFF
582 /* Decide about window layout for diff mode after reading vimrc. */
583 if (params.diff_mode && params.window_layout == 0)
585 if (diffopt_horizontal())
586 params.window_layout = WIN_HOR; /* use horizontal split */
587 else
588 params.window_layout = WIN_VER; /* use vertical split */
590 #endif
593 * Recovery mode without a file name: List swap files.
594 * This uses the 'dir' option, therefore it must be after the
595 * initializations.
597 if (recoverymode && fname == NULL)
599 recover_names(NULL, TRUE, 0);
600 mch_exit(0);
604 * Set a few option defaults after reading .vimrc files:
605 * 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
607 set_init_3();
608 TIME_MSG("inits 3");
611 * "-n" argument: Disable swap file by setting 'updatecount' to 0.
612 * Note that this overrides anything from a vimrc file.
614 if (params.no_swap_file)
615 p_uc = 0;
617 #ifdef FEAT_FKMAP
618 if (curwin->w_p_rl && p_altkeymap)
620 p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
621 # ifdef FEAT_ARABIC
622 curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
623 # endif
624 p_fkmap = TRUE; /* Set the Farsi keymap mode */
626 #endif
628 #ifdef FEAT_GUI
629 if (gui.starting)
631 #if defined(UNIX) || defined(VMS)
632 /* When something caused a message from a vimrc script, need to output
633 * an extra newline before the shell prompt. */
634 if (did_emsg || msg_didout)
635 putchar('\n');
636 #endif
638 gui_start(); /* will set full_screen to TRUE */
639 TIME_MSG("starting GUI");
641 /* When running "evim" or "gvim -y" we need the menus, exit if we
642 * don't have them. */
643 if (!gui.in_use && params.evim_mode)
644 mch_exit(1);
646 #endif
648 #ifdef SPAWNO /* special MSDOS swapping library */
649 init_SPAWNO("", SWAP_ANY);
650 #endif
652 #ifdef FEAT_VIMINFO
654 * Read in registers, history etc, but not marks, from the viminfo file.
655 * This is where v:oldfiles gets filled.
657 if (*p_viminfo != NUL)
659 read_viminfo(NULL, VIF_WANT_INFO | VIF_GET_OLDFILES);
660 TIME_MSG("reading viminfo");
662 #endif
664 #ifdef FEAT_QUICKFIX
666 * "-q errorfile": Load the error file now.
667 * If the error file can't be read, exit before doing anything else.
669 if (params.edit_type == EDIT_QF)
671 if (params.use_ef != NULL)
672 set_string_option_direct((char_u *)"ef", -1,
673 params.use_ef, OPT_FREE, SID_CARG);
674 if (qf_init(NULL, p_ef, p_efm, TRUE) < 0)
676 out_char('\n');
677 mch_exit(3);
679 TIME_MSG("reading errorfile");
681 #endif
684 * Start putting things on the screen.
685 * Scroll screen down before drawing over it
686 * Clear screen now, so file message will not be cleared.
688 starting = NO_BUFFERS;
689 no_wait_return = FALSE;
690 if (!exmode_active)
691 msg_scroll = FALSE;
693 #ifdef FEAT_GUI
695 * This seems to be required to make callbacks to be called now, instead
696 * of after things have been put on the screen, which then may be deleted
697 * when getting a resize callback.
698 * For the Mac this handles putting files dropped on the Vim icon to
699 * global_alist.
701 if (gui.in_use)
703 # ifdef FEAT_SUN_WORKSHOP
704 if (!usingSunWorkShop)
705 # endif
706 gui_wait_for_chars(50L);
707 TIME_MSG("GUI delay");
709 #endif
711 #if defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)
712 qnx_clip_init();
713 #endif
715 #ifdef FEAT_XCLIPBOARD
716 /* Start using the X clipboard, unless the GUI was started. */
717 # ifdef FEAT_GUI
718 if (!gui.in_use)
719 # endif
721 setup_term_clip();
722 TIME_MSG("setup clipboard");
724 #endif
726 #ifdef FEAT_CLIENTSERVER
727 /* Prepare for being a Vim server. */
728 prepare_server(&params);
729 #endif
732 * If "-" argument given: Read file from stdin.
733 * Do this before starting Raw mode, because it may change things that the
734 * writing end of the pipe doesn't like, e.g., in case stdin and stderr
735 * are the same terminal: "cat | vim -".
736 * Using autocommands here may cause trouble...
738 if (params.edit_type == EDIT_STDIN && !recoverymode)
739 read_stdin();
741 #if defined(UNIX) || defined(VMS)
742 /* When switching screens and something caused a message from a vimrc
743 * script, need to output an extra newline on exit. */
744 if ((did_emsg || msg_didout) && *T_TI != NUL)
745 newline_on_exit = TRUE;
746 #endif
749 * When done something that is not allowed or error message call
750 * wait_return. This must be done before starttermcap(), because it may
751 * switch to another screen. It must be done after settmode(TMODE_RAW),
752 * because we want to react on a single key stroke.
753 * Call settmode and starttermcap here, so the T_KS and T_TI may be
754 * defined by termcapinit and redefined in .exrc.
756 settmode(TMODE_RAW);
757 TIME_MSG("setting raw mode");
759 if (need_wait_return || msg_didany)
761 wait_return(TRUE);
762 TIME_MSG("waiting for return");
765 starttermcap(); /* start termcap if not done by wait_return() */
766 TIME_MSG("start termcap");
768 #ifdef FEAT_MOUSE
769 setmouse(); /* may start using the mouse */
770 #endif
771 if (scroll_region)
772 scroll_region_reset(); /* In case Rows changed */
773 scroll_start(); /* may scroll the screen to the right position */
776 * Don't clear the screen when starting in Ex mode, unless using the GUI.
778 if (exmode_active
779 #ifdef FEAT_GUI
780 && !gui.in_use
781 #endif
783 must_redraw = CLEAR;
784 else
786 screenclear(); /* clear screen */
787 TIME_MSG("clearing screen");
790 #ifdef FEAT_CRYPT
791 if (params.ask_for_key)
793 (void)get_crypt_key(TRUE, TRUE);
794 TIME_MSG("getting crypt key");
796 #endif
798 no_wait_return = TRUE;
801 * Create the requested number of windows and edit buffers in them.
802 * Also does recovery if "recoverymode" set.
804 create_windows(&params);
805 TIME_MSG("opening buffers");
807 #ifdef FEAT_EVAL
808 /* clear v:swapcommand */
809 set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
810 #endif
812 /* Ex starts at last line of the file */
813 if (exmode_active)
814 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
816 #ifdef FEAT_AUTOCMD
817 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
818 TIME_MSG("BufEnter autocommands");
819 #endif
820 setpcmark();
822 #ifdef FEAT_QUICKFIX
824 * When started with "-q errorfile" jump to first error now.
826 if (params.edit_type == EDIT_QF)
828 qf_jump(NULL, 0, 0, FALSE);
829 TIME_MSG("jump to first error");
831 #endif
833 #ifdef FEAT_WINDOWS
835 * If opened more than one window, start editing files in the other
836 * windows.
838 edit_buffers(&params);
839 #endif
841 #ifdef FEAT_DIFF
842 if (params.diff_mode)
844 win_T *wp;
846 /* set options in each window for "vimdiff". */
847 for (wp = firstwin; wp != NULL; wp = wp->w_next)
848 diff_win_options(wp, TRUE);
850 #endif
853 * Shorten any of the filenames, but only when absolute.
855 shorten_fnames(FALSE);
858 * Need to jump to the tag before executing the '-c command'.
859 * Makes "vim -c '/return' -t main" work.
861 if (params.tagname != NULL)
863 #if defined(HAS_SWAP_EXISTS_ACTION)
864 swap_exists_did_quit = FALSE;
865 #endif
867 vim_snprintf((char *)IObuff, IOSIZE, "ta %s", params.tagname);
868 do_cmdline_cmd(IObuff);
869 TIME_MSG("jumping to tag");
871 #if defined(HAS_SWAP_EXISTS_ACTION)
872 /* If the user doesn't want to edit the file then we quit here. */
873 if (swap_exists_did_quit)
874 getout(1);
875 #endif
878 /* Execute any "+", "-c" and "-S" arguments. */
879 if (params.n_commands > 0)
880 exe_commands(&params);
882 RedrawingDisabled = 0;
883 redraw_all_later(NOT_VALID);
884 no_wait_return = FALSE;
885 starting = 0;
887 #ifdef FEAT_TERMRESPONSE
888 /* Requesting the termresponse is postponed until here, so that a "-c q"
889 * argument doesn't make it appear in the shell Vim was started from. */
890 may_req_termresponse();
891 #endif
893 /* start in insert mode */
894 if (p_im)
895 need_start_insertmode = TRUE;
897 #ifdef FEAT_AUTOCMD
898 apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
899 TIME_MSG("VimEnter autocommands");
900 #endif
902 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
903 /* When a startup script or session file setup for diff'ing and
904 * scrollbind, sync the scrollbind now. */
905 if (curwin->w_p_diff && curwin->w_p_scb)
907 update_topline();
908 check_scrollbind((linenr_T)0, 0L);
909 TIME_MSG("diff scrollbinding");
911 #endif
913 #if defined(WIN3264) && !defined(FEAT_GUI_W32)
914 mch_set_winsize_now(); /* Allow winsize changes from now on */
915 #endif
917 #if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
918 /* When tab pages were created, may need to update the tab pages line and
919 * scrollbars. This is skipped while creating them. */
920 if (first_tabpage->tp_next != NULL)
922 out_flush();
923 gui_init_which_components(NULL);
924 gui_update_scrollbars(TRUE);
926 need_mouse_correct = TRUE;
927 #endif
929 /* If ":startinsert" command used, stuff a dummy command to be able to
930 * call normal_cmd(), which will then start Insert mode. */
931 if (restart_edit != 0)
932 stuffcharReadbuff(K_NOP);
934 #ifdef FEAT_NETBEANS_INTG
935 if (usingNetbeans)
936 /* Tell the client that it can start sending commands. */
937 netbeans_startup_done();
938 #endif
940 TIME_MSG("before starting main loop");
943 * Call the main command loop. This never returns.
944 * For embedded MzScheme the main_loop will be called by Scheme
945 * for proper stack tracking
947 #ifndef FEAT_MZSCHEME
948 main_loop(FALSE, FALSE);
949 #else
950 mzscheme_main();
951 #endif
953 return 0;
955 #endif /* PROTO */
958 * Main loop: Execute Normal mode commands until exiting Vim.
959 * Also used to handle commands in the command-line window, until the window
960 * is closed.
961 * Also used to handle ":visual" command after ":global": execute Normal mode
962 * commands, return when entering Ex mode. "noexmode" is TRUE then.
964 void
965 main_loop(cmdwin, noexmode)
966 int cmdwin; /* TRUE when working in the command-line window */
967 int noexmode; /* TRUE when return on entering Ex mode */
969 oparg_T oa; /* operator arguments */
970 int previous_got_int = FALSE; /* "got_int" was TRUE */
972 #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
973 /* Setup to catch a terminating error from the X server. Just ignore
974 * it, restore the state and continue. This might not always work
975 * properly, but at least we don't exit unexpectedly when the X server
976 * exists while Vim is running in a console. */
977 if (!cmdwin && !noexmode && SETJMP(x_jump_env))
979 State = NORMAL;
980 # ifdef FEAT_VISUAL
981 VIsual_active = FALSE;
982 # endif
983 got_int = TRUE;
984 need_wait_return = FALSE;
985 global_busy = FALSE;
986 exmode_active = 0;
987 skip_redraw = FALSE;
988 RedrawingDisabled = 0;
989 no_wait_return = 0;
990 # ifdef FEAT_EVAL
991 emsg_skip = 0;
992 # endif
993 emsg_off = 0;
994 # ifdef FEAT_MOUSE
995 setmouse();
996 # endif
997 settmode(TMODE_RAW);
998 starttermcap();
999 scroll_start();
1000 redraw_later_clear();
1002 #endif
1004 clear_oparg(&oa);
1005 while (!cmdwin
1006 #ifdef FEAT_CMDWIN
1007 || cmdwin_result == 0
1008 #endif
1011 if (stuff_empty())
1013 did_check_timestamps = FALSE;
1014 if (need_check_timestamps)
1015 check_timestamps(FALSE);
1016 if (need_wait_return) /* if wait_return still needed ... */
1017 wait_return(FALSE); /* ... call it now */
1018 if (need_start_insertmode && goto_im()
1019 #ifdef FEAT_VISUAL
1020 && !VIsual_active
1021 #endif
1024 need_start_insertmode = FALSE;
1025 stuffReadbuff((char_u *)"i"); /* start insert mode next */
1026 /* skip the fileinfo message now, because it would be shown
1027 * after insert mode finishes! */
1028 need_fileinfo = FALSE;
1032 /* Reset "got_int" now that we got back to the main loop. Except when
1033 * inside a ":g/pat/cmd" command, then the "got_int" needs to abort
1034 * the ":g" command.
1035 * For ":g/pat/vi" we reset "got_int" when used once. When used
1036 * a second time we go back to Ex mode and abort the ":g" command. */
1037 if (got_int)
1039 if (noexmode && global_busy && !exmode_active && previous_got_int)
1041 /* Typed two CTRL-C in a row: go back to ex mode as if "Q" was
1042 * used and keep "got_int" set, so that it aborts ":g". */
1043 exmode_active = EXMODE_NORMAL;
1044 State = NORMAL;
1046 else if (!global_busy || !exmode_active)
1048 if (!quit_more)
1049 (void)vgetc(); /* flush all buffers */
1050 got_int = FALSE;
1052 previous_got_int = TRUE;
1054 else
1055 previous_got_int = FALSE;
1057 if (!exmode_active)
1058 msg_scroll = FALSE;
1059 quit_more = FALSE;
1062 * If skip redraw is set (for ":" in wait_return()), don't redraw now.
1063 * If there is nothing in the stuff_buffer or do_redraw is TRUE,
1064 * update cursor and redraw.
1066 if (skip_redraw || exmode_active)
1067 skip_redraw = FALSE;
1068 else if (do_redraw || stuff_empty())
1070 #ifdef FEAT_AUTOCMD
1071 /* Trigger CursorMoved if the cursor moved. */
1072 if (!finish_op && has_cursormoved()
1073 && !equalpos(last_cursormoved, curwin->w_cursor))
1075 apply_autocmds(EVENT_CURSORMOVED, NULL, NULL, FALSE, curbuf);
1076 last_cursormoved = curwin->w_cursor;
1078 #endif
1080 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
1081 /* Scroll-binding for diff mode may have been postponed until
1082 * here. Avoids doing it for every change. */
1083 if (diff_need_scrollbind)
1085 check_scrollbind((linenr_T)0, 0L);
1086 diff_need_scrollbind = FALSE;
1088 #endif
1089 #if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
1090 /* Include a closed fold completely in the Visual area. */
1091 foldAdjustVisual();
1092 #endif
1093 #ifdef FEAT_FOLDING
1095 * When 'foldclose' is set, apply 'foldlevel' to folds that don't
1096 * contain the cursor.
1097 * When 'foldopen' is "all", open the fold(s) under the cursor.
1098 * This may mark the window for redrawing.
1100 if (hasAnyFolding(curwin) && !char_avail())
1102 foldCheckClose();
1103 if (fdo_flags & FDO_ALL)
1104 foldOpenCursor();
1106 #endif
1109 * Before redrawing, make sure w_topline is correct, and w_leftcol
1110 * if lines don't wrap, and w_skipcol if lines wrap.
1112 update_topline();
1113 validate_cursor();
1115 #ifdef FEAT_VISUAL
1116 if (VIsual_active)
1117 update_curbuf(INVERTED);/* update inverted part */
1118 else
1119 #endif
1120 if (must_redraw)
1121 update_screen(0);
1122 else if (redraw_cmdline || clear_cmdline)
1123 showmode();
1124 #ifdef FEAT_WINDOWS
1125 redraw_statuslines();
1126 #endif
1127 #ifdef FEAT_TITLE
1128 if (need_maketitle)
1129 maketitle();
1130 #endif
1131 /* display message after redraw */
1132 if (keep_msg != NULL)
1134 char_u *p;
1136 /* msg_attr_keep() will set keep_msg to NULL, must free the
1137 * string here. */
1138 p = keep_msg;
1139 keep_msg = NULL;
1140 msg_attr(p, keep_msg_attr);
1141 vim_free(p);
1143 if (need_fileinfo) /* show file info after redraw */
1145 fileinfo(FALSE, TRUE, FALSE);
1146 need_fileinfo = FALSE;
1149 emsg_on_display = FALSE; /* can delete error message now */
1150 did_emsg = FALSE;
1151 msg_didany = FALSE; /* reset lines_left in msg_start() */
1152 may_clear_sb_text(); /* clear scroll-back text on next msg */
1153 showruler(FALSE);
1155 setcursor();
1156 cursor_on();
1158 do_redraw = FALSE;
1160 #ifdef STARTUPTIME
1161 /* Now that we have drawn the first screen all the startup stuff
1162 * has been done, close any file for startup messages. */
1163 if (time_fd != NULL)
1165 TIME_MSG("first screen update");
1166 TIME_MSG("--- VIM STARTED ---");
1167 fclose(time_fd);
1168 time_fd = NULL;
1170 #endif
1172 #ifdef FEAT_GUI
1173 if (need_mouse_correct)
1174 gui_mouse_correct();
1175 #endif
1178 * Update w_curswant if w_set_curswant has been set.
1179 * Postponed until here to avoid computing w_virtcol too often.
1181 update_curswant();
1183 #ifdef FEAT_EVAL
1185 * May perform garbage collection when waiting for a character, but
1186 * only at the very toplevel. Otherwise we may be using a List or
1187 * Dict internally somewhere.
1188 * "may_garbage_collect" is reset in vgetc() which is invoked through
1189 * do_exmode() and normal_cmd().
1191 may_garbage_collect = (!cmdwin && !noexmode);
1192 #endif
1194 * If we're invoked as ex, do a round of ex commands.
1195 * Otherwise, get and execute a normal mode command.
1197 if (exmode_active)
1199 if (noexmode) /* End of ":global/path/visual" commands */
1200 return;
1201 do_exmode(exmode_active == EXMODE_VIM);
1203 else
1204 normal_cmd(&oa, TRUE);
1209 #if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO)
1211 * Exit, but leave behind swap files for modified buffers.
1213 void
1214 getout_preserve_modified(exitval)
1215 int exitval;
1217 # if defined(SIGHUP) && defined(SIG_IGN)
1218 /* Ignore SIGHUP, because a dropped connection causes a read error, which
1219 * makes Vim exit and then handling SIGHUP causes various reentrance
1220 * problems. */
1221 signal(SIGHUP, SIG_IGN);
1222 # endif
1224 ml_close_notmod(); /* close all not-modified buffers */
1225 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
1226 ml_close_all(FALSE); /* close all memfiles, without deleting */
1227 getout(exitval); /* exit Vim properly */
1229 #endif
1232 /* Exit properly */
1233 void
1234 getout(exitval)
1235 int exitval;
1237 #ifdef FEAT_AUTOCMD
1238 buf_T *buf;
1239 win_T *wp;
1240 tabpage_T *tp, *next_tp;
1241 #endif
1243 exiting = TRUE;
1245 /* When running in Ex mode an error causes us to exit with a non-zero exit
1246 * code. POSIX requires this, although it's not 100% clear from the
1247 * standard. */
1248 if (exmode_active)
1249 exitval += ex_exitval;
1251 /* Position the cursor on the last screen line, below all the text */
1252 #ifdef FEAT_GUI
1253 if (!gui.in_use)
1254 #endif
1255 windgoto((int)Rows - 1, 0);
1257 #if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
1258 /* Optionally print hashtable efficiency. */
1259 hash_debug_results();
1260 #endif
1262 #ifdef FEAT_GUI
1263 msg_didany = FALSE;
1264 #endif
1266 #ifdef FEAT_AUTOCMD
1267 /* Trigger BufWinLeave for all windows, but only once per buffer. */
1268 # if defined FEAT_WINDOWS
1269 for (tp = first_tabpage; tp != NULL; tp = next_tp)
1271 next_tp = tp->tp_next;
1272 for (wp = (tp == curtab)
1273 ? firstwin : tp->tp_firstwin; wp != NULL; wp = wp->w_next)
1275 buf = wp->w_buffer;
1276 if (buf->b_changedtick != -1)
1278 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
1279 FALSE, buf);
1280 buf->b_changedtick = -1; /* note that we did it already */
1281 /* start all over, autocommands may mess up the lists */
1282 next_tp = first_tabpage;
1283 break;
1287 # else
1288 apply_autocmds(EVENT_BUFWINLEAVE, curbuf, curbuf->b_fname, FALSE, curbuf);
1289 # endif
1291 /* Trigger BufUnload for buffers that are loaded */
1292 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1293 if (buf->b_ml.ml_mfp != NULL)
1295 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
1296 FALSE, buf);
1297 if (!buf_valid(buf)) /* autocmd may delete the buffer */
1298 break;
1300 apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
1301 #endif
1303 #ifdef FEAT_VIMINFO
1304 if (*p_viminfo != NUL)
1305 /* Write out the registers, history, marks etc, to the viminfo file */
1306 write_viminfo(NULL, FALSE);
1307 #endif
1309 #ifdef FEAT_AUTOCMD
1310 apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
1311 #endif
1313 #ifdef FEAT_PROFILE
1314 profile_dump();
1315 #endif
1317 if (did_emsg
1318 #ifdef FEAT_GUI
1319 || (gui.in_use && msg_didany && p_verbose > 0)
1320 #endif
1323 /* give the user a chance to read the (error) message */
1324 no_wait_return = FALSE;
1325 wait_return(FALSE);
1328 #ifdef FEAT_AUTOCMD
1329 /* Position the cursor again, the autocommands may have moved it */
1330 # ifdef FEAT_GUI
1331 if (!gui.in_use)
1332 # endif
1333 windgoto((int)Rows - 1, 0);
1334 #endif
1336 #ifdef FEAT_MZSCHEME
1337 mzscheme_end();
1338 #endif
1339 #ifdef FEAT_TCL
1340 tcl_end();
1341 #endif
1342 #ifdef FEAT_RUBY
1343 ruby_end();
1344 #endif
1345 #ifdef FEAT_PYTHON
1346 python_end();
1347 #endif
1348 #ifdef FEAT_PERL
1349 perl_end();
1350 #endif
1351 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
1352 iconv_end();
1353 #endif
1354 #ifdef FEAT_NETBEANS_INTG
1355 netbeans_end();
1356 #endif
1357 #ifdef FEAT_CSCOPE
1358 cs_end();
1359 #endif
1360 #ifdef FEAT_EVAL
1361 if (garbage_collect_at_exit)
1362 garbage_collect();
1363 #endif
1365 mch_exit(exitval);
1369 * Get a (optional) count for a Vim argument.
1371 static int
1372 get_number_arg(p, idx, def)
1373 char_u *p; /* pointer to argument */
1374 int *idx; /* index in argument, is incremented */
1375 int def; /* default value */
1377 if (vim_isdigit(p[*idx]))
1379 def = atoi((char *)&(p[*idx]));
1380 while (vim_isdigit(p[*idx]))
1381 *idx = *idx + 1;
1383 return def;
1386 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1388 * Setup to use the current locale (for ctype() and many other things).
1390 static void
1391 init_locale()
1393 setlocale(LC_ALL, "");
1395 # if defined(FEAT_FLOAT) && defined(LC_NUMERIC)
1396 /* Make sure strtod() uses a decimal point, not a comma. */
1397 setlocale(LC_NUMERIC, "C");
1398 # endif
1400 # ifdef WIN32
1401 /* Apparently MS-Windows printf() may cause a crash when we give it 8-bit
1402 * text while it's expecting text in the current locale. This call avoids
1403 * that. */
1404 setlocale(LC_CTYPE, "C");
1405 # endif
1407 # ifdef FEAT_GETTEXT
1409 int mustfree = FALSE;
1410 char_u *p;
1412 # ifdef DYNAMIC_GETTEXT
1413 /* Initialize the gettext library */
1414 dyn_libintl_init(NULL);
1415 # endif
1416 /* expand_env() doesn't work yet, because chartab[] is not initialized
1417 * yet, call vim_getenv() directly */
1418 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1419 if (p != NULL && *p != NUL)
1421 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/lang", p);
1422 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1424 if (mustfree)
1425 vim_free(p);
1426 textdomain(VIMPACKAGE);
1428 # endif
1430 #endif
1433 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1434 * If the executable name starts with "r" we disable shell commands.
1435 * If the next character is "e" we run in Easy mode.
1436 * If the next character is "g" we run the GUI version.
1437 * If the next characters are "view" we start in readonly mode.
1438 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1439 * If the next characters are "ex" we start in Ex mode. If it's followed
1440 * by "im" use improved Ex mode.
1442 static void
1443 parse_command_name(parmp)
1444 mparm_T *parmp;
1446 char_u *initstr;
1448 initstr = gettail((char_u *)parmp->argv[0]);
1450 #ifdef MACOS_X_UNIX
1451 /* An issue has been seen when launching Vim in such a way that
1452 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1453 * executable or a symbolic link of it. Until this issue is resolved
1454 * we prohibit the GUI from being used.
1456 if (STRCMP(initstr, parmp->argv[0]) == 0)
1457 disallow_gui = TRUE;
1459 /* TODO: On MacOS X default to gui if argv[0] ends in:
1460 * /Vim.app/Contents/MacOS/Vim */
1461 #endif
1463 #ifdef FEAT_EVAL
1464 set_vim_var_string(VV_PROGNAME, initstr, -1);
1465 #endif
1467 if (TOLOWER_ASC(initstr[0]) == 'r')
1469 restricted = TRUE;
1470 ++initstr;
1473 /* Avoid using evim mode for "editor". */
1474 if (TOLOWER_ASC(initstr[0]) == 'e'
1475 && (TOLOWER_ASC(initstr[1]) == 'v'
1476 || TOLOWER_ASC(initstr[1]) == 'g'))
1478 #ifdef FEAT_GUI
1479 gui.starting = TRUE;
1480 #endif
1481 parmp->evim_mode = TRUE;
1482 ++initstr;
1485 /* "gvim" starts the GUI. Also accept "Gvim" for MS-Windows. */
1486 if (TOLOWER_ASC(initstr[0]) == 'g')
1488 main_start_gui();
1489 #ifdef FEAT_GUI
1490 ++initstr;
1491 #endif
1494 if (STRNICMP(initstr, "view", 4) == 0)
1496 readonlymode = TRUE;
1497 curbuf->b_p_ro = TRUE;
1498 p_uc = 10000; /* don't update very often */
1499 initstr += 4;
1501 else if (STRNICMP(initstr, "vim", 3) == 0)
1502 initstr += 3;
1504 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1505 if (STRICMP(initstr, "diff") == 0)
1507 #ifdef FEAT_DIFF
1508 parmp->diff_mode = TRUE;
1509 #else
1510 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1511 mch_errmsg("\n");
1512 mch_exit(2);
1513 #endif
1516 if (STRNICMP(initstr, "ex", 2) == 0)
1518 if (STRNICMP(initstr + 2, "im", 2) == 0)
1519 exmode_active = EXMODE_VIM;
1520 else
1521 exmode_active = EXMODE_NORMAL;
1522 change_compatible(TRUE); /* set 'compatible' */
1527 * Get the name of the display, before gui_prepare() removes it from
1528 * argv[]. Used for the xterm-clipboard display.
1530 * Also find the --server... arguments and --socketid and --windowid
1532 static void
1533 early_arg_scan(parmp)
1534 mparm_T *parmp UNUSED;
1536 #if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER) \
1537 || !defined(FEAT_NETBEANS_INTG)
1538 int argc = parmp->argc;
1539 char **argv = parmp->argv;
1540 int i;
1542 for (i = 1; i < argc; i++)
1544 if (STRCMP(argv[i], "--") == 0)
1545 break;
1546 # ifdef FEAT_XCLIPBOARD
1547 else if (STRICMP(argv[i], "-display") == 0
1548 # if defined(FEAT_GUI_GTK)
1549 || STRICMP(argv[i], "--display") == 0
1550 # endif
1553 if (i == argc - 1)
1554 mainerr_arg_missing((char_u *)argv[i]);
1555 xterm_display = argv[++i];
1557 # endif
1558 # ifdef FEAT_CLIENTSERVER
1559 else if (STRICMP(argv[i], "--servername") == 0)
1561 if (i == argc - 1)
1562 mainerr_arg_missing((char_u *)argv[i]);
1563 parmp->serverName_arg = (char_u *)argv[++i];
1565 else if (STRICMP(argv[i], "--serverlist") == 0)
1566 parmp->serverArg = TRUE;
1567 else if (STRNICMP(argv[i], "--remote", 8) == 0)
1569 parmp->serverArg = TRUE;
1570 # ifdef FEAT_GUI
1571 if (strstr(argv[i], "-wait") != 0)
1572 /* don't fork() when starting the GUI to edit files ourself */
1573 gui.dofork = FALSE;
1574 # endif
1576 # endif
1578 # if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1579 # ifdef FEAT_GUI_W32
1580 else if (STRICMP(argv[i], "--windowid") == 0)
1581 # else
1582 else if (STRICMP(argv[i], "--socketid") == 0)
1583 # endif
1585 long_u id;
1586 int count;
1588 if (i == argc - 1)
1589 mainerr_arg_missing((char_u *)argv[i]);
1590 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1591 count = sscanf(&(argv[i + 1][2]), SCANF_HEX_LONG_U, &id);
1592 else
1593 count = sscanf(argv[i + 1], SCANF_DECIMAL_LONG_U, &id);
1594 if (count != 1)
1595 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1596 else
1597 # ifdef FEAT_GUI_W32
1598 win_socket_id = id;
1599 # else
1600 gtk_socket_id = id;
1601 # endif
1602 i++;
1604 # endif
1605 # ifdef FEAT_GUI_GTK
1606 else if (STRICMP(argv[i], "--echo-wid") == 0)
1607 echo_wid_arg = TRUE;
1608 # endif
1609 # ifndef FEAT_NETBEANS_INTG
1610 else if (strncmp(argv[i], "-nb", (size_t)3) == 0)
1612 mch_errmsg(_("'-nb' cannot be used: not enabled at compile time\n"));
1613 mch_exit(2);
1615 # endif
1618 #endif
1622 * Scan the command line arguments.
1624 static void
1625 command_line_scan(parmp)
1626 mparm_T *parmp;
1628 int argc = parmp->argc;
1629 char **argv = parmp->argv;
1630 int argv_idx; /* index in argv[n][] */
1631 int had_minmin = FALSE; /* found "--" argument */
1632 int want_argument; /* option argument with argument */
1633 int c;
1634 char_u *p = NULL;
1635 long n;
1637 --argc;
1638 ++argv;
1639 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1640 while (argc > 0)
1643 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1645 if (argv[0][0] == '+' && !had_minmin)
1647 if (parmp->n_commands >= MAX_ARG_CMDS)
1648 mainerr(ME_EXTRA_CMD, NULL);
1649 argv_idx = -1; /* skip to next argument */
1650 if (argv[0][1] == NUL)
1651 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1652 else
1653 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1657 * Optional argument.
1659 else if (argv[0][0] == '-' && !had_minmin)
1661 want_argument = FALSE;
1662 c = argv[0][argv_idx++];
1663 #ifdef VMS
1665 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1666 * and "-/X" as "-X".
1668 if (c == '/')
1670 c = argv[0][argv_idx++];
1671 c = TOUPPER_ASC(c);
1673 else
1674 c = TOLOWER_ASC(c);
1675 #endif
1676 switch (c)
1678 case NUL: /* "vim -" read from stdin */
1679 /* "ex -" silent mode */
1680 if (exmode_active)
1681 silent_mode = TRUE;
1682 else
1684 if (parmp->edit_type != EDIT_NONE)
1685 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1686 parmp->edit_type = EDIT_STDIN;
1687 read_cmd_fd = 2; /* read from stderr instead of stdin */
1689 argv_idx = -1; /* skip to next argument */
1690 break;
1692 case '-': /* "--" don't take any more option arguments */
1693 /* "--help" give help message */
1694 /* "--version" give version message */
1695 /* "--literal" take files literally */
1696 /* "--nofork" don't fork */
1697 /* "--noplugin[s]" skip plugins */
1698 /* "--cmd <cmd>" execute cmd before vimrc */
1699 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1700 usage();
1701 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1703 Columns = 80; /* need to init Columns */
1704 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1705 list_version();
1706 msg_putchar('\n');
1707 msg_didout = FALSE;
1708 mch_exit(0);
1710 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1712 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1713 parmp->literal = TRUE;
1714 #endif
1716 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1718 #ifdef FEAT_GUI
1719 gui.dofork = FALSE; /* don't fork() when starting GUI */
1720 #endif
1722 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1723 p_lpl = FALSE;
1724 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1726 want_argument = TRUE;
1727 argv_idx += 3;
1729 else if (STRNICMP(argv[0] + argv_idx, "startuptime", 11) == 0)
1731 want_argument = TRUE;
1732 argv_idx += 11;
1734 #ifdef FEAT_CLIENTSERVER
1735 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1736 ; /* already processed -- no arg */
1737 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1738 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1740 /* already processed -- snatch the following arg */
1741 if (argc > 1)
1743 --argc;
1744 ++argv;
1747 #endif
1748 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1749 # ifdef FEAT_GUI_GTK
1750 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1751 # else
1752 else if (STRNICMP(argv[0] + argv_idx, "windowid", 8) == 0)
1753 # endif
1755 /* already processed -- snatch the following arg */
1756 if (argc > 1)
1758 --argc;
1759 ++argv;
1762 #endif
1763 #ifdef FEAT_GUI_GTK
1764 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1766 /* already processed, skip */
1768 #endif
1769 else
1771 if (argv[0][argv_idx])
1772 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1773 had_minmin = TRUE;
1775 if (!want_argument)
1776 argv_idx = -1; /* skip to next argument */
1777 break;
1779 case 'A': /* "-A" start in Arabic mode */
1780 #ifdef FEAT_ARABIC
1781 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1782 #else
1783 mch_errmsg(_(e_noarabic));
1784 mch_exit(2);
1785 #endif
1786 break;
1788 case 'b': /* "-b" binary mode */
1789 /* Needs to be effective before expanding file names, because
1790 * for Win32 this makes us edit a shortcut file itself,
1791 * instead of the file it links to. */
1792 set_options_bin(curbuf->b_p_bin, 1, 0);
1793 curbuf->b_p_bin = 1; /* binary file I/O */
1794 break;
1796 case 'C': /* "-C" Compatible */
1797 change_compatible(TRUE);
1798 break;
1800 case 'e': /* "-e" Ex mode */
1801 exmode_active = EXMODE_NORMAL;
1802 break;
1804 case 'E': /* "-E" Improved Ex mode */
1805 exmode_active = EXMODE_VIM;
1806 break;
1808 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1809 window directly, not with newcli */
1810 #ifdef FEAT_GUI
1811 gui.dofork = FALSE; /* don't fork() when starting GUI */
1812 #endif
1813 break;
1815 case 'g': /* "-g" start GUI */
1816 main_start_gui();
1817 break;
1819 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1820 #ifdef FEAT_FKMAP
1821 p_fkmap = TRUE;
1822 set_option_value((char_u *)"rl", 1L, NULL, 0);
1823 #else
1824 mch_errmsg(_(e_nofarsi));
1825 mch_exit(2);
1826 #endif
1827 break;
1829 case 'h': /* "-h" give help message */
1830 #ifdef FEAT_GUI_GNOME
1831 /* Tell usage() to exit for "gvim". */
1832 gui.starting = FALSE;
1833 #endif
1834 usage();
1835 break;
1837 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1838 #ifdef FEAT_RIGHTLEFT
1839 p_hkmap = TRUE;
1840 set_option_value((char_u *)"rl", 1L, NULL, 0);
1841 #else
1842 mch_errmsg(_(e_nohebrew));
1843 mch_exit(2);
1844 #endif
1845 break;
1847 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1848 #ifdef FEAT_LISP
1849 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1850 p_sm = TRUE;
1851 #endif
1852 break;
1854 case 'M': /* "-M" no changes or writing of files */
1855 reset_modifiable();
1856 /* FALLTHROUGH */
1858 case 'm': /* "-m" no writing of files */
1859 p_write = FALSE;
1860 break;
1862 case 'y': /* "-y" easy mode */
1863 #ifdef FEAT_GUI
1864 gui.starting = TRUE; /* start GUI a bit later */
1865 #endif
1866 parmp->evim_mode = TRUE;
1867 break;
1869 case 'N': /* "-N" Nocompatible */
1870 change_compatible(FALSE);
1871 break;
1873 case 'n': /* "-n" no swap file */
1874 parmp->no_swap_file = TRUE;
1875 break;
1877 case 'p': /* "-p[N]" open N tab pages */
1878 #ifdef TARGET_API_MAC_OSX
1879 /* For some reason on MacOS X, an argument like:
1880 -psn_0_10223617 is passed in when invoke from Finder
1881 or with the 'open' command */
1882 if (argv[0][argv_idx] == 's')
1884 argv_idx = -1; /* bypass full -psn */
1885 main_start_gui();
1886 break;
1888 #endif
1889 #ifdef FEAT_WINDOWS
1890 /* default is 0: open window for each file */
1891 parmp->window_count = get_number_arg((char_u *)argv[0],
1892 &argv_idx, 0);
1893 parmp->window_layout = WIN_TABS;
1894 #endif
1895 break;
1897 case 'o': /* "-o[N]" open N horizontal split windows */
1898 #ifdef FEAT_WINDOWS
1899 /* default is 0: open window for each file */
1900 parmp->window_count = get_number_arg((char_u *)argv[0],
1901 &argv_idx, 0);
1902 parmp->window_layout = WIN_HOR;
1903 #endif
1904 break;
1906 case 'O': /* "-O[N]" open N vertical split windows */
1907 #if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1908 /* default is 0: open window for each file */
1909 parmp->window_count = get_number_arg((char_u *)argv[0],
1910 &argv_idx, 0);
1911 parmp->window_layout = WIN_VER;
1912 #endif
1913 break;
1915 #ifdef FEAT_QUICKFIX
1916 case 'q': /* "-q" QuickFix mode */
1917 if (parmp->edit_type != EDIT_NONE)
1918 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1919 parmp->edit_type = EDIT_QF;
1920 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1922 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1923 argv_idx = -1;
1925 else if (argc > 1) /* "-q {errorfile}" */
1926 want_argument = TRUE;
1927 break;
1928 #endif
1930 case 'R': /* "-R" readonly mode */
1931 readonlymode = TRUE;
1932 curbuf->b_p_ro = TRUE;
1933 p_uc = 10000; /* don't update very often */
1934 break;
1936 case 'r': /* "-r" recovery mode */
1937 case 'L': /* "-L" recovery mode */
1938 recoverymode = 1;
1939 break;
1941 case 's':
1942 if (exmode_active) /* "-s" silent (batch) mode */
1943 silent_mode = TRUE;
1944 else /* "-s {scriptin}" read from script file */
1945 want_argument = TRUE;
1946 break;
1948 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1949 if (parmp->edit_type != EDIT_NONE)
1950 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1951 parmp->edit_type = EDIT_TAG;
1952 if (argv[0][argv_idx]) /* "-t{tag}" */
1954 parmp->tagname = (char_u *)argv[0] + argv_idx;
1955 argv_idx = -1;
1957 else /* "-t {tag}" */
1958 want_argument = TRUE;
1959 break;
1961 #ifdef FEAT_EVAL
1962 case 'D': /* "-D" Debugging */
1963 parmp->use_debug_break_level = 9999;
1964 break;
1965 #endif
1966 #ifdef FEAT_DIFF
1967 case 'd': /* "-d" 'diff' */
1968 # ifdef AMIGA
1969 /* check for "-dev {device}" */
1970 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1971 want_argument = TRUE;
1972 else
1973 # endif
1974 parmp->diff_mode = TRUE;
1975 break;
1976 #endif
1977 case 'V': /* "-V{N}" Verbose level */
1978 /* default is 10: a little bit verbose */
1979 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1980 if (argv[0][argv_idx] != NUL)
1982 set_option_value((char_u *)"verbosefile", 0L,
1983 (char_u *)argv[0] + argv_idx, 0);
1984 argv_idx = (int)STRLEN(argv[0]);
1986 break;
1988 case 'v': /* "-v" Vi-mode (as if called "vi") */
1989 exmode_active = 0;
1990 #ifdef FEAT_GUI
1991 gui.starting = FALSE; /* don't start GUI */
1992 #endif
1993 break;
1995 case 'w': /* "-w{number}" set window height */
1996 /* "-w {scriptout}" write to script */
1997 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
1999 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
2000 set_option_value((char_u *)"window", n, NULL, 0);
2001 break;
2003 want_argument = TRUE;
2004 break;
2006 #ifdef FEAT_CRYPT
2007 case 'x': /* "-x" encrypted reading/writing of files */
2008 parmp->ask_for_key = TRUE;
2009 break;
2010 #endif
2012 case 'X': /* "-X" don't connect to X server */
2013 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
2014 x_no_connect = TRUE;
2015 #endif
2016 break;
2018 case 'Z': /* "-Z" restricted mode */
2019 restricted = TRUE;
2020 break;
2022 case 'c': /* "-c{command}" or "-c {command}" execute
2023 command */
2024 if (argv[0][argv_idx] != NUL)
2026 if (parmp->n_commands >= MAX_ARG_CMDS)
2027 mainerr(ME_EXTRA_CMD, NULL);
2028 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
2029 + argv_idx;
2030 argv_idx = -1;
2031 break;
2033 /*FALLTHROUGH*/
2034 case 'S': /* "-S {file}" execute Vim script */
2035 case 'i': /* "-i {viminfo}" use for viminfo */
2036 #ifndef FEAT_DIFF
2037 case 'd': /* "-d {device}" device (for Amiga) */
2038 #endif
2039 case 'T': /* "-T {terminal}" terminal name */
2040 case 'u': /* "-u {vimrc}" vim inits file */
2041 case 'U': /* "-U {gvimrc}" gvim inits file */
2042 case 'W': /* "-W {scriptout}" overwrite */
2043 #ifdef FEAT_GUI_W32
2044 case 'P': /* "-P {parent title}" MDI parent */
2045 #endif
2046 want_argument = TRUE;
2047 break;
2049 default:
2050 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
2054 * Handle option arguments with argument.
2056 if (want_argument)
2059 * Check for garbage immediately after the option letter.
2061 if (argv[0][argv_idx] != NUL)
2062 mainerr(ME_GARBAGE, (char_u *)argv[0]);
2064 --argc;
2065 if (argc < 1 && c != 'S') /* -S has an optional argument */
2066 mainerr_arg_missing((char_u *)argv[0]);
2067 ++argv;
2068 argv_idx = -1;
2070 switch (c)
2072 case 'c': /* "-c {command}" execute command */
2073 case 'S': /* "-S {file}" execute Vim script */
2074 if (parmp->n_commands >= MAX_ARG_CMDS)
2075 mainerr(ME_EXTRA_CMD, NULL);
2076 if (c == 'S')
2078 char *a;
2080 if (argc < 1)
2081 /* "-S" without argument: use default session file
2082 * name. */
2083 a = SESSION_FILE;
2084 else if (argv[0][0] == '-')
2086 /* "-S" followed by another option: use default
2087 * session file name. */
2088 a = SESSION_FILE;
2089 ++argc;
2090 --argv;
2092 else
2093 a = argv[0];
2094 p = alloc((unsigned)(STRLEN(a) + 4));
2095 if (p == NULL)
2096 mch_exit(2);
2097 sprintf((char *)p, "so %s", a);
2098 parmp->cmds_tofree[parmp->n_commands] = TRUE;
2099 parmp->commands[parmp->n_commands++] = p;
2101 else
2102 parmp->commands[parmp->n_commands++] =
2103 (char_u *)argv[0];
2104 break;
2106 case '-':
2107 if (argv[-1][2] == 'c')
2109 /* "--cmd {command}" execute command */
2110 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
2111 mainerr(ME_EXTRA_CMD, NULL);
2112 parmp->pre_commands[parmp->n_pre_commands++] =
2113 (char_u *)argv[0];
2115 /* "--startuptime <file>" already handled */
2116 break;
2118 /* case 'd': -d {device} is handled in mch_check_win() for the
2119 * Amiga */
2121 #ifdef FEAT_QUICKFIX
2122 case 'q': /* "-q {errorfile}" QuickFix mode */
2123 parmp->use_ef = (char_u *)argv[0];
2124 break;
2125 #endif
2127 case 'i': /* "-i {viminfo}" use for viminfo */
2128 use_viminfo = (char_u *)argv[0];
2129 break;
2131 case 's': /* "-s {scriptin}" read from script file */
2132 if (scriptin[0] != NULL)
2134 scripterror:
2135 mch_errmsg(_("Attempt to open script file again: \""));
2136 mch_errmsg(argv[-1]);
2137 mch_errmsg(" ");
2138 mch_errmsg(argv[0]);
2139 mch_errmsg("\"\n");
2140 mch_exit(2);
2142 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
2144 mch_errmsg(_("Cannot open for reading: \""));
2145 mch_errmsg(argv[0]);
2146 mch_errmsg("\"\n");
2147 mch_exit(2);
2149 if (save_typebuf() == FAIL)
2150 mch_exit(2); /* out of memory */
2151 break;
2153 case 't': /* "-t {tag}" */
2154 parmp->tagname = (char_u *)argv[0];
2155 break;
2157 case 'T': /* "-T {terminal}" terminal name */
2159 * The -T term argument is always available and when
2160 * HAVE_TERMLIB is supported it overrides the environment
2161 * variable TERM.
2163 #ifdef FEAT_GUI
2164 if (term_is_gui((char_u *)argv[0]))
2165 gui.starting = TRUE; /* start GUI a bit later */
2166 else
2167 #endif
2168 parmp->term = (char_u *)argv[0];
2169 break;
2171 case 'u': /* "-u {vimrc}" vim inits file */
2172 parmp->use_vimrc = (char_u *)argv[0];
2173 break;
2175 case 'U': /* "-U {gvimrc}" gvim inits file */
2176 #ifdef FEAT_GUI
2177 use_gvimrc = (char_u *)argv[0];
2178 #endif
2179 break;
2181 case 'w': /* "-w {nr}" 'window' value */
2182 /* "-w {scriptout}" append to script file */
2183 if (vim_isdigit(*((char_u *)argv[0])))
2185 argv_idx = 0;
2186 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
2187 set_option_value((char_u *)"window", n, NULL, 0);
2188 argv_idx = -1;
2189 break;
2191 /*FALLTHROUGH*/
2192 case 'W': /* "-W {scriptout}" overwrite script file */
2193 if (scriptout != NULL)
2194 goto scripterror;
2195 if ((scriptout = mch_fopen(argv[0],
2196 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
2198 mch_errmsg(_("Cannot open for script output: \""));
2199 mch_errmsg(argv[0]);
2200 mch_errmsg("\"\n");
2201 mch_exit(2);
2203 break;
2205 #ifdef FEAT_GUI_W32
2206 case 'P': /* "-P {parent title}" MDI parent */
2207 gui_mch_set_parent(argv[0]);
2208 break;
2209 #endif
2215 * File name argument.
2217 else
2219 argv_idx = -1; /* skip to next argument */
2221 /* Check for only one type of editing. */
2222 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2223 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2224 parmp->edit_type = EDIT_FILE;
2226 #ifdef MSWIN
2227 /* Remember if the argument was a full path before changing
2228 * slashes to backslashes. */
2229 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2230 parmp->full_path = TRUE;
2231 #endif
2233 /* Add the file to the global argument list. */
2234 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2235 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2236 mch_exit(2);
2237 #ifdef FEAT_DIFF
2238 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2239 && !mch_isdir(alist_name(&GARGLIST[0])))
2241 char_u *r;
2243 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2244 if (r != NULL)
2246 vim_free(p);
2247 p = r;
2250 #endif
2251 #if defined(__CYGWIN32__) && !defined(WIN32)
2253 * If vim is invoked by non-Cygwin tools, convert away any
2254 * DOS paths, so things like .swp files are created correctly.
2255 * Look for evidence of non-Cygwin paths before we bother.
2256 * This is only for when using the Unix files.
2258 if (strpbrk(p, "\\:") != NULL)
2260 char posix_path[PATH_MAX];
2262 # if CYGWIN_VERSION_DLL_MAJOR >= 1007
2263 cygwin_conv_path(CCP_WIN_A_TO_POSIX, p, posix_path, PATH_MAX);
2264 # else
2265 cygwin_conv_to_posix_path(p, posix_path);
2266 # endif
2267 vim_free(p);
2268 p = vim_strsave(posix_path);
2269 if (p == NULL)
2270 mch_exit(2);
2272 #endif
2274 #ifdef USE_FNAME_CASE
2275 /* Make the case of the file name match the actual file. */
2276 fname_case(p, 0);
2277 #endif
2279 alist_add(&global_alist, p,
2280 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2281 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
2282 #else
2283 2 /* add buffer number now and use curbuf */
2284 #endif
2287 #if defined(FEAT_MBYTE) && defined(WIN32)
2289 /* Remember this argument has been added to the argument list.
2290 * Needed when 'encoding' is changed. */
2291 used_file_arg(argv[0], parmp->literal, parmp->full_path,
2292 # ifdef FEAT_DIFF
2293 parmp->diff_mode
2294 # else
2295 FALSE
2296 # endif
2299 #endif
2303 * If there are no more letters after the current "-", go to next
2304 * argument. argv_idx is set to -1 when the current argument is to be
2305 * skipped.
2307 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2309 --argc;
2310 ++argv;
2311 argv_idx = 1;
2315 #ifdef FEAT_EVAL
2316 /* If there is a "+123" or "-c" command, set v:swapcommand to the first
2317 * one. */
2318 if (parmp->n_commands > 0)
2320 p = alloc((unsigned)STRLEN(parmp->commands[0]) + 3);
2321 if (p != NULL)
2323 sprintf((char *)p, ":%s\r", parmp->commands[0]);
2324 set_vim_var_string(VV_SWAPCOMMAND, p, -1);
2325 vim_free(p);
2328 #endif
2332 * Print a warning if stdout is not a terminal.
2333 * When starting in Ex mode and commands come from a file, set Silent mode.
2335 static void
2336 check_tty(parmp)
2337 mparm_T *parmp;
2339 int input_isatty; /* is active input a terminal? */
2341 input_isatty = mch_input_isatty();
2342 if (exmode_active)
2344 if (!input_isatty)
2345 silent_mode = TRUE;
2347 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2348 #ifdef FEAT_GUI
2349 /* don't want the delay when started from the desktop */
2350 && !gui.starting
2351 #endif
2354 #ifdef NBDEBUG
2356 * This shouldn't be necessary. But if I run netbeans with the log
2357 * output coming to the console and XOpenDisplay fails, I get vim
2358 * trying to start with input/output to my console tty. This fills my
2359 * input buffer so fast I can't even kill the process in under 2
2360 * minutes (and it beeps continuously the whole time :-)
2362 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2364 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2365 exit(1);
2367 #endif
2368 if (!parmp->stdout_isatty)
2369 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2370 if (!input_isatty)
2371 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2372 out_flush();
2373 if (scriptin[0] == NULL)
2374 ui_delay(2000L, TRUE);
2375 TIME_MSG("Warning delay");
2380 * Read text from stdin.
2382 static void
2383 read_stdin()
2385 int i;
2387 #if defined(HAS_SWAP_EXISTS_ACTION)
2388 /* When getting the ATTENTION prompt here, use a dialog */
2389 swap_exists_action = SEA_DIALOG;
2390 #endif
2391 no_wait_return = TRUE;
2392 i = msg_didany;
2393 set_buflisted(TRUE);
2394 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2395 no_wait_return = FALSE;
2396 msg_didany = i;
2397 TIME_MSG("reading stdin");
2398 #if defined(HAS_SWAP_EXISTS_ACTION)
2399 check_swap_exists_action();
2400 #endif
2401 #if !(defined(AMIGA) || defined(MACOS))
2403 * Close stdin and dup it from stderr. Required for GPM to work
2404 * properly, and for running external commands.
2405 * Is there any other system that cannot do this?
2407 close(0);
2408 ignored = dup(2);
2409 #endif
2413 * Create the requested number of windows and edit buffers in them.
2414 * Also does recovery if "recoverymode" set.
2416 static void
2417 create_windows(parmp)
2418 mparm_T *parmp UNUSED;
2420 #ifdef FEAT_WINDOWS
2421 int dorewind;
2422 int done = 0;
2425 * Create the number of windows that was requested.
2427 if (parmp->window_count == -1) /* was not set */
2428 parmp->window_count = 1;
2429 if (parmp->window_count == 0)
2430 parmp->window_count = GARGCOUNT;
2431 if (parmp->window_count > 1)
2433 /* Don't change the windows if there was a command in .vimrc that
2434 * already split some windows */
2435 if (parmp->window_layout == 0)
2436 parmp->window_layout = WIN_HOR;
2437 if (parmp->window_layout == WIN_TABS)
2439 parmp->window_count = make_tabpages(parmp->window_count);
2440 TIME_MSG("making tab pages");
2442 else if (firstwin->w_next == NULL)
2444 parmp->window_count = make_windows(parmp->window_count,
2445 parmp->window_layout == WIN_VER);
2446 TIME_MSG("making windows");
2448 else
2449 parmp->window_count = win_count();
2451 else
2452 parmp->window_count = 1;
2453 #endif
2455 if (recoverymode) /* do recover */
2457 msg_scroll = TRUE; /* scroll message up */
2458 ml_recover();
2459 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2460 getout(1);
2461 do_modelines(0); /* do modelines */
2463 else
2466 * Open a buffer for windows that don't have one yet.
2467 * Commands in the .vimrc might have loaded a file or split the window.
2468 * Watch out for autocommands that delete a window.
2470 #ifdef FEAT_AUTOCMD
2472 * Don't execute Win/Buf Enter/Leave autocommands here
2474 ++autocmd_no_enter;
2475 ++autocmd_no_leave;
2476 #endif
2477 #ifdef FEAT_WINDOWS
2478 dorewind = TRUE;
2479 while (done++ < 1000)
2481 if (dorewind)
2483 if (parmp->window_layout == WIN_TABS)
2484 goto_tabpage(1);
2485 else
2486 curwin = firstwin;
2488 else if (parmp->window_layout == WIN_TABS)
2490 if (curtab->tp_next == NULL)
2491 break;
2492 goto_tabpage(0);
2494 else
2496 if (curwin->w_next == NULL)
2497 break;
2498 curwin = curwin->w_next;
2500 dorewind = FALSE;
2501 #endif
2502 curbuf = curwin->w_buffer;
2503 if (curbuf->b_ml.ml_mfp == NULL)
2505 #ifdef FEAT_FOLDING
2506 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2507 if (p_fdls >= 0)
2508 curwin->w_p_fdl = p_fdls;
2509 #endif
2510 #if defined(HAS_SWAP_EXISTS_ACTION)
2511 /* When getting the ATTENTION prompt here, use a dialog */
2512 swap_exists_action = SEA_DIALOG;
2513 #endif
2514 set_buflisted(TRUE);
2515 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2517 #if defined(HAS_SWAP_EXISTS_ACTION)
2518 if (swap_exists_action == SEA_QUIT)
2520 if (got_int || only_one_window())
2522 /* abort selected or quit and only one window */
2523 did_emsg = FALSE; /* avoid hit-enter prompt */
2524 getout(1);
2526 /* We can't close the window, it would disturb what
2527 * happens next. Clear the file name and set the arg
2528 * index to -1 to delete it later. */
2529 setfname(curbuf, NULL, NULL, FALSE);
2530 curwin->w_arg_idx = -1;
2531 swap_exists_action = SEA_NONE;
2533 else
2534 handle_swap_exists(NULL);
2535 #endif
2536 #ifdef FEAT_AUTOCMD
2537 dorewind = TRUE; /* start again */
2538 #endif
2540 #ifdef FEAT_WINDOWS
2541 ui_breakcheck();
2542 if (got_int)
2544 (void)vgetc(); /* only break the file loading, not the rest */
2545 break;
2548 #endif
2549 #ifdef FEAT_WINDOWS
2550 if (parmp->window_layout == WIN_TABS)
2551 goto_tabpage(1);
2552 else
2553 curwin = firstwin;
2554 curbuf = curwin->w_buffer;
2555 #endif
2556 #ifdef FEAT_AUTOCMD
2557 --autocmd_no_enter;
2558 --autocmd_no_leave;
2559 #endif
2563 #ifdef FEAT_WINDOWS
2565 * If opened more than one window, start editing files in the other
2566 * windows. make_windows() has already opened the windows.
2568 static void
2569 edit_buffers(parmp)
2570 mparm_T *parmp;
2572 int arg_idx; /* index in argument list */
2573 int i;
2574 int advance = TRUE;
2576 # ifdef FEAT_AUTOCMD
2578 * Don't execute Win/Buf Enter/Leave autocommands here
2580 ++autocmd_no_enter;
2581 ++autocmd_no_leave;
2582 # endif
2584 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2585 if (curwin->w_arg_idx == -1)
2587 win_close(curwin, TRUE);
2588 advance = FALSE;
2591 arg_idx = 1;
2592 for (i = 1; i < parmp->window_count; ++i)
2594 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2595 if (curwin->w_arg_idx == -1)
2597 ++arg_idx;
2598 win_close(curwin, TRUE);
2599 advance = FALSE;
2600 continue;
2603 if (advance)
2605 if (parmp->window_layout == WIN_TABS)
2607 if (curtab->tp_next == NULL) /* just checking */
2608 break;
2609 goto_tabpage(0);
2611 else
2613 if (curwin->w_next == NULL) /* just checking */
2614 break;
2615 win_enter(curwin->w_next, FALSE);
2618 advance = TRUE;
2620 /* Only open the file if there is no file in this window yet (that can
2621 * happen when .vimrc contains ":sall"). */
2622 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2624 curwin->w_arg_idx = arg_idx;
2625 /* Edit file from arg list, if there is one. When "Quit" selected
2626 * at the ATTENTION prompt close the window. */
2627 # ifdef HAS_SWAP_EXISTS_ACTION
2628 swap_exists_did_quit = FALSE;
2629 # endif
2630 (void)do_ecmd(0, arg_idx < GARGCOUNT
2631 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2632 NULL, NULL, ECMD_LASTL, ECMD_HIDE, curwin);
2633 # ifdef HAS_SWAP_EXISTS_ACTION
2634 if (swap_exists_did_quit)
2636 /* abort or quit selected */
2637 if (got_int || only_one_window())
2639 /* abort selected and only one window */
2640 did_emsg = FALSE; /* avoid hit-enter prompt */
2641 getout(1);
2643 win_close(curwin, TRUE);
2644 advance = FALSE;
2646 # endif
2647 if (arg_idx == GARGCOUNT - 1)
2648 arg_had_last = TRUE;
2649 ++arg_idx;
2651 ui_breakcheck();
2652 if (got_int)
2654 (void)vgetc(); /* only break the file loading, not the rest */
2655 break;
2659 if (parmp->window_layout == WIN_TABS)
2660 goto_tabpage(1);
2661 # ifdef FEAT_AUTOCMD
2662 --autocmd_no_enter;
2663 # endif
2664 win_enter(firstwin, FALSE); /* back to first window */
2665 # ifdef FEAT_AUTOCMD
2666 --autocmd_no_leave;
2667 # endif
2668 TIME_MSG("editing files in windows");
2669 if (parmp->window_count > 1 && parmp->window_layout != WIN_TABS)
2670 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2672 #endif /* FEAT_WINDOWS */
2675 * Execute the commands from --cmd arguments "cmds[cnt]".
2677 static void
2678 exe_pre_commands(parmp)
2679 mparm_T *parmp;
2681 char_u **cmds = parmp->pre_commands;
2682 int cnt = parmp->n_pre_commands;
2683 int i;
2685 if (cnt > 0)
2687 curwin->w_cursor.lnum = 0; /* just in case.. */
2688 sourcing_name = (char_u *)_("pre-vimrc command line");
2689 # ifdef FEAT_EVAL
2690 current_SID = SID_CMDARG;
2691 # endif
2692 for (i = 0; i < cnt; ++i)
2693 do_cmdline_cmd(cmds[i]);
2694 sourcing_name = NULL;
2695 # ifdef FEAT_EVAL
2696 current_SID = 0;
2697 # endif
2698 TIME_MSG("--cmd commands");
2703 * Execute "+", "-c" and "-S" arguments.
2705 static void
2706 exe_commands(parmp)
2707 mparm_T *parmp;
2709 int i;
2712 * We start commands on line 0, make "vim +/pat file" match a
2713 * pattern on line 1. But don't move the cursor when an autocommand
2714 * with g`" was used.
2716 msg_scroll = TRUE;
2717 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2718 curwin->w_cursor.lnum = 0;
2719 sourcing_name = (char_u *)"command line";
2720 #ifdef FEAT_EVAL
2721 current_SID = SID_CARG;
2722 #endif
2723 for (i = 0; i < parmp->n_commands; ++i)
2725 do_cmdline_cmd(parmp->commands[i]);
2726 if (parmp->cmds_tofree[i])
2727 vim_free(parmp->commands[i]);
2729 sourcing_name = NULL;
2730 #ifdef FEAT_EVAL
2731 current_SID = 0;
2732 #endif
2733 if (curwin->w_cursor.lnum == 0)
2734 curwin->w_cursor.lnum = 1;
2736 if (!exmode_active)
2737 msg_scroll = FALSE;
2739 #ifdef FEAT_QUICKFIX
2740 /* When started with "-q errorfile" jump to first error again. */
2741 if (parmp->edit_type == EDIT_QF)
2742 qf_jump(NULL, 0, 0, FALSE);
2743 #endif
2744 TIME_MSG("executing command arguments");
2748 * Source startup scripts.
2750 static void
2751 source_startup_scripts(parmp)
2752 mparm_T *parmp;
2754 int i;
2757 * For "evim" source evim.vim first of all, so that the user can overrule
2758 * any things he doesn't like.
2760 if (parmp->evim_mode)
2762 (void)do_source((char_u *)EVIM_FILE, FALSE, DOSO_NONE);
2763 TIME_MSG("source evim file");
2767 * If -u argument given, use only the initializations from that file and
2768 * nothing else.
2770 if (parmp->use_vimrc != NULL)
2772 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2773 || STRCMP(parmp->use_vimrc, "NORC") == 0)
2775 #ifdef FEAT_GUI
2776 if (use_gvimrc == NULL) /* don't load gvimrc either */
2777 use_gvimrc = parmp->use_vimrc;
2778 #endif
2779 if (parmp->use_vimrc[2] == 'N')
2780 p_lpl = FALSE; /* don't load plugins either */
2782 else
2784 if (do_source(parmp->use_vimrc, FALSE, DOSO_NONE) != OK)
2785 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2788 else if (!silent_mode)
2790 #ifdef AMIGA
2791 struct Process *proc = (struct Process *)FindTask(0L);
2792 APTR save_winptr = proc->pr_WindowPtr;
2794 /* Avoid a requester here for a volume that doesn't exist. */
2795 proc->pr_WindowPtr = (APTR)-1L;
2796 #endif
2799 * Get system wide defaults, if the file name is defined.
2801 #ifdef SYS_VIMRC_FILE
2802 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, DOSO_NONE);
2803 #endif
2804 #ifdef MACOS_X
2805 (void)do_source((char_u *)"$VIMRUNTIME/macmap.vim", FALSE, DOSO_NONE);
2806 #endif
2809 * Try to read initialization commands from the following places:
2810 * - environment variable VIMINIT
2811 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2812 * - second user vimrc file ($VIM/.vimrc for Dos)
2813 * - environment variable EXINIT
2814 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2815 * - second user exrc file ($VIM/.exrc for Dos)
2816 * The first that exists is used, the rest is ignored.
2818 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2820 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, DOSO_VIMRC) == FAIL
2821 #ifdef USR_VIMRC_FILE2
2822 && do_source((char_u *)USR_VIMRC_FILE2, TRUE,
2823 DOSO_VIMRC) == FAIL
2824 #endif
2825 #ifdef USR_VIMRC_FILE3
2826 && do_source((char_u *)USR_VIMRC_FILE3, TRUE,
2827 DOSO_VIMRC) == FAIL
2828 #endif
2829 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2830 && do_source((char_u *)USR_EXRC_FILE, FALSE, DOSO_NONE) == FAIL)
2832 #ifdef USR_EXRC_FILE2
2833 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, DOSO_NONE);
2834 #endif
2839 * Read initialization commands from ".vimrc" or ".exrc" in current
2840 * directory. This is only done if the 'exrc' option is set.
2841 * Because of security reasons we disallow shell and write commands
2842 * now, except for unix if the file is owned by the user or 'secure'
2843 * option has been reset in environment of global ".exrc" or ".vimrc".
2844 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2845 * SYS_VIMRC_FILE.
2847 if (p_exrc)
2849 #if defined(UNIX) || defined(VMS)
2850 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2851 if (!file_owned(VIMRC_FILE))
2852 #endif
2853 secure = p_secure;
2855 i = FAIL;
2856 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2857 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2858 #ifdef USR_VIMRC_FILE2
2859 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2860 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2861 #endif
2862 #ifdef USR_VIMRC_FILE3
2863 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2864 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2865 #endif
2866 #ifdef SYS_VIMRC_FILE
2867 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2868 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2869 #endif
2871 i = do_source((char_u *)VIMRC_FILE, TRUE, DOSO_VIMRC);
2873 if (i == FAIL)
2875 #if defined(UNIX) || defined(VMS)
2876 /* if ".exrc" is not owned by user set 'secure' mode */
2877 if (!file_owned(EXRC_FILE))
2878 secure = p_secure;
2879 else
2880 secure = 0;
2881 #endif
2882 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2883 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2884 #ifdef USR_EXRC_FILE2
2885 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2886 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2887 #endif
2889 (void)do_source((char_u *)EXRC_FILE, FALSE, DOSO_NONE);
2892 if (secure == 2)
2893 need_wait_return = TRUE;
2894 secure = 0;
2895 #ifdef AMIGA
2896 proc->pr_WindowPtr = save_winptr;
2897 #endif
2899 TIME_MSG("sourcing vimrc file(s)");
2903 * Setup to start using the GUI. Exit with an error when not available.
2905 static void
2906 main_start_gui()
2908 #ifdef FEAT_GUI
2909 gui.starting = TRUE; /* start GUI a bit later */
2910 #else
2911 mch_errmsg(_(e_nogvim));
2912 mch_errmsg("\n");
2913 mch_exit(2);
2914 #endif
2918 * Get an environment variable, and execute it as Ex commands.
2919 * Returns FAIL if the environment variable was not executed, OK otherwise.
2922 process_env(env, is_viminit)
2923 char_u *env;
2924 int is_viminit; /* when TRUE, called for VIMINIT */
2926 char_u *initstr;
2927 char_u *save_sourcing_name;
2928 linenr_T save_sourcing_lnum;
2929 #ifdef FEAT_EVAL
2930 scid_T save_sid;
2931 #endif
2933 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2935 if (is_viminit)
2936 vimrc_found(NULL, NULL);
2937 save_sourcing_name = sourcing_name;
2938 save_sourcing_lnum = sourcing_lnum;
2939 sourcing_name = env;
2940 sourcing_lnum = 0;
2941 #ifdef FEAT_EVAL
2942 save_sid = current_SID;
2943 current_SID = SID_ENV;
2944 #endif
2945 do_cmdline_cmd(initstr);
2946 sourcing_name = save_sourcing_name;
2947 sourcing_lnum = save_sourcing_lnum;
2948 #ifdef FEAT_EVAL
2949 current_SID = save_sid;;
2950 #endif
2951 return OK;
2953 return FAIL;
2956 #if defined(UNIX) || defined(VMS)
2958 * Return TRUE if we are certain the user owns the file "fname".
2959 * Used for ".vimrc" and ".exrc".
2960 * Use both stat() and lstat() for extra security.
2962 static int
2963 file_owned(fname)
2964 char *fname;
2966 struct stat s;
2967 # ifdef UNIX
2968 uid_t uid = getuid();
2969 # else /* VMS */
2970 uid_t uid = ((getgid() << 16) | getuid());
2971 # endif
2973 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2974 # ifdef HAVE_LSTAT
2975 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2976 # endif
2979 #endif
2982 * Give an error message main_errors["n"] and exit.
2984 static void
2985 mainerr(n, str)
2986 int n; /* one of the ME_ defines */
2987 char_u *str; /* extra argument or NULL */
2989 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
2990 reset_signals(); /* kill us with CTRL-C here, if you like */
2991 #endif
2993 mch_errmsg(longVersion);
2994 mch_errmsg("\n");
2995 mch_errmsg(_(main_errors[n]));
2996 if (str != NULL)
2998 mch_errmsg(": \"");
2999 mch_errmsg((char *)str);
3000 mch_errmsg("\"");
3002 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
3004 mch_exit(1);
3007 void
3008 mainerr_arg_missing(str)
3009 char_u *str;
3011 mainerr(ME_ARG_MISSING, str);
3015 * print a message with three spaces prepended and '\n' appended.
3017 static void
3018 main_msg(s)
3019 char *s;
3021 mch_msg(" ");
3022 mch_msg(s);
3023 mch_msg("\n");
3027 * Print messages for "vim -h" or "vim --help" and exit.
3029 static void
3030 usage()
3032 int i;
3033 static char *(use[]) =
3035 N_("[file ..] edit specified file(s)"),
3036 N_("- read text from stdin"),
3037 N_("-t tag edit file where tag is defined"),
3038 #ifdef FEAT_QUICKFIX
3039 N_("-q [errorfile] edit file with first error")
3040 #endif
3043 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
3044 reset_signals(); /* kill us with CTRL-C here, if you like */
3045 #endif
3047 mch_msg(longVersion);
3048 mch_msg(_("\n\nusage:"));
3049 for (i = 0; ; ++i)
3051 mch_msg(_(" vim [arguments] "));
3052 mch_msg(_(use[i]));
3053 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
3054 break;
3055 mch_msg(_("\n or:"));
3057 #ifdef VMS
3058 mch_msg(_("\nWhere case is ignored prepend / to make flag upper case"));
3059 #endif
3061 mch_msg(_("\n\nArguments:\n"));
3062 main_msg(_("--\t\t\tOnly file names after this"));
3063 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
3064 main_msg(_("--literal\t\tDon't expand wildcards"));
3065 #endif
3066 #ifdef FEAT_OLE
3067 main_msg(_("-register\t\tRegister this gvim for OLE"));
3068 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
3069 #endif
3070 #ifdef FEAT_GUI
3071 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
3072 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
3073 #endif
3074 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
3075 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
3076 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
3077 #ifdef FEAT_DIFF
3078 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
3079 #endif
3080 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
3081 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
3082 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
3083 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
3084 main_msg(_("-M\t\t\tModifications in text not allowed"));
3085 main_msg(_("-b\t\t\tBinary mode"));
3086 #ifdef FEAT_LISP
3087 main_msg(_("-l\t\t\tLisp mode"));
3088 #endif
3089 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
3090 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
3091 main_msg(_("-V[N][fname]\t\tBe verbose [level N] [log messages to fname]"));
3092 #ifdef FEAT_EVAL
3093 main_msg(_("-D\t\t\tDebugging mode"));
3094 #endif
3095 main_msg(_("-n\t\t\tNo swap file, use memory only"));
3096 main_msg(_("-r\t\t\tList swap files and exit"));
3097 main_msg(_("-r (with file name)\tRecover crashed session"));
3098 main_msg(_("-L\t\t\tSame as -r"));
3099 #ifdef AMIGA
3100 main_msg(_("-f\t\t\tDon't use newcli to open window"));
3101 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
3102 #endif
3103 #ifdef FEAT_ARABIC
3104 main_msg(_("-A\t\t\tstart in Arabic mode"));
3105 #endif
3106 #ifdef FEAT_RIGHTLEFT
3107 main_msg(_("-H\t\t\tStart in Hebrew mode"));
3108 #endif
3109 #ifdef FEAT_FKMAP
3110 main_msg(_("-F\t\t\tStart in Farsi mode"));
3111 #endif
3112 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
3113 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
3114 #ifdef FEAT_GUI
3115 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
3116 #endif
3117 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
3118 #ifdef FEAT_WINDOWS
3119 main_msg(_("-p[N]\t\tOpen N tab pages (default: one for each file)"));
3120 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
3121 main_msg(_("-O[N]\t\tLike -o but split vertically"));
3122 #endif
3123 main_msg(_("+\t\t\tStart at end of file"));
3124 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
3125 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
3126 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
3127 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
3128 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
3129 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
3130 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
3131 #ifdef FEAT_CRYPT
3132 main_msg(_("-x\t\t\tEdit encrypted files"));
3133 #endif
3134 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
3135 # if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
3136 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
3137 # endif
3138 main_msg(_("-X\t\t\tDo not connect to X server"));
3139 #endif
3140 #ifdef FEAT_CLIENTSERVER
3141 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
3142 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
3143 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
3144 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
3145 # ifdef FEAT_WINDOWS
3146 main_msg(_("--remote-tab[-wait][-silent] <files> As --remote but use tab page per file"));
3147 # endif
3148 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
3149 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
3150 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
3151 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
3152 #endif
3153 #ifdef STARTUPTIME
3154 main_msg(_("--startuptime=<file>\tWrite startup timing messages to <file>"));
3155 #endif
3156 #ifdef FEAT_VIMINFO
3157 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
3158 #endif
3159 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
3160 main_msg(_("--version\t\tPrint version information and exit"));
3162 #ifdef FEAT_GUI_X11
3163 # ifdef FEAT_GUI_MOTIF
3164 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
3165 # else
3166 # ifdef FEAT_GUI_ATHENA
3167 # ifdef FEAT_GUI_NEXTAW
3168 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
3169 # else
3170 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
3171 # endif
3172 # endif
3173 # endif
3174 main_msg(_("-display <display>\tRun vim on <display>"));
3175 main_msg(_("-iconic\t\tStart vim iconified"));
3176 # if 0
3177 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
3178 mch_msg(_("\t\t\t (Unimplemented)\n"));
3179 # endif
3180 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
3181 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
3182 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3183 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
3184 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
3185 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3186 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
3187 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
3188 # ifdef FEAT_GUI_ATHENA
3189 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
3190 # endif
3191 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3192 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
3193 main_msg(_("-xrm <resource>\tSet the specified resource"));
3194 #endif /* FEAT_GUI_X11 */
3195 #if defined(FEAT_GUI) && defined(RISCOS)
3196 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
3197 main_msg(_("--columns <number>\tInitial width of window in columns"));
3198 main_msg(_("--rows <number>\tInitial height of window in rows"));
3199 #endif
3200 #ifdef FEAT_GUI_GTK
3201 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
3202 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3203 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3204 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3205 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
3206 # ifdef HAVE_GTK2
3207 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
3208 # endif
3209 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
3210 #endif
3211 #ifdef FEAT_GUI_W32
3212 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
3213 main_msg(_("--windowid <HWND>\tOpen Vim inside another win32 widget"));
3214 #endif
3216 #ifdef FEAT_GUI_GNOME
3217 /* Gnome gives extra messages for --help if we continue, but not for -h. */
3218 if (gui.starting)
3219 mch_msg("\n");
3220 else
3221 #endif
3222 mch_exit(0);
3225 #if defined(HAS_SWAP_EXISTS_ACTION)
3227 * Check the result of the ATTENTION dialog:
3228 * When "Quit" selected, exit Vim.
3229 * When "Recover" selected, recover the file.
3231 static void
3232 check_swap_exists_action()
3234 if (swap_exists_action == SEA_QUIT)
3235 getout(1);
3236 handle_swap_exists(NULL);
3238 #endif
3240 #if defined(STARTUPTIME) || defined(PROTO)
3241 static void time_diff __ARGS((struct timeval *then, struct timeval *now));
3243 static struct timeval prev_timeval;
3245 # ifdef WIN3264
3247 * Windows doesn't have gettimeofday(), although it does have struct timeval.
3249 static int
3250 gettimeofday(struct timeval *tv, char *dummy)
3252 long t = clock();
3253 tv->tv_sec = t / CLOCKS_PER_SEC;
3254 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
3255 return 0;
3257 # endif
3260 * Save the previous time before doing something that could nest.
3261 * set "*tv_rel" to the time elapsed so far.
3263 void
3264 time_push(tv_rel, tv_start)
3265 void *tv_rel, *tv_start;
3267 *((struct timeval *)tv_rel) = prev_timeval;
3268 gettimeofday(&prev_timeval, NULL);
3269 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
3270 - ((struct timeval *)tv_rel)->tv_usec;
3271 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
3272 - ((struct timeval *)tv_rel)->tv_sec;
3273 if (((struct timeval *)tv_rel)->tv_usec < 0)
3275 ((struct timeval *)tv_rel)->tv_usec += 1000000;
3276 --((struct timeval *)tv_rel)->tv_sec;
3278 *(struct timeval *)tv_start = prev_timeval;
3282 * Compute the previous time after doing something that could nest.
3283 * Subtract "*tp" from prev_timeval;
3284 * Note: The arguments are (void *) to avoid trouble with systems that don't
3285 * have struct timeval.
3287 void
3288 time_pop(tp)
3289 void *tp; /* actually (struct timeval *) */
3291 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
3292 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
3293 if (prev_timeval.tv_usec < 0)
3295 prev_timeval.tv_usec += 1000000;
3296 --prev_timeval.tv_sec;
3300 static void
3301 time_diff(then, now)
3302 struct timeval *then;
3303 struct timeval *now;
3305 long usec;
3306 long msec;
3308 usec = now->tv_usec - then->tv_usec;
3309 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
3310 usec = usec % 1000L;
3311 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
3314 void
3315 time_msg(msg, tv_start)
3316 char *msg;
3317 void *tv_start; /* only for do_source: start time; actually
3318 (struct timeval *) */
3320 static struct timeval start;
3321 struct timeval now;
3323 if (time_fd != NULL)
3325 if (strstr(msg, "STARTING") != NULL)
3327 gettimeofday(&start, NULL);
3328 prev_timeval = start;
3329 fprintf(time_fd, "\n\ntimes in msec\n");
3330 fprintf(time_fd, " clock self+sourced self: sourced script\n");
3331 fprintf(time_fd, " clock elapsed: other lines\n\n");
3333 gettimeofday(&now, NULL);
3334 time_diff(&start, &now);
3335 if (((struct timeval *)tv_start) != NULL)
3337 fprintf(time_fd, " ");
3338 time_diff(((struct timeval *)tv_start), &now);
3340 fprintf(time_fd, " ");
3341 time_diff(&prev_timeval, &now);
3342 prev_timeval = now;
3343 fprintf(time_fd, ": %s\n", msg);
3347 #endif
3349 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3352 * Common code for the X command server and the Win32 command server.
3355 static char_u *build_drop_cmd __ARGS((int filec, char **filev, int tabs, int sendReply));
3358 * Do the client-server stuff, unless "--servername ''" was used.
3360 static void
3361 exec_on_server(parmp)
3362 mparm_T *parmp;
3364 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3366 # ifdef WIN32
3367 /* Initialise the client/server messaging infrastructure. */
3368 serverInitMessaging();
3369 # endif
3372 * When a command server argument was found, execute it. This may
3373 * exit Vim when it was successful. Otherwise it's executed further
3374 * on. Remember the encoding used here in "serverStrEnc".
3376 if (parmp->serverArg)
3378 cmdsrv_main(&parmp->argc, parmp->argv,
3379 parmp->serverName_arg, &parmp->serverStr);
3380 # ifdef FEAT_MBYTE
3381 parmp->serverStrEnc = vim_strsave(p_enc);
3382 # endif
3385 /* If we're still running, get the name to register ourselves.
3386 * On Win32 can register right now, for X11 need to setup the
3387 * clipboard first, it's further down. */
3388 parmp->servername = serverMakeName(parmp->serverName_arg,
3389 parmp->argv[0]);
3390 # ifdef WIN32
3391 if (parmp->servername != NULL)
3393 serverSetName(parmp->servername);
3394 vim_free(parmp->servername);
3396 # endif
3401 * Prepare for running as a Vim server.
3403 static void
3404 prepare_server(parmp)
3405 mparm_T *parmp;
3407 # if defined(FEAT_X11)
3409 * Register for remote command execution with :serversend and --remote
3410 * unless there was a -X or a --servername '' on the command line.
3411 * Only register nongui-vim's with an explicit --servername argument.
3412 * When running as root --servername is also required.
3414 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3415 # ifdef FEAT_GUI
3416 (gui.in_use
3417 # ifdef UNIX
3418 && getuid() != ROOT_UID
3419 # endif
3420 ) ||
3421 # endif
3422 parmp->serverName_arg != NULL))
3424 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3425 vim_free(parmp->servername);
3426 TIME_MSG("register server name");
3428 else
3429 serverDelayedStartName = parmp->servername;
3430 # endif
3433 * Execute command ourselves if we're here because the send failed (or
3434 * else we would have exited above).
3436 if (parmp->serverStr != NULL)
3438 char_u *p;
3440 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3441 parmp->serverStr, &p));
3442 vim_free(p);
3446 static void
3447 cmdsrv_main(argc, argv, serverName_arg, serverStr)
3448 int *argc;
3449 char **argv;
3450 char_u *serverName_arg;
3451 char_u **serverStr;
3453 char_u *res;
3454 int i;
3455 char_u *sname;
3456 int ret;
3457 int didone = FALSE;
3458 int exiterr = 0;
3459 char **newArgV = argv + 1;
3460 int newArgC = 1,
3461 Argc = *argc;
3462 int argtype;
3463 #define ARGTYPE_OTHER 0
3464 #define ARGTYPE_EDIT 1
3465 #define ARGTYPE_EDIT_WAIT 2
3466 #define ARGTYPE_SEND 3
3467 int silent = FALSE;
3468 int tabs = FALSE;
3469 # ifndef FEAT_X11
3470 HWND srv;
3471 # else
3472 Window srv;
3474 setup_term_clip();
3475 # endif
3477 sname = serverMakeName(serverName_arg, argv[0]);
3478 if (sname == NULL)
3479 return;
3482 * Execute the command server related arguments and remove them
3483 * from the argc/argv array; We may have to return into main()
3485 for (i = 1; i < Argc; i++)
3487 res = NULL;
3488 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
3490 for (; i < *argc; i++)
3492 *newArgV++ = argv[i];
3493 newArgC++;
3495 break;
3498 if (STRICMP(argv[i], "--remote-send") == 0)
3499 argtype = ARGTYPE_SEND;
3500 else if (STRNICMP(argv[i], "--remote", 8) == 0)
3502 char *p = argv[i] + 8;
3504 argtype = ARGTYPE_EDIT;
3505 while (*p != NUL)
3507 if (STRNICMP(p, "-wait", 5) == 0)
3509 argtype = ARGTYPE_EDIT_WAIT;
3510 p += 5;
3512 else if (STRNICMP(p, "-silent", 7) == 0)
3514 silent = TRUE;
3515 p += 7;
3517 else if (STRNICMP(p, "-tab", 4) == 0)
3519 tabs = TRUE;
3520 p += 4;
3522 else
3524 argtype = ARGTYPE_OTHER;
3525 break;
3529 else
3530 argtype = ARGTYPE_OTHER;
3532 if (argtype != ARGTYPE_OTHER)
3534 if (i == *argc - 1)
3535 mainerr_arg_missing((char_u *)argv[i]);
3536 if (argtype == ARGTYPE_SEND)
3538 *serverStr = (char_u *)argv[i + 1];
3539 i++;
3541 else
3543 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3544 tabs, argtype == ARGTYPE_EDIT_WAIT);
3545 if (*serverStr == NULL)
3547 /* Probably out of memory, exit. */
3548 didone = TRUE;
3549 exiterr = 1;
3550 break;
3552 Argc = i;
3554 # ifdef FEAT_X11
3555 if (xterm_dpy == NULL)
3557 mch_errmsg(_("No display"));
3558 ret = -1;
3560 else
3561 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3562 NULL, &srv, 0, 0, silent);
3563 # else
3564 /* Win32 always works? */
3565 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3566 # endif
3567 if (ret < 0)
3569 if (argtype == ARGTYPE_SEND)
3571 /* Failed to send, abort. */
3572 mch_errmsg(_(": Send failed.\n"));
3573 didone = TRUE;
3574 exiterr = 1;
3576 else if (!silent)
3577 /* Let vim start normally. */
3578 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3579 break;
3582 # ifdef FEAT_GUI_W32
3583 /* Guess that when the server name starts with "g" it's a GUI
3584 * server, which we can bring to the foreground here.
3585 * Foreground() in the server doesn't work very well. */
3586 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3587 SetForegroundWindow(srv);
3588 # endif
3591 * For --remote-wait: Wait until the server did edit each
3592 * file. Also detect that the server no longer runs.
3594 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3596 int numFiles = *argc - i - 1;
3597 int j;
3598 char_u *done = alloc(numFiles);
3599 char_u *p;
3600 # ifdef FEAT_GUI_W32
3601 NOTIFYICONDATA ni;
3602 int count = 0;
3603 extern HWND message_window;
3604 # endif
3606 if (numFiles > 0 && argv[i + 1][0] == '+')
3607 /* Skip "+cmd" argument, don't wait for it to be edited. */
3608 --numFiles;
3610 # ifdef FEAT_GUI_W32
3611 ni.cbSize = sizeof(ni);
3612 ni.hWnd = message_window;
3613 ni.uID = 0;
3614 ni.uFlags = NIF_ICON|NIF_TIP;
3615 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3616 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3617 Shell_NotifyIcon(NIM_ADD, &ni);
3618 # endif
3620 /* Wait for all files to unload in remote */
3621 memset(done, 0, numFiles);
3622 while (memchr(done, 0, numFiles) != NULL)
3624 # ifdef WIN32
3625 p = serverGetReply(srv, NULL, TRUE, TRUE);
3626 if (p == NULL)
3627 break;
3628 # else
3629 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3630 break;
3631 # endif
3632 j = atoi((char *)p);
3633 if (j >= 0 && j < numFiles)
3635 # ifdef FEAT_GUI_W32
3636 ++count;
3637 sprintf(ni.szTip, _("%d of %d edited"),
3638 count, numFiles);
3639 Shell_NotifyIcon(NIM_MODIFY, &ni);
3640 # endif
3641 done[j] = 1;
3644 # ifdef FEAT_GUI_W32
3645 Shell_NotifyIcon(NIM_DELETE, &ni);
3646 # endif
3649 else if (STRICMP(argv[i], "--remote-expr") == 0)
3651 if (i == *argc - 1)
3652 mainerr_arg_missing((char_u *)argv[i]);
3653 # ifdef WIN32
3654 /* Win32 always works? */
3655 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3656 &res, NULL, 1, FALSE) < 0)
3657 # else
3658 if (xterm_dpy == NULL)
3659 mch_errmsg(_("No display: Send expression failed.\n"));
3660 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3661 &res, NULL, 1, 1, FALSE) < 0)
3662 # endif
3664 if (res != NULL && *res != NUL)
3666 /* Output error from remote */
3667 mch_errmsg((char *)res);
3668 vim_free(res);
3669 res = NULL;
3671 mch_errmsg(_(": Send expression failed.\n"));
3674 else if (STRICMP(argv[i], "--serverlist") == 0)
3676 # ifdef WIN32
3677 /* Win32 always works? */
3678 res = serverGetVimNames();
3679 # else
3680 if (xterm_dpy != NULL)
3681 res = serverGetVimNames(xterm_dpy);
3682 # endif
3683 if (called_emsg)
3684 mch_errmsg("\n");
3686 else if (STRICMP(argv[i], "--servername") == 0)
3688 /* Alredy processed. Take it out of the command line */
3689 i++;
3690 continue;
3692 else
3694 *newArgV++ = argv[i];
3695 newArgC++;
3696 continue;
3698 didone = TRUE;
3699 if (res != NULL && *res != NUL)
3701 mch_msg((char *)res);
3702 if (res[STRLEN(res) - 1] != '\n')
3703 mch_msg("\n");
3705 vim_free(res);
3708 if (didone)
3710 display_errors(); /* display any collected messages */
3711 exit(exiterr); /* Mission accomplished - get out */
3714 /* Return back into main() */
3715 *argc = newArgC;
3716 vim_free(sname);
3720 * Build a ":drop" command to send to a Vim server.
3722 static char_u *
3723 build_drop_cmd(filec, filev, tabs, sendReply)
3724 int filec;
3725 char **filev;
3726 int tabs; /* Use ":tab drop" instead of ":drop". */
3727 int sendReply;
3729 garray_T ga;
3730 int i;
3731 char_u *inicmd = NULL;
3732 char_u *p;
3733 char_u cwd[MAXPATHL];
3735 if (filec > 0 && filev[0][0] == '+')
3737 inicmd = (char_u *)filev[0] + 1;
3738 filev++;
3739 filec--;
3741 /* Check if we have at least one argument. */
3742 if (filec <= 0)
3743 mainerr_arg_missing((char_u *)filev[-1]);
3744 if (mch_dirname(cwd, MAXPATHL) != OK)
3745 return NULL;
3746 if ((p = vim_strsave_escaped_ext(cwd,
3747 #ifdef BACKSLASH_IN_FILENAME
3748 "", /* rem_backslash() will tell what chars to escape */
3749 #else
3750 PATH_ESC_CHARS,
3751 #endif
3752 '\\', TRUE)) == NULL)
3753 return NULL;
3754 ga_init2(&ga, 1, 100);
3755 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3756 ga_concat(&ga, p);
3757 vim_free(p);
3759 /* Call inputsave() so that a prompt for an encryption key works. */
3760 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|");
3761 if (tabs)
3762 ga_concat(&ga, (char_u *)"tab ");
3763 ga_concat(&ga, (char_u *)"drop");
3764 for (i = 0; i < filec; i++)
3766 /* On Unix the shell has already expanded the wildcards, don't want to
3767 * do it again in the Vim server. On MS-Windows only escape
3768 * non-wildcard characters. */
3769 p = vim_strsave_escaped((char_u *)filev[i],
3770 #ifdef UNIX
3771 PATH_ESC_CHARS
3772 #else
3773 (char_u *)" \t%#"
3774 #endif
3776 if (p == NULL)
3778 vim_free(ga.ga_data);
3779 return NULL;
3781 ga_concat(&ga, (char_u *)" ");
3782 ga_concat(&ga, p);
3783 vim_free(p);
3785 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3786 * CTRL-\ CTRL-N again. */
3787 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3788 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3789 if (sendReply)
3790 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3791 ga_concat(&ga, (char_u *)"<CR>:");
3792 if (inicmd != NULL)
3794 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3795 * the following commands to be inserted as text. Use a "|",
3796 * hopefully "inicmd" does allow this... */
3797 ga_concat(&ga, inicmd);
3798 ga_concat(&ga, (char_u *)"|");
3800 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3801 * clear command line. */
3802 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
3803 ga_append(&ga, NUL);
3804 return ga.ga_data;
3808 * Replace termcodes such as <CR> and insert as key presses if there is room.
3810 void
3811 server_to_input_buf(str)
3812 char_u *str;
3814 char_u *ptr = NULL;
3815 char_u *cpo_save = p_cpo;
3817 /* Set 'cpoptions' the way we want it.
3818 * B set - backslashes are *not* treated specially
3819 * k set - keycodes are *not* reverse-engineered
3820 * < unset - <Key> sequences *are* interpreted
3821 * The last but one parameter of replace_termcodes() is TRUE so that the
3822 * <lt> sequence is recognised - needed for a real backslash.
3824 p_cpo = (char_u *)"Bk";
3825 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE, FALSE);
3826 p_cpo = cpo_save;
3828 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3831 * Add the string to the input stream.
3832 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3834 * First clear typed characters from the typeahead buffer, there could
3835 * be half a mapping there. Then append to the existing string, so
3836 * that multiple commands from a client are concatenated.
3838 if (typebuf.tb_maplen < typebuf.tb_len)
3839 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3840 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3842 /* Let input_available() know we inserted text in the typeahead
3843 * buffer. */
3844 typebuf_was_filled = TRUE;
3846 vim_free((char_u *)ptr);
3850 * Evaluate an expression that the client sent to a string.
3851 * Handles disabling error messages and disables debugging, otherwise Vim
3852 * hangs, waiting for "cont" to be typed.
3854 char_u *
3855 eval_client_expr_to_string(expr)
3856 char_u *expr;
3858 char_u *res;
3859 int save_dbl = debug_break_level;
3860 int save_ro = redir_off;
3862 debug_break_level = -1;
3863 redir_off = 0;
3864 ++emsg_skip;
3866 res = eval_to_string(expr, NULL, TRUE);
3868 debug_break_level = save_dbl;
3869 redir_off = save_ro;
3870 --emsg_skip;
3872 /* A client can tell us to redraw, but not to display the cursor, so do
3873 * that here. */
3874 setcursor();
3875 out_flush();
3876 #ifdef FEAT_GUI
3877 if (gui.in_use)
3878 gui_update_cursor(FALSE, FALSE);
3879 #endif
3881 return res;
3885 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3886 * return an allocated string. Otherwise return "data".
3887 * "*tofree" is set to the result when it needs to be freed later.
3889 char_u *
3890 serverConvert(client_enc, data, tofree)
3891 char_u *client_enc UNUSED;
3892 char_u *data;
3893 char_u **tofree;
3895 char_u *res = data;
3897 *tofree = NULL;
3898 # ifdef FEAT_MBYTE
3899 if (client_enc != NULL && p_enc != NULL)
3901 vimconv_T vimconv;
3903 vimconv.vc_type = CONV_NONE;
3904 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3905 && vimconv.vc_type != CONV_NONE)
3907 res = string_convert(&vimconv, data, NULL);
3908 if (res == NULL)
3909 res = data;
3910 else
3911 *tofree = res;
3913 convert_setup(&vimconv, NULL, NULL);
3915 # endif
3916 return res;
3921 * Make our basic server name: use the specified "arg" if given, otherwise use
3922 * the tail of the command "cmd" we were started with.
3923 * Return the name in allocated memory. This doesn't include a serial number.
3925 static char_u *
3926 serverMakeName(arg, cmd)
3927 char_u *arg;
3928 char *cmd;
3930 char_u *p;
3932 if (arg != NULL && *arg != NUL)
3933 p = vim_strsave_up(arg);
3934 else
3936 p = vim_strsave_up(gettail((char_u *)cmd));
3937 /* Remove .exe or .bat from the name. */
3938 if (p != NULL && vim_strchr(p, '.') != NULL)
3939 *vim_strchr(p, '.') = NUL;
3941 return p;
3943 #endif /* FEAT_CLIENTSERVER */
3946 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3948 #if defined(FEAT_FKMAP) || defined(PROTO)
3949 # include "farsi.c"
3950 #endif
3953 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3955 #if defined(FEAT_ARABIC) || defined(PROTO)
3956 # include "arabic.c"
3957 #endif