Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / main.c
blob31c11c7846aa29163dced62f282b99d6529cf6af
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(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 <sys/cygwin.h> /* for cygwin_conv_to_posix_path() */
24 # endif
25 # include <limits.h>
26 #endif
28 /* Maximum number of commands from + or -c arguments. */
29 #define MAX_ARG_CMDS 10
31 /* values for "window_layout" */
32 #define WIN_HOR 1 /* "-o" horizontally split windows */
33 #define WIN_VER 2 /* "-O" vertically split windows */
34 #define WIN_TABS 3 /* "-p" windows on tab pages */
36 /* Struct for various parameters passed between main() and other functions. */
37 typedef struct
39 int argc;
40 char **argv;
42 int evim_mode; /* started as "evim" */
43 char_u *use_vimrc; /* vimrc from -u argument */
45 int n_commands; /* no. of commands from + or -c */
46 char_u *commands[MAX_ARG_CMDS]; /* commands from + or -c arg. */
47 char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
48 int n_pre_commands; /* no. of commands from --cmd */
49 char_u *pre_commands[MAX_ARG_CMDS]; /* commands from --cmd argument */
51 int edit_type; /* type of editing to do */
52 char_u *tagname; /* tag from -t argument */
53 #ifdef FEAT_QUICKFIX
54 char_u *use_ef; /* 'errorfile' from -q argument */
55 #endif
57 int want_full_screen;
58 int stdout_isatty; /* is stdout a terminal? */
59 char_u *term; /* specified terminal name */
60 #ifdef FEAT_CRYPT
61 int ask_for_key; /* -x argument */
62 #endif
63 int no_swap_file; /* "-n" argument used */
64 #ifdef FEAT_EVAL
65 int use_debug_break_level;
66 #endif
67 #ifdef FEAT_WINDOWS
68 int window_count; /* number of windows to use */
69 int window_layout; /* 0, WIN_HOR, WIN_VER or WIN_TABS */
70 #endif
72 #ifdef FEAT_CLIENTSERVER
73 int serverArg; /* TRUE when argument for a server */
74 char_u *serverName_arg; /* cmdline arg for server name */
75 char_u *serverStr; /* remote server command */
76 char_u *serverStrEnc; /* encoding of serverStr */
77 char_u *servername; /* allocated name for our server */
78 #endif
79 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
80 int literal; /* don't expand file names */
81 #endif
82 #ifdef MSWIN
83 int full_path; /* file name argument was full path */
84 #endif
85 #ifdef FEAT_DIFF
86 int diff_mode; /* start with 'diff' set */
87 #endif
88 } mparm_T;
90 /* Values for edit_type. */
91 #define EDIT_NONE 0 /* no edit type yet */
92 #define EDIT_FILE 1 /* file name argument[s] given, use argument list */
93 #define EDIT_STDIN 2 /* read file from stdin */
94 #define EDIT_TAG 3 /* tag name argument given, use tagname */
95 #define EDIT_QF 4 /* start in quickfix mode */
97 #if defined(UNIX) || defined(VMS)
98 static int file_owned __ARGS((char *fname));
99 #endif
100 static void mainerr __ARGS((int, char_u *));
101 static void main_msg __ARGS((char *s));
102 static void usage __ARGS((void));
103 static int get_number_arg __ARGS((char_u *p, int *idx, int def));
104 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
105 static void init_locale __ARGS((void));
106 #endif
107 static void parse_command_name __ARGS((mparm_T *parmp));
108 static void early_arg_scan __ARGS((mparm_T *parmp));
109 static void command_line_scan __ARGS((mparm_T *parmp));
110 static void check_tty __ARGS((mparm_T *parmp));
111 static void read_stdin __ARGS((void));
112 static void create_windows __ARGS((mparm_T *parmp));
113 #ifdef FEAT_WINDOWS
114 static void edit_buffers __ARGS((mparm_T *parmp));
115 #endif
116 static void exe_pre_commands __ARGS((mparm_T *parmp));
117 static void exe_commands __ARGS((mparm_T *parmp));
118 static void source_startup_scripts __ARGS((mparm_T *parmp));
119 static void main_start_gui __ARGS((void));
120 #if defined(HAS_SWAP_EXISTS_ACTION)
121 static void check_swap_exists_action __ARGS((void));
122 #endif
123 #ifdef FEAT_CLIENTSERVER
124 static void exec_on_server __ARGS((mparm_T *parmp));
125 static void prepare_server __ARGS((mparm_T *parmp));
126 static void cmdsrv_main __ARGS((int *argc, char **argv, char_u *serverName_arg, char_u **serverStr));
127 static char_u *serverMakeName __ARGS((char_u *arg, char *cmd));
128 #endif
131 #ifdef STARTUPTIME
132 static FILE *time_fd = NULL;
133 #endif
136 * Different types of error messages.
138 static char *(main_errors[]) =
140 N_("Unknown option argument"),
141 #define ME_UNKNOWN_OPTION 0
142 N_("Too many edit arguments"),
143 #define ME_TOO_MANY_ARGS 1
144 N_("Argument missing after"),
145 #define ME_ARG_MISSING 2
146 N_("Garbage after option argument"),
147 #define ME_GARBAGE 3
148 N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments"),
149 #define ME_EXTRA_CMD 4
150 N_("Invalid argument for"),
151 #define ME_INVALID_ARG 5
154 #ifndef PROTO /* don't want a prototype for main() */
156 # ifdef VIMDLL
157 _export
158 # endif
159 # ifdef FEAT_GUI_MSWIN
160 # ifdef __BORLANDC__
161 _cdecl
162 # endif
163 VimMain
164 # else
165 main
166 # endif
167 (argc, argv)
168 int argc;
169 char **argv;
171 char_u *fname = NULL; /* file name from command line */
172 mparm_T params; /* various parameters passed between
173 * main() and other functions. */
176 * Do any system-specific initialisations. These can NOT use IObuff or
177 * NameBuff. Thus emsg2() cannot be called!
179 mch_early_init();
181 /* Many variables are in "params" so that we can pass them to invoked
182 * functions without a lot of arguments. "argc" and "argv" are also
183 * copied, so that they can be changed. */
184 vim_memset(&params, 0, sizeof(params));
185 params.argc = argc;
186 params.argv = argv;
187 params.want_full_screen = TRUE;
188 #ifdef FEAT_EVAL
189 params.use_debug_break_level = -1;
190 #endif
191 #ifdef FEAT_WINDOWS
192 params.window_count = -1;
193 #endif
195 #ifdef FEAT_TCL
196 vim_tcl_init(params.argv[0]);
197 #endif
199 #ifdef MEM_PROFILE
200 atexit(vim_mem_profile_dump);
201 #endif
203 #ifdef STARTUPTIME
204 time_fd = mch_fopen(STARTUPTIME, "a");
205 TIME_MSG("--- VIM STARTING ---");
206 #endif
207 starttime = time(NULL);
209 #ifdef __EMX__
210 _wildcard(&params.argc, &params.argv);
211 #endif
213 #ifdef FEAT_MBYTE
214 (void)mb_init(); /* init mb_bytelen_tab[] to ones */
215 #endif
216 #ifdef FEAT_EVAL
217 eval_init(); /* init global variables */
218 #endif
220 #ifdef __QNXNTO__
221 qnx_init(); /* PhAttach() for clipboard, (and gui) */
222 #endif
224 #ifdef MAC_OS_CLASSIC
225 /* Prepare for possibly starting GUI sometime */
226 /* Macintosh needs this before any memory is allocated. */
227 gui_prepare(&params.argc, params.argv);
228 TIME_MSG("GUI prepared");
229 #endif
231 /* Init the table of Normal mode commands. */
232 init_normal_cmds();
234 #if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC)
235 make_version(); /* Construct the long version string. */
236 #endif
239 * Allocate space for the generic buffers (needed for set_init_1() and
240 * EMSG2()).
242 if ((IObuff = alloc(IOSIZE)) == NULL
243 || (NameBuff = alloc(MAXPATHL)) == NULL)
244 mch_exit(0);
245 TIME_MSG("Allocated generic buffers");
247 #ifdef NBDEBUG
248 /* Wait a moment for debugging NetBeans. Must be after allocating
249 * NameBuff. */
250 nbdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL");
251 nbdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20);
252 TIME_MSG("NetBeans debug wait");
253 #endif
255 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
257 * Setup to use the current locale (for ctype() and many other things).
258 * NOTE: Translated messages with encodings other than latin1 will not
259 * work until set_init_1() has been called!
261 init_locale();
262 TIME_MSG("locale set");
263 #endif
265 #ifdef FEAT_GUI
266 gui.dofork = TRUE; /* default is to use fork() */
267 #endif
270 * Do a first scan of the arguments in "argv[]":
271 * -display or --display
272 * --server...
273 * --socketid
274 * --windowid
276 early_arg_scan(&params);
278 #ifdef FEAT_SUN_WORKSHOP
279 findYourself(params.argv[0]);
280 #endif
281 #if defined(FEAT_GUI) && !defined(MAC_OS_CLASSIC)
282 /* Prepare for possibly starting GUI sometime */
283 gui_prepare(&params.argc, params.argv);
284 TIME_MSG("GUI prepared");
285 #endif
287 #ifdef FEAT_CLIPBOARD
288 clip_init(FALSE); /* Initialise clipboard stuff */
289 TIME_MSG("clipboard setup");
290 #endif
293 * Check if we have an interactive window.
294 * On the Amiga: If there is no window, we open one with a newcli command
295 * (needed for :! to * work). mch_check_win() will also handle the -d or
296 * -dev argument.
298 params.stdout_isatty = (mch_check_win(params.argc, params.argv) != FAIL);
299 TIME_MSG("window checked");
302 * Allocate the first window and buffer.
303 * Can't do anything without it, exit when it fails.
305 if (win_alloc_first() == FAIL)
306 mch_exit(0);
308 init_yank(); /* init yank buffers */
310 alist_init(&global_alist); /* Init the argument list to empty. */
313 * Set the default values for the options.
314 * NOTE: Non-latin1 translated messages are working only after this,
315 * because this is where "has_mbyte" will be set, which is used by
316 * msg_outtrans_len_attr().
317 * First find out the home directory, needed to expand "~" in options.
319 init_homedir(); /* find real value of $HOME */
320 set_init_1();
321 TIME_MSG("inits 1");
323 #ifdef FEAT_EVAL
324 set_lang_var(); /* set v:lang and v:ctype */
325 #endif
327 #ifdef FEAT_CLIENTSERVER
329 * Do the client-server stuff, unless "--servername ''" was used.
330 * This may exit Vim if the command was sent to the server.
332 exec_on_server(&params);
333 #endif
336 * Figure out the way to work from the command name argv[0].
337 * "vimdiff" starts diff mode, "rvim" sets "restricted", etc.
339 parse_command_name(&params);
342 * Process the command line arguments. File names are put in the global
343 * argument list "global_alist".
345 command_line_scan(&params);
346 TIME_MSG("parsing arguments");
349 * On some systems, when we compile with the GUI, we always use it. On Mac
350 * there is no terminal version, and on Windows we can't fork one off with
351 * :gui.
353 #ifdef ALWAYS_USE_GUI
354 gui.starting = TRUE;
355 #else
356 # if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
358 * Check if the GUI can be started. Reset gui.starting if not.
359 * Don't know about other systems, stay on the safe side and don't check.
361 if (gui.starting && gui_init_check() == FAIL)
363 gui.starting = FALSE;
365 /* When running "evim" or "gvim -y" we need the menus, exit if we
366 * don't have them. */
367 if (params.evim_mode)
368 mch_exit(1);
370 # endif
371 #endif
373 if (GARGCOUNT > 0)
375 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
377 * Expand wildcards in file names.
379 if (!params.literal)
381 /* Temporarily add '(' and ')' to 'isfname'. These are valid
382 * filename characters but are excluded from 'isfname' to make
383 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
384 do_cmdline_cmd((char_u *)":set isf+=(,)");
385 alist_expand(NULL, 0);
386 do_cmdline_cmd((char_u *)":set isf&");
388 #endif
389 fname = alist_name(&GARGLIST[0]);
392 #if defined(WIN32) && defined(FEAT_MBYTE)
394 extern void set_alist_count(void);
396 /* Remember the number of entries in the argument list. If it changes
397 * we don't react on setting 'encoding'. */
398 set_alist_count();
400 #endif
402 #ifdef MSWIN
403 if (GARGCOUNT == 1 && params.full_path)
406 * If there is one filename, fully qualified, we have very probably
407 * been invoked from explorer, so change to the file's directory.
408 * Hint: to avoid this when typing a command use a forward slash.
409 * If the cd fails, it doesn't matter.
411 (void)vim_chdirfile(fname);
413 #endif
414 TIME_MSG("expanding arguments");
416 #ifdef FEAT_DIFF
417 if (params.diff_mode && params.window_count == -1)
418 params.window_count = 0; /* open up to 3 windows */
419 #endif
421 /* Don't redraw until much later. */
422 ++RedrawingDisabled;
425 * When listing swap file names, don't do cursor positioning et. al.
427 if (recoverymode && fname == NULL)
428 params.want_full_screen = FALSE;
431 * When certain to start the GUI, don't check capabilities of terminal.
432 * For GTK we can't be sure, but when started from the desktop it doesn't
433 * make sense to try using a terminal.
435 #if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
436 if (gui.starting
437 # ifdef FEAT_GUI_GTK
438 && !isatty(2)
439 # endif
441 params.want_full_screen = FALSE;
442 #endif
444 #if defined(FEAT_GUI_MAC) && defined(MACOS_X_UNIX)
445 /* When the GUI is started from Finder, need to display messages in a
446 * message box. isatty(2) returns TRUE anyway, thus we need to check the
447 * name to know we're not started from a terminal. */
448 if (gui.starting && (!isatty(2) || strcmp("/dev/console", ttyname(2)) == 0))
450 params.want_full_screen = FALSE;
452 /* Avoid always using "/" as the current directory. Note that when
453 * started from Finder the arglist will be filled later in
454 * HandleODocAE() and "fname" will be NULL. */
455 if (getcwd((char *)NameBuff, MAXPATHL) != NULL
456 && STRCMP(NameBuff, "/") == 0)
458 if (fname != NULL)
459 (void)vim_chdirfile(fname);
460 else
462 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
463 vim_chdir(NameBuff);
467 #endif
470 * mch_init() sets up the terminal (window) for use. This must be
471 * done after resetting full_screen, otherwise it may move the cursor
472 * (MSDOS).
473 * Note that we may use mch_exit() before mch_init()!
475 mch_init();
476 TIME_MSG("shell init");
478 #ifdef USE_XSMP
480 * For want of anywhere else to do it, try to connect to xsmp here.
481 * Fitting it in after gui_mch_init, but before gui_init (via termcapinit).
482 * Hijacking -X 'no X connection' to also disable XSMP connection as that
483 * has a similar delay upon failure.
484 * Only try if SESSION_MANAGER is set to something non-null.
486 if (!x_no_connect)
488 char *p = getenv("SESSION_MANAGER");
490 if (p != NULL && *p != NUL)
492 xsmp_init();
493 TIME_MSG("xsmp init");
496 #endif
499 * Print a warning if stdout is not a terminal.
501 check_tty(&params);
503 /* This message comes before term inits, but after setting "silent_mode"
504 * when the input is not a tty. */
505 if (GARGCOUNT > 1 && !silent_mode)
506 printf(_("%d files to edit\n"), GARGCOUNT);
508 if (params.want_full_screen && !silent_mode)
510 termcapinit(params.term); /* set terminal name and get terminal
511 capabilities (will set full_screen) */
512 screen_start(); /* don't know where cursor is now */
513 TIME_MSG("Termcap init");
517 * Set the default values for the options that use Rows and Columns.
519 ui_get_shellsize(); /* inits Rows and Columns */
520 #ifdef FEAT_NETBEANS_INTG
521 if (usingNetbeans)
522 Columns += 2; /* leave room for glyph gutter */
523 #endif
524 win_init_size();
525 #ifdef FEAT_DIFF
526 /* Set the 'diff' option now, so that it can be checked for in a .vimrc
527 * file. There is no buffer yet though. */
528 if (params.diff_mode)
529 diff_win_options(firstwin, FALSE);
530 #endif
532 cmdline_row = Rows - p_ch;
533 msg_row = cmdline_row;
534 screenalloc(FALSE); /* allocate screen buffers */
535 set_init_2();
536 TIME_MSG("inits 2");
538 msg_scroll = TRUE;
539 no_wait_return = TRUE;
541 init_mappings(); /* set up initial mappings */
543 init_highlight(TRUE, FALSE); /* set the default highlight groups */
544 TIME_MSG("init highlight");
546 #ifdef FEAT_EVAL
547 /* Set the break level after the terminal is initialized. */
548 debug_break_level = params.use_debug_break_level;
549 #endif
551 /* Execute --cmd arguments. */
552 exe_pre_commands(&params);
554 /* Source startup scripts. */
555 source_startup_scripts(&params);
557 #ifdef FEAT_EVAL
559 * Read all the plugin files.
560 * Only when compiled with +eval, since most plugins need it.
562 if (p_lpl)
564 # ifdef VMS /* Somehow VMS doesn't handle the "**". */
565 source_runtime((char_u *)"plugin/*.vim", TRUE);
566 # else
567 source_runtime((char_u *)"plugin/**/*.vim", TRUE);
568 # endif
569 TIME_MSG("loading plugins");
571 #endif
573 #ifdef FEAT_DIFF
574 /* Decide about window layout for diff mode after reading vimrc. */
575 if (params.diff_mode && params.window_layout == 0)
577 if (diffopt_horizontal())
578 params.window_layout = WIN_HOR; /* use horizontal split */
579 else
580 params.window_layout = WIN_VER; /* use vertical split */
582 #endif
585 * Recovery mode without a file name: List swap files.
586 * This uses the 'dir' option, therefore it must be after the
587 * initializations.
589 if (recoverymode && fname == NULL)
591 recover_names(NULL, TRUE, 0);
592 mch_exit(0);
596 * Set a few option defaults after reading .vimrc files:
597 * 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
599 set_init_3();
600 TIME_MSG("inits 3");
603 * "-n" argument: Disable swap file by setting 'updatecount' to 0.
604 * Note that this overrides anything from a vimrc file.
606 if (params.no_swap_file)
607 p_uc = 0;
609 #ifdef FEAT_FKMAP
610 if (curwin->w_p_rl && p_altkeymap)
612 p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
613 # ifdef FEAT_ARABIC
614 curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
615 # endif
616 p_fkmap = TRUE; /* Set the Farsi keymap mode */
618 #endif
620 #ifdef FEAT_GUI
621 if (gui.starting)
623 #if defined(UNIX) || defined(VMS)
624 /* When something caused a message from a vimrc script, need to output
625 * an extra newline before the shell prompt. */
626 if (did_emsg || msg_didout)
627 putchar('\n');
628 #endif
630 gui_start(); /* will set full_screen to TRUE */
631 TIME_MSG("starting GUI");
633 /* When running "evim" or "gvim -y" we need the menus, exit if we
634 * don't have them. */
635 if (!gui.in_use && params.evim_mode)
636 mch_exit(1);
638 #endif
640 #ifdef SPAWNO /* special MSDOS swapping library */
641 init_SPAWNO("", SWAP_ANY);
642 #endif
644 #ifdef FEAT_VIMINFO
646 * Read in registers, history etc, but not marks, from the viminfo file
648 if (*p_viminfo != NUL)
650 read_viminfo(NULL, TRUE, FALSE, FALSE);
651 TIME_MSG("reading viminfo");
653 #endif
655 #ifdef FEAT_QUICKFIX
657 * "-q errorfile": Load the error file now.
658 * If the error file can't be read, exit before doing anything else.
660 if (params.edit_type == EDIT_QF)
662 if (params.use_ef != NULL)
663 set_string_option_direct((char_u *)"ef", -1,
664 params.use_ef, OPT_FREE, SID_CARG);
665 if (qf_init(NULL, p_ef, p_efm, TRUE) < 0)
667 out_char('\n');
668 mch_exit(3);
670 TIME_MSG("reading errorfile");
672 #endif
675 * Start putting things on the screen.
676 * Scroll screen down before drawing over it
677 * Clear screen now, so file message will not be cleared.
679 starting = NO_BUFFERS;
680 no_wait_return = FALSE;
681 if (!exmode_active)
682 msg_scroll = FALSE;
684 #ifdef FEAT_GUI
686 * This seems to be required to make callbacks to be called now, instead
687 * of after things have been put on the screen, which then may be deleted
688 * when getting a resize callback.
689 * For the Mac this handles putting files dropped on the Vim icon to
690 * global_alist.
692 if (gui.in_use)
694 # ifdef FEAT_SUN_WORKSHOP
695 if (!usingSunWorkShop)
696 # endif
697 gui_wait_for_chars(50L);
698 TIME_MSG("GUI delay");
700 #endif
702 #if defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)
703 qnx_clip_init();
704 #endif
706 #ifdef FEAT_XCLIPBOARD
707 /* Start using the X clipboard, unless the GUI was started. */
708 # ifdef FEAT_GUI
709 if (!gui.in_use)
710 # endif
712 setup_term_clip();
713 TIME_MSG("setup clipboard");
715 #endif
717 #ifdef FEAT_CLIENTSERVER
718 /* Prepare for being a Vim server. */
719 prepare_server(&params);
720 #endif
723 * If "-" argument given: Read file from stdin.
724 * Do this before starting Raw mode, because it may change things that the
725 * writing end of the pipe doesn't like, e.g., in case stdin and stderr
726 * are the same terminal: "cat | vim -".
727 * Using autocommands here may cause trouble...
729 if (params.edit_type == EDIT_STDIN && !recoverymode)
730 read_stdin();
732 #if defined(UNIX) || defined(VMS)
733 /* When switching screens and something caused a message from a vimrc
734 * script, need to output an extra newline on exit. */
735 if ((did_emsg || msg_didout) && *T_TI != NUL)
736 newline_on_exit = TRUE;
737 #endif
740 * When done something that is not allowed or error message call
741 * wait_return. This must be done before starttermcap(), because it may
742 * switch to another screen. It must be done after settmode(TMODE_RAW),
743 * because we want to react on a single key stroke.
744 * Call settmode and starttermcap here, so the T_KS and T_TI may be
745 * defined by termcapinit and redefined in .exrc.
747 settmode(TMODE_RAW);
748 TIME_MSG("setting raw mode");
750 if (need_wait_return || msg_didany)
752 wait_return(TRUE);
753 TIME_MSG("waiting for return");
756 starttermcap(); /* start termcap if not done by wait_return() */
757 TIME_MSG("start termcap");
759 #ifdef FEAT_MOUSE
760 setmouse(); /* may start using the mouse */
761 #endif
762 if (scroll_region)
763 scroll_region_reset(); /* In case Rows changed */
764 scroll_start(); /* may scroll the screen to the right position */
767 * Don't clear the screen when starting in Ex mode, unless using the GUI.
769 if (exmode_active
770 #ifdef FEAT_GUI
771 && !gui.in_use
772 #endif
774 must_redraw = CLEAR;
775 else
777 screenclear(); /* clear screen */
778 TIME_MSG("clearing screen");
781 #ifdef FEAT_CRYPT
782 if (params.ask_for_key)
784 (void)get_crypt_key(TRUE, TRUE);
785 TIME_MSG("getting crypt key");
787 #endif
789 no_wait_return = TRUE;
792 * Create the requested number of windows and edit buffers in them.
793 * Also does recovery if "recoverymode" set.
795 create_windows(&params);
796 TIME_MSG("opening buffers");
798 #ifdef FEAT_EVAL
799 /* clear v:swapcommand */
800 set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
801 #endif
803 /* Ex starts at last line of the file */
804 if (exmode_active)
805 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
807 #ifdef FEAT_AUTOCMD
808 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
809 TIME_MSG("BufEnter autocommands");
810 #endif
811 setpcmark();
813 #ifdef FEAT_QUICKFIX
815 * When started with "-q errorfile" jump to first error now.
817 if (params.edit_type == EDIT_QF)
819 qf_jump(NULL, 0, 0, FALSE);
820 TIME_MSG("jump to first error");
822 #endif
824 #ifdef FEAT_WINDOWS
826 * If opened more than one window, start editing files in the other
827 * windows.
829 edit_buffers(&params);
830 #endif
832 #ifdef FEAT_DIFF
833 if (params.diff_mode)
835 win_T *wp;
837 /* set options in each window for "vimdiff". */
838 for (wp = firstwin; wp != NULL; wp = wp->w_next)
839 diff_win_options(wp, TRUE);
841 #endif
844 * Shorten any of the filenames, but only when absolute.
846 shorten_fnames(FALSE);
849 * Need to jump to the tag before executing the '-c command'.
850 * Makes "vim -c '/return' -t main" work.
852 if (params.tagname != NULL)
854 #if defined(HAS_SWAP_EXISTS_ACTION)
855 swap_exists_did_quit = FALSE;
856 #endif
858 vim_snprintf((char *)IObuff, IOSIZE, "ta %s", params.tagname);
859 do_cmdline_cmd(IObuff);
860 TIME_MSG("jumping to tag");
862 #if defined(HAS_SWAP_EXISTS_ACTION)
863 /* If the user doesn't want to edit the file then we quit here. */
864 if (swap_exists_did_quit)
865 getout(1);
866 #endif
869 /* Execute any "+", "-c" and "-S" arguments. */
870 if (params.n_commands > 0)
871 exe_commands(&params);
873 RedrawingDisabled = 0;
874 redraw_all_later(NOT_VALID);
875 no_wait_return = FALSE;
876 starting = 0;
878 #ifdef FEAT_TERMRESPONSE
879 /* Requesting the termresponse is postponed until here, so that a "-c q"
880 * argument doesn't make it appear in the shell Vim was started from. */
881 may_req_termresponse();
882 #endif
884 /* start in insert mode */
885 if (p_im)
886 need_start_insertmode = TRUE;
888 #ifdef FEAT_AUTOCMD
889 apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
890 TIME_MSG("VimEnter autocommands");
891 #endif
893 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
894 /* When a startup script or session file setup for diff'ing and
895 * scrollbind, sync the scrollbind now. */
896 if (curwin->w_p_diff && curwin->w_p_scb)
898 update_topline();
899 check_scrollbind((linenr_T)0, 0L);
900 TIME_MSG("diff scrollbinding");
902 #endif
904 #if defined(WIN3264) && !defined(FEAT_GUI_W32)
905 mch_set_winsize_now(); /* Allow winsize changes from now on */
906 #endif
908 #if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
909 /* When tab pages were created, may need to update the tab pages line and
910 * scrollbars. This is skipped while creating them. */
911 if (first_tabpage->tp_next != NULL)
913 out_flush();
914 gui_init_which_components(NULL);
915 gui_update_scrollbars(TRUE);
917 need_mouse_correct = TRUE;
918 #endif
920 /* If ":startinsert" command used, stuff a dummy command to be able to
921 * call normal_cmd(), which will then start Insert mode. */
922 if (restart_edit != 0)
923 stuffcharReadbuff(K_NOP);
925 #ifdef FEAT_NETBEANS_INTG
926 if (usingNetbeans)
927 /* Tell the client that it can start sending commands. */
928 netbeans_startup_done();
929 #endif
931 TIME_MSG("before starting main loop");
934 * Call the main command loop. This never returns.
936 main_loop(FALSE, FALSE);
938 return 0;
940 #endif /* PROTO */
943 * Main loop: Execute Normal mode commands until exiting Vim.
944 * Also used to handle commands in the command-line window, until the window
945 * is closed.
946 * Also used to handle ":visual" command after ":global": execute Normal mode
947 * commands, return when entering Ex mode. "noexmode" is TRUE then.
949 void
950 main_loop(cmdwin, noexmode)
951 int cmdwin; /* TRUE when working in the command-line window */
952 int noexmode; /* TRUE when return on entering Ex mode */
954 oparg_T oa; /* operator arguments */
955 int previous_got_int = FALSE; /* "got_int" was TRUE */
957 #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
958 /* Setup to catch a terminating error from the X server. Just ignore
959 * it, restore the state and continue. This might not always work
960 * properly, but at least we don't exit unexpectedly when the X server
961 * exists while Vim is running in a console. */
962 if (!cmdwin && !noexmode && SETJMP(x_jump_env))
964 State = NORMAL;
965 # ifdef FEAT_VISUAL
966 VIsual_active = FALSE;
967 # endif
968 got_int = TRUE;
969 need_wait_return = FALSE;
970 global_busy = FALSE;
971 exmode_active = 0;
972 skip_redraw = FALSE;
973 RedrawingDisabled = 0;
974 no_wait_return = 0;
975 # ifdef FEAT_EVAL
976 emsg_skip = 0;
977 # endif
978 emsg_off = 0;
979 # ifdef FEAT_MOUSE
980 setmouse();
981 # endif
982 settmode(TMODE_RAW);
983 starttermcap();
984 scroll_start();
985 redraw_later_clear();
987 #endif
989 clear_oparg(&oa);
990 while (!cmdwin
991 #ifdef FEAT_CMDWIN
992 || cmdwin_result == 0
993 #endif
996 if (stuff_empty())
998 did_check_timestamps = FALSE;
999 if (need_check_timestamps)
1000 check_timestamps(FALSE);
1001 if (need_wait_return) /* if wait_return still needed ... */
1002 wait_return(FALSE); /* ... call it now */
1003 if (need_start_insertmode && goto_im()
1004 #ifdef FEAT_VISUAL
1005 && !VIsual_active
1006 #endif
1009 need_start_insertmode = FALSE;
1010 stuffReadbuff((char_u *)"i"); /* start insert mode next */
1011 /* skip the fileinfo message now, because it would be shown
1012 * after insert mode finishes! */
1013 need_fileinfo = FALSE;
1017 /* Reset "got_int" now that we got back to the main loop. Except when
1018 * inside a ":g/pat/cmd" command, then the "got_int" needs to abort
1019 * the ":g" command.
1020 * For ":g/pat/vi" we reset "got_int" when used once. When used
1021 * a second time we go back to Ex mode and abort the ":g" command. */
1022 if (got_int)
1024 if (noexmode && global_busy && !exmode_active && previous_got_int)
1026 /* Typed two CTRL-C in a row: go back to ex mode as if "Q" was
1027 * used and keep "got_int" set, so that it aborts ":g". */
1028 exmode_active = EXMODE_NORMAL;
1029 State = NORMAL;
1031 else if (!global_busy || !exmode_active)
1033 if (!quit_more)
1034 (void)vgetc(); /* flush all buffers */
1035 got_int = FALSE;
1037 previous_got_int = TRUE;
1039 else
1040 previous_got_int = FALSE;
1042 if (!exmode_active)
1043 msg_scroll = FALSE;
1044 quit_more = FALSE;
1047 * If skip redraw is set (for ":" in wait_return()), don't redraw now.
1048 * If there is nothing in the stuff_buffer or do_redraw is TRUE,
1049 * update cursor and redraw.
1051 if (skip_redraw || exmode_active)
1052 skip_redraw = FALSE;
1053 else if (do_redraw || stuff_empty())
1055 #ifdef FEAT_AUTOCMD
1056 /* Trigger CursorMoved if the cursor moved. */
1057 if (!finish_op && has_cursormoved()
1058 && !equalpos(last_cursormoved, curwin->w_cursor))
1060 apply_autocmds(EVENT_CURSORMOVED, NULL, NULL, FALSE, curbuf);
1061 last_cursormoved = curwin->w_cursor;
1063 #endif
1065 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
1066 /* Scroll-binding for diff mode may have been postponed until
1067 * here. Avoids doing it for every change. */
1068 if (diff_need_scrollbind)
1070 check_scrollbind((linenr_T)0, 0L);
1071 diff_need_scrollbind = FALSE;
1073 #endif
1074 #if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
1075 /* Include a closed fold completely in the Visual area. */
1076 foldAdjustVisual();
1077 #endif
1078 #ifdef FEAT_FOLDING
1080 * When 'foldclose' is set, apply 'foldlevel' to folds that don't
1081 * contain the cursor.
1082 * When 'foldopen' is "all", open the fold(s) under the cursor.
1083 * This may mark the window for redrawing.
1085 if (hasAnyFolding(curwin) && !char_avail())
1087 foldCheckClose();
1088 if (fdo_flags & FDO_ALL)
1089 foldOpenCursor();
1091 #endif
1094 * Before redrawing, make sure w_topline is correct, and w_leftcol
1095 * if lines don't wrap, and w_skipcol if lines wrap.
1097 update_topline();
1098 validate_cursor();
1100 #ifdef FEAT_VISUAL
1101 if (VIsual_active)
1102 update_curbuf(INVERTED);/* update inverted part */
1103 else
1104 #endif
1105 if (must_redraw)
1106 update_screen(0);
1107 else if (redraw_cmdline || clear_cmdline)
1108 showmode();
1109 #ifdef FEAT_WINDOWS
1110 redraw_statuslines();
1111 #endif
1112 #ifdef FEAT_TITLE
1113 if (need_maketitle)
1114 maketitle();
1115 #endif
1116 /* display message after redraw */
1117 if (keep_msg != NULL)
1119 char_u *p;
1121 /* msg_attr_keep() will set keep_msg to NULL, must free the
1122 * string here. */
1123 p = keep_msg;
1124 keep_msg = NULL;
1125 msg_attr(p, keep_msg_attr);
1126 vim_free(p);
1128 if (need_fileinfo) /* show file info after redraw */
1130 fileinfo(FALSE, TRUE, FALSE);
1131 need_fileinfo = FALSE;
1134 emsg_on_display = FALSE; /* can delete error message now */
1135 did_emsg = FALSE;
1136 msg_didany = FALSE; /* reset lines_left in msg_start() */
1137 may_clear_sb_text(); /* clear scroll-back text on next msg */
1138 showruler(FALSE);
1140 setcursor();
1141 cursor_on();
1143 do_redraw = FALSE;
1145 #ifdef FEAT_GUI
1146 if (need_mouse_correct)
1147 gui_mouse_correct();
1148 #endif
1151 * Update w_curswant if w_set_curswant has been set.
1152 * Postponed until here to avoid computing w_virtcol too often.
1154 update_curswant();
1156 #ifdef FEAT_EVAL
1158 * May perform garbage collection when waiting for a character, but
1159 * only at the very toplevel. Otherwise we may be using a List or
1160 * Dict internally somewhere.
1161 * "may_garbage_collect" is reset in vgetc() which is invoked through
1162 * do_exmode() and normal_cmd().
1164 may_garbage_collect = (!cmdwin && !noexmode);
1165 #endif
1167 * If we're invoked as ex, do a round of ex commands.
1168 * Otherwise, get and execute a normal mode command.
1170 if (exmode_active)
1172 if (noexmode) /* End of ":global/path/visual" commands */
1173 return;
1174 do_exmode(exmode_active == EXMODE_VIM);
1176 else
1177 normal_cmd(&oa, TRUE);
1182 #if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO)
1184 * Exit, but leave behind swap files for modified buffers.
1186 void
1187 getout_preserve_modified(exitval)
1188 int exitval;
1190 # if defined(SIGHUP) && defined(SIG_IGN)
1191 /* Ignore SIGHUP, because a dropped connection causes a read error, which
1192 * makes Vim exit and then handling SIGHUP causes various reentrance
1193 * problems. */
1194 signal(SIGHUP, SIG_IGN);
1195 # endif
1197 ml_close_notmod(); /* close all not-modified buffers */
1198 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
1199 ml_close_all(FALSE); /* close all memfiles, without deleting */
1200 getout(exitval); /* exit Vim properly */
1202 #endif
1205 /* Exit properly */
1206 void
1207 getout(exitval)
1208 int exitval;
1210 #ifdef FEAT_AUTOCMD
1211 buf_T *buf;
1212 win_T *wp;
1213 tabpage_T *tp, *next_tp;
1214 #endif
1216 exiting = TRUE;
1218 /* When running in Ex mode an error causes us to exit with a non-zero exit
1219 * code. POSIX requires this, although it's not 100% clear from the
1220 * standard. */
1221 if (exmode_active)
1222 exitval += ex_exitval;
1224 /* Position the cursor on the last screen line, below all the text */
1225 #ifdef FEAT_GUI
1226 if (!gui.in_use)
1227 #endif
1228 windgoto((int)Rows - 1, 0);
1230 #if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
1231 /* Optionally print hashtable efficiency. */
1232 hash_debug_results();
1233 #endif
1235 #ifdef FEAT_GUI
1236 msg_didany = FALSE;
1237 #endif
1239 #ifdef FEAT_AUTOCMD
1240 /* Trigger BufWinLeave for all windows, but only once per buffer. */
1241 # if defined FEAT_WINDOWS
1242 for (tp = first_tabpage; tp != NULL; tp = next_tp)
1244 next_tp = tp->tp_next;
1245 for (wp = (tp == curtab)
1246 ? firstwin : tp->tp_firstwin; wp != NULL; wp = wp->w_next)
1248 buf = wp->w_buffer;
1249 if (buf->b_changedtick != -1)
1251 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
1252 FALSE, buf);
1253 buf->b_changedtick = -1; /* note that we did it already */
1254 /* start all over, autocommands may mess up the lists */
1255 next_tp = first_tabpage;
1256 break;
1260 # else
1261 apply_autocmds(EVENT_BUFWINLEAVE, curbuf, curbuf->b_fname, FALSE, curbuf);
1262 # endif
1264 /* Trigger BufUnload for buffers that are loaded */
1265 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1266 if (buf->b_ml.ml_mfp != NULL)
1268 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
1269 FALSE, buf);
1270 if (!buf_valid(buf)) /* autocmd may delete the buffer */
1271 break;
1273 apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
1274 #endif
1276 #ifdef FEAT_VIMINFO
1277 if (*p_viminfo != NUL)
1278 /* Write out the registers, history, marks etc, to the viminfo file */
1279 write_viminfo(NULL, FALSE);
1280 #endif
1282 #ifdef FEAT_AUTOCMD
1283 apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
1284 #endif
1286 #ifdef FEAT_PROFILE
1287 profile_dump();
1288 #endif
1290 if (did_emsg
1291 #ifdef FEAT_GUI
1292 || (gui.in_use && msg_didany && p_verbose > 0)
1293 #endif
1296 /* give the user a chance to read the (error) message */
1297 no_wait_return = FALSE;
1298 wait_return(FALSE);
1301 #ifdef FEAT_AUTOCMD
1302 /* Position the cursor again, the autocommands may have moved it */
1303 # ifdef FEAT_GUI
1304 if (!gui.in_use)
1305 # endif
1306 windgoto((int)Rows - 1, 0);
1307 #endif
1309 #ifdef FEAT_MZSCHEME
1310 mzscheme_end();
1311 #endif
1312 #ifdef FEAT_TCL
1313 tcl_end();
1314 #endif
1315 #ifdef FEAT_RUBY
1316 ruby_end();
1317 #endif
1318 #ifdef FEAT_PYTHON
1319 python_end();
1320 #endif
1321 #ifdef FEAT_PERL
1322 perl_end();
1323 #endif
1324 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
1325 iconv_end();
1326 #endif
1327 #ifdef FEAT_NETBEANS_INTG
1328 netbeans_end();
1329 #endif
1330 #ifdef FEAT_CSCOPE
1331 cs_end();
1332 #endif
1333 #ifdef FEAT_EVAL
1334 if (garbage_collect_at_exit)
1335 garbage_collect();
1336 #endif
1338 mch_exit(exitval);
1342 * Get a (optional) count for a Vim argument.
1344 static int
1345 get_number_arg(p, idx, def)
1346 char_u *p; /* pointer to argument */
1347 int *idx; /* index in argument, is incremented */
1348 int def; /* default value */
1350 if (vim_isdigit(p[*idx]))
1352 def = atoi((char *)&(p[*idx]));
1353 while (vim_isdigit(p[*idx]))
1354 *idx = *idx + 1;
1356 return def;
1359 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1361 * Setup to use the current locale (for ctype() and many other things).
1363 static void
1364 init_locale()
1366 setlocale(LC_ALL, "");
1368 # if defined(FEAT_FLOAT) && defined(LC_NUMERIC)
1369 /* Make sure strtod() uses a decimal point, not a comma. */
1370 setlocale(LC_NUMERIC, "C");
1371 # endif
1373 # ifdef WIN32
1374 /* Apparently MS-Windows printf() may cause a crash when we give it 8-bit
1375 * text while it's expecting text in the current locale. This call avoids
1376 * that. */
1377 setlocale(LC_CTYPE, "C");
1378 # endif
1380 # ifdef FEAT_GETTEXT
1382 int mustfree = FALSE;
1383 char_u *p;
1385 # ifdef DYNAMIC_GETTEXT
1386 /* Initialize the gettext library */
1387 dyn_libintl_init(NULL);
1388 # endif
1389 /* expand_env() doesn't work yet, because chartab[] is not initialized
1390 * yet, call vim_getenv() directly */
1391 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1392 if (p != NULL && *p != NUL)
1394 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/lang", p);
1395 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1397 if (mustfree)
1398 vim_free(p);
1399 textdomain(VIMPACKAGE);
1401 # endif
1403 #endif
1406 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1407 * If the executable name starts with "r" we disable shell commands.
1408 * If the next character is "e" we run in Easy mode.
1409 * If the next character is "g" we run the GUI version.
1410 * If the next characters are "view" we start in readonly mode.
1411 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1412 * If the next characters are "ex" we start in Ex mode. If it's followed
1413 * by "im" use improved Ex mode.
1415 static void
1416 parse_command_name(parmp)
1417 mparm_T *parmp;
1419 char_u *initstr;
1421 initstr = gettail((char_u *)parmp->argv[0]);
1423 #ifdef MACOS_X_UNIX
1424 /* An issue has been seen when launching Vim in such a way that
1425 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1426 * executable or a symbolic link of it. Until this issue is resolved
1427 * we prohibit the GUI from being used.
1429 if (STRCMP(initstr, parmp->argv[0]) == 0)
1430 disallow_gui = TRUE;
1432 /* TODO: On MacOS X default to gui if argv[0] ends in:
1433 * /Vim.app/Contents/MacOS/Vim */
1434 #endif
1436 #ifdef FEAT_EVAL
1437 set_vim_var_string(VV_PROGNAME, initstr, -1);
1438 #endif
1440 if (TOLOWER_ASC(initstr[0]) == 'r')
1442 restricted = TRUE;
1443 ++initstr;
1446 /* Avoid using evim mode for "editor". */
1447 if (TOLOWER_ASC(initstr[0]) == 'e'
1448 && (TOLOWER_ASC(initstr[1]) == 'v'
1449 || TOLOWER_ASC(initstr[1]) == 'g'))
1451 #ifdef FEAT_GUI
1452 gui.starting = TRUE;
1453 #endif
1454 parmp->evim_mode = TRUE;
1455 ++initstr;
1458 if (TOLOWER_ASC(initstr[0]) == 'g' || initstr[0] == 'k')
1460 main_start_gui();
1461 #ifdef FEAT_GUI
1462 ++initstr;
1463 #endif
1466 if (STRNICMP(initstr, "view", 4) == 0)
1468 readonlymode = TRUE;
1469 curbuf->b_p_ro = TRUE;
1470 p_uc = 10000; /* don't update very often */
1471 initstr += 4;
1473 else if (STRNICMP(initstr, "vim", 3) == 0)
1474 initstr += 3;
1476 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1477 if (STRICMP(initstr, "diff") == 0)
1479 #ifdef FEAT_DIFF
1480 parmp->diff_mode = TRUE;
1481 #else
1482 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1483 mch_errmsg("\n");
1484 mch_exit(2);
1485 #endif
1488 if (STRNICMP(initstr, "ex", 2) == 0)
1490 if (STRNICMP(initstr + 2, "im", 2) == 0)
1491 exmode_active = EXMODE_VIM;
1492 else
1493 exmode_active = EXMODE_NORMAL;
1494 change_compatible(TRUE); /* set 'compatible' */
1499 * Get the name of the display, before gui_prepare() removes it from
1500 * argv[]. Used for the xterm-clipboard display.
1502 * Also find the --server... arguments and --socketid and --windowid
1504 /*ARGSUSED*/
1505 static void
1506 early_arg_scan(parmp)
1507 mparm_T *parmp;
1509 #if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER)
1510 int argc = parmp->argc;
1511 char **argv = parmp->argv;
1512 int i;
1514 for (i = 1; i < argc; i++)
1516 if (STRCMP(argv[i], "--") == 0)
1517 break;
1518 # ifdef FEAT_XCLIPBOARD
1519 else if (STRICMP(argv[i], "-display") == 0
1520 # if defined(FEAT_GUI_GTK)
1521 || STRICMP(argv[i], "--display") == 0
1522 # endif
1525 if (i == argc - 1)
1526 mainerr_arg_missing((char_u *)argv[i]);
1527 xterm_display = argv[++i];
1529 # endif
1530 # ifdef FEAT_CLIENTSERVER
1531 else if (STRICMP(argv[i], "--servername") == 0)
1533 if (i == argc - 1)
1534 mainerr_arg_missing((char_u *)argv[i]);
1535 parmp->serverName_arg = (char_u *)argv[++i];
1537 else if (STRICMP(argv[i], "--serverlist") == 0)
1538 parmp->serverArg = TRUE;
1539 else if (STRNICMP(argv[i], "--remote", 8) == 0)
1541 parmp->serverArg = TRUE;
1542 # ifdef FEAT_GUI
1543 if (strstr(argv[i], "-wait") != 0)
1544 /* don't fork() when starting the GUI to edit files ourself */
1545 gui.dofork = FALSE;
1546 # endif
1548 # endif
1550 # if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1551 # ifdef FEAT_GUI_W32
1552 else if (STRICMP(argv[i], "--windowid") == 0)
1553 # else
1554 else if (STRICMP(argv[i], "--socketid") == 0)
1555 # endif
1557 long_u id;
1558 int count;
1560 if (i == argc - 1)
1561 mainerr_arg_missing((char_u *)argv[i]);
1562 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1563 count = sscanf(&(argv[i + 1][2]), SCANF_HEX_LONG_U, &id);
1564 else
1565 count = sscanf(argv[i + 1], SCANF_DECIMAL_LONG_U, &id);
1566 if (count != 1)
1567 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1568 else
1569 # ifdef FEAT_GUI_W32
1570 win_socket_id = id;
1571 # else
1572 gtk_socket_id = id;
1573 # endif
1574 i++;
1576 # endif
1577 # ifdef FEAT_GUI_GTK
1578 else if (STRICMP(argv[i], "--echo-wid") == 0)
1579 echo_wid_arg = TRUE;
1580 # endif
1582 #endif
1586 * Scan the command line arguments.
1588 static void
1589 command_line_scan(parmp)
1590 mparm_T *parmp;
1592 int argc = parmp->argc;
1593 char **argv = parmp->argv;
1594 int argv_idx; /* index in argv[n][] */
1595 int had_minmin = FALSE; /* found "--" argument */
1596 int want_argument; /* option argument with argument */
1597 int c;
1598 char_u *p = NULL;
1599 long n;
1601 --argc;
1602 ++argv;
1603 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1604 while (argc > 0)
1607 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1609 if (argv[0][0] == '+' && !had_minmin)
1611 if (parmp->n_commands >= MAX_ARG_CMDS)
1612 mainerr(ME_EXTRA_CMD, NULL);
1613 argv_idx = -1; /* skip to next argument */
1614 if (argv[0][1] == NUL)
1615 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1616 else
1617 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1621 * Optional argument.
1623 else if (argv[0][0] == '-' && !had_minmin)
1625 want_argument = FALSE;
1626 c = argv[0][argv_idx++];
1627 #ifdef VMS
1629 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1630 * and "-/X" as "-X".
1632 if (c == '/')
1634 c = argv[0][argv_idx++];
1635 c = TOUPPER_ASC(c);
1637 else
1638 c = TOLOWER_ASC(c);
1639 #endif
1640 switch (c)
1642 case NUL: /* "vim -" read from stdin */
1643 /* "ex -" silent mode */
1644 if (exmode_active)
1645 silent_mode = TRUE;
1646 else
1648 if (parmp->edit_type != EDIT_NONE)
1649 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1650 parmp->edit_type = EDIT_STDIN;
1651 read_cmd_fd = 2; /* read from stderr instead of stdin */
1653 argv_idx = -1; /* skip to next argument */
1654 break;
1656 case '-': /* "--" don't take any more option arguments */
1657 /* "--help" give help message */
1658 /* "--version" give version message */
1659 /* "--literal" take files literally */
1660 /* "--nofork" don't fork */
1661 /* "--noplugin[s]" skip plugins */
1662 /* "--cmd <cmd>" execute cmd before vimrc */
1663 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1664 usage();
1665 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1667 Columns = 80; /* need to init Columns */
1668 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1669 list_version();
1670 msg_putchar('\n');
1671 msg_didout = FALSE;
1672 mch_exit(0);
1674 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1676 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1677 parmp->literal = TRUE;
1678 #endif
1680 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1682 #ifdef FEAT_GUI
1683 gui.dofork = FALSE; /* don't fork() when starting GUI */
1684 #endif
1686 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1687 p_lpl = FALSE;
1688 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1690 want_argument = TRUE;
1691 argv_idx += 3;
1693 #ifdef FEAT_CLIENTSERVER
1694 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1695 ; /* already processed -- no arg */
1696 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1697 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1699 /* already processed -- snatch the following arg */
1700 if (argc > 1)
1702 --argc;
1703 ++argv;
1706 #endif
1707 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1708 # ifdef FEAT_GUI_GTK
1709 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1710 # else
1711 else if (STRNICMP(argv[0] + argv_idx, "windowid", 8) == 0)
1712 # endif
1714 /* already processed -- snatch the following arg */
1715 if (argc > 1)
1717 --argc;
1718 ++argv;
1721 #endif
1722 #ifdef FEAT_GUI_GTK
1723 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1725 /* already processed, skip */
1727 #endif
1728 else
1730 if (argv[0][argv_idx])
1731 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1732 had_minmin = TRUE;
1734 if (!want_argument)
1735 argv_idx = -1; /* skip to next argument */
1736 break;
1738 case 'A': /* "-A" start in Arabic mode */
1739 #ifdef FEAT_ARABIC
1740 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1741 #else
1742 mch_errmsg(_(e_noarabic));
1743 mch_exit(2);
1744 #endif
1745 break;
1747 case 'b': /* "-b" binary mode */
1748 /* Needs to be effective before expanding file names, because
1749 * for Win32 this makes us edit a shortcut file itself,
1750 * instead of the file it links to. */
1751 set_options_bin(curbuf->b_p_bin, 1, 0);
1752 curbuf->b_p_bin = 1; /* binary file I/O */
1753 break;
1755 case 'C': /* "-C" Compatible */
1756 change_compatible(TRUE);
1757 break;
1759 case 'e': /* "-e" Ex mode */
1760 exmode_active = EXMODE_NORMAL;
1761 break;
1763 case 'E': /* "-E" Improved Ex mode */
1764 exmode_active = EXMODE_VIM;
1765 break;
1767 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1768 window directly, not with newcli */
1769 #ifdef FEAT_GUI
1770 gui.dofork = FALSE; /* don't fork() when starting GUI */
1771 #endif
1772 break;
1774 case 'g': /* "-g" start GUI */
1775 main_start_gui();
1776 break;
1778 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1779 #ifdef FEAT_FKMAP
1780 p_fkmap = TRUE;
1781 set_option_value((char_u *)"rl", 1L, NULL, 0);
1782 #else
1783 mch_errmsg(_(e_nofarsi));
1784 mch_exit(2);
1785 #endif
1786 break;
1788 case 'h': /* "-h" give help message */
1789 #ifdef FEAT_GUI_GNOME
1790 /* Tell usage() to exit for "gvim". */
1791 gui.starting = FALSE;
1792 #endif
1793 usage();
1794 break;
1796 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1797 #ifdef FEAT_RIGHTLEFT
1798 p_hkmap = TRUE;
1799 set_option_value((char_u *)"rl", 1L, NULL, 0);
1800 #else
1801 mch_errmsg(_(e_nohebrew));
1802 mch_exit(2);
1803 #endif
1804 break;
1806 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1807 #ifdef FEAT_LISP
1808 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1809 p_sm = TRUE;
1810 #endif
1811 break;
1813 case 'M': /* "-M" no changes or writing of files */
1814 reset_modifiable();
1815 /* FALLTHROUGH */
1817 case 'm': /* "-m" no writing of files */
1818 p_write = FALSE;
1819 break;
1821 case 'y': /* "-y" easy mode */
1822 #ifdef FEAT_GUI
1823 gui.starting = TRUE; /* start GUI a bit later */
1824 #endif
1825 parmp->evim_mode = TRUE;
1826 break;
1828 case 'N': /* "-N" Nocompatible */
1829 change_compatible(FALSE);
1830 break;
1832 case 'n': /* "-n" no swap file */
1833 parmp->no_swap_file = TRUE;
1834 break;
1836 case 'p': /* "-p[N]" open N tab pages */
1837 #ifdef TARGET_API_MAC_OSX
1838 /* For some reason on MacOS X, an argument like:
1839 -psn_0_10223617 is passed in when invoke from Finder
1840 or with the 'open' command */
1841 if (argv[0][argv_idx] == 's')
1843 argv_idx = -1; /* bypass full -psn */
1844 main_start_gui();
1845 break;
1847 #endif
1848 #ifdef FEAT_WINDOWS
1849 /* default is 0: open window for each file */
1850 parmp->window_count = get_number_arg((char_u *)argv[0],
1851 &argv_idx, 0);
1852 parmp->window_layout = WIN_TABS;
1853 #endif
1854 break;
1856 case 'o': /* "-o[N]" open N horizontal split windows */
1857 #ifdef FEAT_WINDOWS
1858 /* default is 0: open window for each file */
1859 parmp->window_count = get_number_arg((char_u *)argv[0],
1860 &argv_idx, 0);
1861 parmp->window_layout = WIN_HOR;
1862 #endif
1863 break;
1865 case 'O': /* "-O[N]" open N vertical split windows */
1866 #if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1867 /* default is 0: open window for each file */
1868 parmp->window_count = get_number_arg((char_u *)argv[0],
1869 &argv_idx, 0);
1870 parmp->window_layout = WIN_VER;
1871 #endif
1872 break;
1874 #ifdef FEAT_QUICKFIX
1875 case 'q': /* "-q" QuickFix mode */
1876 if (parmp->edit_type != EDIT_NONE)
1877 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1878 parmp->edit_type = EDIT_QF;
1879 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1881 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1882 argv_idx = -1;
1884 else if (argc > 1) /* "-q {errorfile}" */
1885 want_argument = TRUE;
1886 break;
1887 #endif
1889 case 'R': /* "-R" readonly mode */
1890 readonlymode = TRUE;
1891 curbuf->b_p_ro = TRUE;
1892 p_uc = 10000; /* don't update very often */
1893 break;
1895 case 'r': /* "-r" recovery mode */
1896 case 'L': /* "-L" recovery mode */
1897 recoverymode = 1;
1898 break;
1900 case 's':
1901 if (exmode_active) /* "-s" silent (batch) mode */
1902 silent_mode = TRUE;
1903 else /* "-s {scriptin}" read from script file */
1904 want_argument = TRUE;
1905 break;
1907 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1908 if (parmp->edit_type != EDIT_NONE)
1909 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1910 parmp->edit_type = EDIT_TAG;
1911 if (argv[0][argv_idx]) /* "-t{tag}" */
1913 parmp->tagname = (char_u *)argv[0] + argv_idx;
1914 argv_idx = -1;
1916 else /* "-t {tag}" */
1917 want_argument = TRUE;
1918 break;
1920 #ifdef FEAT_EVAL
1921 case 'D': /* "-D" Debugging */
1922 parmp->use_debug_break_level = 9999;
1923 break;
1924 #endif
1925 #ifdef FEAT_DIFF
1926 case 'd': /* "-d" 'diff' */
1927 # ifdef AMIGA
1928 /* check for "-dev {device}" */
1929 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1930 want_argument = TRUE;
1931 else
1932 # endif
1933 parmp->diff_mode = TRUE;
1934 break;
1935 #endif
1936 case 'V': /* "-V{N}" Verbose level */
1937 /* default is 10: a little bit verbose */
1938 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1939 if (argv[0][argv_idx] != NUL)
1941 set_option_value((char_u *)"verbosefile", 0L,
1942 (char_u *)argv[0] + argv_idx, 0);
1943 argv_idx = (int)STRLEN(argv[0]);
1945 break;
1947 case 'v': /* "-v" Vi-mode (as if called "vi") */
1948 exmode_active = 0;
1949 #ifdef FEAT_GUI
1950 gui.starting = FALSE; /* don't start GUI */
1951 #endif
1952 break;
1954 case 'w': /* "-w{number}" set window height */
1955 /* "-w {scriptout}" write to script */
1956 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
1958 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1959 set_option_value((char_u *)"window", n, NULL, 0);
1960 break;
1962 want_argument = TRUE;
1963 break;
1965 #ifdef FEAT_CRYPT
1966 case 'x': /* "-x" encrypted reading/writing of files */
1967 parmp->ask_for_key = TRUE;
1968 break;
1969 #endif
1971 case 'X': /* "-X" don't connect to X server */
1972 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
1973 x_no_connect = TRUE;
1974 #endif
1975 break;
1977 case 'Z': /* "-Z" restricted mode */
1978 restricted = TRUE;
1979 break;
1981 case 'c': /* "-c{command}" or "-c {command}" execute
1982 command */
1983 if (argv[0][argv_idx] != NUL)
1985 if (parmp->n_commands >= MAX_ARG_CMDS)
1986 mainerr(ME_EXTRA_CMD, NULL);
1987 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
1988 + argv_idx;
1989 argv_idx = -1;
1990 break;
1992 /*FALLTHROUGH*/
1993 case 'S': /* "-S {file}" execute Vim script */
1994 case 'i': /* "-i {viminfo}" use for viminfo */
1995 #ifndef FEAT_DIFF
1996 case 'd': /* "-d {device}" device (for Amiga) */
1997 #endif
1998 case 'T': /* "-T {terminal}" terminal name */
1999 case 'u': /* "-u {vimrc}" vim inits file */
2000 case 'U': /* "-U {gvimrc}" gvim inits file */
2001 case 'W': /* "-W {scriptout}" overwrite */
2002 #ifdef FEAT_GUI_W32
2003 case 'P': /* "-P {parent title}" MDI parent */
2004 #endif
2005 want_argument = TRUE;
2006 break;
2008 default:
2009 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
2013 * Handle option arguments with argument.
2015 if (want_argument)
2018 * Check for garbage immediately after the option letter.
2020 if (argv[0][argv_idx] != NUL)
2021 mainerr(ME_GARBAGE, (char_u *)argv[0]);
2023 --argc;
2024 if (argc < 1 && c != 'S')
2025 mainerr_arg_missing((char_u *)argv[0]);
2026 ++argv;
2027 argv_idx = -1;
2029 switch (c)
2031 case 'c': /* "-c {command}" execute command */
2032 case 'S': /* "-S {file}" execute Vim script */
2033 if (parmp->n_commands >= MAX_ARG_CMDS)
2034 mainerr(ME_EXTRA_CMD, NULL);
2035 if (c == 'S')
2037 char *a;
2039 if (argc < 1)
2040 /* "-S" without argument: use default session file
2041 * name. */
2042 a = SESSION_FILE;
2043 else if (argv[0][0] == '-')
2045 /* "-S" followed by another option: use default
2046 * session file name. */
2047 a = SESSION_FILE;
2048 ++argc;
2049 --argv;
2051 else
2052 a = argv[0];
2053 p = alloc((unsigned)(STRLEN(a) + 4));
2054 if (p == NULL)
2055 mch_exit(2);
2056 sprintf((char *)p, "so %s", a);
2057 parmp->cmds_tofree[parmp->n_commands] = TRUE;
2058 parmp->commands[parmp->n_commands++] = p;
2060 else
2061 parmp->commands[parmp->n_commands++] =
2062 (char_u *)argv[0];
2063 break;
2065 case '-': /* "--cmd {command}" execute command */
2066 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
2067 mainerr(ME_EXTRA_CMD, NULL);
2068 parmp->pre_commands[parmp->n_pre_commands++] =
2069 (char_u *)argv[0];
2070 break;
2072 /* case 'd': -d {device} is handled in mch_check_win() for the
2073 * Amiga */
2075 #ifdef FEAT_QUICKFIX
2076 case 'q': /* "-q {errorfile}" QuickFix mode */
2077 parmp->use_ef = (char_u *)argv[0];
2078 break;
2079 #endif
2081 case 'i': /* "-i {viminfo}" use for viminfo */
2082 use_viminfo = (char_u *)argv[0];
2083 break;
2085 case 's': /* "-s {scriptin}" read from script file */
2086 if (scriptin[0] != NULL)
2088 scripterror:
2089 mch_errmsg(_("Attempt to open script file again: \""));
2090 mch_errmsg(argv[-1]);
2091 mch_errmsg(" ");
2092 mch_errmsg(argv[0]);
2093 mch_errmsg("\"\n");
2094 mch_exit(2);
2096 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
2098 mch_errmsg(_("Cannot open for reading: \""));
2099 mch_errmsg(argv[0]);
2100 mch_errmsg("\"\n");
2101 mch_exit(2);
2103 if (save_typebuf() == FAIL)
2104 mch_exit(2); /* out of memory */
2105 break;
2107 case 't': /* "-t {tag}" */
2108 parmp->tagname = (char_u *)argv[0];
2109 break;
2111 case 'T': /* "-T {terminal}" terminal name */
2113 * The -T term argument is always available and when
2114 * HAVE_TERMLIB is supported it overrides the environment
2115 * variable TERM.
2117 #ifdef FEAT_GUI
2118 if (term_is_gui((char_u *)argv[0]))
2119 gui.starting = TRUE; /* start GUI a bit later */
2120 else
2121 #endif
2122 parmp->term = (char_u *)argv[0];
2123 break;
2125 case 'u': /* "-u {vimrc}" vim inits file */
2126 parmp->use_vimrc = (char_u *)argv[0];
2127 break;
2129 case 'U': /* "-U {gvimrc}" gvim inits file */
2130 #ifdef FEAT_GUI
2131 use_gvimrc = (char_u *)argv[0];
2132 #endif
2133 break;
2135 case 'w': /* "-w {nr}" 'window' value */
2136 /* "-w {scriptout}" append to script file */
2137 if (vim_isdigit(*((char_u *)argv[0])))
2139 argv_idx = 0;
2140 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
2141 set_option_value((char_u *)"window", n, NULL, 0);
2142 argv_idx = -1;
2143 break;
2145 /*FALLTHROUGH*/
2146 case 'W': /* "-W {scriptout}" overwrite script file */
2147 if (scriptout != NULL)
2148 goto scripterror;
2149 if ((scriptout = mch_fopen(argv[0],
2150 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
2152 mch_errmsg(_("Cannot open for script output: \""));
2153 mch_errmsg(argv[0]);
2154 mch_errmsg("\"\n");
2155 mch_exit(2);
2157 break;
2159 #ifdef FEAT_GUI_W32
2160 case 'P': /* "-P {parent title}" MDI parent */
2161 gui_mch_set_parent(argv[0]);
2162 break;
2163 #endif
2169 * File name argument.
2171 else
2173 argv_idx = -1; /* skip to next argument */
2175 /* Check for only one type of editing. */
2176 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2177 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2178 parmp->edit_type = EDIT_FILE;
2180 #ifdef MSWIN
2181 /* Remember if the argument was a full path before changing
2182 * slashes to backslashes. */
2183 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2184 parmp->full_path = TRUE;
2185 #endif
2187 /* Add the file to the global argument list. */
2188 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2189 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2190 mch_exit(2);
2191 #ifdef FEAT_DIFF
2192 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2193 && !mch_isdir(alist_name(&GARGLIST[0])))
2195 char_u *r;
2197 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2198 if (r != NULL)
2200 vim_free(p);
2201 p = r;
2204 #endif
2205 #if defined(__CYGWIN32__) && !defined(WIN32)
2207 * If vim is invoked by non-Cygwin tools, convert away any
2208 * DOS paths, so things like .swp files are created correctly.
2209 * Look for evidence of non-Cygwin paths before we bother.
2210 * This is only for when using the Unix files.
2212 if (strpbrk(p, "\\:") != NULL)
2214 char posix_path[PATH_MAX];
2216 cygwin_conv_to_posix_path(p, posix_path);
2217 vim_free(p);
2218 p = vim_strsave(posix_path);
2219 if (p == NULL)
2220 mch_exit(2);
2222 #endif
2224 #ifdef USE_FNAME_CASE
2225 /* Make the case of the file name match the actual file. */
2226 fname_case(p, 0);
2227 #endif
2229 alist_add(&global_alist, p,
2230 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2231 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
2232 #else
2233 2 /* add buffer number now and use curbuf */
2234 #endif
2237 #if defined(FEAT_MBYTE) && defined(WIN32)
2239 /* Remember this argument has been added to the argument list.
2240 * Needed when 'encoding' is changed. */
2241 used_file_arg(argv[0], parmp->literal, parmp->full_path,
2242 parmp->diff_mode);
2244 #endif
2248 * If there are no more letters after the current "-", go to next
2249 * argument. argv_idx is set to -1 when the current argument is to be
2250 * skipped.
2252 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2254 --argc;
2255 ++argv;
2256 argv_idx = 1;
2260 #ifdef FEAT_EVAL
2261 /* If there is a "+123" or "-c" command, set v:swapcommand to the first
2262 * one. */
2263 if (parmp->n_commands > 0)
2265 p = alloc((unsigned)STRLEN(parmp->commands[0]) + 3);
2266 if (p != NULL)
2268 sprintf((char *)p, ":%s\r", parmp->commands[0]);
2269 set_vim_var_string(VV_SWAPCOMMAND, p, -1);
2270 vim_free(p);
2273 #endif
2277 * Print a warning if stdout is not a terminal.
2278 * When starting in Ex mode and commands come from a file, set Silent mode.
2280 static void
2281 check_tty(parmp)
2282 mparm_T *parmp;
2284 int input_isatty; /* is active input a terminal? */
2286 input_isatty = mch_input_isatty();
2287 if (exmode_active)
2289 if (!input_isatty)
2290 silent_mode = TRUE;
2292 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2293 #ifdef FEAT_GUI
2294 /* don't want the delay when started from the desktop */
2295 && !gui.starting
2296 #endif
2299 #ifdef NBDEBUG
2301 * This shouldn't be necessary. But if I run netbeans with the log
2302 * output coming to the console and XOpenDisplay fails, I get vim
2303 * trying to start with input/output to my console tty. This fills my
2304 * input buffer so fast I can't even kill the process in under 2
2305 * minutes (and it beeps continuously the whole time :-)
2307 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2309 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2310 exit(1);
2312 #endif
2313 if (!parmp->stdout_isatty)
2314 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2315 if (!input_isatty)
2316 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2317 out_flush();
2318 if (scriptin[0] == NULL)
2319 ui_delay(2000L, TRUE);
2320 TIME_MSG("Warning delay");
2325 * Read text from stdin.
2327 static void
2328 read_stdin()
2330 int i;
2332 #if defined(HAS_SWAP_EXISTS_ACTION)
2333 /* When getting the ATTENTION prompt here, use a dialog */
2334 swap_exists_action = SEA_DIALOG;
2335 #endif
2336 no_wait_return = TRUE;
2337 i = msg_didany;
2338 set_buflisted(TRUE);
2339 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2340 no_wait_return = FALSE;
2341 msg_didany = i;
2342 TIME_MSG("reading stdin");
2343 #if defined(HAS_SWAP_EXISTS_ACTION)
2344 check_swap_exists_action();
2345 #endif
2346 #if !(defined(AMIGA) || defined(MACOS))
2348 * Close stdin and dup it from stderr. Required for GPM to work
2349 * properly, and for running external commands.
2350 * Is there any other system that cannot do this?
2352 close(0);
2353 dup(2);
2354 #endif
2358 * Create the requested number of windows and edit buffers in them.
2359 * Also does recovery if "recoverymode" set.
2361 /*ARGSUSED*/
2362 static void
2363 create_windows(parmp)
2364 mparm_T *parmp;
2366 #ifdef FEAT_WINDOWS
2367 int dorewind;
2368 int done = 0;
2371 * Create the number of windows that was requested.
2373 if (parmp->window_count == -1) /* was not set */
2374 parmp->window_count = 1;
2375 if (parmp->window_count == 0)
2376 parmp->window_count = GARGCOUNT;
2377 if (parmp->window_count > 1)
2379 /* Don't change the windows if there was a command in .vimrc that
2380 * already split some windows */
2381 if (parmp->window_layout == 0)
2382 parmp->window_layout = WIN_HOR;
2383 if (parmp->window_layout == WIN_TABS)
2385 parmp->window_count = make_tabpages(parmp->window_count);
2386 TIME_MSG("making tab pages");
2388 else if (firstwin->w_next == NULL)
2390 parmp->window_count = make_windows(parmp->window_count,
2391 parmp->window_layout == WIN_VER);
2392 TIME_MSG("making windows");
2394 else
2395 parmp->window_count = win_count();
2397 else
2398 parmp->window_count = 1;
2399 #endif
2401 if (recoverymode) /* do recover */
2403 msg_scroll = TRUE; /* scroll message up */
2404 ml_recover();
2405 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2406 getout(1);
2407 do_modelines(0); /* do modelines */
2409 else
2412 * Open a buffer for windows that don't have one yet.
2413 * Commands in the .vimrc might have loaded a file or split the window.
2414 * Watch out for autocommands that delete a window.
2416 #ifdef FEAT_AUTOCMD
2418 * Don't execute Win/Buf Enter/Leave autocommands here
2420 ++autocmd_no_enter;
2421 ++autocmd_no_leave;
2422 #endif
2423 #ifdef FEAT_WINDOWS
2424 dorewind = TRUE;
2425 while (done++ < 1000)
2427 if (dorewind)
2429 if (parmp->window_layout == WIN_TABS)
2430 goto_tabpage(1);
2431 else
2432 curwin = firstwin;
2434 else if (parmp->window_layout == WIN_TABS)
2436 if (curtab->tp_next == NULL)
2437 break;
2438 goto_tabpage(0);
2440 else
2442 if (curwin->w_next == NULL)
2443 break;
2444 curwin = curwin->w_next;
2446 dorewind = FALSE;
2447 #endif
2448 curbuf = curwin->w_buffer;
2449 if (curbuf->b_ml.ml_mfp == NULL)
2451 #ifdef FEAT_FOLDING
2452 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2453 if (p_fdls >= 0)
2454 curwin->w_p_fdl = p_fdls;
2455 #endif
2456 #if defined(HAS_SWAP_EXISTS_ACTION)
2457 /* When getting the ATTENTION prompt here, use a dialog */
2458 swap_exists_action = SEA_DIALOG;
2459 #endif
2460 set_buflisted(TRUE);
2461 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2463 #if defined(HAS_SWAP_EXISTS_ACTION)
2464 if (swap_exists_action == SEA_QUIT)
2466 if (got_int || only_one_window())
2468 /* abort selected or quit and only one window */
2469 did_emsg = FALSE; /* avoid hit-enter prompt */
2470 getout(1);
2472 /* We can't close the window, it would disturb what
2473 * happens next. Clear the file name and set the arg
2474 * index to -1 to delete it later. */
2475 setfname(curbuf, NULL, NULL, FALSE);
2476 curwin->w_arg_idx = -1;
2477 swap_exists_action = SEA_NONE;
2479 else
2480 handle_swap_exists(NULL);
2481 #endif
2482 #ifdef FEAT_AUTOCMD
2483 dorewind = TRUE; /* start again */
2484 #endif
2486 #ifdef FEAT_WINDOWS
2487 ui_breakcheck();
2488 if (got_int)
2490 (void)vgetc(); /* only break the file loading, not the rest */
2491 break;
2494 #endif
2495 #ifdef FEAT_WINDOWS
2496 if (parmp->window_layout == WIN_TABS)
2497 goto_tabpage(1);
2498 else
2499 curwin = firstwin;
2500 curbuf = curwin->w_buffer;
2501 #endif
2502 #ifdef FEAT_AUTOCMD
2503 --autocmd_no_enter;
2504 --autocmd_no_leave;
2505 #endif
2509 #ifdef FEAT_WINDOWS
2511 * If opened more than one window, start editing files in the other
2512 * windows. make_windows() has already opened the windows.
2514 static void
2515 edit_buffers(parmp)
2516 mparm_T *parmp;
2518 int arg_idx; /* index in argument list */
2519 int i;
2520 int advance = TRUE;
2521 buf_T *old_curbuf;
2523 # ifdef FEAT_AUTOCMD
2525 * Don't execute Win/Buf Enter/Leave autocommands here
2527 ++autocmd_no_enter;
2528 ++autocmd_no_leave;
2529 # endif
2531 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2532 if (curwin->w_arg_idx == -1)
2534 win_close(curwin, TRUE);
2535 advance = FALSE;
2538 arg_idx = 1;
2539 for (i = 1; i < parmp->window_count; ++i)
2541 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2542 if (curwin->w_arg_idx == -1)
2544 ++arg_idx;
2545 win_close(curwin, TRUE);
2546 advance = FALSE;
2547 continue;
2550 if (advance)
2552 if (parmp->window_layout == WIN_TABS)
2554 if (curtab->tp_next == NULL) /* just checking */
2555 break;
2556 goto_tabpage(0);
2558 else
2560 if (curwin->w_next == NULL) /* just checking */
2561 break;
2562 win_enter(curwin->w_next, FALSE);
2565 advance = TRUE;
2567 /* Only open the file if there is no file in this window yet (that can
2568 * happen when .vimrc contains ":sall"). */
2569 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2571 curwin->w_arg_idx = arg_idx;
2572 /* Edit file from arg list, if there is one. When "Quit" selected
2573 * at the ATTENTION prompt close the window. */
2574 old_curbuf = curbuf;
2575 (void)do_ecmd(0, arg_idx < GARGCOUNT
2576 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2577 NULL, NULL, ECMD_LASTL, ECMD_HIDE);
2578 if (curbuf == old_curbuf)
2580 if (got_int || only_one_window())
2582 /* abort selected or quit and only one window */
2583 did_emsg = FALSE; /* avoid hit-enter prompt */
2584 getout(1);
2586 win_close(curwin, TRUE);
2587 advance = FALSE;
2589 if (arg_idx == GARGCOUNT - 1)
2590 arg_had_last = TRUE;
2591 ++arg_idx;
2593 ui_breakcheck();
2594 if (got_int)
2596 (void)vgetc(); /* only break the file loading, not the rest */
2597 break;
2601 if (parmp->window_layout == WIN_TABS)
2602 goto_tabpage(1);
2603 # ifdef FEAT_AUTOCMD
2604 --autocmd_no_enter;
2605 # endif
2606 win_enter(firstwin, FALSE); /* back to first window */
2607 # ifdef FEAT_AUTOCMD
2608 --autocmd_no_leave;
2609 # endif
2610 TIME_MSG("editing files in windows");
2611 if (parmp->window_count > 1 && parmp->window_layout != WIN_TABS)
2612 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2614 #endif /* FEAT_WINDOWS */
2617 * Execute the commands from --cmd arguments "cmds[cnt]".
2619 static void
2620 exe_pre_commands(parmp)
2621 mparm_T *parmp;
2623 char_u **cmds = parmp->pre_commands;
2624 int cnt = parmp->n_pre_commands;
2625 int i;
2627 if (cnt > 0)
2629 curwin->w_cursor.lnum = 0; /* just in case.. */
2630 sourcing_name = (char_u *)_("pre-vimrc command line");
2631 # ifdef FEAT_EVAL
2632 current_SID = SID_CMDARG;
2633 # endif
2634 for (i = 0; i < cnt; ++i)
2635 do_cmdline_cmd(cmds[i]);
2636 sourcing_name = NULL;
2637 # ifdef FEAT_EVAL
2638 current_SID = 0;
2639 # endif
2640 TIME_MSG("--cmd commands");
2645 * Execute "+", "-c" and "-S" arguments.
2647 static void
2648 exe_commands(parmp)
2649 mparm_T *parmp;
2651 int i;
2654 * We start commands on line 0, make "vim +/pat file" match a
2655 * pattern on line 1. But don't move the cursor when an autocommand
2656 * with g`" was used.
2658 msg_scroll = TRUE;
2659 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2660 curwin->w_cursor.lnum = 0;
2661 sourcing_name = (char_u *)"command line";
2662 #ifdef FEAT_EVAL
2663 current_SID = SID_CARG;
2664 #endif
2665 for (i = 0; i < parmp->n_commands; ++i)
2667 do_cmdline_cmd(parmp->commands[i]);
2668 if (parmp->cmds_tofree[i])
2669 vim_free(parmp->commands[i]);
2671 sourcing_name = NULL;
2672 #ifdef FEAT_EVAL
2673 current_SID = 0;
2674 #endif
2675 if (curwin->w_cursor.lnum == 0)
2676 curwin->w_cursor.lnum = 1;
2678 if (!exmode_active)
2679 msg_scroll = FALSE;
2681 #ifdef FEAT_QUICKFIX
2682 /* When started with "-q errorfile" jump to first error again. */
2683 if (parmp->edit_type == EDIT_QF)
2684 qf_jump(NULL, 0, 0, FALSE);
2685 #endif
2686 TIME_MSG("executing command arguments");
2690 * Source startup scripts.
2692 static void
2693 source_startup_scripts(parmp)
2694 mparm_T *parmp;
2696 int i;
2699 * For "evim" source evim.vim first of all, so that the user can overrule
2700 * any things he doesn't like.
2702 if (parmp->evim_mode)
2704 (void)do_source((char_u *)EVIM_FILE, FALSE, DOSO_NONE);
2705 TIME_MSG("source evim file");
2709 * If -u argument given, use only the initializations from that file and
2710 * nothing else.
2712 if (parmp->use_vimrc != NULL)
2714 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2715 || STRCMP(parmp->use_vimrc, "NORC") == 0)
2717 #ifdef FEAT_GUI
2718 if (use_gvimrc == NULL) /* don't load gvimrc either */
2719 use_gvimrc = parmp->use_vimrc;
2720 #endif
2721 if (parmp->use_vimrc[2] == 'N')
2722 p_lpl = FALSE; /* don't load plugins either */
2724 else
2726 if (do_source(parmp->use_vimrc, FALSE, DOSO_NONE) != OK)
2727 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2730 else if (!silent_mode)
2732 #ifdef AMIGA
2733 struct Process *proc = (struct Process *)FindTask(0L);
2734 APTR save_winptr = proc->pr_WindowPtr;
2736 /* Avoid a requester here for a volume that doesn't exist. */
2737 proc->pr_WindowPtr = (APTR)-1L;
2738 #endif
2741 * Get system wide defaults, if the file name is defined.
2743 #ifdef SYS_VIMRC_FILE
2744 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, DOSO_NONE);
2745 #endif
2746 #ifdef MACOS_X
2747 (void)do_source((char_u *)"$VIMRUNTIME/macmap.vim", FALSE, DOSO_NONE);
2748 #endif
2751 * Try to read initialization commands from the following places:
2752 * - environment variable VIMINIT
2753 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2754 * - second user vimrc file ($VIM/.vimrc for Dos)
2755 * - environment variable EXINIT
2756 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2757 * - second user exrc file ($VIM/.exrc for Dos)
2758 * The first that exists is used, the rest is ignored.
2760 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2762 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, DOSO_VIMRC) == FAIL
2763 #ifdef USR_VIMRC_FILE2
2764 && do_source((char_u *)USR_VIMRC_FILE2, TRUE,
2765 DOSO_VIMRC) == FAIL
2766 #endif
2767 #ifdef USR_VIMRC_FILE3
2768 && do_source((char_u *)USR_VIMRC_FILE3, TRUE,
2769 DOSO_VIMRC) == FAIL
2770 #endif
2771 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2772 && do_source((char_u *)USR_EXRC_FILE, FALSE, DOSO_NONE) == FAIL)
2774 #ifdef USR_EXRC_FILE2
2775 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, DOSO_NONE);
2776 #endif
2781 * Read initialization commands from ".vimrc" or ".exrc" in current
2782 * directory. This is only done if the 'exrc' option is set.
2783 * Because of security reasons we disallow shell and write commands
2784 * now, except for unix if the file is owned by the user or 'secure'
2785 * option has been reset in environment of global ".exrc" or ".vimrc".
2786 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2787 * SYS_VIMRC_FILE.
2789 if (p_exrc)
2791 #if defined(UNIX) || defined(VMS)
2792 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2793 if (!file_owned(VIMRC_FILE))
2794 #endif
2795 secure = p_secure;
2797 i = FAIL;
2798 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2799 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2800 #ifdef USR_VIMRC_FILE2
2801 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2802 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2803 #endif
2804 #ifdef USR_VIMRC_FILE3
2805 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2806 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2807 #endif
2808 #ifdef SYS_VIMRC_FILE
2809 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2810 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2811 #endif
2813 i = do_source((char_u *)VIMRC_FILE, TRUE, DOSO_VIMRC);
2815 if (i == FAIL)
2817 #if defined(UNIX) || defined(VMS)
2818 /* if ".exrc" is not owned by user set 'secure' mode */
2819 if (!file_owned(EXRC_FILE))
2820 secure = p_secure;
2821 else
2822 secure = 0;
2823 #endif
2824 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2825 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2826 #ifdef USR_EXRC_FILE2
2827 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2828 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2829 #endif
2831 (void)do_source((char_u *)EXRC_FILE, FALSE, DOSO_NONE);
2834 if (secure == 2)
2835 need_wait_return = TRUE;
2836 secure = 0;
2837 #ifdef AMIGA
2838 proc->pr_WindowPtr = save_winptr;
2839 #endif
2841 TIME_MSG("sourcing vimrc file(s)");
2845 * Setup to start using the GUI. Exit with an error when not available.
2847 static void
2848 main_start_gui()
2850 #ifdef FEAT_GUI
2851 gui.starting = TRUE; /* start GUI a bit later */
2852 #else
2853 mch_errmsg(_(e_nogvim));
2854 mch_errmsg("\n");
2855 mch_exit(2);
2856 #endif
2860 * Get an environment variable, and execute it as Ex commands.
2861 * Returns FAIL if the environment variable was not executed, OK otherwise.
2864 process_env(env, is_viminit)
2865 char_u *env;
2866 int is_viminit; /* when TRUE, called for VIMINIT */
2868 char_u *initstr;
2869 char_u *save_sourcing_name;
2870 linenr_T save_sourcing_lnum;
2871 #ifdef FEAT_EVAL
2872 scid_T save_sid;
2873 #endif
2875 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2877 if (is_viminit)
2878 vimrc_found(NULL, NULL);
2879 save_sourcing_name = sourcing_name;
2880 save_sourcing_lnum = sourcing_lnum;
2881 sourcing_name = env;
2882 sourcing_lnum = 0;
2883 #ifdef FEAT_EVAL
2884 save_sid = current_SID;
2885 current_SID = SID_ENV;
2886 #endif
2887 do_cmdline_cmd(initstr);
2888 sourcing_name = save_sourcing_name;
2889 sourcing_lnum = save_sourcing_lnum;
2890 #ifdef FEAT_EVAL
2891 current_SID = save_sid;;
2892 #endif
2893 return OK;
2895 return FAIL;
2898 #if defined(UNIX) || defined(VMS)
2900 * Return TRUE if we are certain the user owns the file "fname".
2901 * Used for ".vimrc" and ".exrc".
2902 * Use both stat() and lstat() for extra security.
2904 static int
2905 file_owned(fname)
2906 char *fname;
2908 struct stat s;
2909 # ifdef UNIX
2910 uid_t uid = getuid();
2911 # else /* VMS */
2912 uid_t uid = ((getgid() << 16) | getuid());
2913 # endif
2915 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2916 # ifdef HAVE_LSTAT
2917 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2918 # endif
2921 #endif
2924 * Give an error message main_errors["n"] and exit.
2926 static void
2927 mainerr(n, str)
2928 int n; /* one of the ME_ defines */
2929 char_u *str; /* extra argument or NULL */
2931 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
2932 reset_signals(); /* kill us with CTRL-C here, if you like */
2933 #endif
2935 mch_errmsg(longVersion);
2936 mch_errmsg("\n");
2937 mch_errmsg(_(main_errors[n]));
2938 if (str != NULL)
2940 mch_errmsg(": \"");
2941 mch_errmsg((char *)str);
2942 mch_errmsg("\"");
2944 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
2946 mch_exit(1);
2949 void
2950 mainerr_arg_missing(str)
2951 char_u *str;
2953 mainerr(ME_ARG_MISSING, str);
2957 * print a message with three spaces prepended and '\n' appended.
2959 static void
2960 main_msg(s)
2961 char *s;
2963 mch_msg(" ");
2964 mch_msg(s);
2965 mch_msg("\n");
2969 * Print messages for "vim -h" or "vim --help" and exit.
2971 static void
2972 usage()
2974 int i;
2975 static char *(use[]) =
2977 N_("[file ..] edit specified file(s)"),
2978 N_("- read text from stdin"),
2979 N_("-t tag edit file where tag is defined"),
2980 #ifdef FEAT_QUICKFIX
2981 N_("-q [errorfile] edit file with first error")
2982 #endif
2985 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
2986 reset_signals(); /* kill us with CTRL-C here, if you like */
2987 #endif
2989 mch_msg(longVersion);
2990 mch_msg(_("\n\nusage:"));
2991 for (i = 0; ; ++i)
2993 mch_msg(_(" vim [arguments] "));
2994 mch_msg(_(use[i]));
2995 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
2996 break;
2997 mch_msg(_("\n or:"));
2999 #ifdef VMS
3000 mch_msg(_("\nWhere case is ignored prepend / to make flag upper case"));
3001 #endif
3003 mch_msg(_("\n\nArguments:\n"));
3004 main_msg(_("--\t\t\tOnly file names after this"));
3005 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
3006 main_msg(_("--literal\t\tDon't expand wildcards"));
3007 #endif
3008 #ifdef FEAT_OLE
3009 main_msg(_("-register\t\tRegister this gvim for OLE"));
3010 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
3011 #endif
3012 #ifdef FEAT_GUI
3013 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
3014 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
3015 #endif
3016 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
3017 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
3018 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
3019 #ifdef FEAT_DIFF
3020 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
3021 #endif
3022 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
3023 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
3024 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
3025 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
3026 main_msg(_("-M\t\t\tModifications in text not allowed"));
3027 main_msg(_("-b\t\t\tBinary mode"));
3028 #ifdef FEAT_LISP
3029 main_msg(_("-l\t\t\tLisp mode"));
3030 #endif
3031 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
3032 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
3033 main_msg(_("-V[N][fname]\t\tBe verbose [level N] [log messages to fname]"));
3034 #ifdef FEAT_EVAL
3035 main_msg(_("-D\t\t\tDebugging mode"));
3036 #endif
3037 main_msg(_("-n\t\t\tNo swap file, use memory only"));
3038 main_msg(_("-r\t\t\tList swap files and exit"));
3039 main_msg(_("-r (with file name)\tRecover crashed session"));
3040 main_msg(_("-L\t\t\tSame as -r"));
3041 #ifdef AMIGA
3042 main_msg(_("-f\t\t\tDon't use newcli to open window"));
3043 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
3044 #endif
3045 #ifdef FEAT_ARABIC
3046 main_msg(_("-A\t\t\tstart in Arabic mode"));
3047 #endif
3048 #ifdef FEAT_RIGHTLEFT
3049 main_msg(_("-H\t\t\tStart in Hebrew mode"));
3050 #endif
3051 #ifdef FEAT_FKMAP
3052 main_msg(_("-F\t\t\tStart in Farsi mode"));
3053 #endif
3054 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
3055 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
3056 #ifdef FEAT_GUI
3057 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
3058 #endif
3059 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
3060 #ifdef FEAT_WINDOWS
3061 main_msg(_("-p[N]\t\tOpen N tab pages (default: one for each file)"));
3062 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
3063 main_msg(_("-O[N]\t\tLike -o but split vertically"));
3064 #endif
3065 main_msg(_("+\t\t\tStart at end of file"));
3066 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
3067 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
3068 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
3069 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
3070 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
3071 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
3072 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
3073 #ifdef FEAT_CRYPT
3074 main_msg(_("-x\t\t\tEdit encrypted files"));
3075 #endif
3076 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
3077 # if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
3078 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
3079 # endif
3080 main_msg(_("-X\t\t\tDo not connect to X server"));
3081 #endif
3082 #ifdef FEAT_CLIENTSERVER
3083 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
3084 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
3085 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
3086 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
3087 # ifdef FEAT_WINDOWS
3088 main_msg(_("--remote-tab[-wait][-silent] <files> As --remote but use tab page per file"));
3089 # endif
3090 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
3091 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
3092 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
3093 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
3094 #endif
3095 #ifdef FEAT_VIMINFO
3096 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
3097 #endif
3098 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
3099 main_msg(_("--version\t\tPrint version information and exit"));
3101 #ifdef FEAT_GUI_X11
3102 # ifdef FEAT_GUI_MOTIF
3103 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
3104 # else
3105 # ifdef FEAT_GUI_ATHENA
3106 # ifdef FEAT_GUI_NEXTAW
3107 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
3108 # else
3109 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
3110 # endif
3111 # endif
3112 # endif
3113 main_msg(_("-display <display>\tRun vim on <display>"));
3114 main_msg(_("-iconic\t\tStart vim iconified"));
3115 # if 0
3116 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
3117 mch_msg(_("\t\t\t (Unimplemented)\n"));
3118 # endif
3119 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
3120 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
3121 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3122 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
3123 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
3124 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3125 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
3126 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
3127 # ifdef FEAT_GUI_ATHENA
3128 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
3129 # endif
3130 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3131 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
3132 main_msg(_("-xrm <resource>\tSet the specified resource"));
3133 #endif /* FEAT_GUI_X11 */
3134 #if defined(FEAT_GUI) && defined(RISCOS)
3135 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
3136 main_msg(_("--columns <number>\tInitial width of window in columns"));
3137 main_msg(_("--rows <number>\tInitial height of window in rows"));
3138 #endif
3139 #ifdef FEAT_GUI_GTK
3140 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
3141 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3142 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3143 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3144 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
3145 # ifdef HAVE_GTK2
3146 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
3147 # endif
3148 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
3149 #endif
3150 #ifdef FEAT_GUI_W32
3151 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
3152 main_msg(_("--windowid <HWND>\tOpen Vim inside another win32 widget"));
3153 #endif
3155 #ifdef FEAT_GUI_GNOME
3156 /* Gnome gives extra messages for --help if we continue, but not for -h. */
3157 if (gui.starting)
3158 mch_msg("\n");
3159 else
3160 #endif
3161 mch_exit(0);
3164 #if defined(HAS_SWAP_EXISTS_ACTION)
3166 * Check the result of the ATTENTION dialog:
3167 * When "Quit" selected, exit Vim.
3168 * When "Recover" selected, recover the file.
3170 static void
3171 check_swap_exists_action()
3173 if (swap_exists_action == SEA_QUIT)
3174 getout(1);
3175 handle_swap_exists(NULL);
3177 #endif
3179 #if defined(STARTUPTIME) || defined(PROTO)
3180 static void time_diff __ARGS((struct timeval *then, struct timeval *now));
3182 static struct timeval prev_timeval;
3185 * Save the previous time before doing something that could nest.
3186 * set "*tv_rel" to the time elapsed so far.
3188 void
3189 time_push(tv_rel, tv_start)
3190 void *tv_rel, *tv_start;
3192 *((struct timeval *)tv_rel) = prev_timeval;
3193 gettimeofday(&prev_timeval, NULL);
3194 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
3195 - ((struct timeval *)tv_rel)->tv_usec;
3196 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
3197 - ((struct timeval *)tv_rel)->tv_sec;
3198 if (((struct timeval *)tv_rel)->tv_usec < 0)
3200 ((struct timeval *)tv_rel)->tv_usec += 1000000;
3201 --((struct timeval *)tv_rel)->tv_sec;
3203 *(struct timeval *)tv_start = prev_timeval;
3207 * Compute the previous time after doing something that could nest.
3208 * Subtract "*tp" from prev_timeval;
3209 * Note: The arguments are (void *) to avoid trouble with systems that don't
3210 * have struct timeval.
3212 void
3213 time_pop(tp)
3214 void *tp; /* actually (struct timeval *) */
3216 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
3217 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
3218 if (prev_timeval.tv_usec < 0)
3220 prev_timeval.tv_usec += 1000000;
3221 --prev_timeval.tv_sec;
3225 static void
3226 time_diff(then, now)
3227 struct timeval *then;
3228 struct timeval *now;
3230 long usec;
3231 long msec;
3233 usec = now->tv_usec - then->tv_usec;
3234 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
3235 usec = usec % 1000L;
3236 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
3239 void
3240 time_msg(msg, tv_start)
3241 char *msg;
3242 void *tv_start; /* only for do_source: start time; actually
3243 (struct timeval *) */
3245 static struct timeval start;
3246 struct timeval now;
3248 if (time_fd != NULL)
3250 if (strstr(msg, "STARTING") != NULL)
3252 gettimeofday(&start, NULL);
3253 prev_timeval = start;
3254 fprintf(time_fd, "\n\ntimes in msec\n");
3255 fprintf(time_fd, " clock self+sourced self: sourced script\n");
3256 fprintf(time_fd, " clock elapsed: other lines\n\n");
3258 gettimeofday(&now, NULL);
3259 time_diff(&start, &now);
3260 if (((struct timeval *)tv_start) != NULL)
3262 fprintf(time_fd, " ");
3263 time_diff(((struct timeval *)tv_start), &now);
3265 fprintf(time_fd, " ");
3266 time_diff(&prev_timeval, &now);
3267 prev_timeval = now;
3268 fprintf(time_fd, ": %s\n", msg);
3272 # ifdef WIN3264
3274 * Windows doesn't have gettimeofday(), although it does have struct timeval.
3277 gettimeofday(struct timeval *tv, char *dummy)
3279 long t = clock();
3280 tv->tv_sec = t / CLOCKS_PER_SEC;
3281 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
3282 return 0;
3284 # endif
3286 #endif
3288 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3291 * Common code for the X command server and the Win32 command server.
3294 static char_u *build_drop_cmd __ARGS((int filec, char **filev, int tabs, int sendReply));
3297 * Do the client-server stuff, unless "--servername ''" was used.
3299 static void
3300 exec_on_server(parmp)
3301 mparm_T *parmp;
3303 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3305 # ifdef WIN32
3306 /* Initialise the client/server messaging infrastructure. */
3307 serverInitMessaging();
3308 # endif
3311 * When a command server argument was found, execute it. This may
3312 * exit Vim when it was successful. Otherwise it's executed further
3313 * on. Remember the encoding used here in "serverStrEnc".
3315 if (parmp->serverArg)
3317 cmdsrv_main(&parmp->argc, parmp->argv,
3318 parmp->serverName_arg, &parmp->serverStr);
3319 # ifdef FEAT_MBYTE
3320 parmp->serverStrEnc = vim_strsave(p_enc);
3321 # endif
3324 /* If we're still running, get the name to register ourselves.
3325 * On Win32 can register right now, for X11 need to setup the
3326 * clipboard first, it's further down. */
3327 parmp->servername = serverMakeName(parmp->serverName_arg,
3328 parmp->argv[0]);
3329 # ifdef WIN32
3330 if (parmp->servername != NULL)
3332 serverSetName(parmp->servername);
3333 vim_free(parmp->servername);
3335 # endif
3340 * Prepare for running as a Vim server.
3342 static void
3343 prepare_server(parmp)
3344 mparm_T *parmp;
3346 # if defined(FEAT_X11)
3348 * Register for remote command execution with :serversend and --remote
3349 * unless there was a -X or a --servername '' on the command line.
3350 * Only register nongui-vim's with an explicit --servername argument.
3351 * When running as root --servername is also required.
3353 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3354 # ifdef FEAT_GUI
3355 (gui.in_use
3356 # ifdef UNIX
3357 && getuid() != ROOT_UID
3358 # endif
3359 ) ||
3360 # endif
3361 parmp->serverName_arg != NULL))
3363 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3364 vim_free(parmp->servername);
3365 TIME_MSG("register server name");
3367 else
3368 serverDelayedStartName = parmp->servername;
3369 # endif
3372 * Execute command ourselves if we're here because the send failed (or
3373 * else we would have exited above).
3375 if (parmp->serverStr != NULL)
3377 char_u *p;
3379 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3380 parmp->serverStr, &p));
3381 vim_free(p);
3385 static void
3386 cmdsrv_main(argc, argv, serverName_arg, serverStr)
3387 int *argc;
3388 char **argv;
3389 char_u *serverName_arg;
3390 char_u **serverStr;
3392 char_u *res;
3393 int i;
3394 char_u *sname;
3395 int ret;
3396 int didone = FALSE;
3397 int exiterr = 0;
3398 char **newArgV = argv + 1;
3399 int newArgC = 1,
3400 Argc = *argc;
3401 int argtype;
3402 #define ARGTYPE_OTHER 0
3403 #define ARGTYPE_EDIT 1
3404 #define ARGTYPE_EDIT_WAIT 2
3405 #define ARGTYPE_SEND 3
3406 int silent = FALSE;
3407 int tabs = FALSE;
3408 # ifndef FEAT_X11
3409 HWND srv;
3410 # else
3411 Window srv;
3413 setup_term_clip();
3414 # endif
3416 sname = serverMakeName(serverName_arg, argv[0]);
3417 if (sname == NULL)
3418 return;
3421 * Execute the command server related arguments and remove them
3422 * from the argc/argv array; We may have to return into main()
3424 for (i = 1; i < Argc; i++)
3426 res = NULL;
3427 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
3429 for (; i < *argc; i++)
3431 *newArgV++ = argv[i];
3432 newArgC++;
3434 break;
3437 if (STRICMP(argv[i], "--remote-send") == 0)
3438 argtype = ARGTYPE_SEND;
3439 else if (STRNICMP(argv[i], "--remote", 8) == 0)
3441 char *p = argv[i] + 8;
3443 argtype = ARGTYPE_EDIT;
3444 while (*p != NUL)
3446 if (STRNICMP(p, "-wait", 5) == 0)
3448 argtype = ARGTYPE_EDIT_WAIT;
3449 p += 5;
3451 else if (STRNICMP(p, "-silent", 7) == 0)
3453 silent = TRUE;
3454 p += 7;
3456 else if (STRNICMP(p, "-tab", 4) == 0)
3458 tabs = TRUE;
3459 p += 4;
3461 else
3463 argtype = ARGTYPE_OTHER;
3464 break;
3468 else
3469 argtype = ARGTYPE_OTHER;
3471 if (argtype != ARGTYPE_OTHER)
3473 if (i == *argc - 1)
3474 mainerr_arg_missing((char_u *)argv[i]);
3475 if (argtype == ARGTYPE_SEND)
3477 *serverStr = (char_u *)argv[i + 1];
3478 i++;
3480 else
3482 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3483 tabs, argtype == ARGTYPE_EDIT_WAIT);
3484 if (*serverStr == NULL)
3486 /* Probably out of memory, exit. */
3487 didone = TRUE;
3488 exiterr = 1;
3489 break;
3491 Argc = i;
3493 # ifdef FEAT_X11
3494 if (xterm_dpy == NULL)
3496 mch_errmsg(_("No display"));
3497 ret = -1;
3499 else
3500 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3501 NULL, &srv, 0, 0, silent);
3502 # else
3503 /* Win32 always works? */
3504 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3505 # endif
3506 if (ret < 0)
3508 if (argtype == ARGTYPE_SEND)
3510 /* Failed to send, abort. */
3511 mch_errmsg(_(": Send failed.\n"));
3512 didone = TRUE;
3513 exiterr = 1;
3515 else if (!silent)
3516 /* Let vim start normally. */
3517 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3518 break;
3521 # ifdef FEAT_GUI_W32
3522 /* Guess that when the server name starts with "g" it's a GUI
3523 * server, which we can bring to the foreground here.
3524 * Foreground() in the server doesn't work very well. */
3525 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3526 SetForegroundWindow(srv);
3527 # endif
3530 * For --remote-wait: Wait until the server did edit each
3531 * file. Also detect that the server no longer runs.
3533 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3535 int numFiles = *argc - i - 1;
3536 int j;
3537 char_u *done = alloc(numFiles);
3538 char_u *p;
3539 # ifdef FEAT_GUI_W32
3540 NOTIFYICONDATA ni;
3541 int count = 0;
3542 extern HWND message_window;
3543 # endif
3545 if (numFiles > 0 && argv[i + 1][0] == '+')
3546 /* Skip "+cmd" argument, don't wait for it to be edited. */
3547 --numFiles;
3549 # ifdef FEAT_GUI_W32
3550 ni.cbSize = sizeof(ni);
3551 ni.hWnd = message_window;
3552 ni.uID = 0;
3553 ni.uFlags = NIF_ICON|NIF_TIP;
3554 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3555 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3556 Shell_NotifyIcon(NIM_ADD, &ni);
3557 # endif
3559 /* Wait for all files to unload in remote */
3560 memset(done, 0, numFiles);
3561 while (memchr(done, 0, numFiles) != NULL)
3563 # ifdef WIN32
3564 p = serverGetReply(srv, NULL, TRUE, TRUE);
3565 if (p == NULL)
3566 break;
3567 # else
3568 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3569 break;
3570 # endif
3571 j = atoi((char *)p);
3572 if (j >= 0 && j < numFiles)
3574 # ifdef FEAT_GUI_W32
3575 ++count;
3576 sprintf(ni.szTip, _("%d of %d edited"),
3577 count, numFiles);
3578 Shell_NotifyIcon(NIM_MODIFY, &ni);
3579 # endif
3580 done[j] = 1;
3583 # ifdef FEAT_GUI_W32
3584 Shell_NotifyIcon(NIM_DELETE, &ni);
3585 # endif
3588 else if (STRICMP(argv[i], "--remote-expr") == 0)
3590 if (i == *argc - 1)
3591 mainerr_arg_missing((char_u *)argv[i]);
3592 # ifdef WIN32
3593 /* Win32 always works? */
3594 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3595 &res, NULL, 1, FALSE) < 0)
3596 # else
3597 if (xterm_dpy == NULL)
3598 mch_errmsg(_("No display: Send expression failed.\n"));
3599 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3600 &res, NULL, 1, 1, FALSE) < 0)
3601 # endif
3603 if (res != NULL && *res != NUL)
3605 /* Output error from remote */
3606 mch_errmsg((char *)res);
3607 vim_free(res);
3608 res = NULL;
3610 mch_errmsg(_(": Send expression failed.\n"));
3613 else if (STRICMP(argv[i], "--serverlist") == 0)
3615 # ifdef WIN32
3616 /* Win32 always works? */
3617 res = serverGetVimNames();
3618 # else
3619 if (xterm_dpy != NULL)
3620 res = serverGetVimNames(xterm_dpy);
3621 # endif
3622 if (called_emsg)
3623 mch_errmsg("\n");
3625 else if (STRICMP(argv[i], "--servername") == 0)
3627 /* Alredy processed. Take it out of the command line */
3628 i++;
3629 continue;
3631 else
3633 *newArgV++ = argv[i];
3634 newArgC++;
3635 continue;
3637 didone = TRUE;
3638 if (res != NULL && *res != NUL)
3640 mch_msg((char *)res);
3641 if (res[STRLEN(res) - 1] != '\n')
3642 mch_msg("\n");
3644 vim_free(res);
3647 if (didone)
3649 display_errors(); /* display any collected messages */
3650 exit(exiterr); /* Mission accomplished - get out */
3653 /* Return back into main() */
3654 *argc = newArgC;
3655 vim_free(sname);
3659 * Build a ":drop" command to send to a Vim server.
3661 static char_u *
3662 build_drop_cmd(filec, filev, tabs, sendReply)
3663 int filec;
3664 char **filev;
3665 int tabs; /* Use ":tab drop" instead of ":drop". */
3666 int sendReply;
3668 garray_T ga;
3669 int i;
3670 char_u *inicmd = NULL;
3671 char_u *p;
3672 char_u cwd[MAXPATHL];
3674 if (filec > 0 && filev[0][0] == '+')
3676 inicmd = (char_u *)filev[0] + 1;
3677 filev++;
3678 filec--;
3680 /* Check if we have at least one argument. */
3681 if (filec <= 0)
3682 mainerr_arg_missing((char_u *)filev[-1]);
3683 if (mch_dirname(cwd, MAXPATHL) != OK)
3684 return NULL;
3685 if ((p = vim_strsave_escaped_ext(cwd,
3686 #ifdef BACKSLASH_IN_FILENAME
3687 "", /* rem_backslash() will tell what chars to escape */
3688 #else
3689 PATH_ESC_CHARS,
3690 #endif
3691 '\\', TRUE)) == NULL)
3692 return NULL;
3693 ga_init2(&ga, 1, 100);
3694 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3695 ga_concat(&ga, p);
3696 vim_free(p);
3698 /* Call inputsave() so that a prompt for an encryption key works. */
3699 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|");
3700 if (tabs)
3701 ga_concat(&ga, (char_u *)"tab ");
3702 ga_concat(&ga, (char_u *)"drop");
3703 for (i = 0; i < filec; i++)
3705 /* On Unix the shell has already expanded the wildcards, don't want to
3706 * do it again in the Vim server. On MS-Windows only escape
3707 * non-wildcard characters. */
3708 p = vim_strsave_escaped((char_u *)filev[i],
3709 #ifdef UNIX
3710 PATH_ESC_CHARS
3711 #else
3712 (char_u *)" \t%#"
3713 #endif
3715 if (p == NULL)
3717 vim_free(ga.ga_data);
3718 return NULL;
3720 ga_concat(&ga, (char_u *)" ");
3721 ga_concat(&ga, p);
3722 vim_free(p);
3724 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3725 * CTRL-\ CTRL-N again. */
3726 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3727 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3728 if (sendReply)
3729 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3730 ga_concat(&ga, (char_u *)"<CR>:");
3731 if (inicmd != NULL)
3733 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3734 * the following commands to be inserted as text. Use a "|",
3735 * hopefully "inicmd" does allow this... */
3736 ga_concat(&ga, inicmd);
3737 ga_concat(&ga, (char_u *)"|");
3739 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3740 * clear command line. */
3741 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
3742 ga_append(&ga, NUL);
3743 return ga.ga_data;
3747 * Replace termcodes such as <CR> and insert as key presses if there is room.
3749 void
3750 server_to_input_buf(str)
3751 char_u *str;
3753 char_u *ptr = NULL;
3754 char_u *cpo_save = p_cpo;
3756 /* Set 'cpoptions' the way we want it.
3757 * B set - backslashes are *not* treated specially
3758 * k set - keycodes are *not* reverse-engineered
3759 * < unset - <Key> sequences *are* interpreted
3760 * The last but one parameter of replace_termcodes() is TRUE so that the
3761 * <lt> sequence is recognised - needed for a real backslash.
3763 p_cpo = (char_u *)"Bk";
3764 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE, FALSE);
3765 p_cpo = cpo_save;
3767 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3770 * Add the string to the input stream.
3771 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3773 * First clear typed characters from the typeahead buffer, there could
3774 * be half a mapping there. Then append to the existing string, so
3775 * that multiple commands from a client are concatenated.
3777 if (typebuf.tb_maplen < typebuf.tb_len)
3778 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3779 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3781 /* Let input_available() know we inserted text in the typeahead
3782 * buffer. */
3783 typebuf_was_filled = TRUE;
3785 vim_free((char_u *)ptr);
3789 * Evaluate an expression that the client sent to a string.
3790 * Handles disabling error messages and disables debugging, otherwise Vim
3791 * hangs, waiting for "cont" to be typed.
3793 char_u *
3794 eval_client_expr_to_string(expr)
3795 char_u *expr;
3797 char_u *res;
3798 int save_dbl = debug_break_level;
3799 int save_ro = redir_off;
3801 debug_break_level = -1;
3802 redir_off = 0;
3803 ++emsg_skip;
3805 res = eval_to_string(expr, NULL, TRUE);
3807 debug_break_level = save_dbl;
3808 redir_off = save_ro;
3809 --emsg_skip;
3811 /* A client can tell us to redraw, but not to display the cursor, so do
3812 * that here. */
3813 setcursor();
3814 out_flush();
3815 #ifdef FEAT_GUI
3816 if (gui.in_use)
3817 gui_update_cursor(FALSE, FALSE);
3818 #endif
3820 return res;
3824 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3825 * return an allocated string. Otherwise return "data".
3826 * "*tofree" is set to the result when it needs to be freed later.
3828 /*ARGSUSED*/
3829 char_u *
3830 serverConvert(client_enc, data, tofree)
3831 char_u *client_enc;
3832 char_u *data;
3833 char_u **tofree;
3835 char_u *res = data;
3837 *tofree = NULL;
3838 # ifdef FEAT_MBYTE
3839 if (client_enc != NULL && p_enc != NULL)
3841 vimconv_T vimconv;
3843 vimconv.vc_type = CONV_NONE;
3844 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3845 && vimconv.vc_type != CONV_NONE)
3847 res = string_convert(&vimconv, data, NULL);
3848 if (res == NULL)
3849 res = data;
3850 else
3851 *tofree = res;
3853 convert_setup(&vimconv, NULL, NULL);
3855 # endif
3856 return res;
3861 * Make our basic server name: use the specified "arg" if given, otherwise use
3862 * the tail of the command "cmd" we were started with.
3863 * Return the name in allocated memory. This doesn't include a serial number.
3865 static char_u *
3866 serverMakeName(arg, cmd)
3867 char_u *arg;
3868 char *cmd;
3870 char_u *p;
3872 if (arg != NULL && *arg != NUL)
3873 p = vim_strsave_up(arg);
3874 else
3876 p = vim_strsave_up(gettail((char_u *)cmd));
3877 /* Remove .exe or .bat from the name. */
3878 if (p != NULL && vim_strchr(p, '.') != NULL)
3879 *vim_strchr(p, '.') = NUL;
3881 return p;
3883 #endif /* FEAT_CLIENTSERVER */
3886 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3888 #if defined(FEAT_FKMAP) || defined(PROTO)
3889 # include "farsi.c"
3890 #endif
3893 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3895 #if defined(FEAT_ARABIC) || defined(PROTO)
3896 # include "arabic.c"
3897 #endif