Merge branch 'vim' into master
[MacVim/KaoriYa.git] / src / main.c
blob3ad0805e3d36fb072219ad327125929acf30b322
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 <cygwin/version.h>
24 # include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
25 * cygwin_conv_path() */
26 # endif
27 # include <limits.h>
28 #endif
30 #if FEAT_GUI_MACVIM
31 #include <objc/objc-runtime.h> /* for objc_*() and sel_*() */
32 #endif
34 /* Maximum number of commands from + or -c arguments. */
35 #define MAX_ARG_CMDS 10
37 /* values for "window_layout" */
38 #define WIN_HOR 1 /* "-o" horizontally split windows */
39 #define WIN_VER 2 /* "-O" vertically split windows */
40 #define WIN_TABS 3 /* "-p" windows on tab pages */
42 /* Struct for various parameters passed between main() and other functions. */
43 typedef struct
45 int argc;
46 char **argv;
48 int evim_mode; /* started as "evim" */
49 char_u *use_vimrc; /* vimrc from -u argument */
51 int n_commands; /* no. of commands from + or -c */
52 char_u *commands[MAX_ARG_CMDS]; /* commands from + or -c arg. */
53 char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
54 int n_pre_commands; /* no. of commands from --cmd */
55 char_u *pre_commands[MAX_ARG_CMDS]; /* commands from --cmd argument */
57 int edit_type; /* type of editing to do */
58 char_u *tagname; /* tag from -t argument */
59 #ifdef FEAT_QUICKFIX
60 char_u *use_ef; /* 'errorfile' from -q argument */
61 #endif
63 int want_full_screen;
64 int stdout_isatty; /* is stdout a terminal? */
65 char_u *term; /* specified terminal name */
66 #ifdef FEAT_CRYPT
67 int ask_for_key; /* -x argument */
68 #endif
69 int no_swap_file; /* "-n" argument used */
70 #ifdef FEAT_EVAL
71 int use_debug_break_level;
72 #endif
73 #ifdef FEAT_WINDOWS
74 int window_count; /* number of windows to use */
75 int window_layout; /* 0, WIN_HOR, WIN_VER or WIN_TABS */
76 #endif
78 #ifdef FEAT_CLIENTSERVER
79 int serverArg; /* TRUE when argument for a server */
80 char_u *serverName_arg; /* cmdline arg for server name */
81 char_u *serverStr; /* remote server command */
82 char_u *serverStrEnc; /* encoding of serverStr */
83 char_u *servername; /* allocated name for our server */
84 #endif
85 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
86 int literal; /* don't expand file names */
87 #endif
88 #ifdef MSWIN
89 int full_path; /* file name argument was full path */
90 #endif
91 #ifdef FEAT_DIFF
92 int diff_mode; /* start with 'diff' set */
93 #endif
94 } mparm_T;
96 /* Values for edit_type. */
97 #define EDIT_NONE 0 /* no edit type yet */
98 #define EDIT_FILE 1 /* file name argument[s] given, use argument list */
99 #define EDIT_STDIN 2 /* read file from stdin */
100 #define EDIT_TAG 3 /* tag name argument given, use tagname */
101 #define EDIT_QF 4 /* start in quickfix mode */
103 #if defined(UNIX) || defined(VMS)
104 static int file_owned __ARGS((char *fname));
105 #endif
106 static void mainerr __ARGS((int, char_u *));
107 static void main_msg __ARGS((char *s));
108 static void usage __ARGS((void));
109 static int get_number_arg __ARGS((char_u *p, int *idx, int def));
110 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
111 static void init_locale __ARGS((void));
112 #endif
113 static void parse_command_name __ARGS((mparm_T *parmp));
114 static void early_arg_scan __ARGS((mparm_T *parmp));
115 static void command_line_scan __ARGS((mparm_T *parmp));
116 static void check_tty __ARGS((mparm_T *parmp));
117 static void read_stdin __ARGS((void));
118 static void create_windows __ARGS((mparm_T *parmp));
119 #ifdef FEAT_WINDOWS
120 static void edit_buffers __ARGS((mparm_T *parmp));
121 #endif
122 static void exe_pre_commands __ARGS((mparm_T *parmp));
123 static void exe_commands __ARGS((mparm_T *parmp));
124 static void source_startup_scripts __ARGS((mparm_T *parmp));
125 static void main_start_gui __ARGS((void));
126 #if defined(HAS_SWAP_EXISTS_ACTION)
127 static void check_swap_exists_action __ARGS((void));
128 #endif
129 #ifdef FEAT_CLIENTSERVER
130 static void exec_on_server __ARGS((mparm_T *parmp));
131 static void prepare_server __ARGS((mparm_T *parmp));
132 static void cmdsrv_main __ARGS((int *argc, char **argv, char_u *serverName_arg, char_u **serverStr));
133 static char_u *serverMakeName __ARGS((char_u *arg, char *cmd));
134 #endif
137 #ifdef STARTUPTIME
138 static FILE *time_fd = NULL;
139 #endif
142 * Different types of error messages.
144 static char *(main_errors[]) =
146 N_("Unknown option argument"),
147 #define ME_UNKNOWN_OPTION 0
148 N_("Too many edit arguments"),
149 #define ME_TOO_MANY_ARGS 1
150 N_("Argument missing after"),
151 #define ME_ARG_MISSING 2
152 N_("Garbage after option argument"),
153 #define ME_GARBAGE 3
154 N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments"),
155 #define ME_EXTRA_CMD 4
156 N_("Invalid argument for"),
157 #define ME_INVALID_ARG 5
160 #ifndef PROTO /* don't want a prototype for main() */
162 # ifdef VIMDLL
163 _export
164 # endif
165 # ifdef FEAT_GUI_MSWIN
166 # ifdef __BORLANDC__
167 _cdecl
168 # endif
169 VimMain
170 # else
171 main
172 # endif
173 (argc, argv)
174 int argc;
175 char **argv;
177 char_u *fname = NULL; /* file name from command line */
178 mparm_T params; /* various parameters passed between
179 * main() and other functions. */
181 #if FEAT_GUI_MACVIM
182 // Cocoa needs an NSAutoreleasePool in place or it will leak memory.
183 // This particular pool will hold autorelease objects created during
184 // initialization.
185 id autoreleasePool = objc_msgSend(objc_msgSend(
186 objc_getClass("NSAutoreleasePool"),sel_getUid("alloc")
187 ), sel_getUid("init"));
188 #endif
191 * Do any system-specific initialisations. These can NOT use IObuff or
192 * NameBuff. Thus emsg2() cannot be called!
194 mch_early_init();
196 /* Many variables are in "params" so that we can pass them to invoked
197 * functions without a lot of arguments. "argc" and "argv" are also
198 * copied, so that they can be changed. */
199 vim_memset(&params, 0, sizeof(params));
200 params.argc = argc;
201 params.argv = argv;
202 params.want_full_screen = TRUE;
203 #ifdef FEAT_EVAL
204 params.use_debug_break_level = -1;
205 #endif
206 #ifdef FEAT_WINDOWS
207 params.window_count = -1;
208 #endif
210 #ifdef FEAT_TCL
211 vim_tcl_init(params.argv[0]);
212 #endif
214 #ifdef MEM_PROFILE
215 atexit(vim_mem_profile_dump);
216 #endif
218 #ifdef STARTUPTIME
219 time_fd = mch_fopen(STARTUPTIME, "a");
220 TIME_MSG("--- VIM STARTING ---");
221 #endif
222 starttime = time(NULL);
224 #ifdef __EMX__
225 _wildcard(&params.argc, &params.argv);
226 #endif
228 #ifdef FEAT_MBYTE
229 (void)mb_init(); /* init mb_bytelen_tab[] to ones */
230 #endif
231 #ifdef FEAT_EVAL
232 eval_init(); /* init global variables */
233 #endif
235 #ifdef __QNXNTO__
236 qnx_init(); /* PhAttach() for clipboard, (and gui) */
237 #endif
239 #ifdef MAC_OS_CLASSIC
240 /* Prepare for possibly starting GUI sometime */
241 /* Macintosh needs this before any memory is allocated. */
242 gui_prepare(&params.argc, params.argv);
243 TIME_MSG("GUI prepared");
244 #endif
246 /* Init the table of Normal mode commands. */
247 init_normal_cmds();
249 #if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC)
250 make_version(); /* Construct the long version string. */
251 #endif
254 * Allocate space for the generic buffers (needed for set_init_1() and
255 * EMSG2()).
257 if ((IObuff = alloc(IOSIZE)) == NULL
258 || (NameBuff = alloc(MAXPATHL)) == NULL)
259 mch_exit(0);
260 TIME_MSG("Allocated generic buffers");
262 #ifdef NBDEBUG
263 /* Wait a moment for debugging NetBeans. Must be after allocating
264 * NameBuff. */
265 nbdebug_log_init("SPRO_GVIM_DEBUG", "SPRO_GVIM_DLEVEL");
266 nbdebug_wait(WT_ENV | WT_WAIT | WT_STOP, "SPRO_GVIM_WAIT", 20);
267 TIME_MSG("NetBeans debug wait");
268 #endif
270 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
272 * Setup to use the current locale (for ctype() and many other things).
273 * NOTE: Translated messages with encodings other than latin1 will not
274 * work until set_init_1() has been called!
276 init_locale();
277 TIME_MSG("locale set");
278 #endif
280 #ifdef FEAT_GUI
281 gui.dofork = TRUE; /* default is to use fork() */
282 #endif
285 * Do a first scan of the arguments in "argv[]":
286 * -display or --display
287 * --server...
288 * --socketid
289 * --windowid
291 early_arg_scan(&params);
293 #ifdef FEAT_SUN_WORKSHOP
294 findYourself(params.argv[0]);
295 #endif
296 #if defined(FEAT_GUI) && !defined(MAC_OS_CLASSIC)
297 /* Prepare for possibly starting GUI sometime */
298 gui_prepare(&params.argc, params.argv);
299 TIME_MSG("GUI prepared");
300 #endif
302 #ifdef FEAT_CLIPBOARD
303 clip_init(FALSE); /* Initialise clipboard stuff */
304 TIME_MSG("clipboard setup");
305 #endif
308 * Check if we have an interactive window.
309 * On the Amiga: If there is no window, we open one with a newcli command
310 * (needed for :! to * work). mch_check_win() will also handle the -d or
311 * -dev argument.
313 params.stdout_isatty = (mch_check_win(params.argc, params.argv) != FAIL);
314 TIME_MSG("window checked");
317 * Allocate the first window and buffer.
318 * Can't do anything without it, exit when it fails.
320 if (win_alloc_first() == FAIL)
321 mch_exit(0);
323 init_yank(); /* init yank buffers */
325 alist_init(&global_alist); /* Init the argument list to empty. */
328 * Set the default values for the options.
329 * NOTE: Non-latin1 translated messages are working only after this,
330 * because this is where "has_mbyte" will be set, which is used by
331 * msg_outtrans_len_attr().
332 * First find out the home directory, needed to expand "~" in options.
334 init_homedir(); /* find real value of $HOME */
335 set_init_1();
336 TIME_MSG("inits 1");
338 #ifdef FEAT_EVAL
339 set_lang_var(); /* set v:lang and v:ctype */
340 #endif
342 #ifdef FEAT_CLIENTSERVER
344 * Do the client-server stuff, unless "--servername ''" was used.
345 * This may exit Vim if the command was sent to the server.
347 exec_on_server(&params);
348 #endif
351 * Figure out the way to work from the command name argv[0].
352 * "vimdiff" starts diff mode, "rvim" sets "restricted", etc.
354 parse_command_name(&params);
357 * Process the command line arguments. File names are put in the global
358 * argument list "global_alist".
360 command_line_scan(&params);
361 TIME_MSG("parsing arguments");
364 * On some systems, when we compile with the GUI, we always use it. On Mac
365 * there is no terminal version, and on Windows we can't fork one off with
366 * :gui.
368 #ifdef ALWAYS_USE_GUI
369 gui.starting = TRUE;
370 #else
371 # if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
373 * Check if the GUI can be started. Reset gui.starting if not.
374 * Don't know about other systems, stay on the safe side and don't check.
376 if (gui.starting && gui_init_check() == FAIL)
378 gui.starting = FALSE;
380 /* When running "evim" or "gvim -y" we need the menus, exit if we
381 * don't have them. */
382 if (params.evim_mode)
383 mch_exit(1);
385 # endif
386 #endif
388 if (GARGCOUNT > 0)
390 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
392 * Expand wildcards in file names.
394 if (!params.literal)
396 /* Temporarily add '(' and ')' to 'isfname'. These are valid
397 * filename characters but are excluded from 'isfname' to make
398 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
399 do_cmdline_cmd((char_u *)":set isf+=(,)");
400 alist_expand(NULL, 0);
401 do_cmdline_cmd((char_u *)":set isf&");
403 #endif
404 fname = alist_name(&GARGLIST[0]);
407 #if defined(WIN32) && defined(FEAT_MBYTE)
409 extern void set_alist_count(void);
411 /* Remember the number of entries in the argument list. If it changes
412 * we don't react on setting 'encoding'. */
413 set_alist_count();
415 #endif
417 #ifdef MSWIN
418 if (GARGCOUNT == 1 && params.full_path)
421 * If there is one filename, fully qualified, we have very probably
422 * been invoked from explorer, so change to the file's directory.
423 * Hint: to avoid this when typing a command use a forward slash.
424 * If the cd fails, it doesn't matter.
426 (void)vim_chdirfile(fname);
428 #endif
429 TIME_MSG("expanding arguments");
431 #ifdef FEAT_DIFF
432 if (params.diff_mode && params.window_count == -1)
433 params.window_count = 0; /* open up to 3 windows */
434 #endif
436 /* Don't redraw until much later. */
437 ++RedrawingDisabled;
440 * When listing swap file names, don't do cursor positioning et. al.
442 if (recoverymode && fname == NULL)
443 params.want_full_screen = FALSE;
446 * When certain to start the GUI, don't check capabilities of terminal.
447 * For GTK we can't be sure, but when started from the desktop it doesn't
448 * make sense to try using a terminal.
450 #if defined(ALWAYS_USE_GUI) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
451 if (gui.starting
452 # ifdef FEAT_GUI_GTK
453 && !isatty(2)
454 # endif
456 params.want_full_screen = FALSE;
457 #endif
459 #if (defined(FEAT_GUI_MAC) || defined(FEAT_GUI_MACVIM)) && defined(MACOS_X_UNIX)
460 /* When the GUI is started from Finder, need to display messages in a
461 * message box. isatty(2) returns TRUE anyway, thus we need to check the
462 * name to know we're not started from a terminal. */
463 if (gui.starting && (!isatty(2) || strcmp("/dev/console", ttyname(2)) == 0))
465 params.want_full_screen = FALSE;
467 /* Avoid always using "/" as the current directory. Note that when
468 * started from Finder the arglist will be filled later in
469 * HandleODocAE() and "fname" will be NULL. */
470 if (getcwd((char *)NameBuff, MAXPATHL) != NULL
471 && STRCMP(NameBuff, "/") == 0)
473 if (fname != NULL)
474 (void)vim_chdirfile(fname);
475 else
477 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
478 vim_chdir(NameBuff);
482 #endif
485 * mch_init() sets up the terminal (window) for use. This must be
486 * done after resetting full_screen, otherwise it may move the cursor
487 * (MSDOS).
488 * Note that we may use mch_exit() before mch_init()!
490 mch_init();
491 TIME_MSG("shell init");
493 #ifdef USE_XSMP
495 * For want of anywhere else to do it, try to connect to xsmp here.
496 * Fitting it in after gui_mch_init, but before gui_init (via termcapinit).
497 * Hijacking -X 'no X connection' to also disable XSMP connection as that
498 * has a similar delay upon failure.
499 * Only try if SESSION_MANAGER is set to something non-null.
501 if (!x_no_connect)
503 char *p = getenv("SESSION_MANAGER");
505 if (p != NULL && *p != NUL)
507 xsmp_init();
508 TIME_MSG("xsmp init");
511 #endif
514 * Print a warning if stdout is not a terminal.
516 check_tty(&params);
518 /* This message comes before term inits, but after setting "silent_mode"
519 * when the input is not a tty. */
520 if (GARGCOUNT > 1 && !silent_mode)
521 printf(_("%d files to edit\n"), GARGCOUNT);
523 if (params.want_full_screen && !silent_mode)
525 termcapinit(params.term); /* set terminal name and get terminal
526 capabilities (will set full_screen) */
527 screen_start(); /* don't know where cursor is now */
528 TIME_MSG("Termcap init");
532 * Set the default values for the options that use Rows and Columns.
534 ui_get_shellsize(); /* inits Rows and Columns */
535 #ifdef FEAT_NETBEANS_INTG
536 if (usingNetbeans)
537 Columns += 2; /* leave room for glyph gutter */
538 #endif
539 win_init_size();
540 #ifdef FEAT_DIFF
541 /* Set the 'diff' option now, so that it can be checked for in a .vimrc
542 * file. There is no buffer yet though. */
543 if (params.diff_mode)
544 diff_win_options(firstwin, FALSE);
545 #endif
547 cmdline_row = Rows - p_ch;
548 msg_row = cmdline_row;
549 screenalloc(FALSE); /* allocate screen buffers */
550 set_init_2();
551 TIME_MSG("inits 2");
553 msg_scroll = TRUE;
554 no_wait_return = TRUE;
556 init_mappings(); /* set up initial mappings */
558 init_highlight(TRUE, FALSE); /* set the default highlight groups */
559 TIME_MSG("init highlight");
561 #ifdef FEAT_EVAL
562 /* Set the break level after the terminal is initialized. */
563 debug_break_level = params.use_debug_break_level;
564 #endif
566 /* Execute --cmd arguments. */
567 exe_pre_commands(&params);
569 /* Source startup scripts. */
570 source_startup_scripts(&params);
572 #ifdef FEAT_EVAL
574 * Read all the plugin files.
575 * Only when compiled with +eval, since most plugins need it.
577 if (p_lpl)
579 # ifdef VMS /* Somehow VMS doesn't handle the "**". */
580 source_runtime((char_u *)"plugin/*.vim", TRUE);
581 # else
582 source_runtime((char_u *)"plugin/**/*.vim", TRUE);
583 # endif
584 TIME_MSG("loading plugins");
586 #endif
588 #ifdef FEAT_DIFF
589 /* Decide about window layout for diff mode after reading vimrc. */
590 if (params.diff_mode && params.window_layout == 0)
592 if (diffopt_horizontal())
593 params.window_layout = WIN_HOR; /* use horizontal split */
594 else
595 params.window_layout = WIN_VER; /* use vertical split */
597 #endif
600 * Recovery mode without a file name: List swap files.
601 * This uses the 'dir' option, therefore it must be after the
602 * initializations.
604 if (recoverymode && fname == NULL)
606 recover_names(NULL, TRUE, 0);
607 mch_exit(0);
611 * Set a few option defaults after reading .vimrc files:
612 * 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
614 set_init_3();
615 TIME_MSG("inits 3");
618 * "-n" argument: Disable swap file by setting 'updatecount' to 0.
619 * Note that this overrides anything from a vimrc file.
621 if (params.no_swap_file)
622 p_uc = 0;
624 #ifdef FEAT_FKMAP
625 if (curwin->w_p_rl && p_altkeymap)
627 p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
628 # ifdef FEAT_ARABIC
629 curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
630 # endif
631 p_fkmap = TRUE; /* Set the Farsi keymap mode */
633 #endif
635 #ifdef FEAT_GUI
636 if (gui.starting)
638 #if defined(UNIX) || defined(VMS)
639 /* When something caused a message from a vimrc script, need to output
640 * an extra newline before the shell prompt. */
641 if (did_emsg || msg_didout)
642 putchar('\n');
643 #endif
645 gui_start(); /* will set full_screen to TRUE */
646 TIME_MSG("starting GUI");
648 /* When running "evim" or "gvim -y" we need the menus, exit if we
649 * don't have them. */
650 if (!gui.in_use && params.evim_mode)
651 mch_exit(1);
653 #endif
655 #ifdef SPAWNO /* special MSDOS swapping library */
656 init_SPAWNO("", SWAP_ANY);
657 #endif
659 #ifdef FEAT_VIMINFO
661 * Read in registers, history etc, but not marks, from the viminfo file
663 if (*p_viminfo != NUL)
665 read_viminfo(NULL, TRUE, FALSE, FALSE);
666 TIME_MSG("reading viminfo");
668 #endif
670 #ifdef FEAT_QUICKFIX
672 * "-q errorfile": Load the error file now.
673 * If the error file can't be read, exit before doing anything else.
675 if (params.edit_type == EDIT_QF)
677 if (params.use_ef != NULL)
678 set_string_option_direct((char_u *)"ef", -1,
679 params.use_ef, OPT_FREE, SID_CARG);
680 if (qf_init(NULL, p_ef, p_efm, TRUE) < 0)
682 out_char('\n');
683 mch_exit(3);
685 TIME_MSG("reading errorfile");
687 #endif
690 * Start putting things on the screen.
691 * Scroll screen down before drawing over it
692 * Clear screen now, so file message will not be cleared.
694 starting = NO_BUFFERS;
695 no_wait_return = FALSE;
696 if (!exmode_active)
697 msg_scroll = FALSE;
699 #ifdef FEAT_GUI
701 * This seems to be required to make callbacks to be called now, instead
702 * of after things have been put on the screen, which then may be deleted
703 * when getting a resize callback.
704 * For the Mac this handles putting files dropped on the Vim icon to
705 * global_alist.
707 if (gui.in_use)
709 # ifdef FEAT_SUN_WORKSHOP
710 if (!usingSunWorkShop)
711 # endif
712 gui_wait_for_chars(50L);
713 TIME_MSG("GUI delay");
715 #endif
717 #if defined(FEAT_GUI_PHOTON) && defined(FEAT_CLIPBOARD)
718 qnx_clip_init();
719 #endif
721 #ifdef FEAT_XCLIPBOARD
722 /* Start using the X clipboard, unless the GUI was started. */
723 # ifdef FEAT_GUI
724 if (!gui.in_use)
725 # endif
727 setup_term_clip();
728 TIME_MSG("setup clipboard");
730 #endif
732 #ifdef FEAT_CLIENTSERVER
733 /* Prepare for being a Vim server. */
734 prepare_server(&params);
735 #endif
738 * If "-" argument given: Read file from stdin.
739 * Do this before starting Raw mode, because it may change things that the
740 * writing end of the pipe doesn't like, e.g., in case stdin and stderr
741 * are the same terminal: "cat | vim -".
742 * Using autocommands here may cause trouble...
744 if (params.edit_type == EDIT_STDIN && !recoverymode)
745 read_stdin();
747 #if defined(UNIX) || defined(VMS)
748 /* When switching screens and something caused a message from a vimrc
749 * script, need to output an extra newline on exit. */
750 if ((did_emsg || msg_didout) && *T_TI != NUL)
751 newline_on_exit = TRUE;
752 #endif
755 * When done something that is not allowed or error message call
756 * wait_return. This must be done before starttermcap(), because it may
757 * switch to another screen. It must be done after settmode(TMODE_RAW),
758 * because we want to react on a single key stroke.
759 * Call settmode and starttermcap here, so the T_KS and T_TI may be
760 * defined by termcapinit and redefined in .exrc.
762 settmode(TMODE_RAW);
763 TIME_MSG("setting raw mode");
765 if (need_wait_return || msg_didany)
767 wait_return(TRUE);
768 TIME_MSG("waiting for return");
771 starttermcap(); /* start termcap if not done by wait_return() */
772 TIME_MSG("start termcap");
774 #ifdef FEAT_MOUSE
775 setmouse(); /* may start using the mouse */
776 #endif
777 if (scroll_region)
778 scroll_region_reset(); /* In case Rows changed */
779 scroll_start(); /* may scroll the screen to the right position */
782 * Don't clear the screen when starting in Ex mode, unless using the GUI.
784 if (exmode_active
785 #ifdef FEAT_GUI
786 && !gui.in_use
787 #endif
789 must_redraw = CLEAR;
790 else
792 screenclear(); /* clear screen */
793 TIME_MSG("clearing screen");
796 #ifdef FEAT_CRYPT
797 if (params.ask_for_key)
799 (void)get_crypt_key(TRUE, TRUE);
800 TIME_MSG("getting crypt key");
802 #endif
804 no_wait_return = TRUE;
807 * Create the requested number of windows and edit buffers in them.
808 * Also does recovery if "recoverymode" set.
810 create_windows(&params);
811 TIME_MSG("opening buffers");
813 #ifdef FEAT_EVAL
814 /* clear v:swapcommand */
815 set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
816 #endif
818 /* Ex starts at last line of the file */
819 if (exmode_active)
820 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
822 #ifdef FEAT_AUTOCMD
823 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
824 TIME_MSG("BufEnter autocommands");
825 #endif
826 setpcmark();
828 #ifdef FEAT_QUICKFIX
830 * When started with "-q errorfile" jump to first error now.
832 if (params.edit_type == EDIT_QF)
834 qf_jump(NULL, 0, 0, FALSE);
835 TIME_MSG("jump to first error");
837 #endif
839 #ifdef FEAT_WINDOWS
841 * If opened more than one window, start editing files in the other
842 * windows.
844 edit_buffers(&params);
845 #endif
847 #ifdef FEAT_DIFF
848 if (params.diff_mode)
850 win_T *wp;
852 /* set options in each window for "vimdiff". */
853 for (wp = firstwin; wp != NULL; wp = wp->w_next)
854 diff_win_options(wp, TRUE);
856 #endif
859 * Shorten any of the filenames, but only when absolute.
861 shorten_fnames(FALSE);
864 * Need to jump to the tag before executing the '-c command'.
865 * Makes "vim -c '/return' -t main" work.
867 if (params.tagname != NULL)
869 #if defined(HAS_SWAP_EXISTS_ACTION)
870 swap_exists_did_quit = FALSE;
871 #endif
873 vim_snprintf((char *)IObuff, IOSIZE, "ta %s", params.tagname);
874 do_cmdline_cmd(IObuff);
875 TIME_MSG("jumping to tag");
877 #if defined(HAS_SWAP_EXISTS_ACTION)
878 /* If the user doesn't want to edit the file then we quit here. */
879 if (swap_exists_did_quit)
880 getout(1);
881 #endif
884 /* Execute any "+", "-c" and "-S" arguments. */
885 if (params.n_commands > 0)
886 exe_commands(&params);
888 RedrawingDisabled = 0;
889 redraw_all_later(NOT_VALID);
890 no_wait_return = FALSE;
891 starting = 0;
893 #ifdef FEAT_TERMRESPONSE
894 /* Requesting the termresponse is postponed until here, so that a "-c q"
895 * argument doesn't make it appear in the shell Vim was started from. */
896 may_req_termresponse();
897 #endif
899 /* start in insert mode */
900 if (p_im)
901 need_start_insertmode = TRUE;
903 #ifdef FEAT_AUTOCMD
904 apply_autocmds(EVENT_VIMENTER, NULL, NULL, FALSE, curbuf);
905 TIME_MSG("VimEnter autocommands");
906 #endif
908 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
909 /* When a startup script or session file setup for diff'ing and
910 * scrollbind, sync the scrollbind now. */
911 if (curwin->w_p_diff && curwin->w_p_scb)
913 update_topline();
914 check_scrollbind((linenr_T)0, 0L);
915 TIME_MSG("diff scrollbinding");
917 #endif
919 #if defined(WIN3264) && !defined(FEAT_GUI_W32)
920 mch_set_winsize_now(); /* Allow winsize changes from now on */
921 #endif
923 #if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
924 /* When tab pages were created, may need to update the tab pages line and
925 * scrollbars. This is skipped while creating them. */
926 if (first_tabpage->tp_next != NULL)
928 out_flush();
929 gui_init_which_components(NULL);
930 gui_update_scrollbars(TRUE);
932 need_mouse_correct = TRUE;
933 #endif
935 /* If ":startinsert" command used, stuff a dummy command to be able to
936 * call normal_cmd(), which will then start Insert mode. */
937 if (restart_edit != 0)
938 stuffcharReadbuff(K_NOP);
940 #ifdef FEAT_NETBEANS_INTG
941 if (usingNetbeans)
942 /* Tell the client that it can start sending commands. */
943 netbeans_startup_done();
944 #endif
946 TIME_MSG("before starting main loop");
948 #if FEAT_GUI_MACVIM
949 // The autorelease pool might have filled up quite a bit during
950 // initialization, so purge it before entering the main loop.
951 objc_msgSend(autoreleasePool, sel_getUid("release"));
953 // The main loop sets up its own autorelease pool, but to be safe we still
954 // realloc this one here.
955 autoreleasePool = objc_msgSend(objc_msgSend(
956 objc_getClass("NSAutoreleasePool"),sel_getUid("alloc")
957 ), sel_getUid("init"));
958 #endif
961 * Call the main command loop. This never returns.
963 main_loop(FALSE, FALSE);
965 #if FEAT_GUI_MACVIM
966 objc_msgSend(autoreleasePool, sel_getUid("release"));
967 #endif
969 return 0;
971 #endif /* PROTO */
974 * Main loop: Execute Normal mode commands until exiting Vim.
975 * Also used to handle commands in the command-line window, until the window
976 * is closed.
977 * Also used to handle ":visual" command after ":global": execute Normal mode
978 * commands, return when entering Ex mode. "noexmode" is TRUE then.
980 void
981 main_loop(cmdwin, noexmode)
982 int cmdwin; /* TRUE when working in the command-line window */
983 int noexmode; /* TRUE when return on entering Ex mode */
985 oparg_T oa; /* operator arguments */
986 int previous_got_int = FALSE; /* "got_int" was TRUE */
988 #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
989 /* Setup to catch a terminating error from the X server. Just ignore
990 * it, restore the state and continue. This might not always work
991 * properly, but at least we don't exit unexpectedly when the X server
992 * exists while Vim is running in a console. */
993 if (!cmdwin && !noexmode && SETJMP(x_jump_env))
995 State = NORMAL;
996 # ifdef FEAT_VISUAL
997 VIsual_active = FALSE;
998 # endif
999 got_int = TRUE;
1000 need_wait_return = FALSE;
1001 global_busy = FALSE;
1002 exmode_active = 0;
1003 skip_redraw = FALSE;
1004 RedrawingDisabled = 0;
1005 no_wait_return = 0;
1006 # ifdef FEAT_EVAL
1007 emsg_skip = 0;
1008 # endif
1009 emsg_off = 0;
1010 # ifdef FEAT_MOUSE
1011 setmouse();
1012 # endif
1013 settmode(TMODE_RAW);
1014 starttermcap();
1015 scroll_start();
1016 redraw_later_clear();
1018 #endif
1020 clear_oparg(&oa);
1021 while (!cmdwin
1022 #ifdef FEAT_CMDWIN
1023 || cmdwin_result == 0
1024 #endif
1027 #if FEAT_GUI_MACVIM
1028 // Cocoa needs an NSAutoreleasePool in place or it will leak memory.
1029 // This particular pool gets released once every loop.
1030 id autoreleasePool = objc_msgSend(objc_msgSend(
1031 objc_getClass("NSAutoreleasePool"),sel_getUid("alloc")
1032 ), sel_getUid("init"));
1033 #endif
1035 if (stuff_empty())
1037 did_check_timestamps = FALSE;
1038 if (need_check_timestamps)
1039 check_timestamps(FALSE);
1040 if (need_wait_return) /* if wait_return still needed ... */
1041 wait_return(FALSE); /* ... call it now */
1042 if (need_start_insertmode && goto_im()
1043 #ifdef FEAT_VISUAL
1044 && !VIsual_active
1045 #endif
1048 need_start_insertmode = FALSE;
1049 stuffReadbuff((char_u *)"i"); /* start insert mode next */
1050 /* skip the fileinfo message now, because it would be shown
1051 * after insert mode finishes! */
1052 need_fileinfo = FALSE;
1056 /* Reset "got_int" now that we got back to the main loop. Except when
1057 * inside a ":g/pat/cmd" command, then the "got_int" needs to abort
1058 * the ":g" command.
1059 * For ":g/pat/vi" we reset "got_int" when used once. When used
1060 * a second time we go back to Ex mode and abort the ":g" command. */
1061 if (got_int)
1063 if (noexmode && global_busy && !exmode_active && previous_got_int)
1065 /* Typed two CTRL-C in a row: go back to ex mode as if "Q" was
1066 * used and keep "got_int" set, so that it aborts ":g". */
1067 exmode_active = EXMODE_NORMAL;
1068 State = NORMAL;
1070 else if (!global_busy || !exmode_active)
1072 if (!quit_more)
1073 (void)vgetc(); /* flush all buffers */
1074 got_int = FALSE;
1076 previous_got_int = TRUE;
1078 else
1079 previous_got_int = FALSE;
1081 if (!exmode_active)
1082 msg_scroll = FALSE;
1083 quit_more = FALSE;
1086 * If skip redraw is set (for ":" in wait_return()), don't redraw now.
1087 * If there is nothing in the stuff_buffer or do_redraw is TRUE,
1088 * update cursor and redraw.
1090 if (skip_redraw || exmode_active)
1091 skip_redraw = FALSE;
1092 else if (do_redraw || stuff_empty())
1094 #ifdef FEAT_AUTOCMD
1095 /* Trigger CursorMoved if the cursor moved. */
1096 if (!finish_op && has_cursormoved()
1097 && !equalpos(last_cursormoved, curwin->w_cursor))
1099 apply_autocmds(EVENT_CURSORMOVED, NULL, NULL, FALSE, curbuf);
1100 last_cursormoved = curwin->w_cursor;
1102 #endif
1104 #if defined(FEAT_DIFF) && defined(FEAT_SCROLLBIND)
1105 /* Scroll-binding for diff mode may have been postponed until
1106 * here. Avoids doing it for every change. */
1107 if (diff_need_scrollbind)
1109 check_scrollbind((linenr_T)0, 0L);
1110 diff_need_scrollbind = FALSE;
1112 #endif
1113 #if defined(FEAT_FOLDING) && defined(FEAT_VISUAL)
1114 /* Include a closed fold completely in the Visual area. */
1115 foldAdjustVisual();
1116 #endif
1117 #ifdef FEAT_FOLDING
1119 * When 'foldclose' is set, apply 'foldlevel' to folds that don't
1120 * contain the cursor.
1121 * When 'foldopen' is "all", open the fold(s) under the cursor.
1122 * This may mark the window for redrawing.
1124 if (hasAnyFolding(curwin) && !char_avail())
1126 foldCheckClose();
1127 if (fdo_flags & FDO_ALL)
1128 foldOpenCursor();
1130 #endif
1133 * Before redrawing, make sure w_topline is correct, and w_leftcol
1134 * if lines don't wrap, and w_skipcol if lines wrap.
1136 update_topline();
1137 validate_cursor();
1139 #ifdef FEAT_VISUAL
1140 if (VIsual_active)
1141 update_curbuf(INVERTED);/* update inverted part */
1142 else
1143 #endif
1144 if (must_redraw)
1145 update_screen(0);
1146 else if (redraw_cmdline || clear_cmdline)
1147 showmode();
1148 #ifdef FEAT_WINDOWS
1149 redraw_statuslines();
1150 #endif
1151 #ifdef FEAT_TITLE
1152 if (need_maketitle)
1153 maketitle();
1154 #endif
1155 /* display message after redraw */
1156 if (keep_msg != NULL)
1158 char_u *p;
1160 /* msg_attr_keep() will set keep_msg to NULL, must free the
1161 * string here. */
1162 p = keep_msg;
1163 keep_msg = NULL;
1164 msg_attr(p, keep_msg_attr);
1165 vim_free(p);
1167 if (need_fileinfo) /* show file info after redraw */
1169 fileinfo(FALSE, TRUE, FALSE);
1170 need_fileinfo = FALSE;
1173 emsg_on_display = FALSE; /* can delete error message now */
1174 did_emsg = FALSE;
1175 msg_didany = FALSE; /* reset lines_left in msg_start() */
1176 may_clear_sb_text(); /* clear scroll-back text on next msg */
1177 showruler(FALSE);
1179 setcursor();
1180 cursor_on();
1182 do_redraw = FALSE;
1184 #ifdef FEAT_GUI
1185 if (need_mouse_correct)
1186 gui_mouse_correct();
1187 #endif
1190 * Update w_curswant if w_set_curswant has been set.
1191 * Postponed until here to avoid computing w_virtcol too often.
1193 update_curswant();
1195 #ifdef FEAT_EVAL
1197 * May perform garbage collection when waiting for a character, but
1198 * only at the very toplevel. Otherwise we may be using a List or
1199 * Dict internally somewhere.
1200 * "may_garbage_collect" is reset in vgetc() which is invoked through
1201 * do_exmode() and normal_cmd().
1203 may_garbage_collect = (!cmdwin && !noexmode);
1204 #endif
1206 * If we're invoked as ex, do a round of ex commands.
1207 * Otherwise, get and execute a normal mode command.
1209 if (exmode_active)
1211 if (noexmode) /* End of ":global/path/visual" commands */
1212 return;
1213 do_exmode(exmode_active == EXMODE_VIM);
1215 else
1216 normal_cmd(&oa, TRUE);
1218 #if FEAT_GUI_MACVIM
1219 // TODO! Make sure there are no continue statements that will cause
1220 // this not to be called or MacVim will leak memory!
1221 objc_msgSend(autoreleasePool, sel_getUid("release"));
1222 #endif
1227 #if defined(USE_XSMP) || defined(FEAT_GUI_MSWIN) || defined(PROTO) \
1228 || defined(FEAT_GUI_MACVIM)
1230 * Exit, but leave behind swap files for modified buffers.
1232 void
1233 getout_preserve_modified(exitval)
1234 int exitval;
1236 # if defined(SIGHUP) && defined(SIG_IGN)
1237 /* Ignore SIGHUP, because a dropped connection causes a read error, which
1238 * makes Vim exit and then handling SIGHUP causes various reentrance
1239 * problems. */
1240 signal(SIGHUP, SIG_IGN);
1241 # endif
1243 ml_close_notmod(); /* close all not-modified buffers */
1244 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
1245 ml_close_all(FALSE); /* close all memfiles, without deleting */
1246 getout(exitval); /* exit Vim properly */
1248 #endif
1251 /* Prepare proper exit*/
1252 void
1253 prepare_getout()
1255 #ifdef FEAT_AUTOCMD
1256 buf_T *buf;
1257 win_T *wp;
1258 tabpage_T *tp, *next_tp;
1259 #endif
1261 exiting = TRUE;
1263 /* Position the cursor on the last screen line, below all the text */
1264 #ifdef FEAT_GUI
1265 if (!gui.in_use)
1266 #endif
1267 windgoto((int)Rows - 1, 0);
1269 #if defined(FEAT_EVAL) || defined(FEAT_SYN_HL)
1270 /* Optionally print hashtable efficiency. */
1271 hash_debug_results();
1272 #endif
1274 #ifdef FEAT_GUI
1275 msg_didany = FALSE;
1276 #endif
1278 #ifdef FEAT_AUTOCMD
1279 /* Trigger BufWinLeave for all windows, but only once per buffer. */
1280 # if defined FEAT_WINDOWS
1281 for (tp = first_tabpage; tp != NULL; tp = next_tp)
1283 next_tp = tp->tp_next;
1284 for (wp = (tp == curtab)
1285 ? firstwin : tp->tp_firstwin; wp != NULL; wp = wp->w_next)
1287 buf = wp->w_buffer;
1288 if (buf->b_changedtick != -1)
1290 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
1291 FALSE, buf);
1292 buf->b_changedtick = -1; /* note that we did it already */
1293 /* start all over, autocommands may mess up the lists */
1294 next_tp = first_tabpage;
1295 break;
1299 # else
1300 apply_autocmds(EVENT_BUFWINLEAVE, curbuf, curbuf->b_fname, FALSE, curbuf);
1301 # endif
1303 /* Trigger BufUnload for buffers that are loaded */
1304 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1305 if (buf->b_ml.ml_mfp != NULL)
1307 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
1308 FALSE, buf);
1309 if (!buf_valid(buf)) /* autocmd may delete the buffer */
1310 break;
1312 apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
1313 #endif
1315 #ifdef FEAT_VIMINFO
1316 if (*p_viminfo != NUL)
1317 /* Write out the registers, history, marks etc, to the viminfo file */
1318 write_viminfo(NULL, FALSE);
1319 #endif
1321 #ifdef FEAT_AUTOCMD
1322 apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
1323 #endif
1325 #ifdef FEAT_PROFILE
1326 profile_dump();
1327 #endif
1329 if (did_emsg
1330 #ifdef FEAT_GUI
1331 || (gui.in_use && msg_didany && p_verbose > 0)
1332 #endif
1335 /* give the user a chance to read the (error) message */
1336 no_wait_return = FALSE;
1337 wait_return(FALSE);
1340 #ifdef FEAT_AUTOCMD
1341 /* Position the cursor again, the autocommands may have moved it */
1342 # ifdef FEAT_GUI
1343 if (!gui.in_use)
1344 # endif
1345 windgoto((int)Rows - 1, 0);
1346 #endif
1348 #ifdef FEAT_MZSCHEME
1349 mzscheme_end();
1350 #endif
1351 #ifdef FEAT_TCL
1352 tcl_end();
1353 #endif
1354 #ifdef FEAT_RUBY
1355 ruby_end();
1356 #endif
1357 #ifdef FEAT_PYTHON
1358 python_end();
1359 #endif
1360 #ifdef FEAT_PERL
1361 perl_end();
1362 #endif
1363 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
1364 iconv_end();
1365 #endif
1366 #ifdef FEAT_NETBEANS_INTG
1367 netbeans_end();
1368 #endif
1369 #ifdef FEAT_ODB_EDITOR
1370 odb_end();
1371 #endif
1372 #ifdef FEAT_CSCOPE
1373 cs_end();
1374 #endif
1375 #ifdef FEAT_EVAL
1376 if (garbage_collect_at_exit)
1377 garbage_collect();
1378 #endif
1381 /* Exit properly */
1382 void
1383 getout(exitval)
1384 int exitval;
1386 /* When running in Ex mode an error causes us to exit with a non-zero exit
1387 * code. POSIX requires this, although it's not 100% clear from the
1388 * standard. */
1389 if (exmode_active)
1390 exitval += ex_exitval;
1392 prepare_getout();
1393 mch_exit(exitval);
1397 * Get a (optional) count for a Vim argument.
1399 static int
1400 get_number_arg(p, idx, def)
1401 char_u *p; /* pointer to argument */
1402 int *idx; /* index in argument, is incremented */
1403 int def; /* default value */
1405 if (vim_isdigit(p[*idx]))
1407 def = atoi((char *)&(p[*idx]));
1408 while (vim_isdigit(p[*idx]))
1409 *idx = *idx + 1;
1411 return def;
1414 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1416 * Setup to use the current locale (for ctype() and many other things).
1418 static void
1419 init_locale()
1421 setlocale(LC_ALL, "");
1423 # if defined(FEAT_FLOAT) && defined(LC_NUMERIC)
1424 /* Make sure strtod() uses a decimal point, not a comma. */
1425 setlocale(LC_NUMERIC, "C");
1426 # endif
1428 # ifdef WIN32
1429 /* Apparently MS-Windows printf() may cause a crash when we give it 8-bit
1430 * text while it's expecting text in the current locale. This call avoids
1431 * that. */
1432 setlocale(LC_CTYPE, "C");
1433 # endif
1435 # ifdef FEAT_GETTEXT
1437 int mustfree = FALSE;
1438 char_u *p;
1440 # ifdef DYNAMIC_GETTEXT
1441 /* Initialize the gettext library */
1442 dyn_libintl_init(NULL);
1443 # endif
1444 /* expand_env() doesn't work yet, because chartab[] is not initialized
1445 * yet, call vim_getenv() directly */
1446 p = vim_getenv((char_u *)"VIMRUNTIME", &mustfree);
1447 if (p != NULL && *p != NUL)
1449 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/lang", p);
1450 bindtextdomain(VIMPACKAGE, (char *)NameBuff);
1452 if (mustfree)
1453 vim_free(p);
1454 textdomain(VIMPACKAGE);
1456 # endif
1458 #endif
1461 * Check for: [r][e][g][vi|vim|view][diff][ex[im]]
1462 * If the executable name starts with "r" we disable shell commands.
1463 * If the next character is "e" we run in Easy mode.
1464 * If the next character is "g" we run the GUI version.
1465 * If the next characters are "view" we start in readonly mode.
1466 * If the next characters are "diff" or "vimdiff" we start in diff mode.
1467 * If the next characters are "ex" we start in Ex mode. If it's followed
1468 * by "im" use improved Ex mode.
1470 static void
1471 parse_command_name(parmp)
1472 mparm_T *parmp;
1474 char_u *initstr;
1476 initstr = gettail((char_u *)parmp->argv[0]);
1478 #ifdef MACOS_X_UNIX
1479 /* An issue has been seen when launching Vim in such a way that
1480 * $PWD/$ARGV[0] or $ARGV[0] is not the absolute path to the
1481 * executable or a symbolic link of it. Until this issue is resolved
1482 * we prohibit the GUI from being used.
1484 if (STRCMP(initstr, parmp->argv[0]) == 0)
1485 disallow_gui = TRUE;
1487 /* TODO: On MacOS X default to gui if argv[0] ends in:
1488 * /Vim.app/Contents/MacOS/Vim */
1489 #endif
1491 #ifdef FEAT_EVAL
1492 set_vim_var_string(VV_PROGNAME, initstr, -1);
1493 #endif
1495 if (TOLOWER_ASC(initstr[0]) == 'r')
1497 restricted = TRUE;
1498 ++initstr;
1501 /* Avoid using evim mode for "editor". */
1502 if (TOLOWER_ASC(initstr[0]) == 'e'
1503 && (TOLOWER_ASC(initstr[1]) == 'v'
1504 || TOLOWER_ASC(initstr[1]) == 'g'))
1506 #ifdef FEAT_GUI
1507 gui.starting = TRUE;
1508 #endif
1509 parmp->evim_mode = TRUE;
1510 ++initstr;
1513 if (TOLOWER_ASC(initstr[0]) == 'g' || initstr[0] == 'k')
1515 main_start_gui();
1516 #ifdef FEAT_GUI
1517 ++initstr;
1518 #endif
1521 if (STRNICMP(initstr, "view", 4) == 0)
1523 readonlymode = TRUE;
1524 curbuf->b_p_ro = TRUE;
1525 p_uc = 10000; /* don't update very often */
1526 initstr += 4;
1528 else if (STRNICMP(initstr, "vim", 3) == 0)
1529 initstr += 3;
1531 /* Catch "[r][g]vimdiff" and "[r][g]viewdiff". */
1532 if (STRICMP(initstr, "diff") == 0)
1534 #ifdef FEAT_DIFF
1535 parmp->diff_mode = TRUE;
1536 #else
1537 mch_errmsg(_("This Vim was not compiled with the diff feature."));
1538 mch_errmsg("\n");
1539 mch_exit(2);
1540 #endif
1543 if (STRNICMP(initstr, "ex", 2) == 0)
1545 if (STRNICMP(initstr + 2, "im", 2) == 0)
1546 exmode_active = EXMODE_VIM;
1547 else
1548 exmode_active = EXMODE_NORMAL;
1549 change_compatible(TRUE); /* set 'compatible' */
1554 * Get the name of the display, before gui_prepare() removes it from
1555 * argv[]. Used for the xterm-clipboard display.
1557 * Also find the --server... arguments and --socketid and --windowid
1559 /*ARGSUSED*/
1560 static void
1561 early_arg_scan(parmp)
1562 mparm_T *parmp;
1564 #if defined(FEAT_XCLIPBOARD) || defined(FEAT_CLIENTSERVER)
1565 int argc = parmp->argc;
1566 char **argv = parmp->argv;
1567 int i;
1569 for (i = 1; i < argc; i++)
1571 if (STRCMP(argv[i], "--") == 0)
1572 break;
1573 # ifdef FEAT_XCLIPBOARD
1574 else if (STRICMP(argv[i], "-display") == 0
1575 # if defined(FEAT_GUI_GTK)
1576 || STRICMP(argv[i], "--display") == 0
1577 # endif
1580 if (i == argc - 1)
1581 mainerr_arg_missing((char_u *)argv[i]);
1582 xterm_display = argv[++i];
1584 # endif
1585 # ifdef FEAT_CLIENTSERVER
1586 else if (STRICMP(argv[i], "--servername") == 0)
1588 if (i == argc - 1)
1589 mainerr_arg_missing((char_u *)argv[i]);
1590 parmp->serverName_arg = (char_u *)argv[++i];
1592 else if (STRICMP(argv[i], "--serverlist") == 0)
1593 parmp->serverArg = TRUE;
1594 else if (STRNICMP(argv[i], "--remote", 8) == 0)
1596 parmp->serverArg = TRUE;
1597 # ifdef FEAT_GUI
1598 if (strstr(argv[i], "-wait") != 0)
1599 /* don't fork() when starting the GUI to edit files ourself */
1600 gui.dofork = FALSE;
1601 # endif
1603 # endif
1605 # if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1606 # ifdef FEAT_GUI_W32
1607 else if (STRICMP(argv[i], "--windowid") == 0)
1608 # else
1609 else if (STRICMP(argv[i], "--socketid") == 0)
1610 # endif
1612 long_u id;
1613 int count;
1615 if (i == argc - 1)
1616 mainerr_arg_missing((char_u *)argv[i]);
1617 if (STRNICMP(argv[i+1], "0x", 2) == 0)
1618 count = sscanf(&(argv[i + 1][2]), SCANF_HEX_LONG_U, &id);
1619 else
1620 count = sscanf(argv[i + 1], SCANF_DECIMAL_LONG_U, &id);
1621 if (count != 1)
1622 mainerr(ME_INVALID_ARG, (char_u *)argv[i]);
1623 else
1624 # ifdef FEAT_GUI_W32
1625 win_socket_id = id;
1626 # else
1627 gtk_socket_id = id;
1628 # endif
1629 i++;
1631 # endif
1632 # ifdef FEAT_GUI_GTK
1633 else if (STRICMP(argv[i], "--echo-wid") == 0)
1634 echo_wid_arg = TRUE;
1635 # endif
1637 #endif
1641 * Scan the command line arguments.
1643 static void
1644 command_line_scan(parmp)
1645 mparm_T *parmp;
1647 int argc = parmp->argc;
1648 char **argv = parmp->argv;
1649 int argv_idx; /* index in argv[n][] */
1650 int had_minmin = FALSE; /* found "--" argument */
1651 int want_argument; /* option argument with argument */
1652 int c;
1653 char_u *p = NULL;
1654 long n;
1656 --argc;
1657 ++argv;
1658 argv_idx = 1; /* active option letter is argv[0][argv_idx] */
1659 while (argc > 0)
1662 * "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1664 if (argv[0][0] == '+' && !had_minmin)
1666 if (parmp->n_commands >= MAX_ARG_CMDS)
1667 mainerr(ME_EXTRA_CMD, NULL);
1668 argv_idx = -1; /* skip to next argument */
1669 if (argv[0][1] == NUL)
1670 parmp->commands[parmp->n_commands++] = (char_u *)"$";
1671 else
1672 parmp->commands[parmp->n_commands++] = (char_u *)&(argv[0][1]);
1676 * Optional argument.
1678 else if (argv[0][0] == '-' && !had_minmin)
1680 want_argument = FALSE;
1681 c = argv[0][argv_idx++];
1682 #ifdef VMS
1684 * VMS only uses upper case command lines. Interpret "-X" as "-x"
1685 * and "-/X" as "-X".
1687 if (c == '/')
1689 c = argv[0][argv_idx++];
1690 c = TOUPPER_ASC(c);
1692 else
1693 c = TOLOWER_ASC(c);
1694 #endif
1695 switch (c)
1697 case NUL: /* "vim -" read from stdin */
1698 /* "ex -" silent mode */
1699 if (exmode_active)
1700 silent_mode = TRUE;
1701 else
1703 if (parmp->edit_type != EDIT_NONE)
1704 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1705 parmp->edit_type = EDIT_STDIN;
1706 read_cmd_fd = 2; /* read from stderr instead of stdin */
1708 argv_idx = -1; /* skip to next argument */
1709 break;
1711 case '-': /* "--" don't take any more option arguments */
1712 /* "--help" give help message */
1713 /* "--version" give version message */
1714 /* "--literal" take files literally */
1715 /* "--nofork" don't fork */
1716 /* "--noplugin[s]" skip plugins */
1717 /* "--cmd <cmd>" execute cmd before vimrc */
1718 if (STRICMP(argv[0] + argv_idx, "help") == 0)
1719 usage();
1720 else if (STRICMP(argv[0] + argv_idx, "version") == 0)
1722 Columns = 80; /* need to init Columns */
1723 info_message = TRUE; /* use mch_msg(), not mch_errmsg() */
1724 list_version();
1725 msg_putchar('\n');
1726 msg_didout = FALSE;
1727 mch_exit(0);
1729 else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0)
1731 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
1732 parmp->literal = TRUE;
1733 #endif
1735 else if (STRNICMP(argv[0] + argv_idx, "nofork", 6) == 0)
1737 #ifdef FEAT_GUI
1738 gui.dofork = FALSE; /* don't fork() when starting GUI */
1739 #endif
1741 else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
1742 p_lpl = FALSE;
1743 else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0)
1745 want_argument = TRUE;
1746 argv_idx += 3;
1748 #ifdef FEAT_CLIENTSERVER
1749 else if (STRNICMP(argv[0] + argv_idx, "serverlist", 10) == 0)
1750 ; /* already processed -- no arg */
1751 else if (STRNICMP(argv[0] + argv_idx, "servername", 10) == 0
1752 || STRNICMP(argv[0] + argv_idx, "serversend", 10) == 0)
1754 /* already processed -- snatch the following arg */
1755 if (argc > 1)
1757 --argc;
1758 ++argv;
1761 #endif
1762 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32)
1763 # ifdef FEAT_GUI_GTK
1764 else if (STRNICMP(argv[0] + argv_idx, "socketid", 8) == 0)
1765 # else
1766 else if (STRNICMP(argv[0] + argv_idx, "windowid", 8) == 0)
1767 # endif
1769 /* already processed -- snatch the following arg */
1770 if (argc > 1)
1772 --argc;
1773 ++argv;
1776 #endif
1777 #ifdef FEAT_GUI_GTK
1778 else if (STRNICMP(argv[0] + argv_idx, "echo-wid", 8) == 0)
1780 /* already processed, skip */
1782 #endif
1783 else
1785 if (argv[0][argv_idx])
1786 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
1787 had_minmin = TRUE;
1789 if (!want_argument)
1790 argv_idx = -1; /* skip to next argument */
1791 break;
1793 case 'A': /* "-A" start in Arabic mode */
1794 #ifdef FEAT_ARABIC
1795 set_option_value((char_u *)"arabic", 1L, NULL, 0);
1796 #else
1797 mch_errmsg(_(e_noarabic));
1798 mch_exit(2);
1799 #endif
1800 break;
1802 case 'b': /* "-b" binary mode */
1803 /* Needs to be effective before expanding file names, because
1804 * for Win32 this makes us edit a shortcut file itself,
1805 * instead of the file it links to. */
1806 set_options_bin(curbuf->b_p_bin, 1, 0);
1807 curbuf->b_p_bin = 1; /* binary file I/O */
1808 break;
1810 case 'C': /* "-C" Compatible */
1811 change_compatible(TRUE);
1812 break;
1814 case 'e': /* "-e" Ex mode */
1815 exmode_active = EXMODE_NORMAL;
1816 break;
1818 case 'E': /* "-E" Improved Ex mode */
1819 exmode_active = EXMODE_VIM;
1820 break;
1822 case 'f': /* "-f" GUI: run in foreground. Amiga: open
1823 window directly, not with newcli */
1824 #ifdef FEAT_GUI
1825 gui.dofork = FALSE; /* don't fork() when starting GUI */
1826 #endif
1827 break;
1829 case 'g': /* "-g" start GUI */
1830 main_start_gui();
1831 break;
1833 case 'F': /* "-F" start in Farsi mode: rl + fkmap set */
1834 #ifdef FEAT_FKMAP
1835 p_fkmap = TRUE;
1836 set_option_value((char_u *)"rl", 1L, NULL, 0);
1837 #else
1838 mch_errmsg(_(e_nofarsi));
1839 mch_exit(2);
1840 #endif
1841 break;
1843 case 'h': /* "-h" give help message */
1844 #ifdef FEAT_GUI_GNOME
1845 /* Tell usage() to exit for "gvim". */
1846 gui.starting = FALSE;
1847 #endif
1848 usage();
1849 break;
1851 case 'H': /* "-H" start in Hebrew mode: rl + hkmap set */
1852 #ifdef FEAT_RIGHTLEFT
1853 p_hkmap = TRUE;
1854 set_option_value((char_u *)"rl", 1L, NULL, 0);
1855 #else
1856 mch_errmsg(_(e_nohebrew));
1857 mch_exit(2);
1858 #endif
1859 break;
1861 case 'l': /* "-l" lisp mode, 'lisp' and 'showmatch' on */
1862 #ifdef FEAT_LISP
1863 set_option_value((char_u *)"lisp", 1L, NULL, 0);
1864 p_sm = TRUE;
1865 #endif
1866 break;
1868 case 'M': /* "-M" no changes or writing of files */
1869 reset_modifiable();
1870 /* FALLTHROUGH */
1872 case 'm': /* "-m" no writing of files */
1873 p_write = FALSE;
1874 break;
1876 case 'y': /* "-y" easy mode */
1877 #ifdef FEAT_GUI
1878 gui.starting = TRUE; /* start GUI a bit later */
1879 #endif
1880 parmp->evim_mode = TRUE;
1881 break;
1883 case 'N': /* "-N" Nocompatible */
1884 change_compatible(FALSE);
1885 break;
1887 case 'n': /* "-n" no swap file */
1888 parmp->no_swap_file = TRUE;
1889 break;
1891 case 'p': /* "-p[N]" open N tab pages */
1892 #ifdef TARGET_API_MAC_OSX
1893 /* For some reason on MacOS X, an argument like:
1894 -psn_0_10223617 is passed in when invoke from Finder
1895 or with the 'open' command */
1896 if (argv[0][argv_idx] == 's')
1898 argv_idx = -1; /* bypass full -psn */
1899 main_start_gui();
1900 break;
1902 #endif
1903 #ifdef FEAT_WINDOWS
1904 /* default is 0: open window for each file */
1905 parmp->window_count = get_number_arg((char_u *)argv[0],
1906 &argv_idx, 0);
1907 parmp->window_layout = WIN_TABS;
1908 #endif
1909 break;
1911 case 'o': /* "-o[N]" open N horizontal split windows */
1912 #ifdef FEAT_WINDOWS
1913 /* default is 0: open window for each file */
1914 parmp->window_count = get_number_arg((char_u *)argv[0],
1915 &argv_idx, 0);
1916 parmp->window_layout = WIN_HOR;
1917 #endif
1918 break;
1920 case 'O': /* "-O[N]" open N vertical split windows */
1921 #if defined(FEAT_VERTSPLIT) && defined(FEAT_WINDOWS)
1922 /* default is 0: open window for each file */
1923 parmp->window_count = get_number_arg((char_u *)argv[0],
1924 &argv_idx, 0);
1925 parmp->window_layout = WIN_VER;
1926 #endif
1927 break;
1929 #ifdef FEAT_QUICKFIX
1930 case 'q': /* "-q" QuickFix mode */
1931 if (parmp->edit_type != EDIT_NONE)
1932 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1933 parmp->edit_type = EDIT_QF;
1934 if (argv[0][argv_idx]) /* "-q{errorfile}" */
1936 parmp->use_ef = (char_u *)argv[0] + argv_idx;
1937 argv_idx = -1;
1939 else if (argc > 1) /* "-q {errorfile}" */
1940 want_argument = TRUE;
1941 break;
1942 #endif
1944 case 'R': /* "-R" readonly mode */
1945 readonlymode = TRUE;
1946 curbuf->b_p_ro = TRUE;
1947 p_uc = 10000; /* don't update very often */
1948 break;
1950 case 'r': /* "-r" recovery mode */
1951 case 'L': /* "-L" recovery mode */
1952 recoverymode = 1;
1953 break;
1955 case 's':
1956 if (exmode_active) /* "-s" silent (batch) mode */
1957 silent_mode = TRUE;
1958 else /* "-s {scriptin}" read from script file */
1959 want_argument = TRUE;
1960 break;
1962 case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
1963 if (parmp->edit_type != EDIT_NONE)
1964 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
1965 parmp->edit_type = EDIT_TAG;
1966 if (argv[0][argv_idx]) /* "-t{tag}" */
1968 parmp->tagname = (char_u *)argv[0] + argv_idx;
1969 argv_idx = -1;
1971 else /* "-t {tag}" */
1972 want_argument = TRUE;
1973 break;
1975 #ifdef FEAT_EVAL
1976 case 'D': /* "-D" Debugging */
1977 parmp->use_debug_break_level = 9999;
1978 break;
1979 #endif
1980 #ifdef FEAT_DIFF
1981 case 'd': /* "-d" 'diff' */
1982 # ifdef AMIGA
1983 /* check for "-dev {device}" */
1984 if (argv[0][argv_idx] == 'e' && argv[0][argv_idx + 1] == 'v')
1985 want_argument = TRUE;
1986 else
1987 # endif
1988 parmp->diff_mode = TRUE;
1989 break;
1990 #endif
1991 case 'V': /* "-V{N}" Verbose level */
1992 /* default is 10: a little bit verbose */
1993 p_verbose = get_number_arg((char_u *)argv[0], &argv_idx, 10);
1994 if (argv[0][argv_idx] != NUL)
1996 set_option_value((char_u *)"verbosefile", 0L,
1997 (char_u *)argv[0] + argv_idx, 0);
1998 argv_idx = (int)STRLEN(argv[0]);
2000 break;
2002 case 'v': /* "-v" Vi-mode (as if called "vi") */
2003 exmode_active = 0;
2004 #ifdef FEAT_GUI
2005 gui.starting = FALSE; /* don't start GUI */
2006 #endif
2007 break;
2009 case 'w': /* "-w{number}" set window height */
2010 /* "-w {scriptout}" write to script */
2011 if (vim_isdigit(((char_u *)argv[0])[argv_idx]))
2013 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
2014 set_option_value((char_u *)"window", n, NULL, 0);
2015 break;
2017 want_argument = TRUE;
2018 break;
2020 #ifdef FEAT_CRYPT
2021 case 'x': /* "-x" encrypted reading/writing of files */
2022 parmp->ask_for_key = TRUE;
2023 break;
2024 #endif
2026 case 'X': /* "-X" don't connect to X server */
2027 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
2028 x_no_connect = TRUE;
2029 #endif
2030 break;
2032 case 'Z': /* "-Z" restricted mode */
2033 restricted = TRUE;
2034 break;
2036 case 'c': /* "-c{command}" or "-c {command}" execute
2037 command */
2038 if (argv[0][argv_idx] != NUL)
2040 if (parmp->n_commands >= MAX_ARG_CMDS)
2041 mainerr(ME_EXTRA_CMD, NULL);
2042 parmp->commands[parmp->n_commands++] = (char_u *)argv[0]
2043 + argv_idx;
2044 argv_idx = -1;
2045 break;
2047 /*FALLTHROUGH*/
2048 case 'S': /* "-S {file}" execute Vim script */
2049 case 'i': /* "-i {viminfo}" use for viminfo */
2050 #ifndef FEAT_DIFF
2051 case 'd': /* "-d {device}" device (for Amiga) */
2052 #endif
2053 case 'T': /* "-T {terminal}" terminal name */
2054 case 'u': /* "-u {vimrc}" vim inits file */
2055 case 'U': /* "-U {gvimrc}" gvim inits file */
2056 case 'W': /* "-W {scriptout}" overwrite */
2057 #ifdef FEAT_GUI_W32
2058 case 'P': /* "-P {parent title}" MDI parent */
2059 #endif
2060 want_argument = TRUE;
2061 break;
2063 default:
2064 mainerr(ME_UNKNOWN_OPTION, (char_u *)argv[0]);
2068 * Handle option arguments with argument.
2070 if (want_argument)
2073 * Check for garbage immediately after the option letter.
2075 if (argv[0][argv_idx] != NUL)
2076 mainerr(ME_GARBAGE, (char_u *)argv[0]);
2078 --argc;
2079 if (argc < 1 && c != 'S')
2080 mainerr_arg_missing((char_u *)argv[0]);
2081 ++argv;
2082 argv_idx = -1;
2084 switch (c)
2086 case 'c': /* "-c {command}" execute command */
2087 case 'S': /* "-S {file}" execute Vim script */
2088 if (parmp->n_commands >= MAX_ARG_CMDS)
2089 mainerr(ME_EXTRA_CMD, NULL);
2090 if (c == 'S')
2092 char *a;
2094 if (argc < 1)
2095 /* "-S" without argument: use default session file
2096 * name. */
2097 a = SESSION_FILE;
2098 else if (argv[0][0] == '-')
2100 /* "-S" followed by another option: use default
2101 * session file name. */
2102 a = SESSION_FILE;
2103 ++argc;
2104 --argv;
2106 else
2107 a = argv[0];
2108 p = alloc((unsigned)(STRLEN(a) + 4));
2109 if (p == NULL)
2110 mch_exit(2);
2111 sprintf((char *)p, "so %s", a);
2112 parmp->cmds_tofree[parmp->n_commands] = TRUE;
2113 parmp->commands[parmp->n_commands++] = p;
2115 else
2116 parmp->commands[parmp->n_commands++] =
2117 (char_u *)argv[0];
2118 break;
2120 case '-': /* "--cmd {command}" execute command */
2121 if (parmp->n_pre_commands >= MAX_ARG_CMDS)
2122 mainerr(ME_EXTRA_CMD, NULL);
2123 parmp->pre_commands[parmp->n_pre_commands++] =
2124 (char_u *)argv[0];
2125 break;
2127 /* case 'd': -d {device} is handled in mch_check_win() for the
2128 * Amiga */
2130 #ifdef FEAT_QUICKFIX
2131 case 'q': /* "-q {errorfile}" QuickFix mode */
2132 parmp->use_ef = (char_u *)argv[0];
2133 break;
2134 #endif
2136 case 'i': /* "-i {viminfo}" use for viminfo */
2137 use_viminfo = (char_u *)argv[0];
2138 break;
2140 case 's': /* "-s {scriptin}" read from script file */
2141 if (scriptin[0] != NULL)
2143 scripterror:
2144 mch_errmsg(_("Attempt to open script file again: \""));
2145 mch_errmsg(argv[-1]);
2146 mch_errmsg(" ");
2147 mch_errmsg(argv[0]);
2148 mch_errmsg("\"\n");
2149 mch_exit(2);
2151 if ((scriptin[0] = mch_fopen(argv[0], READBIN)) == NULL)
2153 mch_errmsg(_("Cannot open for reading: \""));
2154 mch_errmsg(argv[0]);
2155 mch_errmsg("\"\n");
2156 mch_exit(2);
2158 if (save_typebuf() == FAIL)
2159 mch_exit(2); /* out of memory */
2160 break;
2162 case 't': /* "-t {tag}" */
2163 parmp->tagname = (char_u *)argv[0];
2164 break;
2166 case 'T': /* "-T {terminal}" terminal name */
2168 * The -T term argument is always available and when
2169 * HAVE_TERMLIB is supported it overrides the environment
2170 * variable TERM.
2172 #ifdef FEAT_GUI
2173 if (term_is_gui((char_u *)argv[0]))
2174 gui.starting = TRUE; /* start GUI a bit later */
2175 else
2176 #endif
2177 parmp->term = (char_u *)argv[0];
2178 break;
2180 case 'u': /* "-u {vimrc}" vim inits file */
2181 parmp->use_vimrc = (char_u *)argv[0];
2182 break;
2184 case 'U': /* "-U {gvimrc}" gvim inits file */
2185 #ifdef FEAT_GUI
2186 use_gvimrc = (char_u *)argv[0];
2187 #endif
2188 break;
2190 case 'w': /* "-w {nr}" 'window' value */
2191 /* "-w {scriptout}" append to script file */
2192 if (vim_isdigit(*((char_u *)argv[0])))
2194 argv_idx = 0;
2195 n = get_number_arg((char_u *)argv[0], &argv_idx, 10);
2196 set_option_value((char_u *)"window", n, NULL, 0);
2197 argv_idx = -1;
2198 break;
2200 /*FALLTHROUGH*/
2201 case 'W': /* "-W {scriptout}" overwrite script file */
2202 if (scriptout != NULL)
2203 goto scripterror;
2204 if ((scriptout = mch_fopen(argv[0],
2205 c == 'w' ? APPENDBIN : WRITEBIN)) == NULL)
2207 mch_errmsg(_("Cannot open for script output: \""));
2208 mch_errmsg(argv[0]);
2209 mch_errmsg("\"\n");
2210 mch_exit(2);
2212 break;
2214 #ifdef FEAT_GUI_W32
2215 case 'P': /* "-P {parent title}" MDI parent */
2216 gui_mch_set_parent(argv[0]);
2217 break;
2218 #endif
2224 * File name argument.
2226 else
2228 argv_idx = -1; /* skip to next argument */
2230 /* Check for only one type of editing. */
2231 if (parmp->edit_type != EDIT_NONE && parmp->edit_type != EDIT_FILE)
2232 mainerr(ME_TOO_MANY_ARGS, (char_u *)argv[0]);
2233 parmp->edit_type = EDIT_FILE;
2235 #ifdef MSWIN
2236 /* Remember if the argument was a full path before changing
2237 * slashes to backslashes. */
2238 if (argv[0][0] != NUL && argv[0][1] == ':' && argv[0][2] == '\\')
2239 parmp->full_path = TRUE;
2240 #endif
2242 /* Add the file to the global argument list. */
2243 if (ga_grow(&global_alist.al_ga, 1) == FAIL
2244 || (p = vim_strsave((char_u *)argv[0])) == NULL)
2245 mch_exit(2);
2246 #ifdef FEAT_DIFF
2247 if (parmp->diff_mode && mch_isdir(p) && GARGCOUNT > 0
2248 && !mch_isdir(alist_name(&GARGLIST[0])))
2250 char_u *r;
2252 r = concat_fnames(p, gettail(alist_name(&GARGLIST[0])), TRUE);
2253 if (r != NULL)
2255 vim_free(p);
2256 p = r;
2259 #endif
2260 #if defined(__CYGWIN32__) && !defined(WIN32)
2262 * If vim is invoked by non-Cygwin tools, convert away any
2263 * DOS paths, so things like .swp files are created correctly.
2264 * Look for evidence of non-Cygwin paths before we bother.
2265 * This is only for when using the Unix files.
2267 if (strpbrk(p, "\\:") != NULL)
2269 char posix_path[PATH_MAX];
2271 # if CYGWIN_VERSION_DLL_MAJOR >= 1007
2272 cygwin_conv_path(CCP_WIN_A_TO_POSIX, p, posix_path, PATH_MAX);
2273 # else
2274 cygwin_conv_to_posix_path(p, posix_path);
2275 # endif
2276 vim_free(p);
2277 p = vim_strsave(posix_path);
2278 if (p == NULL)
2279 mch_exit(2);
2281 #endif
2283 #ifdef USE_FNAME_CASE
2284 /* Make the case of the file name match the actual file. */
2285 fname_case(p, 0);
2286 #endif
2288 alist_add(&global_alist, p,
2289 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
2290 parmp->literal ? 2 : 0 /* add buffer nr after exp. */
2291 #else
2292 2 /* add buffer number now and use curbuf */
2293 #endif
2296 #if defined(FEAT_MBYTE) && defined(WIN32)
2298 /* Remember this argument has been added to the argument list.
2299 * Needed when 'encoding' is changed. */
2300 used_file_arg(argv[0], parmp->literal, parmp->full_path,
2301 parmp->diff_mode);
2303 #endif
2307 * If there are no more letters after the current "-", go to next
2308 * argument. argv_idx is set to -1 when the current argument is to be
2309 * skipped.
2311 if (argv_idx <= 0 || argv[0][argv_idx] == NUL)
2313 --argc;
2314 ++argv;
2315 argv_idx = 1;
2319 #ifdef FEAT_EVAL
2320 /* If there is a "+123" or "-c" command, set v:swapcommand to the first
2321 * one. */
2322 if (parmp->n_commands > 0)
2324 p = alloc((unsigned)STRLEN(parmp->commands[0]) + 3);
2325 if (p != NULL)
2327 sprintf((char *)p, ":%s\r", parmp->commands[0]);
2328 set_vim_var_string(VV_SWAPCOMMAND, p, -1);
2329 vim_free(p);
2332 #endif
2336 * Print a warning if stdout is not a terminal.
2337 * When starting in Ex mode and commands come from a file, set Silent mode.
2339 static void
2340 check_tty(parmp)
2341 mparm_T *parmp;
2343 int input_isatty; /* is active input a terminal? */
2345 input_isatty = mch_input_isatty();
2346 if (exmode_active)
2348 if (!input_isatty)
2349 silent_mode = TRUE;
2351 else if (parmp->want_full_screen && (!parmp->stdout_isatty || !input_isatty)
2352 #ifdef FEAT_GUI
2353 /* don't want the delay when started from the desktop */
2354 && !gui.starting
2355 #endif
2358 #ifdef NBDEBUG
2360 * This shouldn't be necessary. But if I run netbeans with the log
2361 * output coming to the console and XOpenDisplay fails, I get vim
2362 * trying to start with input/output to my console tty. This fills my
2363 * input buffer so fast I can't even kill the process in under 2
2364 * minutes (and it beeps continuously the whole time :-)
2366 if (usingNetbeans && (!parmp->stdout_isatty || !input_isatty))
2368 mch_errmsg(_("Vim: Error: Failure to start gvim from NetBeans\n"));
2369 exit(1);
2371 #endif
2372 if (!parmp->stdout_isatty)
2373 mch_errmsg(_("Vim: Warning: Output is not to a terminal\n"));
2374 if (!input_isatty)
2375 mch_errmsg(_("Vim: Warning: Input is not from a terminal\n"));
2376 out_flush();
2377 if (scriptin[0] == NULL)
2378 ui_delay(2000L, TRUE);
2379 TIME_MSG("Warning delay");
2384 * Read text from stdin.
2386 static void
2387 read_stdin()
2389 int i;
2391 #if defined(HAS_SWAP_EXISTS_ACTION)
2392 /* When getting the ATTENTION prompt here, use a dialog */
2393 swap_exists_action = SEA_DIALOG;
2394 #endif
2395 no_wait_return = TRUE;
2396 i = msg_didany;
2397 set_buflisted(TRUE);
2398 (void)open_buffer(TRUE, NULL); /* create memfile and read file */
2399 no_wait_return = FALSE;
2400 msg_didany = i;
2401 TIME_MSG("reading stdin");
2402 #if defined(HAS_SWAP_EXISTS_ACTION)
2403 check_swap_exists_action();
2404 #endif
2405 #if !(defined(AMIGA) || defined(MACOS))
2407 * Close stdin and dup it from stderr. Required for GPM to work
2408 * properly, and for running external commands.
2409 * Is there any other system that cannot do this?
2411 close(0);
2412 dup(2);
2413 #endif
2417 * Create the requested number of windows and edit buffers in them.
2418 * Also does recovery if "recoverymode" set.
2420 /*ARGSUSED*/
2421 static void
2422 create_windows(parmp)
2423 mparm_T *parmp;
2425 #ifdef FEAT_WINDOWS
2426 int dorewind;
2427 int done = 0;
2430 * Create the number of windows that was requested.
2432 if (parmp->window_count == -1) /* was not set */
2433 parmp->window_count = 1;
2434 if (parmp->window_count == 0)
2435 parmp->window_count = GARGCOUNT;
2436 if (parmp->window_count > 1)
2438 /* Don't change the windows if there was a command in .vimrc that
2439 * already split some windows */
2440 if (parmp->window_layout == 0)
2441 parmp->window_layout = WIN_HOR;
2442 if (parmp->window_layout == WIN_TABS)
2444 parmp->window_count = make_tabpages(parmp->window_count);
2445 TIME_MSG("making tab pages");
2447 else if (firstwin->w_next == NULL)
2449 parmp->window_count = make_windows(parmp->window_count,
2450 parmp->window_layout == WIN_VER);
2451 TIME_MSG("making windows");
2453 else
2454 parmp->window_count = win_count();
2456 else
2457 parmp->window_count = 1;
2458 #endif
2460 if (recoverymode) /* do recover */
2462 msg_scroll = TRUE; /* scroll message up */
2463 ml_recover();
2464 if (curbuf->b_ml.ml_mfp == NULL) /* failed */
2465 getout(1);
2466 do_modelines(0); /* do modelines */
2468 else
2471 * Open a buffer for windows that don't have one yet.
2472 * Commands in the .vimrc might have loaded a file or split the window.
2473 * Watch out for autocommands that delete a window.
2475 #ifdef FEAT_AUTOCMD
2477 * Don't execute Win/Buf Enter/Leave autocommands here
2479 ++autocmd_no_enter;
2480 ++autocmd_no_leave;
2481 #endif
2482 #ifdef FEAT_WINDOWS
2483 dorewind = TRUE;
2484 while (done++ < 1000)
2486 if (dorewind)
2488 if (parmp->window_layout == WIN_TABS)
2489 goto_tabpage(1);
2490 else
2491 curwin = firstwin;
2493 else if (parmp->window_layout == WIN_TABS)
2495 if (curtab->tp_next == NULL)
2496 break;
2497 goto_tabpage(0);
2499 else
2501 if (curwin->w_next == NULL)
2502 break;
2503 curwin = curwin->w_next;
2505 dorewind = FALSE;
2506 #endif
2507 curbuf = curwin->w_buffer;
2508 if (curbuf->b_ml.ml_mfp == NULL)
2510 #ifdef FEAT_FOLDING
2511 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2512 if (p_fdls >= 0)
2513 curwin->w_p_fdl = p_fdls;
2514 #endif
2515 #if defined(HAS_SWAP_EXISTS_ACTION)
2516 /* When getting the ATTENTION prompt here, use a dialog */
2517 swap_exists_action = SEA_DIALOG;
2518 #endif
2519 set_buflisted(TRUE);
2520 (void)open_buffer(FALSE, NULL); /* create memfile, read file */
2522 #if defined(HAS_SWAP_EXISTS_ACTION)
2523 if (swap_exists_action == SEA_QUIT)
2525 if (got_int || only_one_window())
2527 /* abort selected or quit and only one window */
2528 did_emsg = FALSE; /* avoid hit-enter prompt */
2529 getout(1);
2531 /* We can't close the window, it would disturb what
2532 * happens next. Clear the file name and set the arg
2533 * index to -1 to delete it later. */
2534 setfname(curbuf, NULL, NULL, FALSE);
2535 curwin->w_arg_idx = -1;
2536 swap_exists_action = SEA_NONE;
2538 else
2539 handle_swap_exists(NULL);
2540 #endif
2541 #ifdef FEAT_AUTOCMD
2542 dorewind = TRUE; /* start again */
2543 #endif
2545 #ifdef FEAT_WINDOWS
2546 ui_breakcheck();
2547 if (got_int)
2549 (void)vgetc(); /* only break the file loading, not the rest */
2550 break;
2553 #endif
2554 #ifdef FEAT_WINDOWS
2555 if (parmp->window_layout == WIN_TABS)
2556 goto_tabpage(1);
2557 else
2558 curwin = firstwin;
2559 curbuf = curwin->w_buffer;
2560 #endif
2561 #ifdef FEAT_AUTOCMD
2562 --autocmd_no_enter;
2563 --autocmd_no_leave;
2564 #endif
2568 #ifdef FEAT_WINDOWS
2570 * If opened more than one window, start editing files in the other
2571 * windows. make_windows() has already opened the windows.
2573 static void
2574 edit_buffers(parmp)
2575 mparm_T *parmp;
2577 int arg_idx; /* index in argument list */
2578 int i;
2579 int advance = TRUE;
2580 buf_T *old_curbuf;
2582 # ifdef FEAT_AUTOCMD
2584 * Don't execute Win/Buf Enter/Leave autocommands here
2586 ++autocmd_no_enter;
2587 ++autocmd_no_leave;
2588 # endif
2590 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2591 if (curwin->w_arg_idx == -1)
2593 win_close(curwin, TRUE);
2594 advance = FALSE;
2597 arg_idx = 1;
2598 for (i = 1; i < parmp->window_count; ++i)
2600 /* When w_arg_idx is -1 remove the window (see create_windows()). */
2601 if (curwin->w_arg_idx == -1)
2603 ++arg_idx;
2604 win_close(curwin, TRUE);
2605 advance = FALSE;
2606 continue;
2609 if (advance)
2611 if (parmp->window_layout == WIN_TABS)
2613 if (curtab->tp_next == NULL) /* just checking */
2614 break;
2615 goto_tabpage(0);
2617 else
2619 if (curwin->w_next == NULL) /* just checking */
2620 break;
2621 win_enter(curwin->w_next, FALSE);
2624 advance = TRUE;
2626 /* Only open the file if there is no file in this window yet (that can
2627 * happen when .vimrc contains ":sall"). */
2628 if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL)
2630 curwin->w_arg_idx = arg_idx;
2631 /* Edit file from arg list, if there is one. When "Quit" selected
2632 * at the ATTENTION prompt close the window. */
2633 old_curbuf = curbuf;
2634 (void)do_ecmd(0, arg_idx < GARGCOUNT
2635 ? alist_name(&GARGLIST[arg_idx]) : NULL,
2636 NULL, NULL, ECMD_LASTL, ECMD_HIDE);
2637 if (curbuf == old_curbuf)
2639 if (got_int || only_one_window())
2641 /* abort selected or quit and only one window */
2642 did_emsg = FALSE; /* avoid hit-enter prompt */
2643 getout(1);
2645 win_close(curwin, TRUE);
2646 advance = FALSE;
2648 if (arg_idx == GARGCOUNT - 1)
2649 arg_had_last = TRUE;
2650 ++arg_idx;
2652 ui_breakcheck();
2653 if (got_int)
2655 (void)vgetc(); /* only break the file loading, not the rest */
2656 break;
2660 if (parmp->window_layout == WIN_TABS)
2661 goto_tabpage(1);
2662 # ifdef FEAT_AUTOCMD
2663 --autocmd_no_enter;
2664 # endif
2665 win_enter(firstwin, FALSE); /* back to first window */
2666 # ifdef FEAT_AUTOCMD
2667 --autocmd_no_leave;
2668 # endif
2669 TIME_MSG("editing files in windows");
2670 if (parmp->window_count > 1 && parmp->window_layout != WIN_TABS)
2671 win_equal(curwin, FALSE, 'b'); /* adjust heights */
2673 #endif /* FEAT_WINDOWS */
2676 * Execute the commands from --cmd arguments "cmds[cnt]".
2678 static void
2679 exe_pre_commands(parmp)
2680 mparm_T *parmp;
2682 char_u **cmds = parmp->pre_commands;
2683 int cnt = parmp->n_pre_commands;
2684 int i;
2686 if (cnt > 0)
2688 curwin->w_cursor.lnum = 0; /* just in case.. */
2689 sourcing_name = (char_u *)_("pre-vimrc command line");
2690 # ifdef FEAT_EVAL
2691 current_SID = SID_CMDARG;
2692 # endif
2693 for (i = 0; i < cnt; ++i)
2694 do_cmdline_cmd(cmds[i]);
2695 sourcing_name = NULL;
2696 # ifdef FEAT_EVAL
2697 current_SID = 0;
2698 # endif
2699 TIME_MSG("--cmd commands");
2704 * Execute "+", "-c" and "-S" arguments.
2706 static void
2707 exe_commands(parmp)
2708 mparm_T *parmp;
2710 int i;
2713 * We start commands on line 0, make "vim +/pat file" match a
2714 * pattern on line 1. But don't move the cursor when an autocommand
2715 * with g`" was used.
2717 msg_scroll = TRUE;
2718 if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1)
2719 curwin->w_cursor.lnum = 0;
2720 sourcing_name = (char_u *)"command line";
2721 #ifdef FEAT_EVAL
2722 current_SID = SID_CARG;
2723 #endif
2724 for (i = 0; i < parmp->n_commands; ++i)
2726 do_cmdline_cmd(parmp->commands[i]);
2727 if (parmp->cmds_tofree[i])
2728 vim_free(parmp->commands[i]);
2730 sourcing_name = NULL;
2731 #ifdef FEAT_EVAL
2732 current_SID = 0;
2733 #endif
2734 if (curwin->w_cursor.lnum == 0)
2735 curwin->w_cursor.lnum = 1;
2737 if (!exmode_active)
2738 msg_scroll = FALSE;
2740 #ifdef FEAT_QUICKFIX
2741 /* When started with "-q errorfile" jump to first error again. */
2742 if (parmp->edit_type == EDIT_QF)
2743 qf_jump(NULL, 0, 0, FALSE);
2744 #endif
2745 TIME_MSG("executing command arguments");
2749 * Source startup scripts.
2751 static void
2752 source_startup_scripts(parmp)
2753 mparm_T *parmp;
2755 int i;
2758 * For "evim" source evim.vim first of all, so that the user can overrule
2759 * any things he doesn't like.
2761 if (parmp->evim_mode)
2763 (void)do_source((char_u *)EVIM_FILE, FALSE, DOSO_NONE);
2764 TIME_MSG("source evim file");
2768 * If -u argument given, use only the initializations from that file and
2769 * nothing else.
2771 if (parmp->use_vimrc != NULL)
2773 if (STRCMP(parmp->use_vimrc, "NONE") == 0
2774 || STRCMP(parmp->use_vimrc, "NORC") == 0)
2776 #ifdef FEAT_GUI
2777 if (use_gvimrc == NULL) /* don't load gvimrc either */
2778 use_gvimrc = parmp->use_vimrc;
2779 #endif
2780 if (parmp->use_vimrc[2] == 'N')
2781 p_lpl = FALSE; /* don't load plugins either */
2783 else
2785 if (do_source(parmp->use_vimrc, FALSE, DOSO_NONE) != OK)
2786 EMSG2(_("E282: Cannot read from \"%s\""), parmp->use_vimrc);
2789 else if (!silent_mode)
2791 #ifdef AMIGA
2792 struct Process *proc = (struct Process *)FindTask(0L);
2793 APTR save_winptr = proc->pr_WindowPtr;
2795 /* Avoid a requester here for a volume that doesn't exist. */
2796 proc->pr_WindowPtr = (APTR)-1L;
2797 #endif
2800 * Get system wide defaults, if the file name is defined.
2802 #ifdef SYS_VIMRC_FILE
2803 (void)do_source((char_u *)SYS_VIMRC_FILE, FALSE, DOSO_NONE);
2804 #endif
2805 #if defined(MACOS_X) && !defined(FEAT_GUI_MACVIM)
2806 (void)do_source((char_u *)"$VIMRUNTIME/macmap.vim", FALSE, DOSO_NONE);
2807 #endif
2810 * Try to read initialization commands from the following places:
2811 * - environment variable VIMINIT
2812 * - user vimrc file (s:.vimrc for Amiga, ~/.vimrc otherwise)
2813 * - second user vimrc file ($VIM/.vimrc for Dos)
2814 * - environment variable EXINIT
2815 * - user exrc file (s:.exrc for Amiga, ~/.exrc otherwise)
2816 * - second user exrc file ($VIM/.exrc for Dos)
2817 * The first that exists is used, the rest is ignored.
2819 if (process_env((char_u *)"VIMINIT", TRUE) != OK)
2821 if (do_source((char_u *)USR_VIMRC_FILE, TRUE, DOSO_VIMRC) == FAIL
2822 #ifdef USR_VIMRC_FILE2
2823 && do_source((char_u *)USR_VIMRC_FILE2, TRUE,
2824 DOSO_VIMRC) == FAIL
2825 #endif
2826 #ifdef USR_VIMRC_FILE3
2827 && do_source((char_u *)USR_VIMRC_FILE3, TRUE,
2828 DOSO_VIMRC) == FAIL
2829 #endif
2830 && process_env((char_u *)"EXINIT", FALSE) == FAIL
2831 && do_source((char_u *)USR_EXRC_FILE, FALSE, DOSO_NONE) == FAIL)
2833 #ifdef USR_EXRC_FILE2
2834 (void)do_source((char_u *)USR_EXRC_FILE2, FALSE, DOSO_NONE);
2835 #endif
2840 * Read initialization commands from ".vimrc" or ".exrc" in current
2841 * directory. This is only done if the 'exrc' option is set.
2842 * Because of security reasons we disallow shell and write commands
2843 * now, except for unix if the file is owned by the user or 'secure'
2844 * option has been reset in environment of global ".exrc" or ".vimrc".
2845 * Only do this if VIMRC_FILE is not the same as USR_VIMRC_FILE or
2846 * SYS_VIMRC_FILE.
2848 if (p_exrc)
2850 #if defined(UNIX) || defined(VMS)
2851 /* If ".vimrc" file is not owned by user, set 'secure' mode. */
2852 if (!file_owned(VIMRC_FILE))
2853 #endif
2854 secure = p_secure;
2856 i = FAIL;
2857 if (fullpathcmp((char_u *)USR_VIMRC_FILE,
2858 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2859 #ifdef USR_VIMRC_FILE2
2860 && fullpathcmp((char_u *)USR_VIMRC_FILE2,
2861 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2862 #endif
2863 #ifdef USR_VIMRC_FILE3
2864 && fullpathcmp((char_u *)USR_VIMRC_FILE3,
2865 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2866 #endif
2867 #ifdef SYS_VIMRC_FILE
2868 && fullpathcmp((char_u *)SYS_VIMRC_FILE,
2869 (char_u *)VIMRC_FILE, FALSE) != FPC_SAME
2870 #endif
2872 i = do_source((char_u *)VIMRC_FILE, TRUE, DOSO_VIMRC);
2874 if (i == FAIL)
2876 #if defined(UNIX) || defined(VMS)
2877 /* if ".exrc" is not owned by user set 'secure' mode */
2878 if (!file_owned(EXRC_FILE))
2879 secure = p_secure;
2880 else
2881 secure = 0;
2882 #endif
2883 if ( fullpathcmp((char_u *)USR_EXRC_FILE,
2884 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2885 #ifdef USR_EXRC_FILE2
2886 && fullpathcmp((char_u *)USR_EXRC_FILE2,
2887 (char_u *)EXRC_FILE, FALSE) != FPC_SAME
2888 #endif
2890 (void)do_source((char_u *)EXRC_FILE, FALSE, DOSO_NONE);
2893 if (secure == 2)
2894 need_wait_return = TRUE;
2895 secure = 0;
2896 #ifdef AMIGA
2897 proc->pr_WindowPtr = save_winptr;
2898 #endif
2900 TIME_MSG("sourcing vimrc file(s)");
2904 * Setup to start using the GUI. Exit with an error when not available.
2906 static void
2907 main_start_gui()
2909 #ifdef FEAT_GUI
2910 gui.starting = TRUE; /* start GUI a bit later */
2911 #else
2912 mch_errmsg(_(e_nogvim));
2913 mch_errmsg("\n");
2914 mch_exit(2);
2915 #endif
2919 * Get an environment variable, and execute it as Ex commands.
2920 * Returns FAIL if the environment variable was not executed, OK otherwise.
2923 process_env(env, is_viminit)
2924 char_u *env;
2925 int is_viminit; /* when TRUE, called for VIMINIT */
2927 char_u *initstr;
2928 char_u *save_sourcing_name;
2929 linenr_T save_sourcing_lnum;
2930 #ifdef FEAT_EVAL
2931 scid_T save_sid;
2932 #endif
2934 if ((initstr = mch_getenv(env)) != NULL && *initstr != NUL)
2936 if (is_viminit)
2937 vimrc_found(NULL, NULL);
2938 save_sourcing_name = sourcing_name;
2939 save_sourcing_lnum = sourcing_lnum;
2940 sourcing_name = env;
2941 sourcing_lnum = 0;
2942 #ifdef FEAT_EVAL
2943 save_sid = current_SID;
2944 current_SID = SID_ENV;
2945 #endif
2946 do_cmdline_cmd(initstr);
2947 sourcing_name = save_sourcing_name;
2948 sourcing_lnum = save_sourcing_lnum;
2949 #ifdef FEAT_EVAL
2950 current_SID = save_sid;;
2951 #endif
2952 return OK;
2954 return FAIL;
2957 #if defined(UNIX) || defined(VMS)
2959 * Return TRUE if we are certain the user owns the file "fname".
2960 * Used for ".vimrc" and ".exrc".
2961 * Use both stat() and lstat() for extra security.
2963 static int
2964 file_owned(fname)
2965 char *fname;
2967 struct stat s;
2968 # ifdef UNIX
2969 uid_t uid = getuid();
2970 # else /* VMS */
2971 uid_t uid = ((getgid() << 16) | getuid());
2972 # endif
2974 return !(mch_stat(fname, &s) != 0 || s.st_uid != uid
2975 # ifdef HAVE_LSTAT
2976 || mch_lstat(fname, &s) != 0 || s.st_uid != uid
2977 # endif
2980 #endif
2983 * Give an error message main_errors["n"] and exit.
2985 static void
2986 mainerr(n, str)
2987 int n; /* one of the ME_ defines */
2988 char_u *str; /* extra argument or NULL */
2990 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
2991 reset_signals(); /* kill us with CTRL-C here, if you like */
2992 #endif
2994 mch_errmsg(longVersion);
2995 mch_errmsg("\n");
2996 mch_errmsg(_(main_errors[n]));
2997 if (str != NULL)
2999 mch_errmsg(": \"");
3000 mch_errmsg((char *)str);
3001 mch_errmsg("\"");
3003 mch_errmsg(_("\nMore info with: \"vim -h\"\n"));
3005 mch_exit(1);
3008 void
3009 mainerr_arg_missing(str)
3010 char_u *str;
3012 mainerr(ME_ARG_MISSING, str);
3016 * print a message with three spaces prepended and '\n' appended.
3018 static void
3019 main_msg(s)
3020 char *s;
3022 mch_msg(" ");
3023 mch_msg(s);
3024 mch_msg("\n");
3028 * Print messages for "vim -h" or "vim --help" and exit.
3030 static void
3031 usage()
3033 int i;
3034 static char *(use[]) =
3036 N_("[file ..] edit specified file(s)"),
3037 N_("- read text from stdin"),
3038 N_("-t tag edit file where tag is defined"),
3039 #ifdef FEAT_QUICKFIX
3040 N_("-q [errorfile] edit file with first error")
3041 #endif
3044 #if defined(UNIX) || defined(__EMX__) || defined(VMS)
3045 reset_signals(); /* kill us with CTRL-C here, if you like */
3046 #endif
3048 mch_msg(longVersion);
3049 mch_msg(_("\n\nusage:"));
3050 for (i = 0; ; ++i)
3052 mch_msg(_(" vim [arguments] "));
3053 mch_msg(_(use[i]));
3054 if (i == (sizeof(use) / sizeof(char_u *)) - 1)
3055 break;
3056 mch_msg(_("\n or:"));
3058 #ifdef VMS
3059 mch_msg(_("\nWhere case is ignored prepend / to make flag upper case"));
3060 #endif
3062 mch_msg(_("\n\nArguments:\n"));
3063 main_msg(_("--\t\t\tOnly file names after this"));
3064 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE)
3065 main_msg(_("--literal\t\tDon't expand wildcards"));
3066 #endif
3067 #ifdef FEAT_OLE
3068 main_msg(_("-register\t\tRegister this gvim for OLE"));
3069 main_msg(_("-unregister\t\tUnregister gvim for OLE"));
3070 #endif
3071 #ifdef FEAT_GUI
3072 main_msg(_("-g\t\t\tRun using GUI (like \"gvim\")"));
3073 main_msg(_("-f or --nofork\tForeground: Don't fork when starting GUI"));
3074 #endif
3075 main_msg(_("-v\t\t\tVi mode (like \"vi\")"));
3076 main_msg(_("-e\t\t\tEx mode (like \"ex\")"));
3077 main_msg(_("-s\t\t\tSilent (batch) mode (only for \"ex\")"));
3078 #ifdef FEAT_DIFF
3079 main_msg(_("-d\t\t\tDiff mode (like \"vimdiff\")"));
3080 #endif
3081 main_msg(_("-y\t\t\tEasy mode (like \"evim\", modeless)"));
3082 main_msg(_("-R\t\t\tReadonly mode (like \"view\")"));
3083 main_msg(_("-Z\t\t\tRestricted mode (like \"rvim\")"));
3084 main_msg(_("-m\t\t\tModifications (writing files) not allowed"));
3085 main_msg(_("-M\t\t\tModifications in text not allowed"));
3086 main_msg(_("-b\t\t\tBinary mode"));
3087 #ifdef FEAT_LISP
3088 main_msg(_("-l\t\t\tLisp mode"));
3089 #endif
3090 main_msg(_("-C\t\t\tCompatible with Vi: 'compatible'"));
3091 main_msg(_("-N\t\t\tNot fully Vi compatible: 'nocompatible'"));
3092 main_msg(_("-V[N][fname]\t\tBe verbose [level N] [log messages to fname]"));
3093 #ifdef FEAT_EVAL
3094 main_msg(_("-D\t\t\tDebugging mode"));
3095 #endif
3096 main_msg(_("-n\t\t\tNo swap file, use memory only"));
3097 main_msg(_("-r\t\t\tList swap files and exit"));
3098 main_msg(_("-r (with file name)\tRecover crashed session"));
3099 main_msg(_("-L\t\t\tSame as -r"));
3100 #ifdef AMIGA
3101 main_msg(_("-f\t\t\tDon't use newcli to open window"));
3102 main_msg(_("-dev <device>\t\tUse <device> for I/O"));
3103 #endif
3104 #ifdef FEAT_ARABIC
3105 main_msg(_("-A\t\t\tstart in Arabic mode"));
3106 #endif
3107 #ifdef FEAT_RIGHTLEFT
3108 main_msg(_("-H\t\t\tStart in Hebrew mode"));
3109 #endif
3110 #ifdef FEAT_FKMAP
3111 main_msg(_("-F\t\t\tStart in Farsi mode"));
3112 #endif
3113 main_msg(_("-T <terminal>\tSet terminal type to <terminal>"));
3114 main_msg(_("-u <vimrc>\t\tUse <vimrc> instead of any .vimrc"));
3115 #ifdef FEAT_GUI
3116 main_msg(_("-U <gvimrc>\t\tUse <gvimrc> instead of any .gvimrc"));
3117 #endif
3118 main_msg(_("--noplugin\t\tDon't load plugin scripts"));
3119 #ifdef FEAT_WINDOWS
3120 main_msg(_("-p[N]\t\tOpen N tab pages (default: one for each file)"));
3121 main_msg(_("-o[N]\t\tOpen N windows (default: one for each file)"));
3122 main_msg(_("-O[N]\t\tLike -o but split vertically"));
3123 #endif
3124 main_msg(_("+\t\t\tStart at end of file"));
3125 main_msg(_("+<lnum>\t\tStart at line <lnum>"));
3126 main_msg(_("--cmd <command>\tExecute <command> before loading any vimrc file"));
3127 main_msg(_("-c <command>\t\tExecute <command> after loading the first file"));
3128 main_msg(_("-S <session>\t\tSource file <session> after loading the first file"));
3129 main_msg(_("-s <scriptin>\tRead Normal mode commands from file <scriptin>"));
3130 main_msg(_("-w <scriptout>\tAppend all typed commands to file <scriptout>"));
3131 main_msg(_("-W <scriptout>\tWrite all typed commands to file <scriptout>"));
3132 #ifdef FEAT_CRYPT
3133 main_msg(_("-x\t\t\tEdit encrypted files"));
3134 #endif
3135 #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11)
3136 # if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK)
3137 main_msg(_("-display <display>\tConnect vim to this particular X-server"));
3138 # endif
3139 main_msg(_("-X\t\t\tDo not connect to X server"));
3140 #endif
3141 #ifdef FEAT_CLIENTSERVER
3142 main_msg(_("--remote <files>\tEdit <files> in a Vim server if possible"));
3143 main_msg(_("--remote-silent <files> Same, don't complain if there is no server"));
3144 main_msg(_("--remote-wait <files> As --remote but wait for files to have been edited"));
3145 main_msg(_("--remote-wait-silent <files> Same, don't complain if there is no server"));
3146 # ifdef FEAT_WINDOWS
3147 main_msg(_("--remote-tab[-wait][-silent] <files> As --remote but use tab page per file"));
3148 # endif
3149 main_msg(_("--remote-send <keys>\tSend <keys> to a Vim server and exit"));
3150 main_msg(_("--remote-expr <expr>\tEvaluate <expr> in a Vim server and print result"));
3151 main_msg(_("--serverlist\t\tList available Vim server names and exit"));
3152 main_msg(_("--servername <name>\tSend to/become the Vim server <name>"));
3153 #endif
3154 #ifdef FEAT_VIMINFO
3155 main_msg(_("-i <viminfo>\t\tUse <viminfo> instead of .viminfo"));
3156 #endif
3157 main_msg(_("-h or --help\tPrint Help (this message) and exit"));
3158 main_msg(_("--version\t\tPrint version information and exit"));
3160 #ifdef FEAT_GUI_X11
3161 # ifdef FEAT_GUI_MOTIF
3162 mch_msg(_("\nArguments recognised by gvim (Motif version):\n"));
3163 # else
3164 # ifdef FEAT_GUI_ATHENA
3165 # ifdef FEAT_GUI_NEXTAW
3166 mch_msg(_("\nArguments recognised by gvim (neXtaw version):\n"));
3167 # else
3168 mch_msg(_("\nArguments recognised by gvim (Athena version):\n"));
3169 # endif
3170 # endif
3171 # endif
3172 main_msg(_("-display <display>\tRun vim on <display>"));
3173 main_msg(_("-iconic\t\tStart vim iconified"));
3174 # if 0
3175 main_msg(_("-name <name>\t\tUse resource as if vim was <name>"));
3176 mch_msg(_("\t\t\t (Unimplemented)\n"));
3177 # endif
3178 main_msg(_("-background <color>\tUse <color> for the background (also: -bg)"));
3179 main_msg(_("-foreground <color>\tUse <color> for normal text (also: -fg)"));
3180 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3181 main_msg(_("-boldfont <font>\tUse <font> for bold text"));
3182 main_msg(_("-italicfont <font>\tUse <font> for italic text"));
3183 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3184 main_msg(_("-borderwidth <width>\tUse a border width of <width> (also: -bw)"));
3185 main_msg(_("-scrollbarwidth <width> Use a scrollbar width of <width> (also: -sw)"));
3186 # ifdef FEAT_GUI_ATHENA
3187 main_msg(_("-menuheight <height>\tUse a menu bar height of <height> (also: -mh)"));
3188 # endif
3189 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3190 main_msg(_("+reverse\t\tDon't use reverse video (also: +rv)"));
3191 main_msg(_("-xrm <resource>\tSet the specified resource"));
3192 #endif /* FEAT_GUI_X11 */
3193 #if defined(FEAT_GUI) && defined(RISCOS)
3194 mch_msg(_("\nArguments recognised by gvim (RISC OS version):\n"));
3195 main_msg(_("--columns <number>\tInitial width of window in columns"));
3196 main_msg(_("--rows <number>\tInitial height of window in rows"));
3197 #endif
3198 #ifdef FEAT_GUI_GTK
3199 mch_msg(_("\nArguments recognised by gvim (GTK+ version):\n"));
3200 main_msg(_("-font <font>\t\tUse <font> for normal text (also: -fn)"));
3201 main_msg(_("-geometry <geom>\tUse <geom> for initial geometry (also: -geom)"));
3202 main_msg(_("-reverse\t\tUse reverse video (also: -rv)"));
3203 main_msg(_("-display <display>\tRun vim on <display> (also: --display)"));
3204 # ifdef HAVE_GTK2
3205 main_msg(_("--role <role>\tSet a unique role to identify the main window"));
3206 # endif
3207 main_msg(_("--socketid <xid>\tOpen Vim inside another GTK widget"));
3208 #endif
3209 #ifdef FEAT_GUI_W32
3210 main_msg(_("-P <parent title>\tOpen Vim inside parent application"));
3211 main_msg(_("--windowid <HWND>\tOpen Vim inside another win32 widget"));
3212 #endif
3214 #ifdef FEAT_GUI_GNOME
3215 /* Gnome gives extra messages for --help if we continue, but not for -h. */
3216 if (gui.starting)
3217 mch_msg("\n");
3218 else
3219 #endif
3220 mch_exit(0);
3223 #if defined(HAS_SWAP_EXISTS_ACTION)
3225 * Check the result of the ATTENTION dialog:
3226 * When "Quit" selected, exit Vim.
3227 * When "Recover" selected, recover the file.
3229 static void
3230 check_swap_exists_action()
3232 if (swap_exists_action == SEA_QUIT)
3233 getout(1);
3234 handle_swap_exists(NULL);
3236 #endif
3238 #if defined(STARTUPTIME) || defined(PROTO)
3239 static void time_diff __ARGS((struct timeval *then, struct timeval *now));
3241 static struct timeval prev_timeval;
3244 * Save the previous time before doing something that could nest.
3245 * set "*tv_rel" to the time elapsed so far.
3247 void
3248 time_push(tv_rel, tv_start)
3249 void *tv_rel, *tv_start;
3251 *((struct timeval *)tv_rel) = prev_timeval;
3252 gettimeofday(&prev_timeval, NULL);
3253 ((struct timeval *)tv_rel)->tv_usec = prev_timeval.tv_usec
3254 - ((struct timeval *)tv_rel)->tv_usec;
3255 ((struct timeval *)tv_rel)->tv_sec = prev_timeval.tv_sec
3256 - ((struct timeval *)tv_rel)->tv_sec;
3257 if (((struct timeval *)tv_rel)->tv_usec < 0)
3259 ((struct timeval *)tv_rel)->tv_usec += 1000000;
3260 --((struct timeval *)tv_rel)->tv_sec;
3262 *(struct timeval *)tv_start = prev_timeval;
3266 * Compute the previous time after doing something that could nest.
3267 * Subtract "*tp" from prev_timeval;
3268 * Note: The arguments are (void *) to avoid trouble with systems that don't
3269 * have struct timeval.
3271 void
3272 time_pop(tp)
3273 void *tp; /* actually (struct timeval *) */
3275 prev_timeval.tv_usec -= ((struct timeval *)tp)->tv_usec;
3276 prev_timeval.tv_sec -= ((struct timeval *)tp)->tv_sec;
3277 if (prev_timeval.tv_usec < 0)
3279 prev_timeval.tv_usec += 1000000;
3280 --prev_timeval.tv_sec;
3284 static void
3285 time_diff(then, now)
3286 struct timeval *then;
3287 struct timeval *now;
3289 long usec;
3290 long msec;
3292 usec = now->tv_usec - then->tv_usec;
3293 msec = (now->tv_sec - then->tv_sec) * 1000L + usec / 1000L,
3294 usec = usec % 1000L;
3295 fprintf(time_fd, "%03ld.%03ld", msec, usec >= 0 ? usec : usec + 1000L);
3298 void
3299 time_msg(msg, tv_start)
3300 char *msg;
3301 void *tv_start; /* only for do_source: start time; actually
3302 (struct timeval *) */
3304 static struct timeval start;
3305 struct timeval now;
3307 if (time_fd != NULL)
3309 if (strstr(msg, "STARTING") != NULL)
3311 gettimeofday(&start, NULL);
3312 prev_timeval = start;
3313 fprintf(time_fd, "\n\ntimes in msec\n");
3314 fprintf(time_fd, " clock self+sourced self: sourced script\n");
3315 fprintf(time_fd, " clock elapsed: other lines\n\n");
3317 gettimeofday(&now, NULL);
3318 time_diff(&start, &now);
3319 if (((struct timeval *)tv_start) != NULL)
3321 fprintf(time_fd, " ");
3322 time_diff(((struct timeval *)tv_start), &now);
3324 fprintf(time_fd, " ");
3325 time_diff(&prev_timeval, &now);
3326 prev_timeval = now;
3327 fprintf(time_fd, ": %s\n", msg);
3331 # ifdef WIN3264
3333 * Windows doesn't have gettimeofday(), although it does have struct timeval.
3336 gettimeofday(struct timeval *tv, char *dummy)
3338 long t = clock();
3339 tv->tv_sec = t / CLOCKS_PER_SEC;
3340 tv->tv_usec = (t - tv->tv_sec * CLOCKS_PER_SEC) * 1000000 / CLOCKS_PER_SEC;
3341 return 0;
3343 # endif
3345 #endif
3347 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
3350 * Common code for the X command server and the Win32 command server.
3353 static char_u *build_drop_cmd __ARGS((int filec, char **filev, int tabs, int sendReply));
3356 * Do the client-server stuff, unless "--servername ''" was used.
3358 static void
3359 exec_on_server(parmp)
3360 mparm_T *parmp;
3362 if (parmp->serverName_arg == NULL || *parmp->serverName_arg != NUL)
3364 # ifdef WIN32
3365 /* Initialise the client/server messaging infrastructure. */
3366 serverInitMessaging();
3367 # endif
3370 * When a command server argument was found, execute it. This may
3371 * exit Vim when it was successful. Otherwise it's executed further
3372 * on. Remember the encoding used here in "serverStrEnc".
3374 if (parmp->serverArg)
3376 cmdsrv_main(&parmp->argc, parmp->argv,
3377 parmp->serverName_arg, &parmp->serverStr);
3378 # ifdef FEAT_MBYTE
3379 parmp->serverStrEnc = vim_strsave(p_enc);
3380 # endif
3383 /* If we're still running, get the name to register ourselves.
3384 * On Win32 can register right now, for X11 need to setup the
3385 * clipboard first, it's further down. */
3386 parmp->servername = serverMakeName(parmp->serverName_arg,
3387 parmp->argv[0]);
3388 # ifdef WIN32
3389 if (parmp->servername != NULL)
3391 serverSetName(parmp->servername);
3392 vim_free(parmp->servername);
3394 # endif
3399 * Prepare for running as a Vim server.
3401 static void
3402 prepare_server(parmp)
3403 mparm_T *parmp;
3405 # if defined(FEAT_X11)
3407 * Register for remote command execution with :serversend and --remote
3408 * unless there was a -X or a --servername '' on the command line.
3409 * Only register nongui-vim's with an explicit --servername argument.
3410 * When running as root --servername is also required.
3412 if (X_DISPLAY != NULL && parmp->servername != NULL && (
3413 # ifdef FEAT_GUI
3414 (gui.in_use
3415 # ifdef UNIX
3416 && getuid() != ROOT_UID
3417 # endif
3418 ) ||
3419 # endif
3420 parmp->serverName_arg != NULL))
3422 (void)serverRegisterName(X_DISPLAY, parmp->servername);
3423 vim_free(parmp->servername);
3424 TIME_MSG("register server name");
3426 else
3427 serverDelayedStartName = parmp->servername;
3428 # elif defined(MAC_CLIENTSERVER)
3429 // NOTE: Can't set server name at same time as WIN32 because gui.in_use
3430 // isn't set then. Servers are only supported in GUI mode.
3431 if (parmp->servername != NULL && gui.in_use)
3433 serverRegisterName(parmp->servername);
3434 vim_free(parmp->servername);
3436 # endif
3439 * Execute command ourselves if we're here because the send failed (or
3440 * else we would have exited above).
3442 if (parmp->serverStr != NULL)
3444 char_u *p;
3446 server_to_input_buf(serverConvert(parmp->serverStrEnc,
3447 parmp->serverStr, &p));
3448 vim_free(p);
3452 static void
3453 cmdsrv_main(argc, argv, serverName_arg, serverStr)
3454 int *argc;
3455 char **argv;
3456 char_u *serverName_arg;
3457 char_u **serverStr;
3459 char_u *res;
3460 int i;
3461 char_u *sname;
3462 int ret;
3463 int didone = FALSE;
3464 int exiterr = 0;
3465 char **newArgV = argv + 1;
3466 int newArgC = 1,
3467 Argc = *argc;
3468 int argtype;
3469 #define ARGTYPE_OTHER 0
3470 #define ARGTYPE_EDIT 1
3471 #define ARGTYPE_EDIT_WAIT 2
3472 #define ARGTYPE_SEND 3
3473 int silent = FALSE;
3474 int tabs = FALSE;
3475 # ifdef WIN32
3476 HWND srv;
3477 # elif defined(MAC_CLIENTSERVER)
3478 int srv;
3479 # elif defined(FEAT_X11)
3480 Window srv;
3482 setup_term_clip();
3483 # endif
3485 sname = serverMakeName(serverName_arg, argv[0]);
3486 if (sname == NULL)
3487 return;
3490 * Execute the command server related arguments and remove them
3491 * from the argc/argv array; We may have to return into main()
3493 for (i = 1; i < Argc; i++)
3495 res = NULL;
3496 if (STRCMP(argv[i], "--") == 0) /* end of option arguments */
3498 for (; i < *argc; i++)
3500 *newArgV++ = argv[i];
3501 newArgC++;
3503 break;
3506 if (STRICMP(argv[i], "--remote-send") == 0)
3507 argtype = ARGTYPE_SEND;
3508 else if (STRNICMP(argv[i], "--remote", 8) == 0)
3510 char *p = argv[i] + 8;
3512 argtype = ARGTYPE_EDIT;
3513 while (*p != NUL)
3515 if (STRNICMP(p, "-wait", 5) == 0)
3517 argtype = ARGTYPE_EDIT_WAIT;
3518 p += 5;
3520 else if (STRNICMP(p, "-silent", 7) == 0)
3522 silent = TRUE;
3523 p += 7;
3525 else if (STRNICMP(p, "-tab", 4) == 0)
3527 tabs = TRUE;
3528 p += 4;
3530 else
3532 argtype = ARGTYPE_OTHER;
3533 break;
3537 else
3538 argtype = ARGTYPE_OTHER;
3540 if (argtype != ARGTYPE_OTHER)
3542 if (i == *argc - 1)
3543 mainerr_arg_missing((char_u *)argv[i]);
3544 if (argtype == ARGTYPE_SEND)
3546 *serverStr = (char_u *)argv[i + 1];
3547 i++;
3549 else
3551 *serverStr = build_drop_cmd(*argc - i - 1, argv + i + 1,
3552 tabs, argtype == ARGTYPE_EDIT_WAIT);
3553 if (*serverStr == NULL)
3555 /* Probably out of memory, exit. */
3556 didone = TRUE;
3557 exiterr = 1;
3558 break;
3560 Argc = i;
3562 # ifdef FEAT_X11
3563 if (xterm_dpy == NULL)
3565 mch_errmsg(_("No display"));
3566 ret = -1;
3568 else
3569 ret = serverSendToVim(xterm_dpy, sname, *serverStr,
3570 NULL, &srv, 0, 0, silent);
3571 # elif defined(WIN32) || defined(MAC_CLIENTSERVER)
3572 /* Win32 always works? */
3573 ret = serverSendToVim(sname, *serverStr, NULL, &srv, 0, silent);
3574 # endif
3575 if (ret < 0)
3577 if (argtype == ARGTYPE_SEND)
3579 /* Failed to send, abort. */
3580 mch_errmsg(_(": Send failed.\n"));
3581 didone = TRUE;
3582 exiterr = 1;
3584 else if (!silent)
3585 /* Let vim start normally. */
3586 mch_errmsg(_(": Send failed. Trying to execute locally\n"));
3587 break;
3590 # ifdef FEAT_GUI_W32
3591 /* Guess that when the server name starts with "g" it's a GUI
3592 * server, which we can bring to the foreground here.
3593 * Foreground() in the server doesn't work very well. */
3594 if (argtype != ARGTYPE_SEND && TOUPPER_ASC(*sname) == 'G')
3595 SetForegroundWindow(srv);
3596 # endif
3599 * For --remote-wait: Wait until the server did edit each
3600 * file. Also detect that the server no longer runs.
3602 if (ret >= 0 && argtype == ARGTYPE_EDIT_WAIT)
3604 int numFiles = *argc - i - 1;
3605 int j;
3606 char_u *done = alloc(numFiles);
3607 char_u *p;
3608 # ifdef FEAT_GUI_W32
3609 NOTIFYICONDATA ni;
3610 int count = 0;
3611 extern HWND message_window;
3612 # endif
3614 if (numFiles > 0 && argv[i + 1][0] == '+')
3615 /* Skip "+cmd" argument, don't wait for it to be edited. */
3616 --numFiles;
3618 # ifdef FEAT_GUI_W32
3619 ni.cbSize = sizeof(ni);
3620 ni.hWnd = message_window;
3621 ni.uID = 0;
3622 ni.uFlags = NIF_ICON|NIF_TIP;
3623 ni.hIcon = LoadIcon((HINSTANCE)GetModuleHandle(0), "IDR_VIM");
3624 sprintf(ni.szTip, _("%d of %d edited"), count, numFiles);
3625 Shell_NotifyIcon(NIM_ADD, &ni);
3626 # endif
3628 /* Wait for all files to unload in remote */
3629 memset(done, 0, numFiles);
3630 while (memchr(done, 0, numFiles) != NULL)
3632 # ifdef WIN32
3633 p = serverGetReply(srv, NULL, TRUE, TRUE);
3634 if (p == NULL)
3635 break;
3636 # elif defined(FEAT_X11)
3637 if (serverReadReply(xterm_dpy, srv, &p, TRUE) < 0)
3638 break;
3639 # elif defined(MAC_CLIENTSERVER)
3640 if (serverReadReply(srv, &p) < 0)
3641 break;
3642 # endif
3643 j = atoi((char *)p);
3644 if (j >= 0 && j < numFiles)
3646 # ifdef FEAT_GUI_W32
3647 ++count;
3648 sprintf(ni.szTip, _("%d of %d edited"),
3649 count, numFiles);
3650 Shell_NotifyIcon(NIM_MODIFY, &ni);
3651 # endif
3652 done[j] = 1;
3655 # ifdef FEAT_GUI_W32
3656 Shell_NotifyIcon(NIM_DELETE, &ni);
3657 # endif
3660 else if (STRICMP(argv[i], "--remote-expr") == 0)
3662 if (i == *argc - 1)
3663 mainerr_arg_missing((char_u *)argv[i]);
3664 # ifdef WIN32
3665 /* Win32 always works? */
3666 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3667 &res, NULL, 1, FALSE) < 0)
3668 # elif defined(FEAT_X11)
3669 if (xterm_dpy == NULL)
3670 mch_errmsg(_("No display: Send expression failed.\n"));
3671 else if (serverSendToVim(xterm_dpy, sname, (char_u *)argv[i + 1],
3672 &res, NULL, 1, 1, FALSE) < 0)
3673 # elif defined(MAC_CLIENTSERVER)
3674 if (serverSendToVim(sname, (char_u *)argv[i + 1],
3675 &res, NULL, 1, FALSE) < 0)
3676 # endif
3678 if (res != NULL && *res != NUL)
3680 /* Output error from remote */
3681 mch_errmsg((char *)res);
3682 vim_free(res);
3683 res = NULL;
3685 mch_errmsg(_(": Send expression failed.\n"));
3688 else if (STRICMP(argv[i], "--serverlist") == 0)
3690 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
3691 /* Win32 always works? */
3692 res = serverGetVimNames();
3693 # elif defined(FEAT_X11)
3694 if (xterm_dpy != NULL)
3695 res = serverGetVimNames(xterm_dpy);
3696 # endif
3697 if (called_emsg)
3698 mch_errmsg("\n");
3700 else if (STRICMP(argv[i], "--servername") == 0)
3702 /* Alredy processed. Take it out of the command line */
3703 i++;
3704 continue;
3706 else
3708 *newArgV++ = argv[i];
3709 newArgC++;
3710 continue;
3712 didone = TRUE;
3713 if (res != NULL && *res != NUL)
3715 mch_msg((char *)res);
3716 if (res[STRLEN(res) - 1] != '\n')
3717 mch_msg("\n");
3719 vim_free(res);
3722 if (didone)
3724 display_errors(); /* display any collected messages */
3725 exit(exiterr); /* Mission accomplished - get out */
3728 /* Return back into main() */
3729 *argc = newArgC;
3730 vim_free(sname);
3734 * Build a ":drop" command to send to a Vim server.
3736 static char_u *
3737 build_drop_cmd(filec, filev, tabs, sendReply)
3738 int filec;
3739 char **filev;
3740 int tabs; /* Use ":tab drop" instead of ":drop". */
3741 int sendReply;
3743 garray_T ga;
3744 int i;
3745 char_u *inicmd = NULL;
3746 char_u *p;
3747 char_u cwd[MAXPATHL];
3749 if (filec > 0 && filev[0][0] == '+')
3751 inicmd = (char_u *)filev[0] + 1;
3752 filev++;
3753 filec--;
3755 /* Check if we have at least one argument. */
3756 if (filec <= 0)
3757 mainerr_arg_missing((char_u *)filev[-1]);
3758 if (mch_dirname(cwd, MAXPATHL) != OK)
3759 return NULL;
3760 if ((p = vim_strsave_escaped_ext(cwd,
3761 #ifdef BACKSLASH_IN_FILENAME
3762 "", /* rem_backslash() will tell what chars to escape */
3763 #else
3764 PATH_ESC_CHARS,
3765 #endif
3766 '\\', TRUE)) == NULL)
3767 return NULL;
3768 ga_init2(&ga, 1, 100);
3769 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd ");
3770 ga_concat(&ga, p);
3771 vim_free(p);
3773 /* Call inputsave() so that a prompt for an encryption key works. */
3774 ga_concat(&ga, (char_u *)"<CR>:if exists('*inputsave')|call inputsave()|endif|");
3775 if (tabs)
3776 ga_concat(&ga, (char_u *)"tab ");
3777 ga_concat(&ga, (char_u *)"drop");
3778 for (i = 0; i < filec; i++)
3780 /* On Unix the shell has already expanded the wildcards, don't want to
3781 * do it again in the Vim server. On MS-Windows only escape
3782 * non-wildcard characters. */
3783 p = vim_strsave_escaped((char_u *)filev[i],
3784 #ifdef UNIX
3785 PATH_ESC_CHARS
3786 #else
3787 (char_u *)" \t%#"
3788 #endif
3790 if (p == NULL)
3792 vim_free(ga.ga_data);
3793 return NULL;
3795 ga_concat(&ga, (char_u *)" ");
3796 ga_concat(&ga, p);
3797 vim_free(p);
3799 /* The :drop commands goes to Insert mode when 'insertmode' is set, use
3800 * CTRL-\ CTRL-N again. */
3801 ga_concat(&ga, (char_u *)"|if exists('*inputrestore')|call inputrestore()|endif<CR>");
3802 ga_concat(&ga, (char_u *)"<C-\\><C-N>:cd -");
3803 if (sendReply)
3804 ga_concat(&ga, (char_u *)"<CR>:call SetupRemoteReplies()");
3805 ga_concat(&ga, (char_u *)"<CR>:");
3806 if (inicmd != NULL)
3808 /* Can't use <CR> after "inicmd", because an "startinsert" would cause
3809 * the following commands to be inserted as text. Use a "|",
3810 * hopefully "inicmd" does allow this... */
3811 ga_concat(&ga, inicmd);
3812 ga_concat(&ga, (char_u *)"|");
3814 /* Bring the window to the foreground, goto Insert mode when 'im' set and
3815 * clear command line. */
3816 ga_concat(&ga, (char_u *)"cal foreground()|if &im|star|en|redr|f<CR>");
3817 ga_append(&ga, NUL);
3818 return ga.ga_data;
3822 * Replace termcodes such as <CR> and insert as key presses if there is room.
3824 void
3825 server_to_input_buf(str)
3826 char_u *str;
3828 char_u *ptr = NULL;
3829 char_u *cpo_save = p_cpo;
3831 /* Set 'cpoptions' the way we want it.
3832 * B set - backslashes are *not* treated specially
3833 * k set - keycodes are *not* reverse-engineered
3834 * < unset - <Key> sequences *are* interpreted
3835 * The last but one parameter of replace_termcodes() is TRUE so that the
3836 * <lt> sequence is recognised - needed for a real backslash.
3838 p_cpo = (char_u *)"Bk";
3839 str = replace_termcodes((char_u *)str, &ptr, FALSE, TRUE, FALSE);
3840 p_cpo = cpo_save;
3842 if (*ptr != NUL) /* trailing CTRL-V results in nothing */
3845 * Add the string to the input stream.
3846 * Can't use add_to_input_buf() here, we now have K_SPECIAL bytes.
3848 * First clear typed characters from the typeahead buffer, there could
3849 * be half a mapping there. Then append to the existing string, so
3850 * that multiple commands from a client are concatenated.
3852 if (typebuf.tb_maplen < typebuf.tb_len)
3853 del_typebuf(typebuf.tb_len - typebuf.tb_maplen, typebuf.tb_maplen);
3854 (void)ins_typebuf(str, REMAP_NONE, typebuf.tb_len, TRUE, FALSE);
3856 /* Let input_available() know we inserted text in the typeahead
3857 * buffer. */
3858 typebuf_was_filled = TRUE;
3860 vim_free((char_u *)ptr);
3864 * Evaluate an expression that the client sent to a string.
3865 * Handles disabling error messages and disables debugging, otherwise Vim
3866 * hangs, waiting for "cont" to be typed.
3868 char_u *
3869 eval_client_expr_to_string(expr)
3870 char_u *expr;
3872 char_u *res;
3873 int save_dbl = debug_break_level;
3874 int save_ro = redir_off;
3876 debug_break_level = -1;
3877 redir_off = 0;
3878 ++emsg_skip;
3880 res = eval_to_string(expr, NULL, TRUE);
3882 debug_break_level = save_dbl;
3883 redir_off = save_ro;
3884 --emsg_skip;
3886 /* A client can tell us to redraw, but not to display the cursor, so do
3887 * that here. */
3888 setcursor();
3889 out_flush();
3890 #ifdef FEAT_GUI
3891 if (gui.in_use)
3892 gui_update_cursor(FALSE, FALSE);
3893 #endif
3895 return res;
3899 * If conversion is needed, convert "data" from "client_enc" to 'encoding' and
3900 * return an allocated string. Otherwise return "data".
3901 * "*tofree" is set to the result when it needs to be freed later.
3903 /*ARGSUSED*/
3904 char_u *
3905 serverConvert(client_enc, data, tofree)
3906 char_u *client_enc;
3907 char_u *data;
3908 char_u **tofree;
3910 char_u *res = data;
3912 *tofree = NULL;
3913 # ifdef FEAT_MBYTE
3914 if (client_enc != NULL && p_enc != NULL)
3916 vimconv_T vimconv;
3918 vimconv.vc_type = CONV_NONE;
3919 if (convert_setup(&vimconv, client_enc, p_enc) != FAIL
3920 && vimconv.vc_type != CONV_NONE)
3922 res = string_convert(&vimconv, data, NULL);
3923 if (res == NULL)
3924 res = data;
3925 else
3926 *tofree = res;
3928 convert_setup(&vimconv, NULL, NULL);
3930 # endif
3931 return res;
3936 * Make our basic server name: use the specified "arg" if given, otherwise use
3937 * the tail of the command "cmd" we were started with.
3938 * Return the name in allocated memory. This doesn't include a serial number.
3940 static char_u *
3941 serverMakeName(arg, cmd)
3942 char_u *arg;
3943 char *cmd;
3945 char_u *p;
3947 if (arg != NULL && *arg != NUL)
3948 p = vim_strsave_up(arg);
3949 else
3951 p = vim_strsave_up(gettail((char_u *)cmd));
3952 /* Remove .exe or .bat from the name. */
3953 if (p != NULL && vim_strchr(p, '.') != NULL)
3954 *vim_strchr(p, '.') = NUL;
3956 return p;
3958 #endif /* FEAT_CLIENTSERVER */
3961 * When FEAT_FKMAP is defined, also compile the Farsi source code.
3963 #if defined(FEAT_FKMAP) || defined(PROTO)
3964 # include "farsi.c"
3965 #endif
3968 * When FEAT_ARABIC is defined, also compile the Arabic source code.
3970 #if defined(FEAT_ARABIC) || defined(PROTO)
3971 # include "arabic.c"
3972 #endif