xref: /vim-8.2.3635/src/ex_docmd.c (revision e16b00a1)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * ex_docmd.c: functions for executing an Ex command line.
12  */
13 
14 #include "vim.h"
15 
16 static int	quitmore = 0;
17 static int	ex_pressedreturn = FALSE;
18 #ifndef FEAT_PRINTER
19 # define ex_hardcopy	ex_ni
20 #endif
21 
22 #ifdef FEAT_USR_CMDS
23 typedef struct ucmd
24 {
25     char_u	*uc_name;	/* The command name */
26     long_u	uc_argt;	/* The argument type */
27     char_u	*uc_rep;	/* The command's replacement string */
28     long	uc_def;		/* The default value for a range/count */
29     int		uc_compl;	/* completion type */
30     int		uc_addr_type;	/* The command's address type */
31 # ifdef FEAT_EVAL
32     scid_T	uc_scriptID;	/* SID where the command was defined */
33 #  ifdef FEAT_CMDL_COMPL
34     char_u	*uc_compl_arg;	/* completion argument if any */
35 #  endif
36 # endif
37 } ucmd_T;
38 
39 #define UC_BUFFER	1	/* -buffer: local to current buffer */
40 
41 static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL};
42 
43 #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
44 #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
45 
46 static void do_ucmd(exarg_T *eap);
47 static void ex_command(exarg_T *eap);
48 static void ex_delcommand(exarg_T *eap);
49 # ifdef FEAT_CMDL_COMPL
50 static char_u *get_user_command_name(int idx);
51 # endif
52 
53 /* Wether a command index indicates a user command. */
54 # define IS_USER_CMDIDX(idx) ((int)(idx) < 0)
55 
56 #else
57 # define ex_command	ex_ni
58 # define ex_comclear	ex_ni
59 # define ex_delcommand	ex_ni
60 /* Wether a command index indicates a user command. */
61 # define IS_USER_CMDIDX(idx) (FALSE)
62 #endif
63 
64 static int compute_buffer_local_count(int addr_type, int lnum, int local);
65 #ifdef FEAT_EVAL
66 static char_u	*do_one_cmd(char_u **, int, struct condstack *, char_u *(*fgetline)(int, void *, int), void *cookie);
67 #else
68 static char_u	*do_one_cmd(char_u **, int, char_u *(*fgetline)(int, void *, int), void *cookie);
69 static int	if_level = 0;		/* depth in :if */
70 #endif
71 static void	append_command(char_u *cmd);
72 static char_u	*find_command(exarg_T *eap, int *full);
73 
74 static void	ex_abbreviate(exarg_T *eap);
75 static void	ex_map(exarg_T *eap);
76 static void	ex_unmap(exarg_T *eap);
77 static void	ex_mapclear(exarg_T *eap);
78 static void	ex_abclear(exarg_T *eap);
79 #ifndef FEAT_MENU
80 # define ex_emenu		ex_ni
81 # define ex_menu		ex_ni
82 # define ex_menutranslate	ex_ni
83 #endif
84 #ifdef FEAT_AUTOCMD
85 static void	ex_autocmd(exarg_T *eap);
86 static void	ex_doautocmd(exarg_T *eap);
87 #else
88 # define ex_autocmd		ex_ni
89 # define ex_doautocmd		ex_ni
90 # define ex_doautoall		ex_ni
91 #endif
92 #ifdef FEAT_LISTCMDS
93 static void	ex_bunload(exarg_T *eap);
94 static void	ex_buffer(exarg_T *eap);
95 static void	ex_bmodified(exarg_T *eap);
96 static void	ex_bnext(exarg_T *eap);
97 static void	ex_bprevious(exarg_T *eap);
98 static void	ex_brewind(exarg_T *eap);
99 static void	ex_blast(exarg_T *eap);
100 #else
101 # define ex_bunload		ex_ni
102 # define ex_buffer		ex_ni
103 # define ex_bmodified		ex_ni
104 # define ex_bnext		ex_ni
105 # define ex_bprevious		ex_ni
106 # define ex_brewind		ex_ni
107 # define ex_blast		ex_ni
108 # define buflist_list		ex_ni
109 # define ex_checktime		ex_ni
110 #endif
111 #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS)
112 # define ex_buffer_all		ex_ni
113 #endif
114 static char_u	*getargcmd(char_u **);
115 static char_u	*skip_cmd_arg(char_u *p, int rembs);
116 static int	getargopt(exarg_T *eap);
117 #ifndef FEAT_QUICKFIX
118 # define ex_make		ex_ni
119 # define ex_cbuffer		ex_ni
120 # define ex_cc			ex_ni
121 # define ex_cnext		ex_ni
122 # define ex_cfile		ex_ni
123 # define qf_list		ex_ni
124 # define qf_age			ex_ni
125 # define qf_history		ex_ni
126 # define ex_helpgrep		ex_ni
127 # define ex_vimgrep		ex_ni
128 #endif
129 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS)
130 # define ex_cclose		ex_ni
131 # define ex_copen		ex_ni
132 # define ex_cwindow		ex_ni
133 # define ex_cbottom		ex_ni
134 #endif
135 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL)
136 # define ex_cexpr		ex_ni
137 #endif
138 
139 static int	check_more(int, int);
140 static linenr_T get_address(exarg_T *, char_u **, int addr_type, int skip, int to_other_file, int address_count);
141 static void	get_flags(exarg_T *eap);
142 #if !defined(FEAT_PERL) \
143 	|| !defined(FEAT_PYTHON) || !defined(FEAT_PYTHON3) \
144 	|| !defined(FEAT_TCL) \
145 	|| !defined(FEAT_RUBY) \
146 	|| !defined(FEAT_LUA) \
147 	|| !defined(FEAT_MZSCHEME)
148 # define HAVE_EX_SCRIPT_NI
149 static void	ex_script_ni(exarg_T *eap);
150 #endif
151 static char_u	*invalid_range(exarg_T *eap);
152 static void	correct_range(exarg_T *eap);
153 #ifdef FEAT_QUICKFIX
154 static char_u	*replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep);
155 #endif
156 static char_u	*repl_cmdline(exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep);
157 static void	ex_highlight(exarg_T *eap);
158 static void	ex_colorscheme(exarg_T *eap);
159 static void	ex_quit(exarg_T *eap);
160 static void	ex_cquit(exarg_T *eap);
161 static void	ex_quit_all(exarg_T *eap);
162 #ifdef FEAT_WINDOWS
163 static void	ex_close(exarg_T *eap);
164 static void	ex_win_close(int forceit, win_T *win, tabpage_T *tp);
165 static void	ex_only(exarg_T *eap);
166 static void	ex_resize(exarg_T *eap);
167 static void	ex_stag(exarg_T *eap);
168 static void	ex_tabclose(exarg_T *eap);
169 static void	ex_tabonly(exarg_T *eap);
170 static void	ex_tabnext(exarg_T *eap);
171 static void	ex_tabmove(exarg_T *eap);
172 static void	ex_tabs(exarg_T *eap);
173 #else
174 # define ex_close		ex_ni
175 # define ex_only		ex_ni
176 # define ex_all			ex_ni
177 # define ex_resize		ex_ni
178 # define ex_splitview		ex_ni
179 # define ex_stag		ex_ni
180 # define ex_tabnext		ex_ni
181 # define ex_tabmove		ex_ni
182 # define ex_tabs		ex_ni
183 # define ex_tabclose		ex_ni
184 # define ex_tabonly		ex_ni
185 #endif
186 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
187 static void	ex_pclose(exarg_T *eap);
188 static void	ex_ptag(exarg_T *eap);
189 static void	ex_pedit(exarg_T *eap);
190 #else
191 # define ex_pclose		ex_ni
192 # define ex_ptag		ex_ni
193 # define ex_pedit		ex_ni
194 #endif
195 static void	ex_hide(exarg_T *eap);
196 static void	ex_stop(exarg_T *eap);
197 static void	ex_exit(exarg_T *eap);
198 static void	ex_print(exarg_T *eap);
199 #ifdef FEAT_BYTEOFF
200 static void	ex_goto(exarg_T *eap);
201 #else
202 # define ex_goto		ex_ni
203 #endif
204 static void	ex_shell(exarg_T *eap);
205 static void	ex_preserve(exarg_T *eap);
206 static void	ex_recover(exarg_T *eap);
207 #ifndef FEAT_LISTCMDS
208 # define ex_argedit		ex_ni
209 # define ex_argadd		ex_ni
210 # define ex_argdelete		ex_ni
211 # define ex_listdo		ex_ni
212 #endif
213 static void	ex_mode(exarg_T *eap);
214 static void	ex_wrongmodifier(exarg_T *eap);
215 static void	ex_find(exarg_T *eap);
216 static void	ex_open(exarg_T *eap);
217 static void	ex_edit(exarg_T *eap);
218 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
219 # define ex_drop		ex_ni
220 #endif
221 #ifndef FEAT_GUI
222 # define ex_gui			ex_nogui
223 static void	ex_nogui(exarg_T *eap);
224 #endif
225 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
226 static void	ex_tearoff(exarg_T *eap);
227 #else
228 # define ex_tearoff		ex_ni
229 #endif
230 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
231 static void	ex_popup(exarg_T *eap);
232 #else
233 # define ex_popup		ex_ni
234 #endif
235 #ifndef FEAT_GUI_MSWIN
236 # define ex_simalt		ex_ni
237 #endif
238 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
239 # define gui_mch_find_dialog	ex_ni
240 # define gui_mch_replace_dialog ex_ni
241 #endif
242 #if !defined(FEAT_GUI_GTK)
243 # define ex_helpfind		ex_ni
244 #endif
245 #ifndef FEAT_CSCOPE
246 # define ex_cscope		ex_ni
247 # define ex_scscope		ex_ni
248 # define ex_cstag		ex_ni
249 #endif
250 #ifndef FEAT_SYN_HL
251 # define ex_syntax		ex_ni
252 # define ex_ownsyntax		ex_ni
253 #endif
254 #if !defined(FEAT_SYN_HL) || !defined(FEAT_PROFILE)
255 # define ex_syntime		ex_ni
256 #endif
257 #ifndef FEAT_SPELL
258 # define ex_spell		ex_ni
259 # define ex_mkspell		ex_ni
260 # define ex_spelldump		ex_ni
261 # define ex_spellinfo		ex_ni
262 # define ex_spellrepall		ex_ni
263 #endif
264 #ifndef FEAT_PERSISTENT_UNDO
265 # define ex_rundo		ex_ni
266 # define ex_wundo		ex_ni
267 #endif
268 #ifndef FEAT_LUA
269 # define ex_lua			ex_script_ni
270 # define ex_luado		ex_ni
271 # define ex_luafile		ex_ni
272 #endif
273 #ifndef FEAT_MZSCHEME
274 # define ex_mzscheme		ex_script_ni
275 # define ex_mzfile		ex_ni
276 #endif
277 #ifndef FEAT_PERL
278 # define ex_perl		ex_script_ni
279 # define ex_perldo		ex_ni
280 #endif
281 #ifndef FEAT_PYTHON
282 # define ex_python		ex_script_ni
283 # define ex_pydo		ex_ni
284 # define ex_pyfile		ex_ni
285 #endif
286 #ifndef FEAT_PYTHON3
287 # define ex_py3			ex_script_ni
288 # define ex_py3do		ex_ni
289 # define ex_py3file		ex_ni
290 #endif
291 #if !defined(FEAT_PYTHON) && !defined(FEAT_PYTHON3)
292 # define ex_pyx			ex_script_ni
293 # define ex_pyxdo		ex_ni
294 # define ex_pyxfile		ex_ni
295 #endif
296 #ifndef FEAT_TCL
297 # define ex_tcl			ex_script_ni
298 # define ex_tcldo		ex_ni
299 # define ex_tclfile		ex_ni
300 #endif
301 #ifndef FEAT_RUBY
302 # define ex_ruby		ex_script_ni
303 # define ex_rubydo		ex_ni
304 # define ex_rubyfile		ex_ni
305 #endif
306 #ifndef FEAT_KEYMAP
307 # define ex_loadkeymap		ex_ni
308 #endif
309 static void	ex_swapname(exarg_T *eap);
310 static void	ex_syncbind(exarg_T *eap);
311 static void	ex_read(exarg_T *eap);
312 static void	ex_pwd(exarg_T *eap);
313 static void	ex_equal(exarg_T *eap);
314 static void	ex_sleep(exarg_T *eap);
315 static void	do_exmap(exarg_T *eap, int isabbrev);
316 static void	ex_winsize(exarg_T *eap);
317 #ifdef FEAT_WINDOWS
318 static void	ex_wincmd(exarg_T *eap);
319 #else
320 # define ex_wincmd	    ex_ni
321 #endif
322 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
323 static void	ex_winpos(exarg_T *eap);
324 #else
325 # define ex_winpos	    ex_ni
326 #endif
327 static void	ex_operators(exarg_T *eap);
328 static void	ex_put(exarg_T *eap);
329 static void	ex_copymove(exarg_T *eap);
330 static void	ex_submagic(exarg_T *eap);
331 static void	ex_join(exarg_T *eap);
332 static void	ex_at(exarg_T *eap);
333 static void	ex_bang(exarg_T *eap);
334 static void	ex_undo(exarg_T *eap);
335 #ifdef FEAT_PERSISTENT_UNDO
336 static void	ex_wundo(exarg_T *eap);
337 static void	ex_rundo(exarg_T *eap);
338 #endif
339 static void	ex_redo(exarg_T *eap);
340 static void	ex_later(exarg_T *eap);
341 static void	ex_redir(exarg_T *eap);
342 static void	ex_redrawstatus(exarg_T *eap);
343 static void	close_redir(void);
344 static void	ex_mkrc(exarg_T *eap);
345 static void	ex_mark(exarg_T *eap);
346 #ifdef FEAT_USR_CMDS
347 static char_u	*uc_fun_cmd(void);
348 static char_u	*find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl);
349 #endif
350 static void	ex_startinsert(exarg_T *eap);
351 static void	ex_stopinsert(exarg_T *eap);
352 #ifdef FEAT_FIND_ID
353 static void	ex_checkpath(exarg_T *eap);
354 static void	ex_findpat(exarg_T *eap);
355 #else
356 # define ex_findpat		ex_ni
357 # define ex_checkpath		ex_ni
358 #endif
359 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
360 static void	ex_psearch(exarg_T *eap);
361 #else
362 # define ex_psearch		ex_ni
363 #endif
364 static void	ex_tag(exarg_T *eap);
365 static void	ex_tag_cmd(exarg_T *eap, char_u *name);
366 #ifndef FEAT_EVAL
367 # define ex_scriptnames		ex_ni
368 # define ex_finish		ex_ni
369 # define ex_echo		ex_ni
370 # define ex_echohl		ex_ni
371 # define ex_execute		ex_ni
372 # define ex_call		ex_ni
373 # define ex_if			ex_ni
374 # define ex_endif		ex_ni
375 # define ex_else		ex_ni
376 # define ex_while		ex_ni
377 # define ex_continue		ex_ni
378 # define ex_break		ex_ni
379 # define ex_endwhile		ex_ni
380 # define ex_throw		ex_ni
381 # define ex_try			ex_ni
382 # define ex_catch		ex_ni
383 # define ex_finally		ex_ni
384 # define ex_endtry		ex_ni
385 # define ex_endfunction		ex_ni
386 # define ex_let			ex_ni
387 # define ex_unlet		ex_ni
388 # define ex_lockvar		ex_ni
389 # define ex_unlockvar		ex_ni
390 # define ex_function		ex_ni
391 # define ex_delfunction		ex_ni
392 # define ex_return		ex_ni
393 # define ex_oldfiles		ex_ni
394 #endif
395 static char_u	*arg_all(void);
396 #ifdef FEAT_SESSION
397 static int	makeopens(FILE *fd, char_u *dirnow);
398 static int	put_view(FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx);
399 static void	ex_loadview(exarg_T *eap);
400 static char_u	*get_view_file(int c);
401 static int	did_lcd;	/* whether ":lcd" was produced for a session */
402 #else
403 # define ex_loadview		ex_ni
404 #endif
405 #ifndef FEAT_EVAL
406 # define ex_compiler		ex_ni
407 #endif
408 #ifdef FEAT_VIMINFO
409 static void	ex_viminfo(exarg_T *eap);
410 #else
411 # define ex_viminfo		ex_ni
412 #endif
413 static void	ex_behave(exarg_T *eap);
414 #ifdef FEAT_AUTOCMD
415 static void	ex_filetype(exarg_T *eap);
416 static void	ex_setfiletype(exarg_T *eap);
417 #else
418 # define ex_filetype		ex_ni
419 # define ex_setfiletype		ex_ni
420 #endif
421 #ifndef FEAT_DIFF
422 # define ex_diffoff		ex_ni
423 # define ex_diffpatch		ex_ni
424 # define ex_diffgetput		ex_ni
425 # define ex_diffsplit		ex_ni
426 # define ex_diffthis		ex_ni
427 # define ex_diffupdate		ex_ni
428 #endif
429 static void	ex_digraphs(exarg_T *eap);
430 static void	ex_set(exarg_T *eap);
431 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
432 # define ex_options		ex_ni
433 #endif
434 #ifdef FEAT_SEARCH_EXTRA
435 static void	ex_nohlsearch(exarg_T *eap);
436 static void	ex_match(exarg_T *eap);
437 #else
438 # define ex_nohlsearch		ex_ni
439 # define ex_match		ex_ni
440 #endif
441 #ifdef FEAT_CRYPT
442 static void	ex_X(exarg_T *eap);
443 #else
444 # define ex_X			ex_ni
445 #endif
446 #ifdef FEAT_FOLDING
447 static void	ex_fold(exarg_T *eap);
448 static void	ex_foldopen(exarg_T *eap);
449 static void	ex_folddo(exarg_T *eap);
450 #else
451 # define ex_fold		ex_ni
452 # define ex_foldopen		ex_ni
453 # define ex_folddo		ex_ni
454 #endif
455 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
456 	&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
457 # define ex_language		ex_ni
458 #endif
459 #ifndef FEAT_SIGNS
460 # define ex_sign		ex_ni
461 #endif
462 #ifndef FEAT_SUN_WORKSHOP
463 # define ex_wsverb		ex_ni
464 #endif
465 #ifndef FEAT_NETBEANS_INTG
466 # define ex_nbclose		ex_ni
467 # define ex_nbkey		ex_ni
468 # define ex_nbstart		ex_ni
469 #endif
470 
471 #ifndef FEAT_EVAL
472 # define ex_debug		ex_ni
473 # define ex_breakadd		ex_ni
474 # define ex_debuggreedy		ex_ni
475 # define ex_breakdel		ex_ni
476 # define ex_breaklist		ex_ni
477 #endif
478 
479 #ifndef FEAT_CMDHIST
480 # define ex_history		ex_ni
481 #endif
482 #ifndef FEAT_JUMPLIST
483 # define ex_jumps		ex_ni
484 # define ex_clearjumps		ex_ni
485 # define ex_changes		ex_ni
486 #endif
487 
488 #ifndef FEAT_PROFILE
489 # define ex_profile		ex_ni
490 #endif
491 #ifndef FEAT_TERMINAL
492 # define ex_terminal		ex_ni
493 #endif
494 
495 /*
496  * Declare cmdnames[].
497  */
498 #define DO_DECLARE_EXCMD
499 #include "ex_cmds.h"
500 #include "ex_cmdidxs.h"
501 
502 static char_u dollar_command[2] = {'$', 0};
503 
504 
505 #ifdef FEAT_EVAL
506 /* Struct for storing a line inside a while/for loop */
507 typedef struct
508 {
509     char_u	*line;		/* command line */
510     linenr_T	lnum;		/* sourcing_lnum of the line */
511 } wcmd_T;
512 
513 /*
514  * Structure used to store info for line position in a while or for loop.
515  * This is required, because do_one_cmd() may invoke ex_function(), which
516  * reads more lines that may come from the while/for loop.
517  */
518 struct loop_cookie
519 {
520     garray_T	*lines_gap;		/* growarray with line info */
521     int		current_line;		/* last read line from growarray */
522     int		repeating;		/* TRUE when looping a second time */
523     /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
524     char_u	*(*getline)(int, void *, int);
525     void	*cookie;
526 };
527 
528 static char_u	*get_loop_line(int c, void *cookie, int indent);
529 static int	store_loop_line(garray_T *gap, char_u *line);
530 static void	free_cmdlines(garray_T *gap);
531 
532 /* Struct to save a few things while debugging.  Used in do_cmdline() only. */
533 struct dbg_stuff
534 {
535     int		trylevel;
536     int		force_abort;
537     except_T	*caught_stack;
538     char_u	*vv_exception;
539     char_u	*vv_throwpoint;
540     int		did_emsg;
541     int		got_int;
542     int		did_throw;
543     int		need_rethrow;
544     int		check_cstack;
545     except_T	*current_exception;
546 };
547 
548 static void save_dbg_stuff(struct dbg_stuff *dsp);
549 static void restore_dbg_stuff(struct dbg_stuff *dsp);
550 
551     static void
552 save_dbg_stuff(struct dbg_stuff *dsp)
553 {
554     dsp->trylevel	= trylevel;		trylevel = 0;
555     dsp->force_abort	= force_abort;		force_abort = FALSE;
556     dsp->caught_stack	= caught_stack;		caught_stack = NULL;
557     dsp->vv_exception	= v_exception(NULL);
558     dsp->vv_throwpoint	= v_throwpoint(NULL);
559 
560     /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
561     dsp->did_emsg	= did_emsg;		did_emsg     = FALSE;
562     dsp->got_int	= got_int;		got_int	     = FALSE;
563     dsp->did_throw	= did_throw;		did_throw    = FALSE;
564     dsp->need_rethrow	= need_rethrow;		need_rethrow = FALSE;
565     dsp->check_cstack	= check_cstack;		check_cstack = FALSE;
566     dsp->current_exception = current_exception;	current_exception = NULL;
567 }
568 
569     static void
570 restore_dbg_stuff(struct dbg_stuff *dsp)
571 {
572     suppress_errthrow = FALSE;
573     trylevel = dsp->trylevel;
574     force_abort = dsp->force_abort;
575     caught_stack = dsp->caught_stack;
576     (void)v_exception(dsp->vv_exception);
577     (void)v_throwpoint(dsp->vv_throwpoint);
578     did_emsg = dsp->did_emsg;
579     got_int = dsp->got_int;
580     did_throw = dsp->did_throw;
581     need_rethrow = dsp->need_rethrow;
582     check_cstack = dsp->check_cstack;
583     current_exception = dsp->current_exception;
584 }
585 #endif
586 
587 /*
588  * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
589  * command is given.
590  */
591     void
592 do_exmode(
593     int		improved)	    /* TRUE for "improved Ex" mode */
594 {
595     int		save_msg_scroll;
596     int		prev_msg_row;
597     linenr_T	prev_line;
598     varnumber_T	changedtick;
599 
600     if (improved)
601 	exmode_active = EXMODE_VIM;
602     else
603 	exmode_active = EXMODE_NORMAL;
604     State = NORMAL;
605 
606     /* When using ":global /pat/ visual" and then "Q" we return to continue
607      * the :global command. */
608     if (global_busy)
609 	return;
610 
611     save_msg_scroll = msg_scroll;
612     ++RedrawingDisabled;	    /* don't redisplay the window */
613     ++no_wait_return;		    /* don't wait for return */
614 #ifdef FEAT_GUI
615     /* Ignore scrollbar and mouse events in Ex mode */
616     ++hold_gui_events;
617 #endif
618 
619     MSG(_("Entering Ex mode.  Type \"visual\" to go to Normal mode."));
620     while (exmode_active)
621     {
622 	/* Check for a ":normal" command and no more characters left. */
623 	if (ex_normal_busy > 0 && typebuf.tb_len == 0)
624 	{
625 	    exmode_active = FALSE;
626 	    break;
627 	}
628 	msg_scroll = TRUE;
629 	need_wait_return = FALSE;
630 	ex_pressedreturn = FALSE;
631 	ex_no_reprint = FALSE;
632 	changedtick = CHANGEDTICK(curbuf);
633 	prev_msg_row = msg_row;
634 	prev_line = curwin->w_cursor.lnum;
635 	if (improved)
636 	{
637 	    cmdline_row = msg_row;
638 	    do_cmdline(NULL, getexline, NULL, 0);
639 	}
640 	else
641 	    do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
642 	lines_left = Rows - 1;
643 
644 	if ((prev_line != curwin->w_cursor.lnum
645 		   || changedtick != CHANGEDTICK(curbuf)) && !ex_no_reprint)
646 	{
647 	    if (curbuf->b_ml.ml_flags & ML_EMPTY)
648 		EMSG(_(e_emptybuf));
649 	    else
650 	    {
651 		if (ex_pressedreturn)
652 		{
653 		    /* go up one line, to overwrite the ":<CR>" line, so the
654 		     * output doesn't contain empty lines. */
655 		    msg_row = prev_msg_row;
656 		    if (prev_msg_row == Rows - 1)
657 			msg_row--;
658 		}
659 		msg_col = 0;
660 		print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE);
661 		msg_clr_eos();
662 	    }
663 	}
664 	else if (ex_pressedreturn && !ex_no_reprint)	/* must be at EOF */
665 	{
666 	    if (curbuf->b_ml.ml_flags & ML_EMPTY)
667 		EMSG(_(e_emptybuf));
668 	    else
669 		EMSG(_("E501: At end-of-file"));
670 	}
671     }
672 
673 #ifdef FEAT_GUI
674     --hold_gui_events;
675 #endif
676     --RedrawingDisabled;
677     --no_wait_return;
678     update_screen(CLEAR);
679     need_wait_return = FALSE;
680     msg_scroll = save_msg_scroll;
681 }
682 
683 /*
684  * Execute a simple command line.  Used for translated commands like "*".
685  */
686     int
687 do_cmdline_cmd(char_u *cmd)
688 {
689     return do_cmdline(cmd, NULL, NULL,
690 				   DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
691 }
692 
693 /*
694  * do_cmdline(): execute one Ex command line
695  *
696  * 1. Execute "cmdline" when it is not NULL.
697  *    If "cmdline" is NULL, or more lines are needed, fgetline() is used.
698  * 2. Split up in parts separated with '|'.
699  *
700  * This function can be called recursively!
701  *
702  * flags:
703  * DOCMD_VERBOSE  - The command will be included in the error message.
704  * DOCMD_NOWAIT   - Don't call wait_return() and friends.
705  * DOCMD_REPEAT   - Repeat execution until fgetline() returns NULL.
706  * DOCMD_KEYTYPED - Don't reset KeyTyped.
707  * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
708  * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
709  *
710  * return FAIL if cmdline could not be executed, OK otherwise
711  */
712     int
713 do_cmdline(
714     char_u	*cmdline,
715     char_u	*(*fgetline)(int, void *, int),
716     void	*cookie,		/* argument for fgetline() */
717     int		flags)
718 {
719     char_u	*next_cmdline;		/* next cmd to execute */
720     char_u	*cmdline_copy = NULL;	/* copy of cmd line */
721     int		used_getline = FALSE;	/* used "fgetline" to obtain command */
722     static int	recursive = 0;		/* recursive depth */
723     int		msg_didout_before_start = 0;
724     int		count = 0;		/* line number count */
725     int		did_inc = FALSE;	/* incremented RedrawingDisabled */
726     int		retval = OK;
727 #ifdef FEAT_EVAL
728     struct condstack cstack;		/* conditional stack */
729     garray_T	lines_ga;		/* keep lines for ":while"/":for" */
730     int		current_line = 0;	/* active line in lines_ga */
731     char_u	*fname = NULL;		/* function or script name */
732     linenr_T	*breakpoint = NULL;	/* ptr to breakpoint field in cookie */
733     int		*dbg_tick = NULL;	/* ptr to dbg_tick field in cookie */
734     struct dbg_stuff debug_saved;	/* saved things for debug mode */
735     int		initial_trylevel;
736     struct msglist	**saved_msg_list = NULL;
737     struct msglist	*private_msg_list;
738 
739     /* "fgetline" and "cookie" passed to do_one_cmd() */
740     char_u	*(*cmd_getline)(int, void *, int);
741     void	*cmd_cookie;
742     struct loop_cookie cmd_loop_cookie;
743     void	*real_cookie;
744     int		getline_is_func;
745 #else
746 # define cmd_getline fgetline
747 # define cmd_cookie cookie
748 #endif
749     static int	call_depth = 0;		/* recursiveness */
750 
751 #ifdef FEAT_EVAL
752     /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
753      * location for storing error messages to be converted to an exception.
754      * This ensures that the do_errthrow() call in do_one_cmd() does not
755      * combine the messages stored by an earlier invocation of do_one_cmd()
756      * with the command name of the later one.  This would happen when
757      * BufWritePost autocommands are executed after a write error. */
758     saved_msg_list = msg_list;
759     msg_list = &private_msg_list;
760     private_msg_list = NULL;
761 #endif
762 
763     /* It's possible to create an endless loop with ":execute", catch that
764      * here.  The value of 200 allows nested function calls, ":source", etc.
765      * Allow 200 or 'maxfuncdepth', whatever is larger. */
766     if (call_depth >= 200
767 #ifdef FEAT_EVAL
768 	    && call_depth >= p_mfd
769 #endif
770 	    )
771     {
772 	EMSG(_("E169: Command too recursive"));
773 #ifdef FEAT_EVAL
774 	/* When converting to an exception, we do not include the command name
775 	 * since this is not an error of the specific command. */
776 	do_errthrow((struct condstack *)NULL, (char_u *)NULL);
777 	msg_list = saved_msg_list;
778 #endif
779 	return FAIL;
780     }
781     ++call_depth;
782 
783 #ifdef FEAT_EVAL
784     cstack.cs_idx = -1;
785     cstack.cs_looplevel = 0;
786     cstack.cs_trylevel = 0;
787     cstack.cs_emsg_silent_list = NULL;
788     cstack.cs_lflags = 0;
789     ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
790 
791     real_cookie = getline_cookie(fgetline, cookie);
792 
793     /* Inside a function use a higher nesting level. */
794     getline_is_func = getline_equal(fgetline, cookie, get_func_line);
795     if (getline_is_func && ex_nesting_level == func_level(real_cookie))
796 	++ex_nesting_level;
797 
798     /* Get the function or script name and the address where the next breakpoint
799      * line and the debug tick for a function or script are stored. */
800     if (getline_is_func)
801     {
802 	fname = func_name(real_cookie);
803 	breakpoint = func_breakpoint(real_cookie);
804 	dbg_tick = func_dbg_tick(real_cookie);
805     }
806     else if (getline_equal(fgetline, cookie, getsourceline))
807     {
808 	fname = sourcing_name;
809 	breakpoint = source_breakpoint(real_cookie);
810 	dbg_tick = source_dbg_tick(real_cookie);
811     }
812 
813     /*
814      * Initialize "force_abort"  and "suppress_errthrow" at the top level.
815      */
816     if (!recursive)
817     {
818 	force_abort = FALSE;
819 	suppress_errthrow = FALSE;
820     }
821 
822     /*
823      * If requested, store and reset the global values controlling the
824      * exception handling (used when debugging).  Otherwise clear it to avoid
825      * a bogus compiler warning when the optimizer uses inline functions...
826      */
827     if (flags & DOCMD_EXCRESET)
828 	save_dbg_stuff(&debug_saved);
829     else
830 	vim_memset(&debug_saved, 0, sizeof(debug_saved));
831 
832     initial_trylevel = trylevel;
833 
834     /*
835      * "did_throw" will be set to TRUE when an exception is being thrown.
836      */
837     did_throw = FALSE;
838 #endif
839     /*
840      * "did_emsg" will be set to TRUE when emsg() is used, in which case we
841      * cancel the whole command line, and any if/endif or loop.
842      * If force_abort is set, we cancel everything.
843      */
844     did_emsg = FALSE;
845 
846     /*
847      * KeyTyped is only set when calling vgetc().  Reset it here when not
848      * calling vgetc() (sourced command lines).
849      */
850     if (!(flags & DOCMD_KEYTYPED)
851 			       && !getline_equal(fgetline, cookie, getexline))
852 	KeyTyped = FALSE;
853 
854     /*
855      * Continue executing command lines:
856      * - when inside an ":if", ":while" or ":for"
857      * - for multiple commands on one line, separated with '|'
858      * - when repeating until there are no more lines (for ":source")
859      */
860     next_cmdline = cmdline;
861     do
862     {
863 #ifdef FEAT_EVAL
864 	getline_is_func = getline_equal(fgetline, cookie, get_func_line);
865 #endif
866 
867 	/* stop skipping cmds for an error msg after all endif/while/for */
868 	if (next_cmdline == NULL
869 #ifdef FEAT_EVAL
870 		&& !force_abort
871 		&& cstack.cs_idx < 0
872 		&& !(getline_is_func && func_has_abort(real_cookie))
873 #endif
874 							)
875 	    did_emsg = FALSE;
876 
877 	/*
878 	 * 1. If repeating a line in a loop, get a line from lines_ga.
879 	 * 2. If no line given: Get an allocated line with fgetline().
880 	 * 3. If a line is given: Make a copy, so we can mess with it.
881 	 */
882 
883 #ifdef FEAT_EVAL
884 	/* 1. If repeating, get a previous line from lines_ga. */
885 	if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
886 	{
887 	    /* Each '|' separated command is stored separately in lines_ga, to
888 	     * be able to jump to it.  Don't use next_cmdline now. */
889 	    vim_free(cmdline_copy);
890 	    cmdline_copy = NULL;
891 
892 	    /* Check if a function has returned or, unless it has an unclosed
893 	     * try conditional, aborted. */
894 	    if (getline_is_func)
895 	    {
896 # ifdef FEAT_PROFILE
897 		if (do_profiling == PROF_YES)
898 		    func_line_end(real_cookie);
899 # endif
900 		if (func_has_ended(real_cookie))
901 		{
902 		    retval = FAIL;
903 		    break;
904 		}
905 	    }
906 #ifdef FEAT_PROFILE
907 	    else if (do_profiling == PROF_YES
908 			    && getline_equal(fgetline, cookie, getsourceline))
909 		script_line_end();
910 #endif
911 
912 	    /* Check if a sourced file hit a ":finish" command. */
913 	    if (source_finished(fgetline, cookie))
914 	    {
915 		retval = FAIL;
916 		break;
917 	    }
918 
919 	    /* If breakpoints have been added/deleted need to check for it. */
920 	    if (breakpoint != NULL && dbg_tick != NULL
921 						   && *dbg_tick != debug_tick)
922 	    {
923 		*breakpoint = dbg_find_breakpoint(
924 				getline_equal(fgetline, cookie, getsourceline),
925 							fname, sourcing_lnum);
926 		*dbg_tick = debug_tick;
927 	    }
928 
929 	    next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
930 	    sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
931 
932 	    /* Did we encounter a breakpoint? */
933 	    if (breakpoint != NULL && *breakpoint != 0
934 					      && *breakpoint <= sourcing_lnum)
935 	    {
936 		dbg_breakpoint(fname, sourcing_lnum);
937 		/* Find next breakpoint. */
938 		*breakpoint = dbg_find_breakpoint(
939 			       getline_equal(fgetline, cookie, getsourceline),
940 							fname, sourcing_lnum);
941 		*dbg_tick = debug_tick;
942 	    }
943 # ifdef FEAT_PROFILE
944 	    if (do_profiling == PROF_YES)
945 	    {
946 		if (getline_is_func)
947 		    func_line_start(real_cookie);
948 		else if (getline_equal(fgetline, cookie, getsourceline))
949 		    script_line_start();
950 	    }
951 # endif
952 	}
953 
954 	if (cstack.cs_looplevel > 0)
955 	{
956 	    /* Inside a while/for loop we need to store the lines and use them
957 	     * again.  Pass a different "fgetline" function to do_one_cmd()
958 	     * below, so that it stores lines in or reads them from
959 	     * "lines_ga".  Makes it possible to define a function inside a
960 	     * while/for loop. */
961 	    cmd_getline = get_loop_line;
962 	    cmd_cookie = (void *)&cmd_loop_cookie;
963 	    cmd_loop_cookie.lines_gap = &lines_ga;
964 	    cmd_loop_cookie.current_line = current_line;
965 	    cmd_loop_cookie.getline = fgetline;
966 	    cmd_loop_cookie.cookie = cookie;
967 	    cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
968 	}
969 	else
970 	{
971 	    cmd_getline = fgetline;
972 	    cmd_cookie = cookie;
973 	}
974 #endif
975 
976 	/* 2. If no line given, get an allocated line with fgetline(). */
977 	if (next_cmdline == NULL)
978 	{
979 	    /*
980 	     * Need to set msg_didout for the first line after an ":if",
981 	     * otherwise the ":if" will be overwritten.
982 	     */
983 	    if (count == 1 && getline_equal(fgetline, cookie, getexline))
984 		msg_didout = TRUE;
985 	    if (fgetline == NULL || (next_cmdline = fgetline(':', cookie,
986 #ifdef FEAT_EVAL
987 		    cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
988 #else
989 		    0
990 #endif
991 			    )) == NULL)
992 	    {
993 		/* Don't call wait_return for aborted command line.  The NULL
994 		 * returned for the end of a sourced file or executed function
995 		 * doesn't do this. */
996 		if (KeyTyped && !(flags & DOCMD_REPEAT))
997 		    need_wait_return = FALSE;
998 		retval = FAIL;
999 		break;
1000 	    }
1001 	    used_getline = TRUE;
1002 
1003 	    /*
1004 	     * Keep the first typed line.  Clear it when more lines are typed.
1005 	     */
1006 	    if (flags & DOCMD_KEEPLINE)
1007 	    {
1008 		vim_free(repeat_cmdline);
1009 		if (count == 0)
1010 		    repeat_cmdline = vim_strsave(next_cmdline);
1011 		else
1012 		    repeat_cmdline = NULL;
1013 	    }
1014 	}
1015 
1016 	/* 3. Make a copy of the command so we can mess with it. */
1017 	else if (cmdline_copy == NULL)
1018 	{
1019 	    next_cmdline = vim_strsave(next_cmdline);
1020 	    if (next_cmdline == NULL)
1021 	    {
1022 		EMSG(_(e_outofmem));
1023 		retval = FAIL;
1024 		break;
1025 	    }
1026 	}
1027 	cmdline_copy = next_cmdline;
1028 
1029 #ifdef FEAT_EVAL
1030 	/*
1031 	 * Save the current line when inside a ":while" or ":for", and when
1032 	 * the command looks like a ":while" or ":for", because we may need it
1033 	 * later.  When there is a '|' and another command, it is stored
1034 	 * separately, because we need to be able to jump back to it from an
1035 	 * :endwhile/:endfor.
1036 	 */
1037 	if (current_line == lines_ga.ga_len
1038 		&& (cstack.cs_looplevel || has_loop_cmd(next_cmdline)))
1039 	{
1040 	    if (store_loop_line(&lines_ga, next_cmdline) == FAIL)
1041 	    {
1042 		retval = FAIL;
1043 		break;
1044 	    }
1045 	}
1046 	did_endif = FALSE;
1047 #endif
1048 
1049 	if (count++ == 0)
1050 	{
1051 	    /*
1052 	     * All output from the commands is put below each other, without
1053 	     * waiting for a return. Don't do this when executing commands
1054 	     * from a script or when being called recursive (e.g. for ":e
1055 	     * +command file").
1056 	     */
1057 	    if (!(flags & DOCMD_NOWAIT) && !recursive)
1058 	    {
1059 		msg_didout_before_start = msg_didout;
1060 		msg_didany = FALSE; /* no output yet */
1061 		msg_start();
1062 		msg_scroll = TRUE;  /* put messages below each other */
1063 		++no_wait_return;   /* don't wait for return until finished */
1064 		++RedrawingDisabled;
1065 		did_inc = TRUE;
1066 	    }
1067 	}
1068 
1069 	if (p_verbose >= 15 && sourcing_name != NULL)
1070 	{
1071 	    ++no_wait_return;
1072 	    verbose_enter_scroll();
1073 
1074 	    smsg((char_u *)_("line %ld: %s"),
1075 					   (long)sourcing_lnum, cmdline_copy);
1076 	    if (msg_silent == 0)
1077 		msg_puts((char_u *)"\n");   /* don't overwrite this */
1078 
1079 	    verbose_leave_scroll();
1080 	    --no_wait_return;
1081 	}
1082 
1083 	/*
1084 	 * 2. Execute one '|' separated command.
1085 	 *    do_one_cmd() will return NULL if there is no trailing '|'.
1086 	 *    "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1087 	 */
1088 	++recursive;
1089 	next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1090 #ifdef FEAT_EVAL
1091 				&cstack,
1092 #endif
1093 				cmd_getline, cmd_cookie);
1094 	--recursive;
1095 
1096 #ifdef FEAT_EVAL
1097 	if (cmd_cookie == (void *)&cmd_loop_cookie)
1098 	    /* Use "current_line" from "cmd_loop_cookie", it may have been
1099 	     * incremented when defining a function. */
1100 	    current_line = cmd_loop_cookie.current_line;
1101 #endif
1102 
1103 	if (next_cmdline == NULL)
1104 	{
1105 	    vim_free(cmdline_copy);
1106 	    cmdline_copy = NULL;
1107 #ifdef FEAT_CMDHIST
1108 	    /*
1109 	     * If the command was typed, remember it for the ':' register.
1110 	     * Do this AFTER executing the command to make :@: work.
1111 	     */
1112 	    if (getline_equal(fgetline, cookie, getexline)
1113 						  && new_last_cmdline != NULL)
1114 	    {
1115 		vim_free(last_cmdline);
1116 		last_cmdline = new_last_cmdline;
1117 		new_last_cmdline = NULL;
1118 	    }
1119 #endif
1120 	}
1121 	else
1122 	{
1123 	    /* need to copy the command after the '|' to cmdline_copy, for the
1124 	     * next do_one_cmd() */
1125 	    STRMOVE(cmdline_copy, next_cmdline);
1126 	    next_cmdline = cmdline_copy;
1127 	}
1128 
1129 
1130 #ifdef FEAT_EVAL
1131 	/* reset did_emsg for a function that is not aborted by an error */
1132 	if (did_emsg && !force_abort
1133 		&& getline_equal(fgetline, cookie, get_func_line)
1134 					      && !func_has_abort(real_cookie))
1135 	    did_emsg = FALSE;
1136 
1137 	if (cstack.cs_looplevel > 0)
1138 	{
1139 	    ++current_line;
1140 
1141 	    /*
1142 	     * An ":endwhile", ":endfor" and ":continue" is handled here.
1143 	     * If we were executing commands, jump back to the ":while" or
1144 	     * ":for".
1145 	     * If we were not executing commands, decrement cs_looplevel.
1146 	     */
1147 	    if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
1148 	    {
1149 		cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
1150 
1151 		/* Jump back to the matching ":while" or ":for".  Be careful
1152 		 * not to use a cs_line[] from an entry that isn't a ":while"
1153 		 * or ":for": It would make "current_line" invalid and can
1154 		 * cause a crash. */
1155 		if (!did_emsg && !got_int && !did_throw
1156 			&& cstack.cs_idx >= 0
1157 			&& (cstack.cs_flags[cstack.cs_idx]
1158 						      & (CSF_WHILE | CSF_FOR))
1159 			&& cstack.cs_line[cstack.cs_idx] >= 0
1160 			&& (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1161 		{
1162 		    current_line = cstack.cs_line[cstack.cs_idx];
1163 						/* remember we jumped there */
1164 		    cstack.cs_lflags |= CSL_HAD_LOOP;
1165 		    line_breakcheck();		/* check if CTRL-C typed */
1166 
1167 		    /* Check for the next breakpoint at or after the ":while"
1168 		     * or ":for". */
1169 		    if (breakpoint != NULL)
1170 		    {
1171 			*breakpoint = dbg_find_breakpoint(
1172 			       getline_equal(fgetline, cookie, getsourceline),
1173 									fname,
1174 			   ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1175 			*dbg_tick = debug_tick;
1176 		    }
1177 		}
1178 		else
1179 		{
1180 		    /* can only get here with ":endwhile" or ":endfor" */
1181 		    if (cstack.cs_idx >= 0)
1182 			rewind_conditionals(&cstack, cstack.cs_idx - 1,
1183 				   CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
1184 		}
1185 	    }
1186 
1187 	    /*
1188 	     * For a ":while" or ":for" we need to remember the line number.
1189 	     */
1190 	    else if (cstack.cs_lflags & CSL_HAD_LOOP)
1191 	    {
1192 		cstack.cs_lflags &= ~CSL_HAD_LOOP;
1193 		cstack.cs_line[cstack.cs_idx] = current_line - 1;
1194 	    }
1195 	}
1196 
1197 	/*
1198 	 * When not inside any ":while" loop, clear remembered lines.
1199 	 */
1200 	if (cstack.cs_looplevel == 0)
1201 	{
1202 	    if (lines_ga.ga_len > 0)
1203 	    {
1204 		sourcing_lnum =
1205 		       ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1206 		free_cmdlines(&lines_ga);
1207 	    }
1208 	    current_line = 0;
1209 	}
1210 
1211 	/*
1212 	 * A ":finally" makes did_emsg, got_int, and did_throw pending for
1213 	 * being restored at the ":endtry".  Reset them here and set the
1214 	 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
1215 	 * This includes the case where a missing ":endif", ":endwhile" or
1216 	 * ":endfor" was detected by the ":finally" itself.
1217 	 */
1218 	if (cstack.cs_lflags & CSL_HAD_FINA)
1219 	{
1220 	    cstack.cs_lflags &= ~CSL_HAD_FINA;
1221 	    report_make_pending(cstack.cs_pending[cstack.cs_idx]
1222 		    & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1223 		    did_throw ? (void *)current_exception : NULL);
1224 	    did_emsg = got_int = did_throw = FALSE;
1225 	    cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1226 	}
1227 
1228 	/* Update global "trylevel" for recursive calls to do_cmdline() from
1229 	 * within this loop. */
1230 	trylevel = initial_trylevel + cstack.cs_trylevel;
1231 
1232 	/*
1233 	 * If the outermost try conditional (across function calls and sourced
1234 	 * files) is aborted because of an error, an interrupt, or an uncaught
1235 	 * exception, cancel everything.  If it is left normally, reset
1236 	 * force_abort to get the non-EH compatible abortion behavior for
1237 	 * the rest of the script.
1238 	 */
1239 	if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1240 	    force_abort = FALSE;
1241 
1242 	/* Convert an interrupt to an exception if appropriate. */
1243 	(void)do_intthrow(&cstack);
1244 #endif /* FEAT_EVAL */
1245 
1246     }
1247     /*
1248      * Continue executing command lines when:
1249      * - no CTRL-C typed, no aborting error, no exception thrown or try
1250      *   conditionals need to be checked for executing finally clauses or
1251      *   catching an interrupt exception
1252      * - didn't get an error message or lines are not typed
1253      * - there is a command after '|', inside a :if, :while, :for or :try, or
1254      *   looping for ":source" command or function call.
1255      */
1256     while (!((got_int
1257 #ifdef FEAT_EVAL
1258 		    || (did_emsg && force_abort) || did_throw
1259 #endif
1260 	     )
1261 #ifdef FEAT_EVAL
1262 		&& cstack.cs_trylevel == 0
1263 #endif
1264 	    )
1265 	    && !(did_emsg
1266 #ifdef FEAT_EVAL
1267 		/* Keep going when inside try/catch, so that the error can be
1268 		 * deal with, except when it is a syntax error, it may cause
1269 		 * the :endtry to be missed. */
1270 		&& (cstack.cs_trylevel == 0 || did_emsg_syntax)
1271 #endif
1272 		&& used_getline
1273 			    && (getline_equal(fgetline, cookie, getexmodeline)
1274 			       || getline_equal(fgetline, cookie, getexline)))
1275 	    && (next_cmdline != NULL
1276 #ifdef FEAT_EVAL
1277 			|| cstack.cs_idx >= 0
1278 #endif
1279 			|| (flags & DOCMD_REPEAT)));
1280 
1281     vim_free(cmdline_copy);
1282     did_emsg_syntax = FALSE;
1283 #ifdef FEAT_EVAL
1284     free_cmdlines(&lines_ga);
1285     ga_clear(&lines_ga);
1286 
1287     if (cstack.cs_idx >= 0)
1288     {
1289 	/*
1290 	 * If a sourced file or executed function ran to its end, report the
1291 	 * unclosed conditional.
1292 	 */
1293 	if (!got_int && !did_throw
1294 		&& ((getline_equal(fgetline, cookie, getsourceline)
1295 			&& !source_finished(fgetline, cookie))
1296 		    || (getline_equal(fgetline, cookie, get_func_line)
1297 					    && !func_has_ended(real_cookie))))
1298 	{
1299 	    if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1300 		EMSG(_(e_endtry));
1301 	    else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1302 		EMSG(_(e_endwhile));
1303 	    else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
1304 		EMSG(_(e_endfor));
1305 	    else
1306 		EMSG(_(e_endif));
1307 	}
1308 
1309 	/*
1310 	 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1311 	 * ":endtry" in a sourced file or executed function.  If the try
1312 	 * conditional is in its finally clause, ignore anything pending.
1313 	 * If it is in a catch clause, finish the caught exception.
1314 	 * Also cleanup any "cs_forinfo" structures.
1315 	 */
1316 	do
1317 	{
1318 	    int idx = cleanup_conditionals(&cstack, 0, TRUE);
1319 
1320 	    if (idx >= 0)
1321 		--idx;	    /* remove try block not in its finally clause */
1322 	    rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
1323 							&cstack.cs_looplevel);
1324 	}
1325 	while (cstack.cs_idx >= 0);
1326 	trylevel = initial_trylevel;
1327     }
1328 
1329     /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
1330      * lack was reported above and the error message is to be converted to an
1331      * exception, do this now after rewinding the cstack. */
1332     do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line)
1333 				  ? (char_u *)"endfunction" : (char_u *)NULL);
1334 
1335     if (trylevel == 0)
1336     {
1337 	/*
1338 	 * When an exception is being thrown out of the outermost try
1339 	 * conditional, discard the uncaught exception, disable the conversion
1340 	 * of interrupts or errors to exceptions, and ensure that no more
1341 	 * commands are executed.
1342 	 */
1343 	if (did_throw)
1344 	{
1345 	    void	*p = NULL;
1346 	    char_u	*saved_sourcing_name;
1347 	    int		saved_sourcing_lnum;
1348 	    struct msglist	*messages = NULL, *next;
1349 
1350 	    /*
1351 	     * If the uncaught exception is a user exception, report it as an
1352 	     * error.  If it is an error exception, display the saved error
1353 	     * message now.  For an interrupt exception, do nothing; the
1354 	     * interrupt message is given elsewhere.
1355 	     */
1356 	    switch (current_exception->type)
1357 	    {
1358 		case ET_USER:
1359 		    vim_snprintf((char *)IObuff, IOSIZE,
1360 			    _("E605: Exception not caught: %s"),
1361 			    current_exception->value);
1362 		    p = vim_strsave(IObuff);
1363 		    break;
1364 		case ET_ERROR:
1365 		    messages = current_exception->messages;
1366 		    current_exception->messages = NULL;
1367 		    break;
1368 		case ET_INTERRUPT:
1369 		    break;
1370 	    }
1371 
1372 	    saved_sourcing_name = sourcing_name;
1373 	    saved_sourcing_lnum = sourcing_lnum;
1374 	    sourcing_name = current_exception->throw_name;
1375 	    sourcing_lnum = current_exception->throw_lnum;
1376 	    current_exception->throw_name = NULL;
1377 
1378 	    discard_current_exception();	/* uses IObuff if 'verbose' */
1379 	    suppress_errthrow = TRUE;
1380 	    force_abort = TRUE;
1381 
1382 	    if (messages != NULL)
1383 	    {
1384 		do
1385 		{
1386 		    next = messages->next;
1387 		    emsg(messages->msg);
1388 		    vim_free(messages->msg);
1389 		    vim_free(messages);
1390 		    messages = next;
1391 		}
1392 		while (messages != NULL);
1393 	    }
1394 	    else if (p != NULL)
1395 	    {
1396 		emsg(p);
1397 		vim_free(p);
1398 	    }
1399 	    vim_free(sourcing_name);
1400 	    sourcing_name = saved_sourcing_name;
1401 	    sourcing_lnum = saved_sourcing_lnum;
1402 	}
1403 
1404 	/*
1405 	 * On an interrupt or an aborting error not converted to an exception,
1406 	 * disable the conversion of errors to exceptions.  (Interrupts are not
1407 	 * converted any more, here.) This enables also the interrupt message
1408 	 * when force_abort is set and did_emsg unset in case of an interrupt
1409 	 * from a finally clause after an error.
1410 	 */
1411 	else if (got_int || (did_emsg && force_abort))
1412 	    suppress_errthrow = TRUE;
1413     }
1414 
1415     /*
1416      * The current cstack will be freed when do_cmdline() returns.  An uncaught
1417      * exception will have to be rethrown in the previous cstack.  If a function
1418      * has just returned or a script file was just finished and the previous
1419      * cstack belongs to the same function or, respectively, script file, it
1420      * will have to be checked for finally clauses to be executed due to the
1421      * ":return" or ":finish".  This is done in do_one_cmd().
1422      */
1423     if (did_throw)
1424 	need_rethrow = TRUE;
1425     if ((getline_equal(fgetline, cookie, getsourceline)
1426 		&& ex_nesting_level > source_level(real_cookie))
1427 	    || (getline_equal(fgetline, cookie, get_func_line)
1428 		&& ex_nesting_level > func_level(real_cookie) + 1))
1429     {
1430 	if (!did_throw)
1431 	    check_cstack = TRUE;
1432     }
1433     else
1434     {
1435 	/* When leaving a function, reduce nesting level. */
1436 	if (getline_equal(fgetline, cookie, get_func_line))
1437 	    --ex_nesting_level;
1438 	/*
1439 	 * Go to debug mode when returning from a function in which we are
1440 	 * single-stepping.
1441 	 */
1442 	if ((getline_equal(fgetline, cookie, getsourceline)
1443 		    || getline_equal(fgetline, cookie, get_func_line))
1444 		&& ex_nesting_level + 1 <= debug_break_level)
1445 	    do_debug(getline_equal(fgetline, cookie, getsourceline)
1446 		    ? (char_u *)_("End of sourced file")
1447 		    : (char_u *)_("End of function"));
1448     }
1449 
1450     /*
1451      * Restore the exception environment (done after returning from the
1452      * debugger).
1453      */
1454     if (flags & DOCMD_EXCRESET)
1455 	restore_dbg_stuff(&debug_saved);
1456 
1457     msg_list = saved_msg_list;
1458 #endif /* FEAT_EVAL */
1459 
1460     /*
1461      * If there was too much output to fit on the command line, ask the user to
1462      * hit return before redrawing the screen. With the ":global" command we do
1463      * this only once after the command is finished.
1464      */
1465     if (did_inc)
1466     {
1467 	--RedrawingDisabled;
1468 	--no_wait_return;
1469 	msg_scroll = FALSE;
1470 
1471 	/*
1472 	 * When just finished an ":if"-":else" which was typed, no need to
1473 	 * wait for hit-return.  Also for an error situation.
1474 	 */
1475 	if (retval == FAIL
1476 #ifdef FEAT_EVAL
1477 		|| (did_endif && KeyTyped && !did_emsg)
1478 #endif
1479 					    )
1480 	{
1481 	    need_wait_return = FALSE;
1482 	    msg_didany = FALSE;		/* don't wait when restarting edit */
1483 	}
1484 	else if (need_wait_return)
1485 	{
1486 	    /*
1487 	     * The msg_start() above clears msg_didout. The wait_return we do
1488 	     * here should not overwrite the command that may be shown before
1489 	     * doing that.
1490 	     */
1491 	    msg_didout |= msg_didout_before_start;
1492 	    wait_return(FALSE);
1493 	}
1494     }
1495 
1496 #ifdef FEAT_EVAL
1497     did_endif = FALSE;  /* in case do_cmdline used recursively */
1498 #else
1499     /*
1500      * Reset if_level, in case a sourced script file contains more ":if" than
1501      * ":endif" (could be ":if x | foo | endif").
1502      */
1503     if_level = 0;
1504 #endif
1505 
1506     --call_depth;
1507     return retval;
1508 }
1509 
1510 #ifdef FEAT_EVAL
1511 /*
1512  * Obtain a line when inside a ":while" or ":for" loop.
1513  */
1514     static char_u *
1515 get_loop_line(int c, void *cookie, int indent)
1516 {
1517     struct loop_cookie	*cp = (struct loop_cookie *)cookie;
1518     wcmd_T		*wp;
1519     char_u		*line;
1520 
1521     if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1522     {
1523 	if (cp->repeating)
1524 	    return NULL;	/* trying to read past ":endwhile"/":endfor" */
1525 
1526 	/* First time inside the ":while"/":for": get line normally. */
1527 	if (cp->getline == NULL)
1528 	    line = getcmdline(c, 0L, indent);
1529 	else
1530 	    line = cp->getline(c, cp->cookie, indent);
1531 	if (line != NULL && store_loop_line(cp->lines_gap, line) == OK)
1532 	    ++cp->current_line;
1533 
1534 	return line;
1535     }
1536 
1537     KeyTyped = FALSE;
1538     ++cp->current_line;
1539     wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1540     sourcing_lnum = wp->lnum;
1541     return vim_strsave(wp->line);
1542 }
1543 
1544 /*
1545  * Store a line in "gap" so that a ":while" loop can execute it again.
1546  */
1547     static int
1548 store_loop_line(garray_T *gap, char_u *line)
1549 {
1550     if (ga_grow(gap, 1) == FAIL)
1551 	return FAIL;
1552     ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1553     ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1554     ++gap->ga_len;
1555     return OK;
1556 }
1557 
1558 /*
1559  * Free the lines stored for a ":while" or ":for" loop.
1560  */
1561     static void
1562 free_cmdlines(garray_T *gap)
1563 {
1564     while (gap->ga_len > 0)
1565     {
1566 	vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1567 	--gap->ga_len;
1568     }
1569 }
1570 #endif
1571 
1572 /*
1573  * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals
1574  * "func".  * Otherwise return TRUE when "fgetline" equals "func".
1575  */
1576     int
1577 getline_equal(
1578     char_u	*(*fgetline)(int, void *, int),
1579     void	*cookie UNUSED,		/* argument for fgetline() */
1580     char_u	*(*func)(int, void *, int))
1581 {
1582 #ifdef FEAT_EVAL
1583     char_u		*(*gp)(int, void *, int);
1584     struct loop_cookie *cp;
1585 
1586     /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1587      * function that's originally used to obtain the lines.  This may be
1588      * nested several levels. */
1589     gp = fgetline;
1590     cp = (struct loop_cookie *)cookie;
1591     while (gp == get_loop_line)
1592     {
1593 	gp = cp->getline;
1594 	cp = cp->cookie;
1595     }
1596     return gp == func;
1597 #else
1598     return fgetline == func;
1599 #endif
1600 }
1601 
1602 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1603 /*
1604  * If "fgetline" is get_loop_line(), return the cookie used by the original
1605  * getline function.  Otherwise return "cookie".
1606  */
1607     void *
1608 getline_cookie(
1609     char_u	*(*fgetline)(int, void *, int) UNUSED,
1610     void	*cookie)		/* argument for fgetline() */
1611 {
1612 # ifdef FEAT_EVAL
1613     char_u		*(*gp)(int, void *, int);
1614     struct loop_cookie *cp;
1615 
1616     /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1617      * cookie that's originally used to obtain the lines.  This may be nested
1618      * several levels. */
1619     gp = fgetline;
1620     cp = (struct loop_cookie *)cookie;
1621     while (gp == get_loop_line)
1622     {
1623 	gp = cp->getline;
1624 	cp = cp->cookie;
1625     }
1626     return cp;
1627 # else
1628     return cookie;
1629 # endif
1630 }
1631 #endif
1632 
1633 
1634 /*
1635  * Helper function to apply an offset for buffer commands, i.e. ":bdelete",
1636  * ":bwipeout", etc.
1637  * Returns the buffer number.
1638  */
1639     static int
1640 compute_buffer_local_count(int addr_type, int lnum, int offset)
1641 {
1642     buf_T   *buf;
1643     buf_T   *nextbuf;
1644     int     count = offset;
1645 
1646     buf = firstbuf;
1647     while (buf->b_next != NULL && buf->b_fnum < lnum)
1648 	buf = buf->b_next;
1649     while (count != 0)
1650     {
1651 	count += (offset < 0) ? 1 : -1;
1652 	nextbuf = (offset < 0) ? buf->b_prev : buf->b_next;
1653 	if (nextbuf == NULL)
1654 	    break;
1655 	buf = nextbuf;
1656 	if (addr_type == ADDR_LOADED_BUFFERS)
1657 	    /* skip over unloaded buffers */
1658 	    while (buf->b_ml.ml_mfp == NULL)
1659 	    {
1660 		nextbuf = (offset < 0) ? buf->b_prev : buf->b_next;
1661 		if (nextbuf == NULL)
1662 		    break;
1663 		buf = nextbuf;
1664 	    }
1665     }
1666     /* we might have gone too far, last buffer is not loadedd */
1667     if (addr_type == ADDR_LOADED_BUFFERS)
1668 	while (buf->b_ml.ml_mfp == NULL)
1669 	{
1670 	    nextbuf = (offset >= 0) ? buf->b_prev : buf->b_next;
1671 	    if (nextbuf == NULL)
1672 		break;
1673 	    buf = nextbuf;
1674 	}
1675     return buf->b_fnum;
1676 }
1677 
1678 #ifdef FEAT_WINDOWS
1679 static int current_win_nr(win_T *win);
1680 static int current_tab_nr(tabpage_T *tab);
1681 
1682     static int
1683 current_win_nr(win_T *win)
1684 {
1685     win_T	*wp;
1686     int		nr = 0;
1687 
1688     FOR_ALL_WINDOWS(wp)
1689     {
1690 	++nr;
1691 	if (wp == win)
1692 	    break;
1693     }
1694     return nr;
1695 }
1696 
1697     static int
1698 current_tab_nr(tabpage_T *tab)
1699 {
1700     tabpage_T	*tp;
1701     int		nr = 0;
1702 
1703     FOR_ALL_TABPAGES(tp)
1704     {
1705 	++nr;
1706 	if (tp == tab)
1707 	    break;
1708     }
1709     return nr;
1710 }
1711 
1712 # define CURRENT_WIN_NR current_win_nr(curwin)
1713 # define LAST_WIN_NR current_win_nr(NULL)
1714 # define CURRENT_TAB_NR current_tab_nr(curtab)
1715 # define LAST_TAB_NR current_tab_nr(NULL)
1716 #else
1717 # define CURRENT_WIN_NR 1
1718 # define LAST_WIN_NR 1
1719 # define CURRENT_TAB_NR 1
1720 # define LAST_TAB_NR 1
1721 #endif
1722 
1723 
1724 /*
1725  * Execute one Ex command.
1726  *
1727  * If 'sourcing' is TRUE, the command will be included in the error message.
1728  *
1729  * 1. skip comment lines and leading space
1730  * 2. handle command modifiers
1731  * 3. find the command
1732  * 4. parse range
1733  * 5. Parse the command.
1734  * 6. parse arguments
1735  * 7. switch on command name
1736  *
1737  * Note: "fgetline" can be NULL.
1738  *
1739  * This function may be called recursively!
1740  */
1741 #if (_MSC_VER == 1200)
1742 /*
1743  * Avoid optimisation bug in VC++ version 6.0
1744  */
1745  #pragma optimize( "g", off )
1746 #endif
1747     static char_u *
1748 do_one_cmd(
1749     char_u		**cmdlinep,
1750     int			sourcing,
1751 #ifdef FEAT_EVAL
1752     struct condstack	*cstack,
1753 #endif
1754     char_u		*(*fgetline)(int, void *, int),
1755     void		*cookie)		/* argument for fgetline() */
1756 {
1757     char_u		*p;
1758     linenr_T		lnum;
1759     long		n;
1760     char_u		*errormsg = NULL;	/* error message */
1761     char_u		*after_modifier = NULL;
1762     exarg_T		ea;			/* Ex command arguments */
1763     long		verbose_save = -1;
1764     int			save_msg_scroll = msg_scroll;
1765     int			save_msg_silent = -1;
1766     int			did_esilent = 0;
1767 #ifdef HAVE_SANDBOX
1768     int			did_sandbox = FALSE;
1769 #endif
1770     cmdmod_T		save_cmdmod;
1771     int			ni;			/* set when Not Implemented */
1772     char_u		*cmd;
1773     int			address_count = 1;
1774 
1775     vim_memset(&ea, 0, sizeof(ea));
1776     ea.line1 = 1;
1777     ea.line2 = 1;
1778 #ifdef FEAT_EVAL
1779     ++ex_nesting_level;
1780 #endif
1781 
1782     /* When the last file has not been edited :q has to be typed twice. */
1783     if (quitmore
1784 #ifdef FEAT_EVAL
1785 	    /* avoid that a function call in 'statusline' does this */
1786 	    && !getline_equal(fgetline, cookie, get_func_line)
1787 #endif
1788 #ifdef FEAT_AUTOCMD
1789 	    /* avoid that an autocommand, e.g. QuitPre, does this */
1790 	    && !getline_equal(fgetline, cookie, getnextac)
1791 #endif
1792 	    )
1793 	--quitmore;
1794 
1795     /*
1796      * Reset browse, confirm, etc..  They are restored when returning, for
1797      * recursive calls.
1798      */
1799     save_cmdmod = cmdmod;
1800     vim_memset(&cmdmod, 0, sizeof(cmdmod));
1801 
1802     /* "#!anything" is handled like a comment. */
1803     if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!')
1804 	goto doend;
1805 
1806     /*
1807      * Repeat until no more command modifiers are found.
1808      */
1809     ea.cmd = *cmdlinep;
1810     for (;;)
1811     {
1812 /*
1813  * 1. Skip comment lines and leading white space and colons.
1814  */
1815 	while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1816 	    ++ea.cmd;
1817 
1818 	/* in ex mode, an empty line works like :+ */
1819 	if (*ea.cmd == NUL && exmode_active
1820 			&& (getline_equal(fgetline, cookie, getexmodeline)
1821 			    || getline_equal(fgetline, cookie, getexline))
1822 			&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1823 	{
1824 	    ea.cmd = (char_u *)"+";
1825 	    ex_pressedreturn = TRUE;
1826 	}
1827 
1828 	/* ignore comment and empty lines */
1829 	if (*ea.cmd == '"')
1830 	    goto doend;
1831 	if (*ea.cmd == NUL)
1832 	{
1833 	    ex_pressedreturn = TRUE;
1834 	    goto doend;
1835 	}
1836 
1837 /*
1838  * 2. Handle command modifiers.
1839  */
1840 	p = skip_range(ea.cmd, NULL);
1841 	switch (*p)
1842 	{
1843 	    /* When adding an entry, also modify cmd_exists(). */
1844 	    case 'a':	if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1845 			    break;
1846 #ifdef FEAT_WINDOWS
1847 			cmdmod.split |= WSP_ABOVE;
1848 #endif
1849 			continue;
1850 
1851 	    case 'b':	if (checkforcmd(&ea.cmd, "belowright", 3))
1852 			{
1853 #ifdef FEAT_WINDOWS
1854 			    cmdmod.split |= WSP_BELOW;
1855 #endif
1856 			    continue;
1857 			}
1858 			if (checkforcmd(&ea.cmd, "browse", 3))
1859 			{
1860 #ifdef FEAT_BROWSE_CMD
1861 			    cmdmod.browse = TRUE;
1862 #endif
1863 			    continue;
1864 			}
1865 			if (!checkforcmd(&ea.cmd, "botright", 2))
1866 			    break;
1867 #ifdef FEAT_WINDOWS
1868 			cmdmod.split |= WSP_BOT;
1869 #endif
1870 			continue;
1871 
1872 	    case 'c':	if (!checkforcmd(&ea.cmd, "confirm", 4))
1873 			    break;
1874 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1875 			cmdmod.confirm = TRUE;
1876 #endif
1877 			continue;
1878 
1879 	    case 'k':	if (checkforcmd(&ea.cmd, "keepmarks", 3))
1880 			{
1881 			    cmdmod.keepmarks = TRUE;
1882 			    continue;
1883 			}
1884 			if (checkforcmd(&ea.cmd, "keepalt", 5))
1885 			{
1886 			    cmdmod.keepalt = TRUE;
1887 			    continue;
1888 			}
1889 			if (checkforcmd(&ea.cmd, "keeppatterns", 5))
1890 			{
1891 			    cmdmod.keeppatterns = TRUE;
1892 			    continue;
1893 			}
1894 			if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1895 			    break;
1896 			cmdmod.keepjumps = TRUE;
1897 			continue;
1898 
1899 	    case 'f':	/* only accept ":filter {pat} cmd" */
1900 			{
1901 			    char_u *reg_pat;
1902 
1903 			    if (!checkforcmd(&p, "filter", 4)
1904 						|| *p == NUL || ends_excmd(*p))
1905 				break;
1906 			    if (*p == '!')
1907 			    {
1908 				cmdmod.filter_force = TRUE;
1909 				p = skipwhite(p + 1);
1910 				if (*p == NUL || ends_excmd(*p))
1911 				    break;
1912 			    }
1913 			    p = skip_vimgrep_pat(p, &reg_pat, NULL);
1914 			    if (p == NULL || *p == NUL)
1915 				break;
1916 			    cmdmod.filter_regmatch.regprog =
1917 						vim_regcomp(reg_pat, RE_MAGIC);
1918 			    if (cmdmod.filter_regmatch.regprog == NULL)
1919 				break;
1920 			    ea.cmd = p;
1921 			    continue;
1922 			}
1923 
1924 			/* ":hide" and ":hide | cmd" are not modifiers */
1925 	    case 'h':	if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1926 					       || *p == NUL || ends_excmd(*p))
1927 			    break;
1928 			ea.cmd = p;
1929 			cmdmod.hide = TRUE;
1930 			continue;
1931 
1932 	    case 'l':	if (checkforcmd(&ea.cmd, "lockmarks", 3))
1933 			{
1934 			    cmdmod.lockmarks = TRUE;
1935 			    continue;
1936 			}
1937 
1938 			if (!checkforcmd(&ea.cmd, "leftabove", 5))
1939 			    break;
1940 #ifdef FEAT_WINDOWS
1941 			cmdmod.split |= WSP_ABOVE;
1942 #endif
1943 			continue;
1944 
1945 	    case 'n':	if (checkforcmd(&ea.cmd, "noautocmd", 3))
1946 			{
1947 #ifdef FEAT_AUTOCMD
1948 			    if (cmdmod.save_ei == NULL)
1949 			    {
1950 				/* Set 'eventignore' to "all". Restore the
1951 				 * existing option value later. */
1952 				cmdmod.save_ei = vim_strsave(p_ei);
1953 				set_string_option_direct((char_u *)"ei", -1,
1954 					 (char_u *)"all", OPT_FREE, SID_NONE);
1955 			    }
1956 #endif
1957 			    continue;
1958 			}
1959 			if (!checkforcmd(&ea.cmd, "noswapfile", 3))
1960 			    break;
1961 			cmdmod.noswapfile = TRUE;
1962 			continue;
1963 
1964 	    case 'r':	if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1965 			    break;
1966 #ifdef FEAT_WINDOWS
1967 			cmdmod.split |= WSP_BELOW;
1968 #endif
1969 			continue;
1970 
1971 	    case 's':	if (checkforcmd(&ea.cmd, "sandbox", 3))
1972 			{
1973 #ifdef HAVE_SANDBOX
1974 			    if (!did_sandbox)
1975 				++sandbox;
1976 			    did_sandbox = TRUE;
1977 #endif
1978 			    continue;
1979 			}
1980 			if (!checkforcmd(&ea.cmd, "silent", 3))
1981 			    break;
1982 			if (save_msg_silent == -1)
1983 			    save_msg_silent = msg_silent;
1984 			++msg_silent;
1985 			if (*ea.cmd == '!' && !VIM_ISWHITE(ea.cmd[-1]))
1986 			{
1987 			    /* ":silent!", but not "silent !cmd" */
1988 			    ea.cmd = skipwhite(ea.cmd + 1);
1989 			    ++emsg_silent;
1990 			    ++did_esilent;
1991 			}
1992 			continue;
1993 
1994 	    case 't':	if (checkforcmd(&p, "tab", 3))
1995 			{
1996 #ifdef FEAT_WINDOWS
1997 			    long tabnr = get_address(&ea, &ea.cmd, ADDR_TABS,
1998 							    ea.skip, FALSE, 1);
1999 			    if (tabnr == MAXLNUM)
2000 				cmdmod.tab = tabpage_index(curtab) + 1;
2001 			    else
2002 			    {
2003 				if (tabnr < 0 || tabnr > LAST_TAB_NR)
2004 				{
2005 				    errormsg = (char_u *)_(e_invrange);
2006 				    goto doend;
2007 				}
2008 				cmdmod.tab = tabnr + 1;
2009 			    }
2010 			    ea.cmd = p;
2011 #endif
2012 			    continue;
2013 			}
2014 			if (!checkforcmd(&ea.cmd, "topleft", 2))
2015 			    break;
2016 #ifdef FEAT_WINDOWS
2017 			cmdmod.split |= WSP_TOP;
2018 #endif
2019 			continue;
2020 
2021 	    case 'u':	if (!checkforcmd(&ea.cmd, "unsilent", 3))
2022 			    break;
2023 			if (save_msg_silent == -1)
2024 			    save_msg_silent = msg_silent;
2025 			msg_silent = 0;
2026 			continue;
2027 
2028 	    case 'v':	if (checkforcmd(&ea.cmd, "vertical", 4))
2029 			{
2030 #ifdef FEAT_WINDOWS
2031 			    cmdmod.split |= WSP_VERT;
2032 #endif
2033 			    continue;
2034 			}
2035 			if (!checkforcmd(&p, "verbose", 4))
2036 			    break;
2037 			if (verbose_save < 0)
2038 			    verbose_save = p_verbose;
2039 			if (vim_isdigit(*ea.cmd))
2040 			    p_verbose = atoi((char *)ea.cmd);
2041 			else
2042 			    p_verbose = 1;
2043 			ea.cmd = p;
2044 			continue;
2045 	}
2046 	break;
2047     }
2048     after_modifier = ea.cmd;
2049 
2050 #ifdef FEAT_EVAL
2051     ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
2052 			 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
2053 #else
2054     ea.skip = (if_level > 0);
2055 #endif
2056 
2057 #ifdef FEAT_EVAL
2058 # ifdef FEAT_PROFILE
2059     /* Count this line for profiling if ea.skip is FALSE. */
2060     if (do_profiling == PROF_YES && !ea.skip)
2061     {
2062 	if (getline_equal(fgetline, cookie, get_func_line))
2063 	    func_line_exec(getline_cookie(fgetline, cookie));
2064 	else if (getline_equal(fgetline, cookie, getsourceline))
2065 	    script_line_exec();
2066     }
2067 #endif
2068 
2069     /* May go to debug mode.  If this happens and the ">quit" debug command is
2070      * used, throw an interrupt exception and skip the next command. */
2071     dbg_check_breakpoint(&ea);
2072     if (!ea.skip && got_int)
2073     {
2074 	ea.skip = TRUE;
2075 	(void)do_intthrow(cstack);
2076     }
2077 #endif
2078 
2079 /*
2080  * 3. Skip over the range to find the command.  Let "p" point to after it.
2081  *
2082  * We need the command to know what kind of range it uses.
2083  */
2084     cmd = ea.cmd;
2085     ea.cmd = skip_range(ea.cmd, NULL);
2086     if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
2087 	ea.cmd = skipwhite(ea.cmd + 1);
2088     p = find_command(&ea, NULL);
2089 
2090 /*
2091  * 4. parse a range specifier of the form: addr [,addr] [;addr] ..
2092  *
2093  * where 'addr' is:
2094  *
2095  * %	      (entire file)
2096  * $  [+-NUM]
2097  * 'x [+-NUM] (where x denotes a currently defined mark)
2098  * .  [+-NUM]
2099  * [+-NUM]..
2100  * NUM
2101  *
2102  * The ea.cmd pointer is updated to point to the first character following the
2103  * range spec. If an initial address is found, but no second, the upper bound
2104  * is equal to the lower.
2105  */
2106 
2107     /* ea.addr_type for user commands is set by find_ucmd */
2108     if (!IS_USER_CMDIDX(ea.cmdidx))
2109     {
2110 	if (ea.cmdidx != CMD_SIZE)
2111 	    ea.addr_type = cmdnames[(int)ea.cmdidx].cmd_addr_type;
2112 	else
2113 	    ea.addr_type = ADDR_LINES;
2114 
2115 #ifdef FEAT_WINDOWS
2116 	/* :wincmd range depends on the argument. */
2117 	if (ea.cmdidx == CMD_wincmd && p != NULL)
2118 	    get_wincmd_addr_type(skipwhite(p), &ea);
2119 #endif
2120     }
2121 
2122     /* repeat for all ',' or ';' separated addresses */
2123     ea.cmd = cmd;
2124     for (;;)
2125     {
2126 	ea.line1 = ea.line2;
2127 	switch (ea.addr_type)
2128 	{
2129 	    case ADDR_LINES:
2130 		/* default is current line number */
2131 		ea.line2 = curwin->w_cursor.lnum;
2132 		break;
2133 	    case ADDR_WINDOWS:
2134 		ea.line2 = CURRENT_WIN_NR;
2135 		break;
2136 	    case ADDR_ARGUMENTS:
2137 		ea.line2 = curwin->w_arg_idx + 1;
2138 		if (ea.line2 > ARGCOUNT)
2139 		    ea.line2 = ARGCOUNT;
2140 		break;
2141 	    case ADDR_LOADED_BUFFERS:
2142 	    case ADDR_BUFFERS:
2143 		ea.line2 = curbuf->b_fnum;
2144 		break;
2145 	    case ADDR_TABS:
2146 		ea.line2 = CURRENT_TAB_NR;
2147 		break;
2148 	    case ADDR_TABS_RELATIVE:
2149 		ea.line2 = 1;
2150 		break;
2151 #ifdef FEAT_QUICKFIX
2152 	    case ADDR_QUICKFIX:
2153 		ea.line2 = qf_get_cur_valid_idx(&ea);
2154 		break;
2155 #endif
2156 	}
2157 	ea.cmd = skipwhite(ea.cmd);
2158 	lnum = get_address(&ea, &ea.cmd, ea.addr_type, ea.skip,
2159 					  ea.addr_count == 0, address_count++);
2160 	if (ea.cmd == NULL)		    /* error detected */
2161 	    goto doend;
2162 	if (lnum == MAXLNUM)
2163 	{
2164 	    if (*ea.cmd == '%')		    /* '%' - all lines */
2165 	    {
2166 		++ea.cmd;
2167 		switch (ea.addr_type)
2168 		{
2169 		    case ADDR_LINES:
2170 			ea.line1 = 1;
2171 			ea.line2 = curbuf->b_ml.ml_line_count;
2172 			break;
2173 		    case ADDR_LOADED_BUFFERS:
2174 			{
2175 			    buf_T	*buf = firstbuf;
2176 
2177 			    while (buf->b_next != NULL
2178 						  && buf->b_ml.ml_mfp == NULL)
2179 				buf = buf->b_next;
2180 			    ea.line1 = buf->b_fnum;
2181 			    buf = lastbuf;
2182 			    while (buf->b_prev != NULL
2183 						  && buf->b_ml.ml_mfp == NULL)
2184 				buf = buf->b_prev;
2185 			    ea.line2 = buf->b_fnum;
2186 			    break;
2187 			}
2188 		    case ADDR_BUFFERS:
2189 			ea.line1 = firstbuf->b_fnum;
2190 			ea.line2 = lastbuf->b_fnum;
2191 			break;
2192 		    case ADDR_WINDOWS:
2193 		    case ADDR_TABS:
2194 			if (IS_USER_CMDIDX(ea.cmdidx))
2195 			{
2196 			    ea.line1 = 1;
2197 			    ea.line2 = ea.addr_type == ADDR_WINDOWS
2198 						  ? LAST_WIN_NR : LAST_TAB_NR;
2199 			}
2200 			else
2201 			{
2202 			    /* there is no Vim command which uses '%' and
2203 			     * ADDR_WINDOWS or ADDR_TABS */
2204 			    errormsg = (char_u *)_(e_invrange);
2205 			    goto doend;
2206 			}
2207 			break;
2208 		    case ADDR_TABS_RELATIVE:
2209 			errormsg = (char_u *)_(e_invrange);
2210 			goto doend;
2211 			break;
2212 		    case ADDR_ARGUMENTS:
2213 			if (ARGCOUNT == 0)
2214 			    ea.line1 = ea.line2 = 0;
2215 			else
2216 			{
2217 			    ea.line1 = 1;
2218 			    ea.line2 = ARGCOUNT;
2219 			}
2220 			break;
2221 #ifdef FEAT_QUICKFIX
2222 		    case ADDR_QUICKFIX:
2223 			ea.line1 = 1;
2224 			ea.line2 = qf_get_size(&ea);
2225 			if (ea.line2 == 0)
2226 			    ea.line2 = 1;
2227 			break;
2228 #endif
2229 		}
2230 		++ea.addr_count;
2231 	    }
2232 					    /* '*' - visual area */
2233 	    else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
2234 	    {
2235 		pos_T	    *fp;
2236 
2237 		if (ea.addr_type != ADDR_LINES)
2238 		{
2239 		    errormsg = (char_u *)_(e_invrange);
2240 		    goto doend;
2241 		}
2242 
2243 		++ea.cmd;
2244 		if (!ea.skip)
2245 		{
2246 		    fp = getmark('<', FALSE);
2247 		    if (check_mark(fp) == FAIL)
2248 			goto doend;
2249 		    ea.line1 = fp->lnum;
2250 		    fp = getmark('>', FALSE);
2251 		    if (check_mark(fp) == FAIL)
2252 			goto doend;
2253 		    ea.line2 = fp->lnum;
2254 		    ++ea.addr_count;
2255 		}
2256 	    }
2257 	}
2258 	else
2259 	    ea.line2 = lnum;
2260 	ea.addr_count++;
2261 
2262 	if (*ea.cmd == ';')
2263 	{
2264 	    if (!ea.skip)
2265 	    {
2266 		curwin->w_cursor.lnum = ea.line2;
2267 		/* don't leave the cursor on an illegal line or column */
2268 		check_cursor();
2269 	    }
2270 	}
2271 	else if (*ea.cmd != ',')
2272 	    break;
2273 	++ea.cmd;
2274     }
2275 
2276     /* One address given: set start and end lines */
2277     if (ea.addr_count == 1)
2278     {
2279 	ea.line1 = ea.line2;
2280 	    /* ... but only implicit: really no address given */
2281 	if (lnum == MAXLNUM)
2282 	    ea.addr_count = 0;
2283     }
2284 
2285 /*
2286  * 5. Parse the command.
2287  */
2288 
2289     /*
2290      * Skip ':' and any white space
2291      */
2292     ea.cmd = skipwhite(ea.cmd);
2293     while (*ea.cmd == ':')
2294 	ea.cmd = skipwhite(ea.cmd + 1);
2295 
2296     /*
2297      * If we got a line, but no command, then go to the line.
2298      * If we find a '|' or '\n' we set ea.nextcmd.
2299      */
2300     if (*ea.cmd == NUL || *ea.cmd == '"'
2301 			      || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
2302     {
2303 	/*
2304 	 * strange vi behaviour:
2305 	 * ":3"		jumps to line 3
2306 	 * ":3|..."	prints line 3
2307 	 * ":|"		prints current line
2308 	 */
2309 	if (ea.skip)	    /* skip this if inside :if */
2310 	    goto doend;
2311 	if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2))
2312 	{
2313 	    ea.cmdidx = CMD_print;
2314 	    ea.argt = RANGE+COUNT+TRLBAR;
2315 	    if ((errormsg = invalid_range(&ea)) == NULL)
2316 	    {
2317 		correct_range(&ea);
2318 		ex_print(&ea);
2319 	    }
2320 	}
2321 	else if (ea.addr_count != 0)
2322 	{
2323 	    if (ea.line2 > curbuf->b_ml.ml_line_count)
2324 	    {
2325 		/* With '-' in 'cpoptions' a line number past the file is an
2326 		 * error, otherwise put it at the end of the file. */
2327 		if (vim_strchr(p_cpo, CPO_MINUS) != NULL)
2328 		    ea.line2 = -1;
2329 		else
2330 		    ea.line2 = curbuf->b_ml.ml_line_count;
2331 	    }
2332 
2333 	    if (ea.line2 < 0)
2334 		errormsg = (char_u *)_(e_invrange);
2335 	    else
2336 	    {
2337 		if (ea.line2 == 0)
2338 		    curwin->w_cursor.lnum = 1;
2339 		else
2340 		    curwin->w_cursor.lnum = ea.line2;
2341 		beginline(BL_SOL | BL_FIX);
2342 	    }
2343 	}
2344 	goto doend;
2345     }
2346 
2347 #ifdef FEAT_AUTOCMD
2348     /* If this looks like an undefined user command and there are CmdUndefined
2349      * autocommands defined, trigger the matching autocommands. */
2350     if (p != NULL && ea.cmdidx == CMD_SIZE && !ea.skip
2351 	    && ASCII_ISUPPER(*ea.cmd)
2352 	    && has_cmdundefined())
2353     {
2354 	int ret;
2355 
2356 	p = ea.cmd;
2357 	while (ASCII_ISALNUM(*p))
2358 	    ++p;
2359 	p = vim_strnsave(ea.cmd, (int)(p - ea.cmd));
2360 	ret = apply_autocmds(EVENT_CMDUNDEFINED, p, p, TRUE, NULL);
2361 	vim_free(p);
2362 	/* If the autocommands did something and didn't cause an error, try
2363 	 * finding the command again. */
2364 	p = (ret && !aborting()) ? find_command(&ea, NULL) : ea.cmd;
2365     }
2366 #endif
2367 
2368 #ifdef FEAT_USR_CMDS
2369     if (p == NULL)
2370     {
2371 	if (!ea.skip)
2372 	    errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
2373 	goto doend;
2374     }
2375     /* Check for wrong commands. */
2376     if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78
2377 	    && !IS_USER_CMDIDX(ea.cmdidx))
2378     {
2379 	errormsg = uc_fun_cmd();
2380 	goto doend;
2381     }
2382 #endif
2383     if (ea.cmdidx == CMD_SIZE)
2384     {
2385 	if (!ea.skip)
2386 	{
2387 	    STRCPY(IObuff, _("E492: Not an editor command"));
2388 	    if (!sourcing)
2389 	    {
2390 		/* If the modifier was parsed OK the error must be in the
2391 		 * following command */
2392 		if (after_modifier != NULL)
2393 		    append_command(after_modifier);
2394 		else
2395 		    append_command(*cmdlinep);
2396 	    }
2397 	    errormsg = IObuff;
2398 	    did_emsg_syntax = TRUE;
2399 	}
2400 	goto doend;
2401     }
2402 
2403     ni = (!IS_USER_CMDIDX(ea.cmdidx)
2404 	    && (cmdnames[ea.cmdidx].cmd_func == ex_ni
2405 #ifdef HAVE_EX_SCRIPT_NI
2406 	     || cmdnames[ea.cmdidx].cmd_func == ex_script_ni
2407 #endif
2408 	     ));
2409 
2410 #ifndef FEAT_EVAL
2411     /*
2412      * When the expression evaluation is disabled, recognize the ":if" and
2413      * ":endif" commands and ignore everything in between it.
2414      */
2415     if (ea.cmdidx == CMD_if)
2416 	++if_level;
2417     if (if_level)
2418     {
2419 	if (ea.cmdidx == CMD_endif)
2420 	    --if_level;
2421 	goto doend;
2422     }
2423 
2424 #endif
2425 
2426     /* forced commands */
2427     if (*p == '!' && ea.cmdidx != CMD_substitute
2428 	    && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic)
2429     {
2430 	++p;
2431 	ea.forceit = TRUE;
2432     }
2433     else
2434 	ea.forceit = FALSE;
2435 
2436 /*
2437  * 6. Parse arguments.
2438  */
2439     if (!IS_USER_CMDIDX(ea.cmdidx))
2440 	ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
2441 
2442     if (!ea.skip)
2443     {
2444 #ifdef HAVE_SANDBOX
2445 	if (sandbox != 0 && !(ea.argt & SBOXOK))
2446 	{
2447 	    /* Command not allowed in sandbox. */
2448 	    errormsg = (char_u *)_(e_sandbox);
2449 	    goto doend;
2450 	}
2451 #endif
2452 	if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2453 	{
2454 	    /* Command not allowed in non-'modifiable' buffer */
2455 	    errormsg = (char_u *)_(e_modifiable);
2456 	    goto doend;
2457 	}
2458 
2459 	if (text_locked() && !(ea.argt & CMDWIN)
2460 		&& !IS_USER_CMDIDX(ea.cmdidx))
2461 	{
2462 	    /* Command not allowed when editing the command line. */
2463 	    errormsg = (char_u *)_(get_text_locked_msg());
2464 	    goto doend;
2465 	}
2466 #ifdef FEAT_AUTOCMD
2467 	/* Disallow editing another buffer when "curbuf_lock" is set.
2468 	 * Do allow ":edit" (check for argument later).
2469 	 * Do allow ":checktime" (it's postponed). */
2470 	if (!(ea.argt & CMDWIN)
2471 		&& ea.cmdidx != CMD_edit
2472 		&& ea.cmdidx != CMD_checktime
2473 		&& !IS_USER_CMDIDX(ea.cmdidx)
2474 		&& curbuf_locked())
2475 	    goto doend;
2476 #endif
2477 
2478 	if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2479 	{
2480 	    /* no range allowed */
2481 	    errormsg = (char_u *)_(e_norange);
2482 	    goto doend;
2483 	}
2484     }
2485 
2486     if (!ni && !(ea.argt & BANG) && ea.forceit)	/* no <!> allowed */
2487     {
2488 	errormsg = (char_u *)_(e_nobang);
2489 	goto doend;
2490     }
2491 
2492     /*
2493      * Don't complain about the range if it is not used
2494      * (could happen if line_count is accidentally set to 0).
2495      */
2496     if (!ea.skip && !ni)
2497     {
2498 	/*
2499 	 * If the range is backwards, ask for confirmation and, if given, swap
2500 	 * ea.line1 & ea.line2 so it's forwards again.
2501 	 * When global command is busy, don't ask, will fail below.
2502 	 */
2503 	if (!global_busy && ea.line1 > ea.line2)
2504 	{
2505 	    if (msg_silent == 0)
2506 	    {
2507 		if (sourcing || exmode_active)
2508 		{
2509 		    errormsg = (char_u *)_("E493: Backwards range given");
2510 		    goto doend;
2511 		}
2512 		if (ask_yesno((char_u *)
2513 			_("Backwards range given, OK to swap"), FALSE) != 'y')
2514 		    goto doend;
2515 	    }
2516 	    lnum = ea.line1;
2517 	    ea.line1 = ea.line2;
2518 	    ea.line2 = lnum;
2519 	}
2520 	if ((errormsg = invalid_range(&ea)) != NULL)
2521 	    goto doend;
2522     }
2523 
2524     if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2525 	ea.line2 = 1;
2526 
2527     correct_range(&ea);
2528 
2529 #ifdef FEAT_FOLDING
2530     if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy
2531 	    && ea.addr_type == ADDR_LINES)
2532     {
2533 	/* Put the first line at the start of a closed fold, put the last line
2534 	 * at the end of a closed fold. */
2535 	(void)hasFolding(ea.line1, &ea.line1, NULL);
2536 	(void)hasFolding(ea.line2, NULL, &ea.line2);
2537     }
2538 #endif
2539 
2540 #ifdef FEAT_QUICKFIX
2541     /*
2542      * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2543      * option here, so things like % get expanded.
2544      */
2545     p = replace_makeprg(&ea, p, cmdlinep);
2546     if (p == NULL)
2547 	goto doend;
2548 #endif
2549 
2550     /*
2551      * Skip to start of argument.
2552      * Don't do this for the ":!" command, because ":!! -l" needs the space.
2553      */
2554     if (ea.cmdidx == CMD_bang)
2555 	ea.arg = p;
2556     else
2557 	ea.arg = skipwhite(p);
2558 
2559     /*
2560      * Check for "++opt=val" argument.
2561      * Must be first, allow ":w ++enc=utf8 !cmd"
2562      */
2563     if (ea.argt & ARGOPT)
2564 	while (ea.arg[0] == '+' && ea.arg[1] == '+')
2565 	    if (getargopt(&ea) == FAIL && !ni)
2566 	    {
2567 		errormsg = (char_u *)_(e_invarg);
2568 		goto doend;
2569 	    }
2570 
2571     if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2572     {
2573 	if (*ea.arg == '>')			/* append */
2574 	{
2575 	    if (*++ea.arg != '>')		/* typed wrong */
2576 	    {
2577 		errormsg = (char_u *)_("E494: Use w or w>>");
2578 		goto doend;
2579 	    }
2580 	    ea.arg = skipwhite(ea.arg + 1);
2581 	    ea.append = TRUE;
2582 	}
2583 	else if (*ea.arg == '!' && ea.cmdidx == CMD_write)  /* :w !filter */
2584 	{
2585 	    ++ea.arg;
2586 	    ea.usefilter = TRUE;
2587 	}
2588     }
2589 
2590     if (ea.cmdidx == CMD_read)
2591     {
2592 	if (ea.forceit)
2593 	{
2594 	    ea.usefilter = TRUE;		/* :r! filter if ea.forceit */
2595 	    ea.forceit = FALSE;
2596 	}
2597 	else if (*ea.arg == '!')		/* :r !filter */
2598 	{
2599 	    ++ea.arg;
2600 	    ea.usefilter = TRUE;
2601 	}
2602     }
2603 
2604     if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2605     {
2606 	ea.amount = 1;
2607 	while (*ea.arg == *ea.cmd)		/* count number of '>' or '<' */
2608 	{
2609 	    ++ea.arg;
2610 	    ++ea.amount;
2611 	}
2612 	ea.arg = skipwhite(ea.arg);
2613     }
2614 
2615     /*
2616      * Check for "+command" argument, before checking for next command.
2617      * Don't do this for ":read !cmd" and ":write !cmd".
2618      */
2619     if ((ea.argt & EDITCMD) && !ea.usefilter)
2620 	ea.do_ecmd_cmd = getargcmd(&ea.arg);
2621 
2622     /*
2623      * Check for '|' to separate commands and '"' to start comments.
2624      * Don't do this for ":read !cmd" and ":write !cmd".
2625      */
2626     if ((ea.argt & TRLBAR) && !ea.usefilter)
2627 	separate_nextcmd(&ea);
2628 
2629     /*
2630      * Check for <newline> to end a shell command.
2631      * Also do this for ":read !cmd", ":write !cmd" and ":global".
2632      * Any others?
2633      */
2634     else if (ea.cmdidx == CMD_bang
2635 	    || ea.cmdidx == CMD_terminal
2636 	    || ea.cmdidx == CMD_global
2637 	    || ea.cmdidx == CMD_vglobal
2638 	    || ea.usefilter)
2639     {
2640 	for (p = ea.arg; *p; ++p)
2641 	{
2642 	    /* Remove one backslash before a newline, so that it's possible to
2643 	     * pass a newline to the shell and also a newline that is preceded
2644 	     * with a backslash.  This makes it impossible to end a shell
2645 	     * command in a backslash, but that doesn't appear useful.
2646 	     * Halving the number of backslashes is incompatible with previous
2647 	     * versions. */
2648 	    if (*p == '\\' && p[1] == '\n')
2649 		STRMOVE(p, p + 1);
2650 	    else if (*p == '\n')
2651 	    {
2652 		ea.nextcmd = p + 1;
2653 		*p = NUL;
2654 		break;
2655 	    }
2656 	}
2657     }
2658 
2659     if ((ea.argt & DFLALL) && ea.addr_count == 0)
2660     {
2661 	buf_T	    *buf;
2662 
2663 	ea.line1 = 1;
2664 	switch (ea.addr_type)
2665 	{
2666 	    case ADDR_LINES:
2667 		ea.line2 = curbuf->b_ml.ml_line_count;
2668 		break;
2669 	    case ADDR_LOADED_BUFFERS:
2670 		buf = firstbuf;
2671 		while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL)
2672 		    buf = buf->b_next;
2673 		ea.line1 = buf->b_fnum;
2674 		buf = lastbuf;
2675 		while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL)
2676 		    buf = buf->b_prev;
2677 		ea.line2 = buf->b_fnum;
2678 		break;
2679 	    case ADDR_BUFFERS:
2680 		ea.line1 = firstbuf->b_fnum;
2681 		ea.line2 = lastbuf->b_fnum;
2682 		break;
2683 	    case ADDR_WINDOWS:
2684 		ea.line2 = LAST_WIN_NR;
2685 		break;
2686 	    case ADDR_TABS:
2687 		ea.line2 = LAST_TAB_NR;
2688 		break;
2689 	    case ADDR_TABS_RELATIVE:
2690 		ea.line2 = 1;
2691 		break;
2692 	    case ADDR_ARGUMENTS:
2693 		if (ARGCOUNT == 0)
2694 		    ea.line1 = ea.line2 = 0;
2695 		else
2696 		    ea.line2 = ARGCOUNT;
2697 		break;
2698 #ifdef FEAT_QUICKFIX
2699 	    case ADDR_QUICKFIX:
2700 		ea.line2 = qf_get_size(&ea);
2701 		if (ea.line2 == 0)
2702 		    ea.line2 = 1;
2703 		break;
2704 #endif
2705 	}
2706     }
2707 
2708     /* accept numbered register only when no count allowed (:put) */
2709     if (       (ea.argt & REGSTR)
2710 	    && *ea.arg != NUL
2711 	       /* Do not allow register = for user commands */
2712 	    && (!IS_USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2713 	    && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2714     {
2715 #ifndef FEAT_CLIPBOARD
2716 	/* check these explicitly for a more specific error message */
2717 	if (*ea.arg == '*' || *ea.arg == '+')
2718 	{
2719 	    errormsg = (char_u *)_(e_invalidreg);
2720 	    goto doend;
2721 	}
2722 #endif
2723 	if (valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2724 					      && !IS_USER_CMDIDX(ea.cmdidx))))
2725 	{
2726 	    ea.regname = *ea.arg++;
2727 #ifdef FEAT_EVAL
2728 	    /* for '=' register: accept the rest of the line as an expression */
2729 	    if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2730 	    {
2731 		set_expr_line(vim_strsave(ea.arg));
2732 		ea.arg += STRLEN(ea.arg);
2733 	    }
2734 #endif
2735 	    ea.arg = skipwhite(ea.arg);
2736 	}
2737     }
2738 
2739     /*
2740      * Check for a count.  When accepting a BUFNAME, don't use "123foo" as a
2741      * count, it's a buffer name.
2742      */
2743     if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2744 	    && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2745 							  || VIM_ISWHITE(*p)))
2746     {
2747 	n = getdigits(&ea.arg);
2748 	ea.arg = skipwhite(ea.arg);
2749 	if (n <= 0 && !ni && (ea.argt & ZEROR) == 0)
2750 	{
2751 	    errormsg = (char_u *)_(e_zerocount);
2752 	    goto doend;
2753 	}
2754 	if (ea.argt & NOTADR)	/* e.g. :buffer 2, :sleep 3 */
2755 	{
2756 	    ea.line2 = n;
2757 	    if (ea.addr_count == 0)
2758 		ea.addr_count = 1;
2759 	}
2760 	else
2761 	{
2762 	    ea.line1 = ea.line2;
2763 	    ea.line2 += n - 1;
2764 	    ++ea.addr_count;
2765 	    /*
2766 	     * Be vi compatible: no error message for out of range.
2767 	     */
2768 	    if (ea.addr_type == ADDR_LINES
2769 		    && ea.line2 > curbuf->b_ml.ml_line_count)
2770 		ea.line2 = curbuf->b_ml.ml_line_count;
2771 	}
2772     }
2773 
2774     /*
2775      * Check for flags: 'l', 'p' and '#'.
2776      */
2777     if (ea.argt & EXFLAGS)
2778 	get_flags(&ea);
2779 						/* no arguments allowed */
2780     if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2781 	    && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0))
2782     {
2783 	errormsg = (char_u *)_(e_trailing);
2784 	goto doend;
2785     }
2786 
2787     if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2788     {
2789 	errormsg = (char_u *)_(e_argreq);
2790 	goto doend;
2791     }
2792 
2793 #ifdef FEAT_EVAL
2794     /*
2795      * Skip the command when it's not going to be executed.
2796      * The commands like :if, :endif, etc. always need to be executed.
2797      * Also make an exception for commands that handle a trailing command
2798      * themselves.
2799      */
2800     if (ea.skip)
2801     {
2802 	switch (ea.cmdidx)
2803 	{
2804 	    /* commands that need evaluation */
2805 	    case CMD_while:
2806 	    case CMD_endwhile:
2807 	    case CMD_for:
2808 	    case CMD_endfor:
2809 	    case CMD_if:
2810 	    case CMD_elseif:
2811 	    case CMD_else:
2812 	    case CMD_endif:
2813 	    case CMD_try:
2814 	    case CMD_catch:
2815 	    case CMD_finally:
2816 	    case CMD_endtry:
2817 	    case CMD_function:
2818 				break;
2819 
2820 	    /* Commands that handle '|' themselves.  Check: A command should
2821 	     * either have the TRLBAR flag, appear in this list or appear in
2822 	     * the list at ":help :bar". */
2823 	    case CMD_aboveleft:
2824 	    case CMD_and:
2825 	    case CMD_belowright:
2826 	    case CMD_botright:
2827 	    case CMD_browse:
2828 	    case CMD_call:
2829 	    case CMD_confirm:
2830 	    case CMD_delfunction:
2831 	    case CMD_djump:
2832 	    case CMD_dlist:
2833 	    case CMD_dsearch:
2834 	    case CMD_dsplit:
2835 	    case CMD_echo:
2836 	    case CMD_echoerr:
2837 	    case CMD_echomsg:
2838 	    case CMD_echon:
2839 	    case CMD_execute:
2840 	    case CMD_filter:
2841 	    case CMD_help:
2842 	    case CMD_hide:
2843 	    case CMD_ijump:
2844 	    case CMD_ilist:
2845 	    case CMD_isearch:
2846 	    case CMD_isplit:
2847 	    case CMD_keepalt:
2848 	    case CMD_keepjumps:
2849 	    case CMD_keepmarks:
2850 	    case CMD_keeppatterns:
2851 	    case CMD_leftabove:
2852 	    case CMD_let:
2853 	    case CMD_lockmarks:
2854 	    case CMD_lua:
2855 	    case CMD_match:
2856 	    case CMD_mzscheme:
2857 	    case CMD_noautocmd:
2858 	    case CMD_noswapfile:
2859 	    case CMD_perl:
2860 	    case CMD_psearch:
2861 	    case CMD_python:
2862 	    case CMD_py3:
2863 	    case CMD_python3:
2864 	    case CMD_return:
2865 	    case CMD_rightbelow:
2866 	    case CMD_ruby:
2867 	    case CMD_silent:
2868 	    case CMD_smagic:
2869 	    case CMD_snomagic:
2870 	    case CMD_substitute:
2871 	    case CMD_syntax:
2872 	    case CMD_tab:
2873 	    case CMD_tcl:
2874 	    case CMD_throw:
2875 	    case CMD_tilde:
2876 	    case CMD_topleft:
2877 	    case CMD_unlet:
2878 	    case CMD_verbose:
2879 	    case CMD_vertical:
2880 	    case CMD_wincmd:
2881 				break;
2882 
2883 	    default:		goto doend;
2884 	}
2885     }
2886 #endif
2887 
2888     if (ea.argt & XFILE)
2889     {
2890 	if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2891 	    goto doend;
2892     }
2893 
2894 #ifdef FEAT_LISTCMDS
2895     /*
2896      * Accept buffer name.  Cannot be used at the same time with a buffer
2897      * number.  Don't do this for a user command.
2898      */
2899     if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2900 	    && !IS_USER_CMDIDX(ea.cmdidx))
2901     {
2902 	/*
2903 	 * :bdelete, :bwipeout and :bunload take several arguments, separated
2904 	 * by spaces: find next space (skipping over escaped characters).
2905 	 * The others take one argument: ignore trailing spaces.
2906 	 */
2907 	if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2908 						  || ea.cmdidx == CMD_bunload)
2909 	    p = skiptowhite_esc(ea.arg);
2910 	else
2911 	{
2912 	    p = ea.arg + STRLEN(ea.arg);
2913 	    while (p > ea.arg && VIM_ISWHITE(p[-1]))
2914 		--p;
2915 	}
2916 	ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0,
2917 								FALSE, FALSE);
2918 	if (ea.line2 < 0)	    /* failed */
2919 	    goto doend;
2920 	ea.addr_count = 1;
2921 	ea.arg = skipwhite(p);
2922     }
2923 #endif
2924 
2925 /*
2926  * 7. Switch on command name.
2927  *
2928  * The "ea" structure holds the arguments that can be used.
2929  */
2930     ea.cmdlinep = cmdlinep;
2931     ea.getline = fgetline;
2932     ea.cookie = cookie;
2933 #ifdef FEAT_EVAL
2934     ea.cstack = cstack;
2935 #endif
2936 
2937 #ifdef FEAT_USR_CMDS
2938     if (IS_USER_CMDIDX(ea.cmdidx))
2939     {
2940 	/*
2941 	 * Execute a user-defined command.
2942 	 */
2943 	do_ucmd(&ea);
2944     }
2945     else
2946 #endif
2947     {
2948 	/*
2949 	 * Call the function to execute the command.
2950 	 */
2951 	ea.errmsg = NULL;
2952 	(cmdnames[ea.cmdidx].cmd_func)(&ea);
2953 	if (ea.errmsg != NULL)
2954 	    errormsg = (char_u *)_(ea.errmsg);
2955     }
2956 
2957 #ifdef FEAT_EVAL
2958     /*
2959      * If the command just executed called do_cmdline(), any throw or ":return"
2960      * or ":finish" encountered there must also check the cstack of the still
2961      * active do_cmdline() that called this do_one_cmd().  Rethrow an uncaught
2962      * exception, or reanimate a returned function or finished script file and
2963      * return or finish it again.
2964      */
2965     if (need_rethrow)
2966 	do_throw(cstack);
2967     else if (check_cstack)
2968     {
2969 	if (source_finished(fgetline, cookie))
2970 	    do_finish(&ea, TRUE);
2971 	else if (getline_equal(fgetline, cookie, get_func_line)
2972 						   && current_func_returned())
2973 	    do_return(&ea, TRUE, FALSE, NULL);
2974     }
2975     need_rethrow = check_cstack = FALSE;
2976 #endif
2977 
2978 doend:
2979     if (curwin->w_cursor.lnum == 0)	/* can happen with zero line number */
2980     {
2981 	curwin->w_cursor.lnum = 1;
2982 	curwin->w_cursor.col = 0;
2983     }
2984 
2985     if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2986     {
2987 	if (sourcing)
2988 	{
2989 	    if (errormsg != IObuff)
2990 	    {
2991 		STRCPY(IObuff, errormsg);
2992 		errormsg = IObuff;
2993 	    }
2994 	    append_command(*cmdlinep);
2995 	}
2996 	emsg(errormsg);
2997     }
2998 #ifdef FEAT_EVAL
2999     do_errthrow(cstack,
3000 	    (ea.cmdidx != CMD_SIZE && !IS_USER_CMDIDX(ea.cmdidx))
3001 			? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
3002 #endif
3003 
3004     if (verbose_save >= 0)
3005 	p_verbose = verbose_save;
3006 #ifdef FEAT_AUTOCMD
3007     if (cmdmod.save_ei != NULL)
3008     {
3009 	/* Restore 'eventignore' to the value before ":noautocmd". */
3010 	set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei,
3011 							  OPT_FREE, SID_NONE);
3012 	free_string_option(cmdmod.save_ei);
3013     }
3014 #endif
3015     if (cmdmod.filter_regmatch.regprog != NULL)
3016 	vim_regfree(cmdmod.filter_regmatch.regprog);
3017 
3018     cmdmod = save_cmdmod;
3019 
3020     if (save_msg_silent != -1)
3021     {
3022 	/* messages could be enabled for a serious error, need to check if the
3023 	 * counters don't become negative */
3024 	if (!did_emsg || msg_silent > save_msg_silent)
3025 	    msg_silent = save_msg_silent;
3026 	emsg_silent -= did_esilent;
3027 	if (emsg_silent < 0)
3028 	    emsg_silent = 0;
3029 	/* Restore msg_scroll, it's set by file I/O commands, even when no
3030 	 * message is actually displayed. */
3031 	msg_scroll = save_msg_scroll;
3032 
3033 	/* "silent reg" or "silent echo x" inside "redir" leaves msg_col
3034 	 * somewhere in the line.  Put it back in the first column. */
3035 	if (redirecting())
3036 	    msg_col = 0;
3037     }
3038 
3039 #ifdef HAVE_SANDBOX
3040     if (did_sandbox)
3041 	--sandbox;
3042 #endif
3043 
3044     if (ea.nextcmd && *ea.nextcmd == NUL)	/* not really a next command */
3045 	ea.nextcmd = NULL;
3046 
3047 #ifdef FEAT_EVAL
3048     --ex_nesting_level;
3049 #endif
3050 
3051     return ea.nextcmd;
3052 }
3053 #if (_MSC_VER == 1200)
3054  #pragma optimize( "", on )
3055 #endif
3056 
3057 /*
3058  * Check for an Ex command with optional tail.
3059  * If there is a match advance "pp" to the argument and return TRUE.
3060  */
3061     int
3062 checkforcmd(
3063     char_u	**pp,		/* start of command */
3064     char	*cmd,		/* name of command */
3065     int		len)		/* required length */
3066 {
3067     int		i;
3068 
3069     for (i = 0; cmd[i] != NUL; ++i)
3070 	if (((char_u *)cmd)[i] != (*pp)[i])
3071 	    break;
3072     if (i >= len && !isalpha((*pp)[i]))
3073     {
3074 	*pp = skipwhite(*pp + i);
3075 	return TRUE;
3076     }
3077     return FALSE;
3078 }
3079 
3080 /*
3081  * Append "cmd" to the error message in IObuff.
3082  * Takes care of limiting the length and handling 0xa0, which would be
3083  * invisible otherwise.
3084  */
3085     static void
3086 append_command(char_u *cmd)
3087 {
3088     char_u *s = cmd;
3089     char_u *d;
3090 
3091     STRCAT(IObuff, ": ");
3092     d = IObuff + STRLEN(IObuff);
3093     while (*s != NUL && d - IObuff < IOSIZE - 7)
3094     {
3095 	if (
3096 #ifdef FEAT_MBYTE
3097 		enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) :
3098 #endif
3099 		*s == 0xa0)
3100 	{
3101 	    s +=
3102 #ifdef FEAT_MBYTE
3103 		enc_utf8 ? 2 :
3104 #endif
3105 		1;
3106 	    STRCPY(d, "<a0>");
3107 	    d += 4;
3108 	}
3109 	else
3110 	    MB_COPY_CHAR(s, d);
3111     }
3112     *d = NUL;
3113 }
3114 
3115 /*
3116  * Find an Ex command by its name, either built-in or user.
3117  * Start of the name can be found at eap->cmd.
3118  * Returns pointer to char after the command name.
3119  * "full" is set to TRUE if the whole command name matched.
3120  * Returns NULL for an ambiguous user command.
3121  */
3122     static char_u *
3123 find_command(exarg_T *eap, int *full UNUSED)
3124 {
3125     int		len;
3126     char_u	*p;
3127     int		i;
3128 
3129     /*
3130      * Isolate the command and search for it in the command table.
3131      * Exceptions:
3132      * - the 'k' command can directly be followed by any character.
3133      * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3134      *	    but :sre[wind] is another command, as are :scr[iptnames],
3135      *	    :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
3136      * - the "d" command can directly be followed by 'l' or 'p' flag.
3137      */
3138     p = eap->cmd;
3139     if (*p == 'k')
3140     {
3141 	eap->cmdidx = CMD_k;
3142 	++p;
3143     }
3144     else if (p[0] == 's'
3145 	    && ((p[1] == 'c' && (p[2] == NUL || (p[2] != 's' && p[2] != 'r'
3146 			&& (p[3] == NUL || (p[3] != 'i' && p[4] != 'p')))))
3147 		|| p[1] == 'g'
3148 		|| (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
3149 		|| p[1] == 'I'
3150 		|| (p[1] == 'r' && p[2] != 'e')))
3151     {
3152 	eap->cmdidx = CMD_substitute;
3153 	++p;
3154     }
3155     else
3156     {
3157 	while (ASCII_ISALPHA(*p))
3158 	    ++p;
3159 	/* for python 3.x support ":py3", ":python3", ":py3file", etc. */
3160 	if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y')
3161 	    while (ASCII_ISALNUM(*p))
3162 		++p;
3163 
3164 	/* check for non-alpha command */
3165 	if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3166 	    ++p;
3167 	len = (int)(p - eap->cmd);
3168 	if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p'))
3169 	{
3170 	    /* Check for ":dl", ":dell", etc. to ":deletel": that's
3171 	     * :delete with the 'l' flag.  Same for 'p'. */
3172 	    for (i = 0; i < len; ++i)
3173 		if (eap->cmd[i] != ((char_u *)"delete")[i])
3174 		    break;
3175 	    if (i == len - 1)
3176 	    {
3177 		--len;
3178 		if (p[-1] == 'l')
3179 		    eap->flags |= EXFLAG_LIST;
3180 		else
3181 		    eap->flags |= EXFLAG_PRINT;
3182 	    }
3183 	}
3184 
3185 	if (ASCII_ISLOWER(eap->cmd[0]))
3186 	{
3187 	    int c1 = eap->cmd[0];
3188 	    int c2 = eap->cmd[1];
3189 
3190 	    if (command_count != (int)CMD_SIZE)
3191 	    {
3192 		iemsg((char_u *)_("E943: Command table needs to be updated, run 'make cmdidxs'"));
3193 		getout(1);
3194 	    }
3195 
3196 	    /* Use a precomputed index for fast look-up in cmdnames[]
3197 	     * taking into account the first 2 letters of eap->cmd. */
3198 	    eap->cmdidx = cmdidxs1[CharOrdLow(c1)];
3199 	    if (ASCII_ISLOWER(c2))
3200 		eap->cmdidx += cmdidxs2[CharOrdLow(c1)][CharOrdLow(c2)];
3201 	}
3202 	else
3203 	    eap->cmdidx = CMD_bang;
3204 
3205 	for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
3206 			       eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
3207 	    if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
3208 							    (size_t)len) == 0)
3209 	    {
3210 #ifdef FEAT_EVAL
3211 		if (full != NULL
3212 			   && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
3213 		    *full = TRUE;
3214 #endif
3215 		break;
3216 	    }
3217 
3218 #ifdef FEAT_USR_CMDS
3219 	/* Look for a user defined command as a last resort.  Let ":Print" be
3220 	 * overruled by a user defined command. */
3221 	if ((eap->cmdidx == CMD_SIZE || eap->cmdidx == CMD_Print)
3222 		&& *eap->cmd >= 'A' && *eap->cmd <= 'Z')
3223 	{
3224 	    /* User defined commands may contain digits. */
3225 	    while (ASCII_ISALNUM(*p))
3226 		++p;
3227 	    p = find_ucmd(eap, p, full, NULL, NULL);
3228 	}
3229 #endif
3230 	if (p == eap->cmd)
3231 	    eap->cmdidx = CMD_SIZE;
3232     }
3233 
3234     return p;
3235 }
3236 
3237 #ifdef FEAT_USR_CMDS
3238 /*
3239  * Search for a user command that matches "eap->cmd".
3240  * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
3241  * Return a pointer to just after the command.
3242  * Return NULL if there is no matching command.
3243  */
3244     static char_u *
3245 find_ucmd(
3246     exarg_T	*eap,
3247     char_u	*p,	/* end of the command (possibly including count) */
3248     int		*full,	/* set to TRUE for a full match */
3249     expand_T	*xp,	/* used for completion, NULL otherwise */
3250     int		*compl)	/* completion flags or NULL */
3251 {
3252     int		len = (int)(p - eap->cmd);
3253     int		j, k, matchlen = 0;
3254     ucmd_T	*uc;
3255     int		found = FALSE;
3256     int		possible = FALSE;
3257     char_u	*cp, *np;	    /* Point into typed cmd and test name */
3258     garray_T	*gap;
3259     int		amb_local = FALSE;  /* Found ambiguous buffer-local command,
3260 				       only full match global is accepted. */
3261 
3262     /*
3263      * Look for buffer-local user commands first, then global ones.
3264      */
3265     gap = &curbuf->b_ucmds;
3266     for (;;)
3267     {
3268 	for (j = 0; j < gap->ga_len; ++j)
3269 	{
3270 	    uc = USER_CMD_GA(gap, j);
3271 	    cp = eap->cmd;
3272 	    np = uc->uc_name;
3273 	    k = 0;
3274 	    while (k < len && *np != NUL && *cp++ == *np++)
3275 		k++;
3276 	    if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
3277 	    {
3278 		/* If finding a second match, the command is ambiguous.  But
3279 		 * not if a buffer-local command wasn't a full match and a
3280 		 * global command is a full match. */
3281 		if (k == len && found && *np != NUL)
3282 		{
3283 		    if (gap == &ucmds)
3284 			return NULL;
3285 		    amb_local = TRUE;
3286 		}
3287 
3288 		if (!found || (k == len && *np == NUL))
3289 		{
3290 		    /* If we matched up to a digit, then there could
3291 		     * be another command including the digit that we
3292 		     * should use instead.
3293 		     */
3294 		    if (k == len)
3295 			found = TRUE;
3296 		    else
3297 			possible = TRUE;
3298 
3299 		    if (gap == &ucmds)
3300 			eap->cmdidx = CMD_USER;
3301 		    else
3302 			eap->cmdidx = CMD_USER_BUF;
3303 		    eap->argt = (long)uc->uc_argt;
3304 		    eap->useridx = j;
3305 		    eap->addr_type = uc->uc_addr_type;
3306 
3307 # ifdef FEAT_CMDL_COMPL
3308 		    if (compl != NULL)
3309 			*compl = uc->uc_compl;
3310 #  ifdef FEAT_EVAL
3311 		    if (xp != NULL)
3312 		    {
3313 			xp->xp_arg = uc->uc_compl_arg;
3314 			xp->xp_scriptID = uc->uc_scriptID;
3315 		    }
3316 #  endif
3317 # endif
3318 		    /* Do not search for further abbreviations
3319 		     * if this is an exact match. */
3320 		    matchlen = k;
3321 		    if (k == len && *np == NUL)
3322 		    {
3323 			if (full != NULL)
3324 			    *full = TRUE;
3325 			amb_local = FALSE;
3326 			break;
3327 		    }
3328 		}
3329 	    }
3330 	}
3331 
3332 	/* Stop if we found a full match or searched all. */
3333 	if (j < gap->ga_len || gap == &ucmds)
3334 	    break;
3335 	gap = &ucmds;
3336     }
3337 
3338     /* Only found ambiguous matches. */
3339     if (amb_local)
3340     {
3341 	if (xp != NULL)
3342 	    xp->xp_context = EXPAND_UNSUCCESSFUL;
3343 	return NULL;
3344     }
3345 
3346     /* The match we found may be followed immediately by a number.  Move "p"
3347      * back to point to it. */
3348     if (found || possible)
3349 	return p + (matchlen - len);
3350     return p;
3351 }
3352 #endif
3353 
3354 #if defined(FEAT_EVAL) || defined(PROTO)
3355 static struct cmdmod
3356 {
3357     char	*name;
3358     int		minlen;
3359     int		has_count;  /* :123verbose  :3tab */
3360 } cmdmods[] = {
3361     {"aboveleft", 3, FALSE},
3362     {"belowright", 3, FALSE},
3363     {"botright", 2, FALSE},
3364     {"browse", 3, FALSE},
3365     {"confirm", 4, FALSE},
3366     {"filter", 4, FALSE},
3367     {"hide", 3, FALSE},
3368     {"keepalt", 5, FALSE},
3369     {"keepjumps", 5, FALSE},
3370     {"keepmarks", 3, FALSE},
3371     {"keeppatterns", 5, FALSE},
3372     {"leftabove", 5, FALSE},
3373     {"lockmarks", 3, FALSE},
3374     {"noautocmd", 3, FALSE},
3375     {"noswapfile", 3, FALSE},
3376     {"rightbelow", 6, FALSE},
3377     {"sandbox", 3, FALSE},
3378     {"silent", 3, FALSE},
3379     {"tab", 3, TRUE},
3380     {"topleft", 2, FALSE},
3381     {"unsilent", 3, FALSE},
3382     {"verbose", 4, TRUE},
3383     {"vertical", 4, FALSE},
3384 };
3385 
3386 /*
3387  * Return length of a command modifier (including optional count).
3388  * Return zero when it's not a modifier.
3389  */
3390     int
3391 modifier_len(char_u *cmd)
3392 {
3393     int		i, j;
3394     char_u	*p = cmd;
3395 
3396     if (VIM_ISDIGIT(*cmd))
3397 	p = skipwhite(skipdigits(cmd));
3398     for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3399     {
3400 	for (j = 0; p[j] != NUL; ++j)
3401 	    if (p[j] != cmdmods[i].name[j])
3402 		break;
3403 	if (!ASCII_ISALPHA(p[j]) && j >= cmdmods[i].minlen
3404 					&& (p == cmd || cmdmods[i].has_count))
3405 	    return j + (int)(p - cmd);
3406     }
3407     return 0;
3408 }
3409 
3410 /*
3411  * Return > 0 if an Ex command "name" exists.
3412  * Return 2 if there is an exact match.
3413  * Return 3 if there is an ambiguous match.
3414  */
3415     int
3416 cmd_exists(char_u *name)
3417 {
3418     exarg_T	ea;
3419     int		full = FALSE;
3420     int		i;
3421     int		j;
3422     char_u	*p;
3423 
3424     /* Check command modifiers. */
3425     for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3426     {
3427 	for (j = 0; name[j] != NUL; ++j)
3428 	    if (name[j] != cmdmods[i].name[j])
3429 		break;
3430 	if (name[j] == NUL && j >= cmdmods[i].minlen)
3431 	    return (cmdmods[i].name[j] == NUL ? 2 : 1);
3432     }
3433 
3434     /* Check built-in commands and user defined commands.
3435      * For ":2match" and ":3match" we need to skip the number. */
3436     ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3437     ea.cmdidx = (cmdidx_T)0;
3438     p = find_command(&ea, &full);
3439     if (p == NULL)
3440 	return 3;
3441     if (vim_isdigit(*name) && ea.cmdidx != CMD_match)
3442 	return 0;
3443     if (*skipwhite(p) != NUL)
3444 	return 0;	/* trailing garbage */
3445     return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
3446 }
3447 #endif
3448 
3449 /*
3450  * This is all pretty much copied from do_one_cmd(), with all the extra stuff
3451  * we don't need/want deleted.	Maybe this could be done better if we didn't
3452  * repeat all this stuff.  The only problem is that they may not stay
3453  * perfectly compatible with each other, but then the command line syntax
3454  * probably won't change that much -- webb.
3455  */
3456     char_u *
3457 set_one_cmd_context(
3458     expand_T	*xp,
3459     char_u	*buff)	    /* buffer for command string */
3460 {
3461     char_u		*p;
3462     char_u		*cmd, *arg;
3463     int			len = 0;
3464     exarg_T		ea;
3465 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3466     int			compl = EXPAND_NOTHING;
3467 #endif
3468 #ifdef FEAT_CMDL_COMPL
3469     int			delim;
3470 #endif
3471     int			forceit = FALSE;
3472     int			usefilter = FALSE;  /* filter instead of file name */
3473 
3474     ExpandInit(xp);
3475     xp->xp_pattern = buff;
3476     xp->xp_context = EXPAND_COMMANDS;	/* Default until we get past command */
3477     ea.argt = 0;
3478 
3479 /*
3480  * 1. skip comment lines and leading space, colons or bars
3481  */
3482     for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
3483 	;
3484     xp->xp_pattern = cmd;
3485 
3486     if (*cmd == NUL)
3487 	return NULL;
3488     if (*cmd == '"')	    /* ignore comment lines */
3489     {
3490 	xp->xp_context = EXPAND_NOTHING;
3491 	return NULL;
3492     }
3493 
3494 /*
3495  * 3. Skip over the range to find the command.
3496  */
3497     cmd = skip_range(cmd, &xp->xp_context);
3498     xp->xp_pattern = cmd;
3499     if (*cmd == NUL)
3500 	return NULL;
3501     if (*cmd == '"')
3502     {
3503 	xp->xp_context = EXPAND_NOTHING;
3504 	return NULL;
3505     }
3506 
3507     if (*cmd == '|' || *cmd == '\n')
3508 	return cmd + 1;			/* There's another command */
3509 
3510     /*
3511      * Isolate the command and search for it in the command table.
3512      * Exceptions:
3513      * - the 'k' command can directly be followed by any character, but
3514      *   do accept "keepmarks", "keepalt" and "keepjumps".
3515      * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3516      */
3517     if (*cmd == 'k' && cmd[1] != 'e')
3518     {
3519 	ea.cmdidx = CMD_k;
3520 	p = cmd + 1;
3521     }
3522     else
3523     {
3524 	p = cmd;
3525 	while (ASCII_ISALPHA(*p) || *p == '*')    /* Allow * wild card */
3526 	    ++p;
3527 	/* a user command may contain digits */
3528 	if (ASCII_ISUPPER(cmd[0]))
3529 	    while (ASCII_ISALNUM(*p) || *p == '*')
3530 		++p;
3531 	/* for python 3.x: ":py3*" commands completion */
3532 	if (cmd[0] == 'p' && cmd[1] == 'y' && p == cmd + 2 && *p == '3')
3533 	{
3534 	    ++p;
3535 	    while (ASCII_ISALPHA(*p) || *p == '*')
3536 		++p;
3537 	}
3538 	/* check for non-alpha command */
3539 	if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3540 	    ++p;
3541 	len = (int)(p - cmd);
3542 
3543 	if (len == 0)
3544 	{
3545 	    xp->xp_context = EXPAND_UNSUCCESSFUL;
3546 	    return NULL;
3547 	}
3548 	for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE;
3549 				   ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1))
3550 	    if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd,
3551 							    (size_t)len) == 0)
3552 		break;
3553 
3554 #ifdef FEAT_USR_CMDS
3555 	if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3556 	    while (ASCII_ISALNUM(*p) || *p == '*')	/* Allow * wild card */
3557 		++p;
3558 #endif
3559     }
3560 
3561     /*
3562      * If the cursor is touching the command, and it ends in an alpha-numeric
3563      * character, complete the command name.
3564      */
3565     if (*p == NUL && ASCII_ISALNUM(p[-1]))
3566 	return NULL;
3567 
3568     if (ea.cmdidx == CMD_SIZE)
3569     {
3570 	if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
3571 	{
3572 	    ea.cmdidx = CMD_substitute;
3573 	    p = cmd + 1;
3574 	}
3575 #ifdef FEAT_USR_CMDS
3576 	else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3577 	{
3578 	    ea.cmd = cmd;
3579 	    p = find_ucmd(&ea, p, NULL, xp,
3580 # if defined(FEAT_CMDL_COMPL)
3581 		    &compl
3582 # else
3583 		    NULL
3584 # endif
3585 		    );
3586 	    if (p == NULL)
3587 		ea.cmdidx = CMD_SIZE;	/* ambiguous user command */
3588 	}
3589 #endif
3590     }
3591     if (ea.cmdidx == CMD_SIZE)
3592     {
3593 	/* Not still touching the command and it was an illegal one */
3594 	xp->xp_context = EXPAND_UNSUCCESSFUL;
3595 	return NULL;
3596     }
3597 
3598     xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3599 
3600     if (*p == '!')		    /* forced commands */
3601     {
3602 	forceit = TRUE;
3603 	++p;
3604     }
3605 
3606 /*
3607  * 6. parse arguments
3608  */
3609     if (!IS_USER_CMDIDX(ea.cmdidx))
3610 	ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
3611 
3612     arg = skipwhite(p);
3613 
3614     if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
3615     {
3616 	if (*arg == '>')			/* append */
3617 	{
3618 	    if (*++arg == '>')
3619 		++arg;
3620 	    arg = skipwhite(arg);
3621 	}
3622 	else if (*arg == '!' && ea.cmdidx == CMD_write)	/* :w !filter */
3623 	{
3624 	    ++arg;
3625 	    usefilter = TRUE;
3626 	}
3627     }
3628 
3629     if (ea.cmdidx == CMD_read)
3630     {
3631 	usefilter = forceit;			/* :r! filter if forced */
3632 	if (*arg == '!')			/* :r !filter */
3633 	{
3634 	    ++arg;
3635 	    usefilter = TRUE;
3636 	}
3637     }
3638 
3639     if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
3640     {
3641 	while (*arg == *cmd)	    /* allow any number of '>' or '<' */
3642 	    ++arg;
3643 	arg = skipwhite(arg);
3644     }
3645 
3646     /* Does command allow "+command"? */
3647     if ((ea.argt & EDITCMD) && !usefilter && *arg == '+')
3648     {
3649 	/* Check if we're in the +command */
3650 	p = arg + 1;
3651 	arg = skip_cmd_arg(arg, FALSE);
3652 
3653 	/* Still touching the command after '+'? */
3654 	if (*arg == NUL)
3655 	    return p;
3656 
3657 	/* Skip space(s) after +command to get to the real argument */
3658 	arg = skipwhite(arg);
3659     }
3660 
3661     /*
3662      * Check for '|' to separate commands and '"' to start comments.
3663      * Don't do this for ":read !cmd" and ":write !cmd".
3664      */
3665     if ((ea.argt & TRLBAR) && !usefilter)
3666     {
3667 	p = arg;
3668 	/* ":redir @" is not the start of a comment */
3669 	if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3670 	    p += 2;
3671 	while (*p)
3672 	{
3673 	    if (*p == Ctrl_V)
3674 	    {
3675 		if (p[1] != NUL)
3676 		    ++p;
3677 	    }
3678 	    else if ( (*p == '"' && !(ea.argt & NOTRLCOM))
3679 		    || *p == '|' || *p == '\n')
3680 	    {
3681 		if (*(p - 1) != '\\')
3682 		{
3683 		    if (*p == '|' || *p == '\n')
3684 			return p + 1;
3685 		    return NULL;    /* It's a comment */
3686 		}
3687 	    }
3688 	    MB_PTR_ADV(p);
3689 	}
3690     }
3691 
3692 						/* no arguments allowed */
3693     if (!(ea.argt & EXTRA) && *arg != NUL &&
3694 				    vim_strchr((char_u *)"|\"", *arg) == NULL)
3695 	return NULL;
3696 
3697     /* Find start of last argument (argument just before cursor): */
3698     p = buff;
3699     xp->xp_pattern = p;
3700     len = (int)STRLEN(buff);
3701     while (*p && p < buff + len)
3702     {
3703 	if (*p == ' ' || *p == TAB)
3704 	{
3705 	    /* argument starts after a space */
3706 	    xp->xp_pattern = ++p;
3707 	}
3708 	else
3709 	{
3710 	    if (*p == '\\' && *(p + 1) != NUL)
3711 		++p; /* skip over escaped character */
3712 	    MB_PTR_ADV(p);
3713 	}
3714     }
3715 
3716     if (ea.argt & XFILE)
3717     {
3718 	int	c;
3719 	int	in_quote = FALSE;
3720 	char_u	*bow = NULL;	/* Beginning of word */
3721 
3722 	/*
3723 	 * Allow spaces within back-quotes to count as part of the argument
3724 	 * being expanded.
3725 	 */
3726 	xp->xp_pattern = skipwhite(arg);
3727 	p = xp->xp_pattern;
3728 	while (*p != NUL)
3729 	{
3730 #ifdef FEAT_MBYTE
3731 	    if (has_mbyte)
3732 		c = mb_ptr2char(p);
3733 	    else
3734 #endif
3735 		c = *p;
3736 	    if (c == '\\' && p[1] != NUL)
3737 		++p;
3738 	    else if (c == '`')
3739 	    {
3740 		if (!in_quote)
3741 		{
3742 		    xp->xp_pattern = p;
3743 		    bow = p + 1;
3744 		}
3745 		in_quote = !in_quote;
3746 	    }
3747 	    /* An argument can contain just about everything, except
3748 	     * characters that end the command and white space. */
3749 	    else if (c == '|' || c == '\n' || c == '"' || (VIM_ISWHITE(c)
3750 #ifdef SPACE_IN_FILENAME
3751 					 && (!(ea.argt & NOSPC) || usefilter)
3752 #endif
3753 		    ))
3754 	    {
3755 		len = 0;  /* avoid getting stuck when space is in 'isfname' */
3756 		while (*p != NUL)
3757 		{
3758 #ifdef FEAT_MBYTE
3759 		    if (has_mbyte)
3760 			c = mb_ptr2char(p);
3761 		    else
3762 #endif
3763 			c = *p;
3764 		    if (c == '`' || vim_isfilec_or_wc(c))
3765 			break;
3766 #ifdef FEAT_MBYTE
3767 		    if (has_mbyte)
3768 			len = (*mb_ptr2len)(p);
3769 		    else
3770 #endif
3771 			len = 1;
3772 		    MB_PTR_ADV(p);
3773 		}
3774 		if (in_quote)
3775 		    bow = p;
3776 		else
3777 		    xp->xp_pattern = p;
3778 		p -= len;
3779 	    }
3780 	    MB_PTR_ADV(p);
3781 	}
3782 
3783 	/*
3784 	 * If we are still inside the quotes, and we passed a space, just
3785 	 * expand from there.
3786 	 */
3787 	if (bow != NULL && in_quote)
3788 	    xp->xp_pattern = bow;
3789 	xp->xp_context = EXPAND_FILES;
3790 
3791 	/* For a shell command more chars need to be escaped. */
3792 	if (usefilter || ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal)
3793 	{
3794 #ifndef BACKSLASH_IN_FILENAME
3795 	    xp->xp_shell = TRUE;
3796 #endif
3797 	    /* When still after the command name expand executables. */
3798 	    if (xp->xp_pattern == skipwhite(arg))
3799 		xp->xp_context = EXPAND_SHELLCMD;
3800 	}
3801 
3802 	/* Check for environment variable */
3803 	if (*xp->xp_pattern == '$'
3804 #if defined(MSWIN)
3805 		|| *xp->xp_pattern == '%'
3806 #endif
3807 		)
3808 	{
3809 	    for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3810 		if (!vim_isIDc(*p))
3811 		    break;
3812 	    if (*p == NUL)
3813 	    {
3814 		xp->xp_context = EXPAND_ENV_VARS;
3815 		++xp->xp_pattern;
3816 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3817 		/* Avoid that the assignment uses EXPAND_FILES again. */
3818 		if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
3819 		    compl = EXPAND_ENV_VARS;
3820 #endif
3821 	    }
3822 	}
3823 #if defined(FEAT_CMDL_COMPL)
3824 	/* Check for user names */
3825 	if (*xp->xp_pattern == '~')
3826 	{
3827 	    for (p = xp->xp_pattern + 1; *p != NUL && *p != '/'; ++p)
3828 		;
3829 	    /* Complete ~user only if it partially matches a user name.
3830 	     * A full match ~user<Tab> will be replaced by user's home
3831 	     * directory i.e. something like ~user<Tab> -> /home/user/ */
3832 	    if (*p == NUL && p > xp->xp_pattern + 1
3833 				       && match_user(xp->xp_pattern + 1) == 1)
3834 	    {
3835 		xp->xp_context = EXPAND_USER;
3836 		++xp->xp_pattern;
3837 	    }
3838 	}
3839 #endif
3840     }
3841 
3842 /*
3843  * 6. Switch on command name.
3844  */
3845     switch (ea.cmdidx)
3846     {
3847 	case CMD_find:
3848 	case CMD_sfind:
3849 	case CMD_tabfind:
3850 	    if (xp->xp_context == EXPAND_FILES)
3851 		xp->xp_context = EXPAND_FILES_IN_PATH;
3852 	    break;
3853 	case CMD_cd:
3854 	case CMD_chdir:
3855 	case CMD_lcd:
3856 	case CMD_lchdir:
3857 	    if (xp->xp_context == EXPAND_FILES)
3858 		xp->xp_context = EXPAND_DIRECTORIES;
3859 	    break;
3860 	case CMD_help:
3861 	    xp->xp_context = EXPAND_HELP;
3862 	    xp->xp_pattern = arg;
3863 	    break;
3864 
3865 	/* Command modifiers: return the argument.
3866 	 * Also for commands with an argument that is a command. */
3867 	case CMD_aboveleft:
3868 	case CMD_argdo:
3869 	case CMD_belowright:
3870 	case CMD_botright:
3871 	case CMD_browse:
3872 	case CMD_bufdo:
3873 	case CMD_cdo:
3874 	case CMD_cfdo:
3875 	case CMD_confirm:
3876 	case CMD_debug:
3877 	case CMD_folddoclosed:
3878 	case CMD_folddoopen:
3879 	case CMD_hide:
3880 	case CMD_keepalt:
3881 	case CMD_keepjumps:
3882 	case CMD_keepmarks:
3883 	case CMD_keeppatterns:
3884 	case CMD_ldo:
3885 	case CMD_leftabove:
3886 	case CMD_lfdo:
3887 	case CMD_lockmarks:
3888 	case CMD_noautocmd:
3889 	case CMD_noswapfile:
3890 	case CMD_rightbelow:
3891 	case CMD_sandbox:
3892 	case CMD_silent:
3893 	case CMD_tab:
3894 	case CMD_tabdo:
3895 	case CMD_topleft:
3896 	case CMD_verbose:
3897 	case CMD_vertical:
3898 	case CMD_windo:
3899 	    return arg;
3900 
3901 	case CMD_filter:
3902 	    if (*arg != NUL)
3903 		arg = skip_vimgrep_pat(arg, NULL, NULL);
3904 	    if (arg == NULL || *arg == NUL)
3905 	    {
3906 		xp->xp_context = EXPAND_NOTHING;
3907 		return NULL;
3908 	    }
3909 	    return skipwhite(arg);
3910 
3911 #ifdef FEAT_CMDL_COMPL
3912 # ifdef FEAT_SEARCH_EXTRA
3913 	case CMD_match:
3914 	    if (*arg == NUL || !ends_excmd(*arg))
3915 	    {
3916 		/* also complete "None" */
3917 		set_context_in_echohl_cmd(xp, arg);
3918 		arg = skipwhite(skiptowhite(arg));
3919 		if (*arg != NUL)
3920 		{
3921 		    xp->xp_context = EXPAND_NOTHING;
3922 		    arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3923 		}
3924 	    }
3925 	    return find_nextcmd(arg);
3926 # endif
3927 
3928 /*
3929  * All completion for the +cmdline_compl feature goes here.
3930  */
3931 
3932 # ifdef FEAT_USR_CMDS
3933 	case CMD_command:
3934 	    /* Check for attributes */
3935 	    while (*arg == '-')
3936 	    {
3937 		arg++;	    /* Skip "-" */
3938 		p = skiptowhite(arg);
3939 		if (*p == NUL)
3940 		{
3941 		    /* Cursor is still in the attribute */
3942 		    p = vim_strchr(arg, '=');
3943 		    if (p == NULL)
3944 		    {
3945 			/* No "=", so complete attribute names */
3946 			xp->xp_context = EXPAND_USER_CMD_FLAGS;
3947 			xp->xp_pattern = arg;
3948 			return NULL;
3949 		    }
3950 
3951 		    /* For the -complete, -nargs and -addr attributes, we complete
3952 		     * their arguments as well.
3953 		     */
3954 		    if (STRNICMP(arg, "complete", p - arg) == 0)
3955 		    {
3956 			xp->xp_context = EXPAND_USER_COMPLETE;
3957 			xp->xp_pattern = p + 1;
3958 			return NULL;
3959 		    }
3960 		    else if (STRNICMP(arg, "nargs", p - arg) == 0)
3961 		    {
3962 			xp->xp_context = EXPAND_USER_NARGS;
3963 			xp->xp_pattern = p + 1;
3964 			return NULL;
3965 		    }
3966 		    else if (STRNICMP(arg, "addr", p - arg) == 0)
3967 		    {
3968 			xp->xp_context = EXPAND_USER_ADDR_TYPE;
3969 			xp->xp_pattern = p + 1;
3970 			return NULL;
3971 		    }
3972 		    return NULL;
3973 		}
3974 		arg = skipwhite(p);
3975 	    }
3976 
3977 	    /* After the attributes comes the new command name */
3978 	    p = skiptowhite(arg);
3979 	    if (*p == NUL)
3980 	    {
3981 		xp->xp_context = EXPAND_USER_COMMANDS;
3982 		xp->xp_pattern = arg;
3983 		break;
3984 	    }
3985 
3986 	    /* And finally comes a normal command */
3987 	    return skipwhite(p);
3988 
3989 	case CMD_delcommand:
3990 	    xp->xp_context = EXPAND_USER_COMMANDS;
3991 	    xp->xp_pattern = arg;
3992 	    break;
3993 # endif
3994 
3995 	case CMD_global:
3996 	case CMD_vglobal:
3997 	    delim = *arg;	    /* get the delimiter */
3998 	    if (delim)
3999 		++arg;		    /* skip delimiter if there is one */
4000 
4001 	    while (arg[0] != NUL && arg[0] != delim)
4002 	    {
4003 		if (arg[0] == '\\' && arg[1] != NUL)
4004 		    ++arg;
4005 		++arg;
4006 	    }
4007 	    if (arg[0] != NUL)
4008 		return arg + 1;
4009 	    break;
4010 	case CMD_and:
4011 	case CMD_substitute:
4012 	    delim = *arg;
4013 	    if (delim)
4014 	    {
4015 		/* skip "from" part */
4016 		++arg;
4017 		arg = skip_regexp(arg, delim, p_magic, NULL);
4018 	    }
4019 	    /* skip "to" part */
4020 	    while (arg[0] != NUL && arg[0] != delim)
4021 	    {
4022 		if (arg[0] == '\\' && arg[1] != NUL)
4023 		    ++arg;
4024 		++arg;
4025 	    }
4026 	    if (arg[0] != NUL)	/* skip delimiter */
4027 		++arg;
4028 	    while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
4029 		++arg;
4030 	    if (arg[0] != NUL)
4031 		return arg;
4032 	    break;
4033 	case CMD_isearch:
4034 	case CMD_dsearch:
4035 	case CMD_ilist:
4036 	case CMD_dlist:
4037 	case CMD_ijump:
4038 	case CMD_psearch:
4039 	case CMD_djump:
4040 	case CMD_isplit:
4041 	case CMD_dsplit:
4042 	    arg = skipwhite(skipdigits(arg));	    /* skip count */
4043 	    if (*arg == '/')	/* Match regexp, not just whole words */
4044 	    {
4045 		for (++arg; *arg && *arg != '/'; arg++)
4046 		    if (*arg == '\\' && arg[1] != NUL)
4047 			arg++;
4048 		if (*arg)
4049 		{
4050 		    arg = skipwhite(arg + 1);
4051 
4052 		    /* Check for trailing illegal characters */
4053 		    if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
4054 			xp->xp_context = EXPAND_NOTHING;
4055 		    else
4056 			return arg;
4057 		}
4058 	    }
4059 	    break;
4060 #ifdef FEAT_AUTOCMD
4061 	case CMD_autocmd:
4062 	    return set_context_in_autocmd(xp, arg, FALSE);
4063 
4064 	case CMD_doautocmd:
4065 	case CMD_doautoall:
4066 	    return set_context_in_autocmd(xp, arg, TRUE);
4067 #endif
4068 	case CMD_set:
4069 	    set_context_in_set_cmd(xp, arg, 0);
4070 	    break;
4071 	case CMD_setglobal:
4072 	    set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
4073 	    break;
4074 	case CMD_setlocal:
4075 	    set_context_in_set_cmd(xp, arg, OPT_LOCAL);
4076 	    break;
4077 	case CMD_tag:
4078 	case CMD_stag:
4079 	case CMD_ptag:
4080 	case CMD_ltag:
4081 	case CMD_tselect:
4082 	case CMD_stselect:
4083 	case CMD_ptselect:
4084 	case CMD_tjump:
4085 	case CMD_stjump:
4086 	case CMD_ptjump:
4087 	    if (*p_wop != NUL)
4088 		xp->xp_context = EXPAND_TAGS_LISTFILES;
4089 	    else
4090 		xp->xp_context = EXPAND_TAGS;
4091 	    xp->xp_pattern = arg;
4092 	    break;
4093 	case CMD_augroup:
4094 	    xp->xp_context = EXPAND_AUGROUP;
4095 	    xp->xp_pattern = arg;
4096 	    break;
4097 #ifdef FEAT_SYN_HL
4098 	case CMD_syntax:
4099 	    set_context_in_syntax_cmd(xp, arg);
4100 	    break;
4101 #endif
4102 #ifdef FEAT_EVAL
4103 	case CMD_let:
4104 	case CMD_if:
4105 	case CMD_elseif:
4106 	case CMD_while:
4107 	case CMD_for:
4108 	case CMD_echo:
4109 	case CMD_echon:
4110 	case CMD_execute:
4111 	case CMD_echomsg:
4112 	case CMD_echoerr:
4113 	case CMD_call:
4114 	case CMD_return:
4115 	case CMD_cexpr:
4116 	case CMD_caddexpr:
4117 	case CMD_cgetexpr:
4118 	case CMD_lexpr:
4119 	case CMD_laddexpr:
4120 	case CMD_lgetexpr:
4121 	    set_context_for_expression(xp, arg, ea.cmdidx);
4122 	    break;
4123 
4124 	case CMD_unlet:
4125 	    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
4126 		arg = xp->xp_pattern + 1;
4127 	    xp->xp_context = EXPAND_USER_VARS;
4128 	    xp->xp_pattern = arg;
4129 	    break;
4130 
4131 	case CMD_function:
4132 	case CMD_delfunction:
4133 	    xp->xp_context = EXPAND_USER_FUNC;
4134 	    xp->xp_pattern = arg;
4135 	    break;
4136 
4137 	case CMD_echohl:
4138 	    set_context_in_echohl_cmd(xp, arg);
4139 	    break;
4140 #endif
4141 	case CMD_highlight:
4142 	    set_context_in_highlight_cmd(xp, arg);
4143 	    break;
4144 #ifdef FEAT_CSCOPE
4145 	case CMD_cscope:
4146 	case CMD_lcscope:
4147 	case CMD_scscope:
4148 	    set_context_in_cscope_cmd(xp, arg, ea.cmdidx);
4149 	    break;
4150 #endif
4151 #ifdef FEAT_SIGNS
4152 	case CMD_sign:
4153 	    set_context_in_sign_cmd(xp, arg);
4154 	    break;
4155 #endif
4156 #ifdef FEAT_LISTCMDS
4157 	case CMD_bdelete:
4158 	case CMD_bwipeout:
4159 	case CMD_bunload:
4160 	    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
4161 		arg = xp->xp_pattern + 1;
4162 	    /*FALLTHROUGH*/
4163 	case CMD_buffer:
4164 	case CMD_sbuffer:
4165 	case CMD_checktime:
4166 	    xp->xp_context = EXPAND_BUFFERS;
4167 	    xp->xp_pattern = arg;
4168 	    break;
4169 #endif
4170 #ifdef FEAT_USR_CMDS
4171 	case CMD_USER:
4172 	case CMD_USER_BUF:
4173 	    if (compl != EXPAND_NOTHING)
4174 	    {
4175 		/* XFILE: file names are handled above */
4176 		if (!(ea.argt & XFILE))
4177 		{
4178 # ifdef FEAT_MENU
4179 		    if (compl == EXPAND_MENUS)
4180 			return set_context_in_menu_cmd(xp, cmd, arg, forceit);
4181 # endif
4182 		    if (compl == EXPAND_COMMANDS)
4183 			return arg;
4184 		    if (compl == EXPAND_MAPPINGS)
4185 			return set_context_in_map_cmd(xp, (char_u *)"map",
4186 					 arg, forceit, FALSE, FALSE, CMD_map);
4187 		    /* Find start of last argument. */
4188 		    p = arg;
4189 		    while (*p)
4190 		    {
4191 			if (*p == ' ')
4192 			    /* argument starts after a space */
4193 			    arg = p + 1;
4194 			else if (*p == '\\' && *(p + 1) != NUL)
4195 			    ++p; /* skip over escaped character */
4196 			MB_PTR_ADV(p);
4197 		    }
4198 		    xp->xp_pattern = arg;
4199 		}
4200 		xp->xp_context = compl;
4201 	    }
4202 	    break;
4203 #endif
4204 	case CMD_map:	    case CMD_noremap:
4205 	case CMD_nmap:	    case CMD_nnoremap:
4206 	case CMD_vmap:	    case CMD_vnoremap:
4207 	case CMD_omap:	    case CMD_onoremap:
4208 	case CMD_imap:	    case CMD_inoremap:
4209 	case CMD_cmap:	    case CMD_cnoremap:
4210 	case CMD_lmap:	    case CMD_lnoremap:
4211 	case CMD_smap:	    case CMD_snoremap:
4212 	case CMD_xmap:	    case CMD_xnoremap:
4213 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
4214 						     FALSE, FALSE, ea.cmdidx);
4215 	case CMD_unmap:
4216 	case CMD_nunmap:
4217 	case CMD_vunmap:
4218 	case CMD_ounmap:
4219 	case CMD_iunmap:
4220 	case CMD_cunmap:
4221 	case CMD_lunmap:
4222 	case CMD_sunmap:
4223 	case CMD_xunmap:
4224 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
4225 						      FALSE, TRUE, ea.cmdidx);
4226 	case CMD_mapclear:
4227 	case CMD_nmapclear:
4228 	case CMD_vmapclear:
4229 	case CMD_omapclear:
4230 	case CMD_imapclear:
4231 	case CMD_cmapclear:
4232 	case CMD_lmapclear:
4233 	case CMD_smapclear:
4234 	case CMD_xmapclear:
4235 	    xp->xp_context = EXPAND_MAPCLEAR;
4236 	    xp->xp_pattern = arg;
4237 	    break;
4238 
4239 	case CMD_abbreviate:	case CMD_noreabbrev:
4240 	case CMD_cabbrev:	case CMD_cnoreabbrev:
4241 	case CMD_iabbrev:	case CMD_inoreabbrev:
4242 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
4243 						      TRUE, FALSE, ea.cmdidx);
4244 	case CMD_unabbreviate:
4245 	case CMD_cunabbrev:
4246 	case CMD_iunabbrev:
4247 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
4248 						       TRUE, TRUE, ea.cmdidx);
4249 #ifdef FEAT_MENU
4250 	case CMD_menu:	    case CMD_noremenu:	    case CMD_unmenu:
4251 	case CMD_amenu:	    case CMD_anoremenu:	    case CMD_aunmenu:
4252 	case CMD_nmenu:	    case CMD_nnoremenu:	    case CMD_nunmenu:
4253 	case CMD_vmenu:	    case CMD_vnoremenu:	    case CMD_vunmenu:
4254 	case CMD_omenu:	    case CMD_onoremenu:	    case CMD_ounmenu:
4255 	case CMD_imenu:	    case CMD_inoremenu:	    case CMD_iunmenu:
4256 	case CMD_cmenu:	    case CMD_cnoremenu:	    case CMD_cunmenu:
4257 	case CMD_tmenu:				    case CMD_tunmenu:
4258 	case CMD_popup:	    case CMD_tearoff:	    case CMD_emenu:
4259 	    return set_context_in_menu_cmd(xp, cmd, arg, forceit);
4260 #endif
4261 
4262 	case CMD_colorscheme:
4263 	    xp->xp_context = EXPAND_COLORS;
4264 	    xp->xp_pattern = arg;
4265 	    break;
4266 
4267 	case CMD_compiler:
4268 	    xp->xp_context = EXPAND_COMPILER;
4269 	    xp->xp_pattern = arg;
4270 	    break;
4271 
4272 	case CMD_ownsyntax:
4273 	    xp->xp_context = EXPAND_OWNSYNTAX;
4274 	    xp->xp_pattern = arg;
4275 	    break;
4276 
4277 	case CMD_setfiletype:
4278 	    xp->xp_context = EXPAND_FILETYPE;
4279 	    xp->xp_pattern = arg;
4280 	    break;
4281 
4282 	case CMD_packadd:
4283 	    xp->xp_context = EXPAND_PACKADD;
4284 	    xp->xp_pattern = arg;
4285 	    break;
4286 
4287 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
4288 	&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
4289 	case CMD_language:
4290 	    p = skiptowhite(arg);
4291 	    if (*p == NUL)
4292 	    {
4293 		xp->xp_context = EXPAND_LANGUAGE;
4294 		xp->xp_pattern = arg;
4295 	    }
4296 	    else
4297 	    {
4298 		if ( STRNCMP(arg, "messages", p - arg) == 0
4299 		  || STRNCMP(arg, "ctype", p - arg) == 0
4300 		  || STRNCMP(arg, "time", p - arg) == 0)
4301 		{
4302 		    xp->xp_context = EXPAND_LOCALES;
4303 		    xp->xp_pattern = skipwhite(p);
4304 		}
4305 		else
4306 		    xp->xp_context = EXPAND_NOTHING;
4307 	    }
4308 	    break;
4309 #endif
4310 #if defined(FEAT_PROFILE)
4311 	case CMD_profile:
4312 	    set_context_in_profile_cmd(xp, arg);
4313 	    break;
4314 #endif
4315 	case CMD_behave:
4316 	    xp->xp_context = EXPAND_BEHAVE;
4317 	    xp->xp_pattern = arg;
4318 	    break;
4319 
4320 	case CMD_messages:
4321 	    xp->xp_context = EXPAND_MESSAGES;
4322 	    xp->xp_pattern = arg;
4323 	    break;
4324 
4325 #if defined(FEAT_CMDHIST)
4326 	case CMD_history:
4327 	    xp->xp_context = EXPAND_HISTORY;
4328 	    xp->xp_pattern = arg;
4329 	    break;
4330 #endif
4331 #if defined(FEAT_PROFILE)
4332 	case CMD_syntime:
4333 	    xp->xp_context = EXPAND_SYNTIME;
4334 	    xp->xp_pattern = arg;
4335 	    break;
4336 #endif
4337 
4338 #endif /* FEAT_CMDL_COMPL */
4339 
4340 	default:
4341 	    break;
4342     }
4343     return NULL;
4344 }
4345 
4346 /*
4347  * skip a range specifier of the form: addr [,addr] [;addr] ..
4348  *
4349  * Backslashed delimiters after / or ? will be skipped, and commands will
4350  * not be expanded between /'s and ?'s or after "'".
4351  *
4352  * Also skip white space and ":" characters.
4353  * Returns the "cmd" pointer advanced to beyond the range.
4354  */
4355     char_u *
4356 skip_range(
4357     char_u	*cmd,
4358     int		*ctx)	/* pointer to xp_context or NULL */
4359 {
4360     unsigned	delim;
4361 
4362     while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;\\", *cmd) != NULL)
4363     {
4364 	if (*cmd == '\\')
4365 	{
4366 	    if (cmd[1] == '?' || cmd[1] == '/' || cmd[1] == '&')
4367 		++cmd;
4368 	    else
4369 		break;
4370 	}
4371 	else if (*cmd == '\'')
4372 	{
4373 	    if (*++cmd == NUL && ctx != NULL)
4374 		*ctx = EXPAND_NOTHING;
4375 	}
4376 	else if (*cmd == '/' || *cmd == '?')
4377 	{
4378 	    delim = *cmd++;
4379 	    while (*cmd != NUL && *cmd != delim)
4380 		if (*cmd++ == '\\' && *cmd != NUL)
4381 		    ++cmd;
4382 	    if (*cmd == NUL && ctx != NULL)
4383 		*ctx = EXPAND_NOTHING;
4384 	}
4385 	if (*cmd != NUL)
4386 	    ++cmd;
4387     }
4388 
4389     /* Skip ":" and white space. */
4390     while (*cmd == ':')
4391 	cmd = skipwhite(cmd + 1);
4392 
4393     return cmd;
4394 }
4395 
4396 /*
4397  * get a single EX address
4398  *
4399  * Set ptr to the next character after the part that was interpreted.
4400  * Set ptr to NULL when an error is encountered.
4401  *
4402  * Return MAXLNUM when no Ex address was found.
4403  */
4404     static linenr_T
4405 get_address(
4406     exarg_T	*eap UNUSED,
4407     char_u	**ptr,
4408     int		addr_type,  /* flag: one of ADDR_LINES, ... */
4409     int		skip,	    /* only skip the address, don't use it */
4410     int		to_other_file,  /* flag: may jump to other file */
4411     int		address_count UNUSED) /* 1 for first address, >1 after comma */
4412 {
4413     int		c;
4414     int		i;
4415     long	n;
4416     char_u	*cmd;
4417     pos_T	pos;
4418     pos_T	*fp;
4419     linenr_T	lnum;
4420     buf_T	*buf;
4421 
4422     cmd = skipwhite(*ptr);
4423     lnum = MAXLNUM;
4424     do
4425     {
4426 	switch (*cmd)
4427 	{
4428 	    case '.':			    /* '.' - Cursor position */
4429 		++cmd;
4430 		switch (addr_type)
4431 		{
4432 		    case ADDR_LINES:
4433 			lnum = curwin->w_cursor.lnum;
4434 			break;
4435 		    case ADDR_WINDOWS:
4436 			lnum = CURRENT_WIN_NR;
4437 			break;
4438 		    case ADDR_ARGUMENTS:
4439 			lnum = curwin->w_arg_idx + 1;
4440 			break;
4441 		    case ADDR_LOADED_BUFFERS:
4442 		    case ADDR_BUFFERS:
4443 			lnum = curbuf->b_fnum;
4444 			break;
4445 		    case ADDR_TABS:
4446 			lnum = CURRENT_TAB_NR;
4447 			break;
4448 		    case ADDR_TABS_RELATIVE:
4449 			EMSG(_(e_invrange));
4450 			cmd = NULL;
4451 			goto error;
4452 			break;
4453 #ifdef FEAT_QUICKFIX
4454 		    case ADDR_QUICKFIX:
4455 			lnum = qf_get_cur_valid_idx(eap);
4456 			break;
4457 #endif
4458 		}
4459 		break;
4460 
4461 	    case '$':			    /* '$' - last line */
4462 		++cmd;
4463 		switch (addr_type)
4464 		{
4465 		    case ADDR_LINES:
4466 			lnum = curbuf->b_ml.ml_line_count;
4467 			break;
4468 		    case ADDR_WINDOWS:
4469 			lnum = LAST_WIN_NR;
4470 			break;
4471 		    case ADDR_ARGUMENTS:
4472 			lnum = ARGCOUNT;
4473 			break;
4474 		    case ADDR_LOADED_BUFFERS:
4475 			buf = lastbuf;
4476 			while (buf->b_ml.ml_mfp == NULL)
4477 			{
4478 			    if (buf->b_prev == NULL)
4479 				break;
4480 			    buf = buf->b_prev;
4481 			}
4482 			lnum = buf->b_fnum;
4483 			break;
4484 		    case ADDR_BUFFERS:
4485 			lnum = lastbuf->b_fnum;
4486 			break;
4487 		    case ADDR_TABS:
4488 			lnum = LAST_TAB_NR;
4489 			break;
4490 		    case ADDR_TABS_RELATIVE:
4491 			EMSG(_(e_invrange));
4492 			cmd = NULL;
4493 			goto error;
4494 			break;
4495 #ifdef FEAT_QUICKFIX
4496 		    case ADDR_QUICKFIX:
4497 			lnum = qf_get_size(eap);
4498 			if (lnum == 0)
4499 			    lnum = 1;
4500 			break;
4501 #endif
4502 		}
4503 		break;
4504 
4505 	    case '\'':			    /* ''' - mark */
4506 		if (*++cmd == NUL)
4507 		{
4508 		    cmd = NULL;
4509 		    goto error;
4510 		}
4511 		if (addr_type != ADDR_LINES)
4512 		{
4513 		    EMSG(_(e_invaddr));
4514 		    cmd = NULL;
4515 		    goto error;
4516 		}
4517 		if (skip)
4518 		    ++cmd;
4519 		else
4520 		{
4521 		    /* Only accept a mark in another file when it is
4522 		     * used by itself: ":'M". */
4523 		    fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
4524 		    ++cmd;
4525 		    if (fp == (pos_T *)-1)
4526 			/* Jumped to another file. */
4527 			lnum = curwin->w_cursor.lnum;
4528 		    else
4529 		    {
4530 			if (check_mark(fp) == FAIL)
4531 			{
4532 			    cmd = NULL;
4533 			    goto error;
4534 			}
4535 			lnum = fp->lnum;
4536 		    }
4537 		}
4538 		break;
4539 
4540 	    case '/':
4541 	    case '?':			/* '/' or '?' - search */
4542 		c = *cmd++;
4543 		if (addr_type != ADDR_LINES)
4544 		{
4545 		    EMSG(_(e_invaddr));
4546 		    cmd = NULL;
4547 		    goto error;
4548 		}
4549 		if (skip)	/* skip "/pat/" */
4550 		{
4551 		    cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
4552 		    if (*cmd == c)
4553 			++cmd;
4554 		}
4555 		else
4556 		{
4557 		    pos = curwin->w_cursor; /* save curwin->w_cursor */
4558 		    /*
4559 		     * When '/' or '?' follows another address, start
4560 		     * from there.
4561 		     */
4562 		    if (lnum != MAXLNUM)
4563 			curwin->w_cursor.lnum = lnum;
4564 		    /*
4565 		     * Start a forward search at the end of the line.
4566 		     * Start a backward search at the start of the line.
4567 		     * This makes sure we never match in the current
4568 		     * line, and can match anywhere in the
4569 		     * next/previous line.
4570 		     */
4571 		    if (c == '/')
4572 			curwin->w_cursor.col = MAXCOL;
4573 		    else
4574 			curwin->w_cursor.col = 0;
4575 		    searchcmdlen = 0;
4576 		    if (!do_search(NULL, c, cmd, 1L,
4577 					  SEARCH_HIS | SEARCH_MSG, NULL, NULL))
4578 		    {
4579 			curwin->w_cursor = pos;
4580 			cmd = NULL;
4581 			goto error;
4582 		    }
4583 		    lnum = curwin->w_cursor.lnum;
4584 		    curwin->w_cursor = pos;
4585 		    /* adjust command string pointer */
4586 		    cmd += searchcmdlen;
4587 		}
4588 		break;
4589 
4590 	    case '\\':		    /* "\?", "\/" or "\&", repeat search */
4591 		++cmd;
4592 		if (addr_type != ADDR_LINES)
4593 		{
4594 		    EMSG(_(e_invaddr));
4595 		    cmd = NULL;
4596 		    goto error;
4597 		}
4598 		if (*cmd == '&')
4599 		    i = RE_SUBST;
4600 		else if (*cmd == '?' || *cmd == '/')
4601 		    i = RE_SEARCH;
4602 		else
4603 		{
4604 		    EMSG(_(e_backslash));
4605 		    cmd = NULL;
4606 		    goto error;
4607 		}
4608 
4609 		if (!skip)
4610 		{
4611 		    /*
4612 		     * When search follows another address, start from
4613 		     * there.
4614 		     */
4615 		    if (lnum != MAXLNUM)
4616 			pos.lnum = lnum;
4617 		    else
4618 			pos.lnum = curwin->w_cursor.lnum;
4619 
4620 		    /*
4621 		     * Start the search just like for the above
4622 		     * do_search().
4623 		     */
4624 		    if (*cmd != '?')
4625 			pos.col = MAXCOL;
4626 		    else
4627 			pos.col = 0;
4628 #ifdef FEAT_VIRTUALEDIT
4629 		    pos.coladd = 0;
4630 #endif
4631 		    if (searchit(curwin, curbuf, &pos,
4632 				*cmd == '?' ? BACKWARD : FORWARD,
4633 				(char_u *)"", 1L, SEARCH_MSG,
4634 					i, (linenr_T)0, NULL, NULL) != FAIL)
4635 			lnum = pos.lnum;
4636 		    else
4637 		    {
4638 			cmd = NULL;
4639 			goto error;
4640 		    }
4641 		}
4642 		++cmd;
4643 		break;
4644 
4645 	    default:
4646 		if (VIM_ISDIGIT(*cmd))	/* absolute line number */
4647 		    lnum = getdigits(&cmd);
4648 	}
4649 
4650 	for (;;)
4651 	{
4652 	    cmd = skipwhite(cmd);
4653 	    if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
4654 		break;
4655 
4656 	    if (lnum == MAXLNUM)
4657 	    {
4658 		switch (addr_type)
4659 		{
4660 		    case ADDR_LINES:
4661 			/* "+1" is same as ".+1" */
4662 			lnum = curwin->w_cursor.lnum;
4663 			break;
4664 		    case ADDR_WINDOWS:
4665 			lnum = CURRENT_WIN_NR;
4666 			break;
4667 		    case ADDR_ARGUMENTS:
4668 			lnum = curwin->w_arg_idx + 1;
4669 			break;
4670 		    case ADDR_LOADED_BUFFERS:
4671 		    case ADDR_BUFFERS:
4672 			lnum = curbuf->b_fnum;
4673 			break;
4674 		    case ADDR_TABS:
4675 			lnum = CURRENT_TAB_NR;
4676 			break;
4677 		    case ADDR_TABS_RELATIVE:
4678 			lnum = 1;
4679 			break;
4680 #ifdef FEAT_QUICKFIX
4681 		    case ADDR_QUICKFIX:
4682 			lnum = qf_get_cur_valid_idx(eap);
4683 			break;
4684 #endif
4685 		}
4686 	    }
4687 
4688 	    if (VIM_ISDIGIT(*cmd))
4689 		i = '+';		/* "number" is same as "+number" */
4690 	    else
4691 		i = *cmd++;
4692 	    if (!VIM_ISDIGIT(*cmd))	/* '+' is '+1', but '+0' is not '+1' */
4693 		n = 1;
4694 	    else
4695 		n = getdigits(&cmd);
4696 
4697 	    if (addr_type == ADDR_TABS_RELATIVE)
4698 	    {
4699 		EMSG(_(e_invrange));
4700 		cmd = NULL;
4701 		goto error;
4702 	    }
4703 	    else if (addr_type == ADDR_LOADED_BUFFERS
4704 		    || addr_type == ADDR_BUFFERS)
4705 		lnum = compute_buffer_local_count(
4706 				    addr_type, lnum, (i == '-') ? -1 * n : n);
4707 	    else
4708 	    {
4709 #ifdef FEAT_FOLDING
4710 		/* Relative line addressing, need to adjust for folded lines
4711 		 * now, but only do it after the first address. */
4712 		if (addr_type == ADDR_LINES && (i == '-' || i == '+')
4713 			&& address_count >= 2)
4714 		    (void)hasFolding(lnum, NULL, &lnum);
4715 #endif
4716 		if (i == '-')
4717 		    lnum -= n;
4718 		else
4719 		    lnum += n;
4720 	    }
4721 	}
4722     } while (*cmd == '/' || *cmd == '?');
4723 
4724 error:
4725     *ptr = cmd;
4726     return lnum;
4727 }
4728 
4729 /*
4730  * Get flags from an Ex command argument.
4731  */
4732     static void
4733 get_flags(exarg_T *eap)
4734 {
4735     while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL)
4736     {
4737 	if (*eap->arg == 'l')
4738 	    eap->flags |= EXFLAG_LIST;
4739 	else if (*eap->arg == 'p')
4740 	    eap->flags |= EXFLAG_PRINT;
4741 	else
4742 	    eap->flags |= EXFLAG_NR;
4743 	eap->arg = skipwhite(eap->arg + 1);
4744     }
4745 }
4746 
4747 /*
4748  * Function called for command which is Not Implemented.  NI!
4749  */
4750     void
4751 ex_ni(exarg_T *eap)
4752 {
4753     if (!eap->skip)
4754 	eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
4755 }
4756 
4757 #ifdef HAVE_EX_SCRIPT_NI
4758 /*
4759  * Function called for script command which is Not Implemented.  NI!
4760  * Skips over ":perl <<EOF" constructs.
4761  */
4762     static void
4763 ex_script_ni(exarg_T *eap)
4764 {
4765     if (!eap->skip)
4766 	ex_ni(eap);
4767     else
4768 	vim_free(script_get(eap, eap->arg));
4769 }
4770 #endif
4771 
4772 /*
4773  * Check range in Ex command for validity.
4774  * Return NULL when valid, error message when invalid.
4775  */
4776     static char_u *
4777 invalid_range(exarg_T *eap)
4778 {
4779     buf_T	*buf;
4780     if (       eap->line1 < 0
4781 	    || eap->line2 < 0
4782 	    || eap->line1 > eap->line2)
4783 	return (char_u *)_(e_invrange);
4784 
4785     if (eap->argt & RANGE)
4786     {
4787 	switch(eap->addr_type)
4788 	{
4789 	    case ADDR_LINES:
4790 		if (!(eap->argt & NOTADR)
4791 			&& eap->line2 > curbuf->b_ml.ml_line_count
4792 #ifdef FEAT_DIFF
4793 			    + (eap->cmdidx == CMD_diffget)
4794 #endif
4795 		   )
4796 		    return (char_u *)_(e_invrange);
4797 		break;
4798 	    case ADDR_ARGUMENTS:
4799 		/* add 1 if ARGCOUNT is 0 */
4800 		if (eap->line2 > ARGCOUNT + (!ARGCOUNT))
4801 		    return (char_u *)_(e_invrange);
4802 		break;
4803 	    case ADDR_BUFFERS:
4804 		if (eap->line1 < firstbuf->b_fnum
4805 			|| eap->line2 > lastbuf->b_fnum)
4806 		    return (char_u *)_(e_invrange);
4807 		break;
4808 	    case ADDR_LOADED_BUFFERS:
4809 		buf = firstbuf;
4810 		while (buf->b_ml.ml_mfp == NULL)
4811 		{
4812 		    if (buf->b_next == NULL)
4813 			return (char_u *)_(e_invrange);
4814 		    buf = buf->b_next;
4815 		}
4816 		if (eap->line1 < buf->b_fnum)
4817 		    return (char_u *)_(e_invrange);
4818 		buf = lastbuf;
4819 		while (buf->b_ml.ml_mfp == NULL)
4820 		{
4821 		    if (buf->b_prev == NULL)
4822 			return (char_u *)_(e_invrange);
4823 		    buf = buf->b_prev;
4824 		}
4825 		if (eap->line2 > buf->b_fnum)
4826 		    return (char_u *)_(e_invrange);
4827 		break;
4828 	    case ADDR_WINDOWS:
4829 		if (eap->line2 > LAST_WIN_NR)
4830 		    return (char_u *)_(e_invrange);
4831 		break;
4832 	    case ADDR_TABS:
4833 		if (eap->line2 > LAST_TAB_NR)
4834 		    return (char_u *)_(e_invrange);
4835 		break;
4836 	    case ADDR_TABS_RELATIVE:
4837 		/* Do nothing */
4838 		break;
4839 #ifdef FEAT_QUICKFIX
4840 	    case ADDR_QUICKFIX:
4841 		if (eap->line2 != 1 && eap->line2 > qf_get_size(eap))
4842 		    return (char_u *)_(e_invrange);
4843 		break;
4844 #endif
4845 	}
4846     }
4847     return NULL;
4848 }
4849 
4850 /*
4851  * Correct the range for zero line number, if required.
4852  */
4853     static void
4854 correct_range(exarg_T *eap)
4855 {
4856     if (!(eap->argt & ZEROR))	    /* zero in range not allowed */
4857     {
4858 	if (eap->line1 == 0)
4859 	    eap->line1 = 1;
4860 	if (eap->line2 == 0)
4861 	    eap->line2 = 1;
4862     }
4863 }
4864 
4865 #ifdef FEAT_QUICKFIX
4866 static char_u	*skip_grep_pat(exarg_T *eap);
4867 
4868 /*
4869  * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
4870  * pattern.  Otherwise return eap->arg.
4871  */
4872     static char_u *
4873 skip_grep_pat(exarg_T *eap)
4874 {
4875     char_u	*p = eap->arg;
4876 
4877     if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
4878 		|| eap->cmdidx == CMD_vimgrepadd
4879 		|| eap->cmdidx == CMD_lvimgrepadd
4880 		|| grep_internal(eap->cmdidx)))
4881     {
4882 	p = skip_vimgrep_pat(p, NULL, NULL);
4883 	if (p == NULL)
4884 	    p = eap->arg;
4885     }
4886     return p;
4887 }
4888 
4889 /*
4890  * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
4891  * in the command line, so that things like % get expanded.
4892  */
4893     static char_u *
4894 replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep)
4895 {
4896     char_u	*new_cmdline;
4897     char_u	*program;
4898     char_u	*pos;
4899     char_u	*ptr;
4900     int		len;
4901     int		i;
4902 
4903     /*
4904      * Don't do it when ":vimgrep" is used for ":grep".
4905      */
4906     if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake
4907 		     || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4908 		     || eap->cmdidx == CMD_grepadd
4909 		     || eap->cmdidx == CMD_lgrepadd)
4910 	    && !grep_internal(eap->cmdidx))
4911     {
4912 	if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4913 	    || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd)
4914 	{
4915 	    if (*curbuf->b_p_gp == NUL)
4916 		program = p_gp;
4917 	    else
4918 		program = curbuf->b_p_gp;
4919 	}
4920 	else
4921 	{
4922 	    if (*curbuf->b_p_mp == NUL)
4923 		program = p_mp;
4924 	    else
4925 		program = curbuf->b_p_mp;
4926 	}
4927 
4928 	p = skipwhite(p);
4929 
4930 	if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4931 	{
4932 	    /* replace $* by given arguments */
4933 	    i = 1;
4934 	    while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
4935 		++i;
4936 	    len = (int)STRLEN(p);
4937 	    new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
4938 	    if (new_cmdline == NULL)
4939 		return NULL;			/* out of memory */
4940 	    ptr = new_cmdline;
4941 	    while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4942 	    {
4943 		i = (int)(pos - program);
4944 		STRNCPY(ptr, program, i);
4945 		STRCPY(ptr += i, p);
4946 		ptr += len;
4947 		program = pos + 2;
4948 	    }
4949 	    STRCPY(ptr, program);
4950 	}
4951 	else
4952 	{
4953 	    new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
4954 	    if (new_cmdline == NULL)
4955 		return NULL;			/* out of memory */
4956 	    STRCPY(new_cmdline, program);
4957 	    STRCAT(new_cmdline, " ");
4958 	    STRCAT(new_cmdline, p);
4959 	}
4960 	msg_make(p);
4961 
4962 	/* 'eap->cmd' is not set here, because it is not used at CMD_make */
4963 	vim_free(*cmdlinep);
4964 	*cmdlinep = new_cmdline;
4965 	p = new_cmdline;
4966     }
4967     return p;
4968 }
4969 #endif
4970 
4971 /*
4972  * Expand file name in Ex command argument.
4973  * Return FAIL for failure, OK otherwise.
4974  */
4975     int
4976 expand_filename(
4977     exarg_T	*eap,
4978     char_u	**cmdlinep,
4979     char_u	**errormsgp)
4980 {
4981     int		has_wildcards;	/* need to expand wildcards */
4982     char_u	*repl;
4983     int		srclen;
4984     char_u	*p;
4985     int		n;
4986     int		escaped;
4987 
4988 #ifdef FEAT_QUICKFIX
4989     /* Skip a regexp pattern for ":vimgrep[add] pat file..." */
4990     p = skip_grep_pat(eap);
4991 #else
4992     p = eap->arg;
4993 #endif
4994 
4995     /*
4996      * Decide to expand wildcards *before* replacing '%', '#', etc.  If
4997      * the file name contains a wildcard it should not cause expanding.
4998      * (it will be expanded anyway if there is a wildcard before replacing).
4999      */
5000     has_wildcards = mch_has_wildcard(p);
5001     while (*p != NUL)
5002     {
5003 #ifdef FEAT_EVAL
5004 	/* Skip over `=expr`, wildcards in it are not expanded. */
5005 	if (p[0] == '`' && p[1] == '=')
5006 	{
5007 	    p += 2;
5008 	    (void)skip_expr(&p);
5009 	    if (*p == '`')
5010 		++p;
5011 	    continue;
5012 	}
5013 #endif
5014 	/*
5015 	 * Quick check if this cannot be the start of a special string.
5016 	 * Also removes backslash before '%', '#' and '<'.
5017 	 */
5018 	if (vim_strchr((char_u *)"%#<", *p) == NULL)
5019 	{
5020 	    ++p;
5021 	    continue;
5022 	}
5023 
5024 	/*
5025 	 * Try to find a match at this position.
5026 	 */
5027 	repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
5028 							 errormsgp, &escaped);
5029 	if (*errormsgp != NULL)		/* error detected */
5030 	    return FAIL;
5031 	if (repl == NULL)		/* no match found */
5032 	{
5033 	    p += srclen;
5034 	    continue;
5035 	}
5036 
5037 	/* Wildcards won't be expanded below, the replacement is taken
5038 	 * literally.  But do expand "~/file", "~user/file" and "$HOME/file". */
5039 	if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
5040 	{
5041 	    char_u *l = repl;
5042 
5043 	    repl = expand_env_save(repl);
5044 	    vim_free(l);
5045 	}
5046 
5047 	/* Need to escape white space et al. with a backslash.
5048 	 * Don't do this for:
5049 	 * - replacement that already has been escaped: "##"
5050 	 * - shell commands (may have to use quotes instead).
5051 	 * - non-unix systems when there is a single argument (spaces don't
5052 	 *   separate arguments then).
5053 	 */
5054 	if (!eap->usefilter
5055 		&& !escaped
5056 		&& eap->cmdidx != CMD_bang
5057 		&& eap->cmdidx != CMD_grep
5058 		&& eap->cmdidx != CMD_grepadd
5059 		&& eap->cmdidx != CMD_hardcopy
5060 		&& eap->cmdidx != CMD_lgrep
5061 		&& eap->cmdidx != CMD_lgrepadd
5062 		&& eap->cmdidx != CMD_lmake
5063 		&& eap->cmdidx != CMD_make
5064 		&& eap->cmdidx != CMD_terminal
5065 #ifndef UNIX
5066 		&& !(eap->argt & NOSPC)
5067 #endif
5068 		)
5069 	{
5070 	    char_u	*l;
5071 #ifdef BACKSLASH_IN_FILENAME
5072 	    /* Don't escape a backslash here, because rem_backslash() doesn't
5073 	     * remove it later. */
5074 	    static char_u *nobslash = (char_u *)" \t\"|";
5075 # define ESCAPE_CHARS nobslash
5076 #else
5077 # define ESCAPE_CHARS escape_chars
5078 #endif
5079 
5080 	    for (l = repl; *l; ++l)
5081 		if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
5082 		{
5083 		    l = vim_strsave_escaped(repl, ESCAPE_CHARS);
5084 		    if (l != NULL)
5085 		    {
5086 			vim_free(repl);
5087 			repl = l;
5088 		    }
5089 		    break;
5090 		}
5091 	}
5092 
5093 	/* For a shell command a '!' must be escaped. */
5094 	if ((eap->usefilter || eap->cmdidx == CMD_bang
5095 						|| eap->cmdidx == CMD_terminal)
5096 			    && vim_strpbrk(repl, (char_u *)"!") != NULL)
5097 	{
5098 	    char_u	*l;
5099 
5100 	    l = vim_strsave_escaped(repl, (char_u *)"!");
5101 	    if (l != NULL)
5102 	    {
5103 		vim_free(repl);
5104 		repl = l;
5105 	    }
5106 	}
5107 
5108 	p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
5109 	vim_free(repl);
5110 	if (p == NULL)
5111 	    return FAIL;
5112     }
5113 
5114     /*
5115      * One file argument: Expand wildcards.
5116      * Don't do this with ":r !command" or ":w !command".
5117      */
5118     if ((eap->argt & NOSPC) && !eap->usefilter)
5119     {
5120 	/*
5121 	 * May do this twice:
5122 	 * 1. Replace environment variables.
5123 	 * 2. Replace any other wildcards, remove backslashes.
5124 	 */
5125 	for (n = 1; n <= 2; ++n)
5126 	{
5127 	    if (n == 2)
5128 	    {
5129 #ifdef UNIX
5130 		/*
5131 		 * Only for Unix we check for more than one file name.
5132 		 * For other systems spaces are considered to be part
5133 		 * of the file name.
5134 		 * Only check here if there is no wildcard, otherwise
5135 		 * ExpandOne() will check for errors. This allows
5136 		 * ":e `ls ve*.c`" on Unix.
5137 		 */
5138 		if (!has_wildcards)
5139 		    for (p = eap->arg; *p; ++p)
5140 		    {
5141 			/* skip escaped characters */
5142 			if (p[1] && (*p == '\\' || *p == Ctrl_V))
5143 			    ++p;
5144 			else if (VIM_ISWHITE(*p))
5145 			{
5146 			    *errormsgp = (char_u *)_("E172: Only one file name allowed");
5147 			    return FAIL;
5148 			}
5149 		    }
5150 #endif
5151 
5152 		/*
5153 		 * Halve the number of backslashes (this is Vi compatible).
5154 		 * For Unix and OS/2, when wildcards are expanded, this is
5155 		 * done by ExpandOne() below.
5156 		 */
5157 #if defined(UNIX)
5158 		if (!has_wildcards)
5159 #endif
5160 		    backslash_halve(eap->arg);
5161 	    }
5162 
5163 	    if (has_wildcards)
5164 	    {
5165 		if (n == 1)
5166 		{
5167 		    /*
5168 		     * First loop: May expand environment variables.  This
5169 		     * can be done much faster with expand_env() than with
5170 		     * something else (e.g., calling a shell).
5171 		     * After expanding environment variables, check again
5172 		     * if there are still wildcards present.
5173 		     */
5174 		    if (vim_strchr(eap->arg, '$') != NULL
5175 			    || vim_strchr(eap->arg, '~') != NULL)
5176 		    {
5177 			expand_env_esc(eap->arg, NameBuff, MAXPATHL,
5178 							    TRUE, TRUE, NULL);
5179 			has_wildcards = mch_has_wildcard(NameBuff);
5180 			p = NameBuff;
5181 		    }
5182 		    else
5183 			p = NULL;
5184 		}
5185 		else /* n == 2 */
5186 		{
5187 		    expand_T	xpc;
5188 		    int		options = WILD_LIST_NOTFOUND|WILD_ADD_SLASH;
5189 
5190 		    ExpandInit(&xpc);
5191 		    xpc.xp_context = EXPAND_FILES;
5192 		    if (p_wic)
5193 			options += WILD_ICASE;
5194 		    p = ExpandOne(&xpc, eap->arg, NULL,
5195 						   options, WILD_EXPAND_FREE);
5196 		    if (p == NULL)
5197 			return FAIL;
5198 		}
5199 		if (p != NULL)
5200 		{
5201 		    (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
5202 								 p, cmdlinep);
5203 		    if (n == 2)	/* p came from ExpandOne() */
5204 			vim_free(p);
5205 		}
5206 	    }
5207 	}
5208     }
5209     return OK;
5210 }
5211 
5212 /*
5213  * Replace part of the command line, keeping eap->cmd, eap->arg and
5214  * eap->nextcmd correct.
5215  * "src" points to the part that is to be replaced, of length "srclen".
5216  * "repl" is the replacement string.
5217  * Returns a pointer to the character after the replaced string.
5218  * Returns NULL for failure.
5219  */
5220     static char_u *
5221 repl_cmdline(
5222     exarg_T	*eap,
5223     char_u	*src,
5224     int		srclen,
5225     char_u	*repl,
5226     char_u	**cmdlinep)
5227 {
5228     int		len;
5229     int		i;
5230     char_u	*new_cmdline;
5231 
5232     /*
5233      * The new command line is build in new_cmdline[].
5234      * First allocate it.
5235      * Careful: a "+cmd" argument may have been NUL terminated.
5236      */
5237     len = (int)STRLEN(repl);
5238     i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
5239     if (eap->nextcmd != NULL)
5240 	i += (int)STRLEN(eap->nextcmd);/* add space for next command */
5241     if ((new_cmdline = alloc((unsigned)i)) == NULL)
5242 	return NULL;			/* out of memory! */
5243 
5244     /*
5245      * Copy the stuff before the expanded part.
5246      * Copy the expanded stuff.
5247      * Copy what came after the expanded part.
5248      * Copy the next commands, if there are any.
5249      */
5250     i = (int)(src - *cmdlinep);	/* length of part before match */
5251     mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
5252 
5253     mch_memmove(new_cmdline + i, repl, (size_t)len);
5254     i += len;				/* remember the end of the string */
5255     STRCPY(new_cmdline + i, src + srclen);
5256     src = new_cmdline + i;		/* remember where to continue */
5257 
5258     if (eap->nextcmd != NULL)		/* append next command */
5259     {
5260 	i = (int)STRLEN(new_cmdline) + 1;
5261 	STRCPY(new_cmdline + i, eap->nextcmd);
5262 	eap->nextcmd = new_cmdline + i;
5263     }
5264     eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
5265     eap->arg = new_cmdline + (eap->arg - *cmdlinep);
5266     if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
5267 	eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
5268     vim_free(*cmdlinep);
5269     *cmdlinep = new_cmdline;
5270 
5271     return src;
5272 }
5273 
5274 /*
5275  * Check for '|' to separate commands and '"' to start comments.
5276  */
5277     void
5278 separate_nextcmd(exarg_T *eap)
5279 {
5280     char_u	*p;
5281 
5282 #ifdef FEAT_QUICKFIX
5283     p = skip_grep_pat(eap);
5284 #else
5285     p = eap->arg;
5286 #endif
5287 
5288     for ( ; *p; MB_PTR_ADV(p))
5289     {
5290 	if (*p == Ctrl_V)
5291 	{
5292 	    if (eap->argt & (USECTRLV | XFILE))
5293 		++p;		/* skip CTRL-V and next char */
5294 	    else
5295 				/* remove CTRL-V and skip next char */
5296 		STRMOVE(p, p + 1);
5297 	    if (*p == NUL)		/* stop at NUL after CTRL-V */
5298 		break;
5299 	}
5300 
5301 #ifdef FEAT_EVAL
5302 	/* Skip over `=expr` when wildcards are expanded. */
5303 	else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE))
5304 	{
5305 	    p += 2;
5306 	    (void)skip_expr(&p);
5307 	}
5308 #endif
5309 
5310 	/* Check for '"': start of comment or '|': next command */
5311 	/* :@" and :*" do not start a comment!
5312 	 * :redir @" doesn't either. */
5313 	else if ((*p == '"' && !(eap->argt & NOTRLCOM)
5314 		    && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
5315 			|| p != eap->arg)
5316 		    && (eap->cmdidx != CMD_redir
5317 			|| p != eap->arg + 1 || p[-1] != '@'))
5318 		|| *p == '|' || *p == '\n')
5319 	{
5320 	    /*
5321 	     * We remove the '\' before the '|', unless USECTRLV is used
5322 	     * AND 'b' is present in 'cpoptions'.
5323 	     */
5324 	    if ((vim_strchr(p_cpo, CPO_BAR) == NULL
5325 			      || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
5326 	    {
5327 		STRMOVE(p - 1, p);	/* remove the '\' */
5328 		--p;
5329 	    }
5330 	    else
5331 	    {
5332 		eap->nextcmd = check_nextcmd(p);
5333 		*p = NUL;
5334 		break;
5335 	    }
5336 	}
5337     }
5338 
5339     if (!(eap->argt & NOTRLCOM))	/* remove trailing spaces */
5340 	del_trailing_spaces(eap->arg);
5341 }
5342 
5343 /*
5344  * get + command from ex argument
5345  */
5346     static char_u *
5347 getargcmd(char_u **argp)
5348 {
5349     char_u *arg = *argp;
5350     char_u *command = NULL;
5351 
5352     if (*arg == '+')	    /* +[command] */
5353     {
5354 	++arg;
5355 	if (vim_isspace(*arg) || *arg == NUL)
5356 	    command = dollar_command;
5357 	else
5358 	{
5359 	    command = arg;
5360 	    arg = skip_cmd_arg(command, TRUE);
5361 	    if (*arg != NUL)
5362 		*arg++ = NUL;		/* terminate command with NUL */
5363 	}
5364 
5365 	arg = skipwhite(arg);	/* skip over spaces */
5366 	*argp = arg;
5367     }
5368     return command;
5369 }
5370 
5371 /*
5372  * Find end of "+command" argument.  Skip over "\ " and "\\".
5373  */
5374     static char_u *
5375 skip_cmd_arg(
5376     char_u *p,
5377     int	   rembs)	/* TRUE to halve the number of backslashes */
5378 {
5379     while (*p && !vim_isspace(*p))
5380     {
5381 	if (*p == '\\' && p[1] != NUL)
5382 	{
5383 	    if (rembs)
5384 		STRMOVE(p, p + 1);
5385 	    else
5386 		++p;
5387 	}
5388 	MB_PTR_ADV(p);
5389     }
5390     return p;
5391 }
5392 
5393 /*
5394  * Get "++opt=arg" argument.
5395  * Return FAIL or OK.
5396  */
5397     static int
5398 getargopt(exarg_T *eap)
5399 {
5400     char_u	*arg = eap->arg + 2;
5401     int		*pp = NULL;
5402 #ifdef FEAT_MBYTE
5403     int		bad_char_idx;
5404     char_u	*p;
5405 #endif
5406 
5407     /* ":edit ++[no]bin[ary] file" */
5408     if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
5409     {
5410 	if (*arg == 'n')
5411 	{
5412 	    arg += 2;
5413 	    eap->force_bin = FORCE_NOBIN;
5414 	}
5415 	else
5416 	    eap->force_bin = FORCE_BIN;
5417 	if (!checkforcmd(&arg, "binary", 3))
5418 	    return FAIL;
5419 	eap->arg = skipwhite(arg);
5420 	return OK;
5421     }
5422 
5423     /* ":read ++edit file" */
5424     if (STRNCMP(arg, "edit", 4) == 0)
5425     {
5426 	eap->read_edit = TRUE;
5427 	eap->arg = skipwhite(arg + 4);
5428 	return OK;
5429     }
5430 
5431     if (STRNCMP(arg, "ff", 2) == 0)
5432     {
5433 	arg += 2;
5434 	pp = &eap->force_ff;
5435     }
5436     else if (STRNCMP(arg, "fileformat", 10) == 0)
5437     {
5438 	arg += 10;
5439 	pp = &eap->force_ff;
5440     }
5441 #ifdef FEAT_MBYTE
5442     else if (STRNCMP(arg, "enc", 3) == 0)
5443     {
5444 	if (STRNCMP(arg, "encoding", 8) == 0)
5445 	    arg += 8;
5446 	else
5447 	    arg += 3;
5448 	pp = &eap->force_enc;
5449     }
5450     else if (STRNCMP(arg, "bad", 3) == 0)
5451     {
5452 	arg += 3;
5453 	pp = &bad_char_idx;
5454     }
5455 #endif
5456 
5457     if (pp == NULL || *arg != '=')
5458 	return FAIL;
5459 
5460     ++arg;
5461     *pp = (int)(arg - eap->cmd);
5462     arg = skip_cmd_arg(arg, FALSE);
5463     eap->arg = skipwhite(arg);
5464     *arg = NUL;
5465 
5466 #ifdef FEAT_MBYTE
5467     if (pp == &eap->force_ff)
5468     {
5469 #endif
5470 	if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
5471 	    return FAIL;
5472 #ifdef FEAT_MBYTE
5473     }
5474     else if (pp == &eap->force_enc)
5475     {
5476 	/* Make 'fileencoding' lower case. */
5477 	for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
5478 	    *p = TOLOWER_ASC(*p);
5479     }
5480     else
5481     {
5482 	/* Check ++bad= argument.  Must be a single-byte character, "keep" or
5483 	 * "drop". */
5484 	p = eap->cmd + bad_char_idx;
5485 	if (STRICMP(p, "keep") == 0)
5486 	    eap->bad_char = BAD_KEEP;
5487 	else if (STRICMP(p, "drop") == 0)
5488 	    eap->bad_char = BAD_DROP;
5489 	else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
5490 	    eap->bad_char = *p;
5491 	else
5492 	    return FAIL;
5493     }
5494 #endif
5495 
5496     return OK;
5497 }
5498 
5499 /*
5500  * ":abbreviate" and friends.
5501  */
5502     static void
5503 ex_abbreviate(exarg_T *eap)
5504 {
5505     do_exmap(eap, TRUE);	/* almost the same as mapping */
5506 }
5507 
5508 /*
5509  * ":map" and friends.
5510  */
5511     static void
5512 ex_map(exarg_T *eap)
5513 {
5514     /*
5515      * If we are sourcing .exrc or .vimrc in current directory we
5516      * print the mappings for security reasons.
5517      */
5518     if (secure)
5519     {
5520 	secure = 2;
5521 	msg_outtrans(eap->cmd);
5522 	msg_putchar('\n');
5523     }
5524     do_exmap(eap, FALSE);
5525 }
5526 
5527 /*
5528  * ":unmap" and friends.
5529  */
5530     static void
5531 ex_unmap(exarg_T *eap)
5532 {
5533     do_exmap(eap, FALSE);
5534 }
5535 
5536 /*
5537  * ":mapclear" and friends.
5538  */
5539     static void
5540 ex_mapclear(exarg_T *eap)
5541 {
5542     map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
5543 }
5544 
5545 /*
5546  * ":abclear" and friends.
5547  */
5548     static void
5549 ex_abclear(exarg_T *eap)
5550 {
5551     map_clear(eap->cmd, eap->arg, TRUE, TRUE);
5552 }
5553 
5554 #if defined(FEAT_AUTOCMD) || defined(PROTO)
5555     static void
5556 ex_autocmd(exarg_T *eap)
5557 {
5558     /*
5559      * Disallow auto commands from .exrc and .vimrc in current
5560      * directory for security reasons.
5561      */
5562     if (secure)
5563     {
5564 	secure = 2;
5565 	eap->errmsg = e_curdir;
5566     }
5567     else if (eap->cmdidx == CMD_autocmd)
5568 	do_autocmd(eap->arg, eap->forceit);
5569     else
5570 	do_augroup(eap->arg, eap->forceit);
5571 }
5572 
5573 /*
5574  * ":doautocmd": Apply the automatic commands to the current buffer.
5575  */
5576     static void
5577 ex_doautocmd(exarg_T *eap)
5578 {
5579     char_u	*arg = eap->arg;
5580     int		call_do_modelines = check_nomodeline(&arg);
5581     int		did_aucmd;
5582 
5583     (void)do_doautocmd(arg, TRUE, &did_aucmd);
5584     /* Only when there is no <nomodeline>. */
5585     if (call_do_modelines && did_aucmd)
5586 	do_modelines(0);
5587 }
5588 #endif
5589 
5590 #ifdef FEAT_LISTCMDS
5591 /*
5592  * :[N]bunload[!] [N] [bufname] unload buffer
5593  * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
5594  * :[N]bwipeout[!] [N] [bufname] delete buffer really
5595  */
5596     static void
5597 ex_bunload(exarg_T *eap)
5598 {
5599     eap->errmsg = do_bufdel(
5600 	    eap->cmdidx == CMD_bdelete ? DOBUF_DEL
5601 		: eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
5602 		: DOBUF_UNLOAD, eap->arg,
5603 	    eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
5604 }
5605 
5606 /*
5607  * :[N]buffer [N]	to buffer N
5608  * :[N]sbuffer [N]	to buffer N
5609  */
5610     static void
5611 ex_buffer(exarg_T *eap)
5612 {
5613     if (*eap->arg)
5614 	eap->errmsg = e_trailing;
5615     else
5616     {
5617 	if (eap->addr_count == 0)	/* default is current buffer */
5618 	    goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
5619 	else
5620 	    goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
5621 	if (eap->do_ecmd_cmd != NULL)
5622 	    do_cmdline_cmd(eap->do_ecmd_cmd);
5623     }
5624 }
5625 
5626 /*
5627  * :[N]bmodified [N]	to next mod. buffer
5628  * :[N]sbmodified [N]	to next mod. buffer
5629  */
5630     static void
5631 ex_bmodified(exarg_T *eap)
5632 {
5633     goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
5634     if (eap->do_ecmd_cmd != NULL)
5635 	do_cmdline_cmd(eap->do_ecmd_cmd);
5636 }
5637 
5638 /*
5639  * :[N]bnext [N]	to next buffer
5640  * :[N]sbnext [N]	split and to next buffer
5641  */
5642     static void
5643 ex_bnext(exarg_T *eap)
5644 {
5645     goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
5646     if (eap->do_ecmd_cmd != NULL)
5647 	do_cmdline_cmd(eap->do_ecmd_cmd);
5648 }
5649 
5650 /*
5651  * :[N]bNext [N]	to previous buffer
5652  * :[N]bprevious [N]	to previous buffer
5653  * :[N]sbNext [N]	split and to previous buffer
5654  * :[N]sbprevious [N]	split and to previous buffer
5655  */
5656     static void
5657 ex_bprevious(exarg_T *eap)
5658 {
5659     goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
5660     if (eap->do_ecmd_cmd != NULL)
5661 	do_cmdline_cmd(eap->do_ecmd_cmd);
5662 }
5663 
5664 /*
5665  * :brewind		to first buffer
5666  * :bfirst		to first buffer
5667  * :sbrewind		split and to first buffer
5668  * :sbfirst		split and to first buffer
5669  */
5670     static void
5671 ex_brewind(exarg_T *eap)
5672 {
5673     goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
5674     if (eap->do_ecmd_cmd != NULL)
5675 	do_cmdline_cmd(eap->do_ecmd_cmd);
5676 }
5677 
5678 /*
5679  * :blast		to last buffer
5680  * :sblast		split and to last buffer
5681  */
5682     static void
5683 ex_blast(exarg_T *eap)
5684 {
5685     goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
5686     if (eap->do_ecmd_cmd != NULL)
5687 	do_cmdline_cmd(eap->do_ecmd_cmd);
5688 }
5689 #endif
5690 
5691     int
5692 ends_excmd(int c)
5693 {
5694     return (c == NUL || c == '|' || c == '"' || c == '\n');
5695 }
5696 
5697 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
5698 	|| defined(PROTO)
5699 /*
5700  * Return the next command, after the first '|' or '\n'.
5701  * Return NULL if not found.
5702  */
5703     char_u *
5704 find_nextcmd(char_u *p)
5705 {
5706     while (*p != '|' && *p != '\n')
5707     {
5708 	if (*p == NUL)
5709 	    return NULL;
5710 	++p;
5711     }
5712     return (p + 1);
5713 }
5714 #endif
5715 
5716 /*
5717  * Check if *p is a separator between Ex commands, skipping over white space.
5718  * Return NULL if it isn't, the following character if it is.
5719  */
5720     char_u *
5721 check_nextcmd(char_u *p)
5722 {
5723     char_u *s = skipwhite(p);
5724 
5725     if (*s == '|' || *s == '\n')
5726 	return (s + 1);
5727     else
5728 	return NULL;
5729 }
5730 
5731 /*
5732  * - if there are more files to edit
5733  * - and this is the last window
5734  * - and forceit not used
5735  * - and not repeated twice on a row
5736  *    return FAIL and give error message if 'message' TRUE
5737  * return OK otherwise
5738  */
5739     static int
5740 check_more(
5741     int message,	    /* when FALSE check only, no messages */
5742     int forceit)
5743 {
5744     int	    n = ARGCOUNT - curwin->w_arg_idx - 1;
5745 
5746     if (!forceit && only_one_window()
5747 	    && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5748     {
5749 	if (message)
5750 	{
5751 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5752 	    if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5753 	    {
5754 		char_u	buff[DIALOG_MSG_SIZE];
5755 
5756 		if (n == 1)
5757 		    vim_strncpy(buff,
5758 			    (char_u *)_("1 more file to edit.  Quit anyway?"),
5759 							 DIALOG_MSG_SIZE - 1);
5760 		else
5761 		    vim_snprintf((char *)buff, DIALOG_MSG_SIZE,
5762 			      _("%d more files to edit.  Quit anyway?"), n);
5763 		if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5764 		    return OK;
5765 		return FAIL;
5766 	    }
5767 #endif
5768 	    if (n == 1)
5769 		EMSG(_("E173: 1 more file to edit"));
5770 	    else
5771 		EMSGN(_("E173: %ld more files to edit"), n);
5772 	    quitmore = 2;	    /* next try to quit is allowed */
5773 	}
5774 	return FAIL;
5775     }
5776     return OK;
5777 }
5778 
5779 #ifdef FEAT_CMDL_COMPL
5780 /*
5781  * Function given to ExpandGeneric() to obtain the list of command names.
5782  */
5783     char_u *
5784 get_command_name(expand_T *xp UNUSED, int idx)
5785 {
5786     if (idx >= (int)CMD_SIZE)
5787 # ifdef FEAT_USR_CMDS
5788 	return get_user_command_name(idx);
5789 # else
5790 	return NULL;
5791 # endif
5792     return cmdnames[idx].cmd_name;
5793 }
5794 #endif
5795 
5796 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5797 static int	uc_add_command(char_u *name, size_t name_len, char_u *rep, long argt, long def, int flags, int compl, char_u *compl_arg, int addr_type, int force);
5798 static void	uc_list(char_u *name, size_t name_len);
5799 static int	uc_scan_attr(char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg, int* attr_type_arg);
5800 static char_u	*uc_split_args(char_u *arg, size_t *lenp);
5801 static size_t	uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd, exarg_T *eap, char_u **split_buf, size_t *split_len);
5802 
5803     static int
5804 uc_add_command(
5805     char_u	*name,
5806     size_t	name_len,
5807     char_u	*rep,
5808     long	argt,
5809     long	def,
5810     int		flags,
5811     int		compl,
5812     char_u	*compl_arg,
5813     int		addr_type,
5814     int		force)
5815 {
5816     ucmd_T	*cmd = NULL;
5817     char_u	*p;
5818     int		i;
5819     int		cmp = 1;
5820     char_u	*rep_buf = NULL;
5821     garray_T	*gap;
5822 
5823     replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5824     if (rep_buf == NULL)
5825     {
5826 	/* Can't replace termcodes - try using the string as is */
5827 	rep_buf = vim_strsave(rep);
5828 
5829 	/* Give up if out of memory */
5830 	if (rep_buf == NULL)
5831 	    return FAIL;
5832     }
5833 
5834     /* get address of growarray: global or in curbuf */
5835     if (flags & UC_BUFFER)
5836     {
5837 	gap = &curbuf->b_ucmds;
5838 	if (gap->ga_itemsize == 0)
5839 	    ga_init2(gap, (int)sizeof(ucmd_T), 4);
5840     }
5841     else
5842 	gap = &ucmds;
5843 
5844     /* Search for the command in the already defined commands. */
5845     for (i = 0; i < gap->ga_len; ++i)
5846     {
5847 	size_t len;
5848 
5849 	cmd = USER_CMD_GA(gap, i);
5850 	len = STRLEN(cmd->uc_name);
5851 	cmp = STRNCMP(name, cmd->uc_name, name_len);
5852 	if (cmp == 0)
5853 	{
5854 	    if (name_len < len)
5855 		cmp = -1;
5856 	    else if (name_len > len)
5857 		cmp = 1;
5858 	}
5859 
5860 	if (cmp == 0)
5861 	{
5862 	    if (!force)
5863 	    {
5864 		EMSG(_("E174: Command already exists: add ! to replace it"));
5865 		goto fail;
5866 	    }
5867 
5868 	    vim_free(cmd->uc_rep);
5869 	    cmd->uc_rep = NULL;
5870 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5871 	    vim_free(cmd->uc_compl_arg);
5872 	    cmd->uc_compl_arg = NULL;
5873 #endif
5874 	    break;
5875 	}
5876 
5877 	/* Stop as soon as we pass the name to add */
5878 	if (cmp < 0)
5879 	    break;
5880     }
5881 
5882     /* Extend the array unless we're replacing an existing command */
5883     if (cmp != 0)
5884     {
5885 	if (ga_grow(gap, 1) != OK)
5886 	    goto fail;
5887 	if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5888 	    goto fail;
5889 
5890 	cmd = USER_CMD_GA(gap, i);
5891 	mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5892 
5893 	++gap->ga_len;
5894 
5895 	cmd->uc_name = p;
5896     }
5897 
5898     cmd->uc_rep = rep_buf;
5899     cmd->uc_argt = argt;
5900     cmd->uc_def = def;
5901     cmd->uc_compl = compl;
5902 #ifdef FEAT_EVAL
5903     cmd->uc_scriptID = current_SID;
5904 # ifdef FEAT_CMDL_COMPL
5905     cmd->uc_compl_arg = compl_arg;
5906 # endif
5907 #endif
5908     cmd->uc_addr_type = addr_type;
5909 
5910     return OK;
5911 
5912 fail:
5913     vim_free(rep_buf);
5914 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5915     vim_free(compl_arg);
5916 #endif
5917     return FAIL;
5918 }
5919 #endif
5920 
5921 #if defined(FEAT_USR_CMDS)
5922 static struct
5923 {
5924     int	    expand;
5925     char    *name;
5926 } addr_type_complete[] =
5927 {
5928     {ADDR_ARGUMENTS, "arguments"},
5929     {ADDR_LINES, "lines"},
5930     {ADDR_LOADED_BUFFERS, "loaded_buffers"},
5931     {ADDR_TABS, "tabs"},
5932     {ADDR_BUFFERS, "buffers"},
5933     {ADDR_WINDOWS, "windows"},
5934     {ADDR_QUICKFIX, "quickfix"},
5935     {-1, NULL}
5936 };
5937 #endif
5938 
5939 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
5940 /*
5941  * List of names for completion for ":command" with the EXPAND_ flag.
5942  * Must be alphabetical for completion.
5943  */
5944 static struct
5945 {
5946     int	    expand;
5947     char    *name;
5948 } command_complete[] =
5949 {
5950     {EXPAND_AUGROUP, "augroup"},
5951     {EXPAND_BEHAVE, "behave"},
5952     {EXPAND_BUFFERS, "buffer"},
5953     {EXPAND_COLORS, "color"},
5954     {EXPAND_COMMANDS, "command"},
5955     {EXPAND_COMPILER, "compiler"},
5956 #if defined(FEAT_CSCOPE)
5957     {EXPAND_CSCOPE, "cscope"},
5958 #endif
5959 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5960     {EXPAND_USER_DEFINED, "custom"},
5961     {EXPAND_USER_LIST, "customlist"},
5962 #endif
5963     {EXPAND_DIRECTORIES, "dir"},
5964     {EXPAND_ENV_VARS, "environment"},
5965     {EXPAND_EVENTS, "event"},
5966     {EXPAND_EXPRESSION, "expression"},
5967     {EXPAND_FILES, "file"},
5968     {EXPAND_FILES_IN_PATH, "file_in_path"},
5969     {EXPAND_FILETYPE, "filetype"},
5970     {EXPAND_FUNCTIONS, "function"},
5971     {EXPAND_HELP, "help"},
5972     {EXPAND_HIGHLIGHT, "highlight"},
5973 #if defined(FEAT_CMDHIST)
5974     {EXPAND_HISTORY, "history"},
5975 #endif
5976 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
5977 	&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
5978     {EXPAND_LOCALES, "locale"},
5979 #endif
5980     {EXPAND_MAPCLEAR, "mapclear"},
5981     {EXPAND_MAPPINGS, "mapping"},
5982     {EXPAND_MENUS, "menu"},
5983     {EXPAND_MESSAGES, "messages"},
5984     {EXPAND_OWNSYNTAX, "syntax"},
5985 #if defined(FEAT_PROFILE)
5986     {EXPAND_SYNTIME, "syntime"},
5987 #endif
5988     {EXPAND_SETTINGS, "option"},
5989     {EXPAND_PACKADD, "packadd"},
5990     {EXPAND_SHELLCMD, "shellcmd"},
5991 #if defined(FEAT_SIGNS)
5992     {EXPAND_SIGN, "sign"},
5993 #endif
5994     {EXPAND_TAGS, "tag"},
5995     {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5996     {EXPAND_USER, "user"},
5997     {EXPAND_USER_VARS, "var"},
5998     {0, NULL}
5999 };
6000 #endif
6001 
6002 #if defined(FEAT_USR_CMDS) || defined(PROTO)
6003     static void
6004 uc_list(char_u *name, size_t name_len)
6005 {
6006     int		i, j;
6007     int		found = FALSE;
6008     ucmd_T	*cmd;
6009     int		len;
6010     long	a;
6011     garray_T	*gap;
6012 
6013     gap = &curbuf->b_ucmds;
6014     for (;;)
6015     {
6016 	for (i = 0; i < gap->ga_len; ++i)
6017 	{
6018 	    cmd = USER_CMD_GA(gap, i);
6019 	    a = (long)cmd->uc_argt;
6020 
6021 	    /* Skip commands which don't match the requested prefix and
6022 	     * commands filtered out. */
6023 	    if (STRNCMP(name, cmd->uc_name, name_len) != 0
6024 		    || message_filtered(cmd->uc_name))
6025 		continue;
6026 
6027 	    /* Put out the title first time */
6028 	    if (!found)
6029 		MSG_PUTS_TITLE(_("\n    Name        Args       Address   Complete  Definition"));
6030 	    found = TRUE;
6031 	    msg_putchar('\n');
6032 	    if (got_int)
6033 		break;
6034 
6035 	    /* Special cases */
6036 	    msg_putchar(a & BANG ? '!' : ' ');
6037 	    msg_putchar(a & REGSTR ? '"' : ' ');
6038 	    msg_putchar(gap != &ucmds ? 'b' : ' ');
6039 	    msg_putchar(' ');
6040 
6041 	    msg_outtrans_attr(cmd->uc_name, HL_ATTR(HLF_D));
6042 	    len = (int)STRLEN(cmd->uc_name) + 4;
6043 
6044 	    do {
6045 		msg_putchar(' ');
6046 		++len;
6047 	    } while (len < 16);
6048 
6049 	    len = 0;
6050 
6051 	    /* Arguments */
6052 	    switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
6053 	    {
6054 	    case 0:			IObuff[len++] = '0'; break;
6055 	    case (EXTRA):		IObuff[len++] = '*'; break;
6056 	    case (EXTRA|NOSPC):		IObuff[len++] = '?'; break;
6057 	    case (EXTRA|NEEDARG):	IObuff[len++] = '+'; break;
6058 	    case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
6059 	    }
6060 
6061 	    do {
6062 		IObuff[len++] = ' ';
6063 	    } while (len < 5);
6064 
6065 	    /* Range */
6066 	    if (a & (RANGE|COUNT))
6067 	    {
6068 		if (a & COUNT)
6069 		{
6070 		    /* -count=N */
6071 		    sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
6072 		    len += (int)STRLEN(IObuff + len);
6073 		}
6074 		else if (a & DFLALL)
6075 		    IObuff[len++] = '%';
6076 		else if (cmd->uc_def >= 0)
6077 		{
6078 		    /* -range=N */
6079 		    sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
6080 		    len += (int)STRLEN(IObuff + len);
6081 		}
6082 		else
6083 		    IObuff[len++] = '.';
6084 	    }
6085 
6086 	    do {
6087 		IObuff[len++] = ' ';
6088 	    } while (len < 11);
6089 
6090 	    /* Address Type */
6091 	    for (j = 0; addr_type_complete[j].expand != -1; ++j)
6092 		if (addr_type_complete[j].expand != ADDR_LINES
6093 			&& addr_type_complete[j].expand == cmd->uc_addr_type)
6094 		{
6095 		    STRCPY(IObuff + len, addr_type_complete[j].name);
6096 		    len += (int)STRLEN(IObuff + len);
6097 		    break;
6098 		}
6099 
6100 	    do {
6101 		IObuff[len++] = ' ';
6102 	    } while (len < 21);
6103 
6104 	    /* Completion */
6105 	    for (j = 0; command_complete[j].expand != 0; ++j)
6106 		if (command_complete[j].expand == cmd->uc_compl)
6107 		{
6108 		    STRCPY(IObuff + len, command_complete[j].name);
6109 		    len += (int)STRLEN(IObuff + len);
6110 		    break;
6111 		}
6112 
6113 	    do {
6114 		IObuff[len++] = ' ';
6115 	    } while (len < 35);
6116 
6117 	    IObuff[len] = '\0';
6118 	    msg_outtrans(IObuff);
6119 
6120 	    msg_outtrans_special(cmd->uc_rep, FALSE);
6121 #ifdef FEAT_EVAL
6122 	    if (p_verbose > 0)
6123 		last_set_msg(cmd->uc_scriptID);
6124 #endif
6125 	    out_flush();
6126 	    ui_breakcheck();
6127 	    if (got_int)
6128 		break;
6129 	}
6130 	if (gap == &ucmds || i < gap->ga_len)
6131 	    break;
6132 	gap = &ucmds;
6133     }
6134 
6135     if (!found)
6136 	MSG(_("No user-defined commands found"));
6137 }
6138 
6139     static char_u *
6140 uc_fun_cmd(void)
6141 {
6142     static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
6143 			    0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
6144 			    0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
6145 			    0xb9, 0x7f, 0};
6146     int		i;
6147 
6148     for (i = 0; fcmd[i]; ++i)
6149 	IObuff[i] = fcmd[i] - 0x40;
6150     IObuff[i] = 0;
6151     return IObuff;
6152 }
6153 
6154     static int
6155 uc_scan_attr(
6156     char_u	*attr,
6157     size_t	len,
6158     long	*argt,
6159     long	*def,
6160     int		*flags,
6161     int		*compl,
6162     char_u	**compl_arg,
6163     int		*addr_type_arg)
6164 {
6165     char_u	*p;
6166 
6167     if (len == 0)
6168     {
6169 	EMSG(_("E175: No attribute specified"));
6170 	return FAIL;
6171     }
6172 
6173     /* First, try the simple attributes (no arguments) */
6174     if (STRNICMP(attr, "bang", len) == 0)
6175 	*argt |= BANG;
6176     else if (STRNICMP(attr, "buffer", len) == 0)
6177 	*flags |= UC_BUFFER;
6178     else if (STRNICMP(attr, "register", len) == 0)
6179 	*argt |= REGSTR;
6180     else if (STRNICMP(attr, "bar", len) == 0)
6181 	*argt |= TRLBAR;
6182     else
6183     {
6184 	int	i;
6185 	char_u	*val = NULL;
6186 	size_t	vallen = 0;
6187 	size_t	attrlen = len;
6188 
6189 	/* Look for the attribute name - which is the part before any '=' */
6190 	for (i = 0; i < (int)len; ++i)
6191 	{
6192 	    if (attr[i] == '=')
6193 	    {
6194 		val = &attr[i + 1];
6195 		vallen = len - i - 1;
6196 		attrlen = i;
6197 		break;
6198 	    }
6199 	}
6200 
6201 	if (STRNICMP(attr, "nargs", attrlen) == 0)
6202 	{
6203 	    if (vallen == 1)
6204 	    {
6205 		if (*val == '0')
6206 		    /* Do nothing - this is the default */;
6207 		else if (*val == '1')
6208 		    *argt |= (EXTRA | NOSPC | NEEDARG);
6209 		else if (*val == '*')
6210 		    *argt |= EXTRA;
6211 		else if (*val == '?')
6212 		    *argt |= (EXTRA | NOSPC);
6213 		else if (*val == '+')
6214 		    *argt |= (EXTRA | NEEDARG);
6215 		else
6216 		    goto wrong_nargs;
6217 	    }
6218 	    else
6219 	    {
6220 wrong_nargs:
6221 		EMSG(_("E176: Invalid number of arguments"));
6222 		return FAIL;
6223 	    }
6224 	}
6225 	else if (STRNICMP(attr, "range", attrlen) == 0)
6226 	{
6227 	    *argt |= RANGE;
6228 	    if (vallen == 1 && *val == '%')
6229 		*argt |= DFLALL;
6230 	    else if (val != NULL)
6231 	    {
6232 		p = val;
6233 		if (*def >= 0)
6234 		{
6235 two_count:
6236 		    EMSG(_("E177: Count cannot be specified twice"));
6237 		    return FAIL;
6238 		}
6239 
6240 		*def = getdigits(&p);
6241 		*argt |= (ZEROR | NOTADR);
6242 
6243 		if (p != val + vallen || vallen == 0)
6244 		{
6245 invalid_count:
6246 		    EMSG(_("E178: Invalid default value for count"));
6247 		    return FAIL;
6248 		}
6249 	    }
6250 	}
6251 	else if (STRNICMP(attr, "count", attrlen) == 0)
6252 	{
6253 	    *argt |= (COUNT | ZEROR | RANGE | NOTADR);
6254 
6255 	    if (val != NULL)
6256 	    {
6257 		p = val;
6258 		if (*def >= 0)
6259 		    goto two_count;
6260 
6261 		*def = getdigits(&p);
6262 
6263 		if (p != val + vallen)
6264 		    goto invalid_count;
6265 	    }
6266 
6267 	    if (*def < 0)
6268 		*def = 0;
6269 	}
6270 	else if (STRNICMP(attr, "complete", attrlen) == 0)
6271 	{
6272 	    if (val == NULL)
6273 	    {
6274 		EMSG(_("E179: argument required for -complete"));
6275 		return FAIL;
6276 	    }
6277 
6278 	    if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
6279 								      == FAIL)
6280 		return FAIL;
6281 	}
6282 	else if (STRNICMP(attr, "addr", attrlen) == 0)
6283 	{
6284 	    *argt |= RANGE;
6285 	    if (val == NULL)
6286 	    {
6287 		EMSG(_("E179: argument required for -addr"));
6288 		return FAIL;
6289 	    }
6290 	    if (parse_addr_type_arg(val, (int)vallen, argt, addr_type_arg)
6291 								      == FAIL)
6292 		return FAIL;
6293 	    if (addr_type_arg != ADDR_LINES)
6294 		*argt |= (ZEROR | NOTADR) ;
6295 	}
6296 	else
6297 	{
6298 	    char_u ch = attr[len];
6299 	    attr[len] = '\0';
6300 	    EMSG2(_("E181: Invalid attribute: %s"), attr);
6301 	    attr[len] = ch;
6302 	    return FAIL;
6303 	}
6304     }
6305 
6306     return OK;
6307 }
6308 
6309 /*
6310  * ":command ..."
6311  */
6312     static void
6313 ex_command(exarg_T *eap)
6314 {
6315     char_u  *name;
6316     char_u  *end;
6317     char_u  *p;
6318     long    argt = 0;
6319     long    def = -1;
6320     int	    flags = 0;
6321     int	    compl = EXPAND_NOTHING;
6322     char_u  *compl_arg = NULL;
6323     int	    addr_type_arg = ADDR_LINES;
6324     int	    has_attr = (eap->arg[0] == '-');
6325     int	    name_len;
6326 
6327     p = eap->arg;
6328 
6329     /* Check for attributes */
6330     while (*p == '-')
6331     {
6332 	++p;
6333 	end = skiptowhite(p);
6334 	if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg, &addr_type_arg)
6335 		== FAIL)
6336 	    return;
6337 	p = skipwhite(end);
6338     }
6339 
6340     /* Get the name (if any) and skip to the following argument */
6341     name = p;
6342     if (ASCII_ISALPHA(*p))
6343 	while (ASCII_ISALNUM(*p))
6344 	    ++p;
6345     if (!ends_excmd(*p) && !VIM_ISWHITE(*p))
6346     {
6347 	EMSG(_("E182: Invalid command name"));
6348 	return;
6349     }
6350     end = p;
6351     name_len = (int)(end - name);
6352 
6353     /* If there is nothing after the name, and no attributes were specified,
6354      * we are listing commands
6355      */
6356     p = skipwhite(end);
6357     if (!has_attr && ends_excmd(*p))
6358     {
6359 	uc_list(name, end - name);
6360     }
6361     else if (!ASCII_ISUPPER(*name))
6362     {
6363 	EMSG(_("E183: User defined commands must start with an uppercase letter"));
6364 	return;
6365     }
6366     else if ((name_len == 1 && *name == 'X')
6367 	  || (name_len <= 4
6368 		  && STRNCMP(name, "Next", name_len > 4 ? 4 : name_len) == 0))
6369     {
6370 	EMSG(_("E841: Reserved name, cannot be used for user defined command"));
6371 	return;
6372     }
6373     else
6374 	uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
6375 								addr_type_arg, eap->forceit);
6376 }
6377 
6378 /*
6379  * ":comclear"
6380  * Clear all user commands, global and for current buffer.
6381  */
6382     void
6383 ex_comclear(exarg_T *eap UNUSED)
6384 {
6385     uc_clear(&ucmds);
6386     uc_clear(&curbuf->b_ucmds);
6387 }
6388 
6389 /*
6390  * Clear all user commands for "gap".
6391  */
6392     void
6393 uc_clear(garray_T *gap)
6394 {
6395     int		i;
6396     ucmd_T	*cmd;
6397 
6398     for (i = 0; i < gap->ga_len; ++i)
6399     {
6400 	cmd = USER_CMD_GA(gap, i);
6401 	vim_free(cmd->uc_name);
6402 	vim_free(cmd->uc_rep);
6403 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6404 	vim_free(cmd->uc_compl_arg);
6405 # endif
6406     }
6407     ga_clear(gap);
6408 }
6409 
6410     static void
6411 ex_delcommand(exarg_T *eap)
6412 {
6413     int		i = 0;
6414     ucmd_T	*cmd = NULL;
6415     int		cmp = -1;
6416     garray_T	*gap;
6417 
6418     gap = &curbuf->b_ucmds;
6419     for (;;)
6420     {
6421 	for (i = 0; i < gap->ga_len; ++i)
6422 	{
6423 	    cmd = USER_CMD_GA(gap, i);
6424 	    cmp = STRCMP(eap->arg, cmd->uc_name);
6425 	    if (cmp <= 0)
6426 		break;
6427 	}
6428 	if (gap == &ucmds || cmp == 0)
6429 	    break;
6430 	gap = &ucmds;
6431     }
6432 
6433     if (cmp != 0)
6434     {
6435 	EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
6436 	return;
6437     }
6438 
6439     vim_free(cmd->uc_name);
6440     vim_free(cmd->uc_rep);
6441 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6442     vim_free(cmd->uc_compl_arg);
6443 # endif
6444 
6445     --gap->ga_len;
6446 
6447     if (i < gap->ga_len)
6448 	mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
6449 }
6450 
6451 /*
6452  * split and quote args for <f-args>
6453  */
6454     static char_u *
6455 uc_split_args(char_u *arg, size_t *lenp)
6456 {
6457     char_u *buf;
6458     char_u *p;
6459     char_u *q;
6460     int len;
6461 
6462     /* Precalculate length */
6463     p = arg;
6464     len = 2; /* Initial and final quotes */
6465 
6466     while (*p)
6467     {
6468 	if (p[0] == '\\' && p[1] == '\\')
6469 	{
6470 	    len += 2;
6471 	    p += 2;
6472 	}
6473 	else if (p[0] == '\\' && VIM_ISWHITE(p[1]))
6474 	{
6475 	    len += 1;
6476 	    p += 2;
6477 	}
6478 	else if (*p == '\\' || *p == '"')
6479 	{
6480 	    len += 2;
6481 	    p += 1;
6482 	}
6483 	else if (VIM_ISWHITE(*p))
6484 	{
6485 	    p = skipwhite(p);
6486 	    if (*p == NUL)
6487 		break;
6488 	    len += 3; /* "," */
6489 	}
6490 	else
6491 	{
6492 #ifdef FEAT_MBYTE
6493 	    int charlen = (*mb_ptr2len)(p);
6494 	    len += charlen;
6495 	    p += charlen;
6496 #else
6497 	    ++len;
6498 	    ++p;
6499 #endif
6500 	}
6501     }
6502 
6503     buf = alloc(len + 1);
6504     if (buf == NULL)
6505     {
6506 	*lenp = 0;
6507 	return buf;
6508     }
6509 
6510     p = arg;
6511     q = buf;
6512     *q++ = '"';
6513     while (*p)
6514     {
6515 	if (p[0] == '\\' && p[1] == '\\')
6516 	{
6517 	    *q++ = '\\';
6518 	    *q++ = '\\';
6519 	    p += 2;
6520 	}
6521 	else if (p[0] == '\\' && VIM_ISWHITE(p[1]))
6522 	{
6523 	    *q++ = p[1];
6524 	    p += 2;
6525 	}
6526 	else if (*p == '\\' || *p == '"')
6527 	{
6528 	    *q++ = '\\';
6529 	    *q++ = *p++;
6530 	}
6531 	else if (VIM_ISWHITE(*p))
6532 	{
6533 	    p = skipwhite(p);
6534 	    if (*p == NUL)
6535 		break;
6536 	    *q++ = '"';
6537 	    *q++ = ',';
6538 	    *q++ = '"';
6539 	}
6540 	else
6541 	{
6542 	    MB_COPY_CHAR(p, q);
6543 	}
6544     }
6545     *q++ = '"';
6546     *q = 0;
6547 
6548     *lenp = len;
6549     return buf;
6550 }
6551 
6552     static size_t
6553 add_cmd_modifier(char_u *buf, char *mod_str, int *multi_mods)
6554 {
6555     size_t result;
6556 
6557     result = STRLEN(mod_str);
6558     if (*multi_mods)
6559 	result += 1;
6560     if (buf != NULL)
6561     {
6562 	if (*multi_mods)
6563 	    STRCAT(buf, " ");
6564 	STRCAT(buf, mod_str);
6565     }
6566 
6567     *multi_mods = 1;
6568 
6569     return result;
6570 }
6571 
6572 /*
6573  * Check for a <> code in a user command.
6574  * "code" points to the '<'.  "len" the length of the <> (inclusive).
6575  * "buf" is where the result is to be added.
6576  * "split_buf" points to a buffer used for splitting, caller should free it.
6577  * "split_len" is the length of what "split_buf" contains.
6578  * Returns the length of the replacement, which has been added to "buf".
6579  * Returns -1 if there was no match, and only the "<" has been copied.
6580  */
6581     static size_t
6582 uc_check_code(
6583     char_u	*code,
6584     size_t	len,
6585     char_u	*buf,
6586     ucmd_T	*cmd,		/* the user command we're expanding */
6587     exarg_T	*eap,		/* ex arguments */
6588     char_u	**split_buf,
6589     size_t	*split_len)
6590 {
6591     size_t	result = 0;
6592     char_u	*p = code + 1;
6593     size_t	l = len - 2;
6594     int		quote = 0;
6595     enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_MODS,
6596 	ct_REGISTER, ct_LT, ct_NONE } type = ct_NONE;
6597 
6598     if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
6599     {
6600 	quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
6601 	p += 2;
6602 	l -= 2;
6603     }
6604 
6605     ++l;
6606     if (l <= 1)
6607 	type = ct_NONE;
6608     else if (STRNICMP(p, "args>", l) == 0)
6609 	type = ct_ARGS;
6610     else if (STRNICMP(p, "bang>", l) == 0)
6611 	type = ct_BANG;
6612     else if (STRNICMP(p, "count>", l) == 0)
6613 	type = ct_COUNT;
6614     else if (STRNICMP(p, "line1>", l) == 0)
6615 	type = ct_LINE1;
6616     else if (STRNICMP(p, "line2>", l) == 0)
6617 	type = ct_LINE2;
6618     else if (STRNICMP(p, "lt>", l) == 0)
6619 	type = ct_LT;
6620     else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
6621 	type = ct_REGISTER;
6622     else if (STRNICMP(p, "mods>", l) == 0)
6623 	type = ct_MODS;
6624 
6625     switch (type)
6626     {
6627     case ct_ARGS:
6628 	/* Simple case first */
6629 	if (*eap->arg == NUL)
6630 	{
6631 	    if (quote == 1)
6632 	    {
6633 		result = 2;
6634 		if (buf != NULL)
6635 		    STRCPY(buf, "''");
6636 	    }
6637 	    else
6638 		result = 0;
6639 	    break;
6640 	}
6641 
6642 	/* When specified there is a single argument don't split it.
6643 	 * Works for ":Cmd %" when % is "a b c". */
6644 	if ((eap->argt & NOSPC) && quote == 2)
6645 	    quote = 1;
6646 
6647 	switch (quote)
6648 	{
6649 	case 0: /* No quoting, no splitting */
6650 	    result = STRLEN(eap->arg);
6651 	    if (buf != NULL)
6652 		STRCPY(buf, eap->arg);
6653 	    break;
6654 	case 1: /* Quote, but don't split */
6655 	    result = STRLEN(eap->arg) + 2;
6656 	    for (p = eap->arg; *p; ++p)
6657 	    {
6658 #ifdef  FEAT_MBYTE
6659 		if (enc_dbcs != 0 && (*mb_ptr2len)(p) == 2)
6660 		    /* DBCS can contain \ in a trail byte, skip the
6661 		     * double-byte character. */
6662 		    ++p;
6663 		else
6664 #endif
6665 		     if (*p == '\\' || *p == '"')
6666 		    ++result;
6667 	    }
6668 
6669 	    if (buf != NULL)
6670 	    {
6671 		*buf++ = '"';
6672 		for (p = eap->arg; *p; ++p)
6673 		{
6674 #ifdef  FEAT_MBYTE
6675 		    if (enc_dbcs != 0 && (*mb_ptr2len)(p) == 2)
6676 			/* DBCS can contain \ in a trail byte, copy the
6677 			 * double-byte character to avoid escaping. */
6678 			*buf++ = *p++;
6679 		    else
6680 #endif
6681 			 if (*p == '\\' || *p == '"')
6682 			*buf++ = '\\';
6683 		    *buf++ = *p;
6684 		}
6685 		*buf = '"';
6686 	    }
6687 
6688 	    break;
6689 	case 2: /* Quote and split (<f-args>) */
6690 	    /* This is hard, so only do it once, and cache the result */
6691 	    if (*split_buf == NULL)
6692 		*split_buf = uc_split_args(eap->arg, split_len);
6693 
6694 	    result = *split_len;
6695 	    if (buf != NULL && result != 0)
6696 		STRCPY(buf, *split_buf);
6697 
6698 	    break;
6699 	}
6700 	break;
6701 
6702     case ct_BANG:
6703 	result = eap->forceit ? 1 : 0;
6704 	if (quote)
6705 	    result += 2;
6706 	if (buf != NULL)
6707 	{
6708 	    if (quote)
6709 		*buf++ = '"';
6710 	    if (eap->forceit)
6711 		*buf++ = '!';
6712 	    if (quote)
6713 		*buf = '"';
6714 	}
6715 	break;
6716 
6717     case ct_LINE1:
6718     case ct_LINE2:
6719     case ct_COUNT:
6720     {
6721 	char num_buf[20];
6722 	long num = (type == ct_LINE1) ? eap->line1 :
6723 		   (type == ct_LINE2) ? eap->line2 :
6724 		   (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
6725 	size_t num_len;
6726 
6727 	sprintf(num_buf, "%ld", num);
6728 	num_len = STRLEN(num_buf);
6729 	result = num_len;
6730 
6731 	if (quote)
6732 	    result += 2;
6733 
6734 	if (buf != NULL)
6735 	{
6736 	    if (quote)
6737 		*buf++ = '"';
6738 	    STRCPY(buf, num_buf);
6739 	    buf += num_len;
6740 	    if (quote)
6741 		*buf = '"';
6742 	}
6743 
6744 	break;
6745     }
6746 
6747     case ct_MODS:
6748     {
6749 	int multi_mods = 0;
6750 	typedef struct {
6751 	    int *varp;
6752 	    char *name;
6753 	} mod_entry_T;
6754 	static mod_entry_T mod_entries[] = {
6755 #ifdef FEAT_BROWSE_CMD
6756 	    {&cmdmod.browse, "browse"},
6757 #endif
6758 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6759 	    {&cmdmod.confirm, "confirm"},
6760 #endif
6761 	    {&cmdmod.hide, "hide"},
6762 	    {&cmdmod.keepalt, "keepalt"},
6763 	    {&cmdmod.keepjumps, "keepjumps"},
6764 	    {&cmdmod.keepmarks, "keepmarks"},
6765 	    {&cmdmod.keeppatterns, "keeppatterns"},
6766 	    {&cmdmod.lockmarks, "lockmarks"},
6767 	    {&cmdmod.noswapfile, "noswapfile"},
6768 	    {NULL, NULL}
6769 	};
6770 	int i;
6771 
6772 	result = quote ? 2 : 0;
6773 	if (buf != NULL)
6774 	{
6775 	    if (quote)
6776 		*buf++ = '"';
6777 	    *buf = '\0';
6778 	}
6779 
6780 #ifdef FEAT_WINDOWS
6781 	/* :aboveleft and :leftabove */
6782 	if (cmdmod.split & WSP_ABOVE)
6783 	    result += add_cmd_modifier(buf, "aboveleft", &multi_mods);
6784 	/* :belowright and :rightbelow */
6785 	if (cmdmod.split & WSP_BELOW)
6786 	    result += add_cmd_modifier(buf, "belowright", &multi_mods);
6787 	/* :botright */
6788 	if (cmdmod.split & WSP_BOT)
6789 	    result += add_cmd_modifier(buf, "botright", &multi_mods);
6790 #endif
6791 
6792 	/* the modifiers that are simple flags */
6793 	for (i = 0; mod_entries[i].varp != NULL; ++i)
6794 	    if (*mod_entries[i].varp)
6795 		result += add_cmd_modifier(buf, mod_entries[i].name,
6796 								 &multi_mods);
6797 
6798 	/* TODO: How to support :noautocmd? */
6799 #ifdef HAVE_SANDBOX
6800 	/* TODO: How to support :sandbox?*/
6801 #endif
6802 	/* :silent */
6803 	if (msg_silent > 0)
6804 	    result += add_cmd_modifier(buf,
6805 		    emsg_silent > 0 ? "silent!" : "silent", &multi_mods);
6806 #ifdef FEAT_WINDOWS
6807 	/* :tab */
6808 	if (cmdmod.tab > 0)
6809 	    result += add_cmd_modifier(buf, "tab", &multi_mods);
6810 	/* :topleft */
6811 	if (cmdmod.split & WSP_TOP)
6812 	    result += add_cmd_modifier(buf, "topleft", &multi_mods);
6813 #endif
6814 	/* TODO: How to support :unsilent?*/
6815 	/* :verbose */
6816 	if (p_verbose > 0)
6817 	    result += add_cmd_modifier(buf, "verbose", &multi_mods);
6818 #ifdef FEAT_WINDOWS
6819 	/* :vertical */
6820 	if (cmdmod.split & WSP_VERT)
6821 	    result += add_cmd_modifier(buf, "vertical", &multi_mods);
6822 #endif
6823 	if (quote && buf != NULL)
6824 	{
6825 	    buf += result - 2;
6826 	    *buf = '"';
6827 	}
6828 	break;
6829     }
6830 
6831     case ct_REGISTER:
6832 	result = eap->regname ? 1 : 0;
6833 	if (quote)
6834 	    result += 2;
6835 	if (buf != NULL)
6836 	{
6837 	    if (quote)
6838 		*buf++ = '\'';
6839 	    if (eap->regname)
6840 		*buf++ = eap->regname;
6841 	    if (quote)
6842 		*buf = '\'';
6843 	}
6844 	break;
6845 
6846     case ct_LT:
6847 	result = 1;
6848 	if (buf != NULL)
6849 	    *buf = '<';
6850 	break;
6851 
6852     default:
6853 	/* Not recognized: just copy the '<' and return -1. */
6854 	result = (size_t)-1;
6855 	if (buf != NULL)
6856 	    *buf = '<';
6857 	break;
6858     }
6859 
6860     return result;
6861 }
6862 
6863     static void
6864 do_ucmd(exarg_T *eap)
6865 {
6866     char_u	*buf;
6867     char_u	*p;
6868     char_u	*q;
6869 
6870     char_u	*start;
6871     char_u	*end = NULL;
6872     char_u	*ksp;
6873     size_t	len, totlen;
6874 
6875     size_t	split_len = 0;
6876     char_u	*split_buf = NULL;
6877     ucmd_T	*cmd;
6878 #ifdef FEAT_EVAL
6879     scid_T	save_current_SID = current_SID;
6880 #endif
6881 
6882     if (eap->cmdidx == CMD_USER)
6883 	cmd = USER_CMD(eap->useridx);
6884     else
6885 	cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
6886 
6887     /*
6888      * Replace <> in the command by the arguments.
6889      * First round: "buf" is NULL, compute length, allocate "buf".
6890      * Second round: copy result into "buf".
6891      */
6892     buf = NULL;
6893     for (;;)
6894     {
6895 	p = cmd->uc_rep;    /* source */
6896 	q = buf;	    /* destination */
6897 	totlen = 0;
6898 
6899 	for (;;)
6900 	{
6901 	    start = vim_strchr(p, '<');
6902 	    if (start != NULL)
6903 		end = vim_strchr(start + 1, '>');
6904 	    if (buf != NULL)
6905 	    {
6906 		for (ksp = p; *ksp != NUL && *ksp != K_SPECIAL; ++ksp)
6907 		    ;
6908 		if (*ksp == K_SPECIAL
6909 			&& (start == NULL || ksp < start || end == NULL)
6910 			&& ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)
6911 # ifdef FEAT_GUI
6912 			    || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI)
6913 # endif
6914 			    ))
6915 		{
6916 		    /* K_SPECIAL has been put in the buffer as K_SPECIAL
6917 		     * KS_SPECIAL KE_FILLER, like for mappings, but
6918 		     * do_cmdline() doesn't handle that, so convert it back.
6919 		     * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */
6920 		    len = ksp - p;
6921 		    if (len > 0)
6922 		    {
6923 			mch_memmove(q, p, len);
6924 			q += len;
6925 		    }
6926 		    *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI;
6927 		    p = ksp + 3;
6928 		    continue;
6929 		}
6930 	    }
6931 
6932 	    /* break if there no <item> is found */
6933 	    if (start == NULL || end == NULL)
6934 		break;
6935 
6936 	    /* Include the '>' */
6937 	    ++end;
6938 
6939 	    /* Take everything up to the '<' */
6940 	    len = start - p;
6941 	    if (buf == NULL)
6942 		totlen += len;
6943 	    else
6944 	    {
6945 		mch_memmove(q, p, len);
6946 		q += len;
6947 	    }
6948 
6949 	    len = uc_check_code(start, end - start, q, cmd, eap,
6950 			     &split_buf, &split_len);
6951 	    if (len == (size_t)-1)
6952 	    {
6953 		/* no match, continue after '<' */
6954 		p = start + 1;
6955 		len = 1;
6956 	    }
6957 	    else
6958 		p = end;
6959 	    if (buf == NULL)
6960 		totlen += len;
6961 	    else
6962 		q += len;
6963 	}
6964 	if (buf != NULL)	    /* second time here, finished */
6965 	{
6966 	    STRCPY(q, p);
6967 	    break;
6968 	}
6969 
6970 	totlen += STRLEN(p);	    /* Add on the trailing characters */
6971 	buf = alloc((unsigned)(totlen + 1));
6972 	if (buf == NULL)
6973 	{
6974 	    vim_free(split_buf);
6975 	    return;
6976 	}
6977     }
6978 
6979 #ifdef FEAT_EVAL
6980     current_SID = cmd->uc_scriptID;
6981 #endif
6982     (void)do_cmdline(buf, eap->getline, eap->cookie,
6983 				   DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6984 #ifdef FEAT_EVAL
6985     current_SID = save_current_SID;
6986 #endif
6987     vim_free(buf);
6988     vim_free(split_buf);
6989 }
6990 
6991 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6992     static char_u *
6993 get_user_command_name(int idx)
6994 {
6995     return get_user_commands(NULL, idx - (int)CMD_SIZE);
6996 }
6997 
6998 /*
6999  * Function given to ExpandGeneric() to obtain the list of user command names.
7000  */
7001     char_u *
7002 get_user_commands(expand_T *xp UNUSED, int idx)
7003 {
7004     if (idx < curbuf->b_ucmds.ga_len)
7005 	return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
7006     idx -= curbuf->b_ucmds.ga_len;
7007     if (idx < ucmds.ga_len)
7008 	return USER_CMD(idx)->uc_name;
7009     return NULL;
7010 }
7011 
7012 /*
7013  * Function given to ExpandGeneric() to obtain the list of user address type names.
7014  */
7015     char_u *
7016 get_user_cmd_addr_type(expand_T *xp UNUSED, int idx)
7017 {
7018     return (char_u *)addr_type_complete[idx].name;
7019 }
7020 
7021 /*
7022  * Function given to ExpandGeneric() to obtain the list of user command
7023  * attributes.
7024  */
7025     char_u *
7026 get_user_cmd_flags(expand_T *xp UNUSED, int idx)
7027 {
7028     static char *user_cmd_flags[] =
7029 	{"addr", "bang", "bar", "buffer", "complete",
7030 	    "count", "nargs", "range", "register"};
7031 
7032     if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0])))
7033 	return NULL;
7034     return (char_u *)user_cmd_flags[idx];
7035 }
7036 
7037 /*
7038  * Function given to ExpandGeneric() to obtain the list of values for -nargs.
7039  */
7040     char_u *
7041 get_user_cmd_nargs(expand_T *xp UNUSED, int idx)
7042 {
7043     static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
7044 
7045     if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0])))
7046 	return NULL;
7047     return (char_u *)user_cmd_nargs[idx];
7048 }
7049 
7050 /*
7051  * Function given to ExpandGeneric() to obtain the list of values for -complete.
7052  */
7053     char_u *
7054 get_user_cmd_complete(expand_T *xp UNUSED, int idx)
7055 {
7056     return (char_u *)command_complete[idx].name;
7057 }
7058 # endif /* FEAT_CMDL_COMPL */
7059 
7060 /*
7061  * Parse address type argument
7062  */
7063     int
7064 parse_addr_type_arg(
7065     char_u	*value,
7066     int		vallen,
7067     long	*argt,
7068     int		*addr_type_arg)
7069 {
7070     int	    i, a, b;
7071 
7072     for (i = 0; addr_type_complete[i].expand != -1; ++i)
7073     {
7074 	a = (int)STRLEN(addr_type_complete[i].name) == vallen;
7075 	b = STRNCMP(value, addr_type_complete[i].name, vallen) == 0;
7076 	if (a && b)
7077 	{
7078 	    *addr_type_arg = addr_type_complete[i].expand;
7079 	    break;
7080 	}
7081     }
7082 
7083     if (addr_type_complete[i].expand == -1)
7084     {
7085 	char_u	*err = value;
7086 
7087 	for (i = 0; err[i] != NUL && !VIM_ISWHITE(err[i]); i++)
7088 	    ;
7089 	err[i] = NUL;
7090 	EMSG2(_("E180: Invalid address type value: %s"), err);
7091 	return FAIL;
7092     }
7093 
7094     if (*addr_type_arg != ADDR_LINES)
7095 	*argt |= NOTADR;
7096 
7097     return OK;
7098 }
7099 
7100 #endif	/* FEAT_USR_CMDS */
7101 
7102 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
7103 /*
7104  * Parse a completion argument "value[vallen]".
7105  * The detected completion goes in "*complp", argument type in "*argt".
7106  * When there is an argument, for function and user defined completion, it's
7107  * copied to allocated memory and stored in "*compl_arg".
7108  * Returns FAIL if something is wrong.
7109  */
7110     int
7111 parse_compl_arg(
7112     char_u	*value,
7113     int		vallen,
7114     int		*complp,
7115     long	*argt,
7116     char_u	**compl_arg UNUSED)
7117 {
7118     char_u	*arg = NULL;
7119 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
7120     size_t	arglen = 0;
7121 # endif
7122     int		i;
7123     int		valend = vallen;
7124 
7125     /* Look for any argument part - which is the part after any ',' */
7126     for (i = 0; i < vallen; ++i)
7127     {
7128 	if (value[i] == ',')
7129 	{
7130 	    arg = &value[i + 1];
7131 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
7132 	    arglen = vallen - i - 1;
7133 # endif
7134 	    valend = i;
7135 	    break;
7136 	}
7137     }
7138 
7139     for (i = 0; command_complete[i].expand != 0; ++i)
7140     {
7141 	if ((int)STRLEN(command_complete[i].name) == valend
7142 		&& STRNCMP(value, command_complete[i].name, valend) == 0)
7143 	{
7144 	    *complp = command_complete[i].expand;
7145 	    if (command_complete[i].expand == EXPAND_BUFFERS)
7146 		*argt |= BUFNAME;
7147 	    else if (command_complete[i].expand == EXPAND_DIRECTORIES
7148 		    || command_complete[i].expand == EXPAND_FILES)
7149 		*argt |= XFILE;
7150 	    break;
7151 	}
7152     }
7153 
7154     if (command_complete[i].expand == 0)
7155     {
7156 	EMSG2(_("E180: Invalid complete value: %s"), value);
7157 	return FAIL;
7158     }
7159 
7160 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
7161     if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
7162 							       && arg != NULL)
7163 # else
7164     if (arg != NULL)
7165 # endif
7166     {
7167 	EMSG(_("E468: Completion argument only allowed for custom completion"));
7168 	return FAIL;
7169     }
7170 
7171 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
7172     if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
7173 							       && arg == NULL)
7174     {
7175 	EMSG(_("E467: Custom completion requires a function argument"));
7176 	return FAIL;
7177     }
7178 
7179     if (arg != NULL)
7180 	*compl_arg = vim_strnsave(arg, (int)arglen);
7181 # endif
7182     return OK;
7183 }
7184 
7185     int
7186 cmdcomplete_str_to_type(char_u *complete_str)
7187 {
7188     int i;
7189 
7190     for (i = 0; command_complete[i].expand != 0; ++i)
7191 	if (STRCMP(complete_str, command_complete[i].name) == 0)
7192 	    return command_complete[i].expand;
7193 
7194     return EXPAND_NOTHING;
7195 }
7196 #endif
7197 
7198     static void
7199 ex_colorscheme(exarg_T *eap)
7200 {
7201     if (*eap->arg == NUL)
7202     {
7203 #ifdef FEAT_EVAL
7204 	char_u *expr = vim_strsave((char_u *)"g:colors_name");
7205 	char_u *p = NULL;
7206 
7207 	if (expr != NULL)
7208 	{
7209 	    ++emsg_off;
7210 	    p = eval_to_string(expr, NULL, FALSE);
7211 	    --emsg_off;
7212 	    vim_free(expr);
7213 	}
7214 	if (p != NULL)
7215 	{
7216 	    MSG(p);
7217 	    vim_free(p);
7218 	}
7219 	else
7220 	    MSG("default");
7221 #else
7222 	MSG(_("unknown"));
7223 #endif
7224     }
7225     else if (load_colors(eap->arg) == FAIL)
7226 	EMSG2(_("E185: Cannot find color scheme '%s'"), eap->arg);
7227 }
7228 
7229     static void
7230 ex_highlight(exarg_T *eap)
7231 {
7232     if (*eap->arg == NUL && eap->cmd[2] == '!')
7233 	MSG(_("Greetings, Vim user!"));
7234     do_highlight(eap->arg, eap->forceit, FALSE);
7235 }
7236 
7237 
7238 /*
7239  * Call this function if we thought we were going to exit, but we won't
7240  * (because of an error).  May need to restore the terminal mode.
7241  */
7242     void
7243 not_exiting(void)
7244 {
7245     exiting = FALSE;
7246     settmode(TMODE_RAW);
7247 }
7248 
7249 /*
7250  * ":quit": quit current window, quit Vim if the last window is closed.
7251  */
7252     static void
7253 ex_quit(exarg_T *eap)
7254 {
7255 #if defined(FEAT_WINDOWS) || defined(FEAT_AUTOCMD)
7256     win_T	*wp;
7257 #endif
7258 
7259 #ifdef FEAT_CMDWIN
7260     if (cmdwin_type != 0)
7261     {
7262 	cmdwin_result = Ctrl_C;
7263 	return;
7264     }
7265 #endif
7266     /* Don't quit while editing the command line. */
7267     if (text_locked())
7268     {
7269 	text_locked_msg();
7270 	return;
7271     }
7272 #ifdef FEAT_WINDOWS
7273     if (eap->addr_count > 0)
7274     {
7275 	int	wnr = eap->line2;
7276 
7277 	for (wp = firstwin; wp->w_next != NULL; wp = wp->w_next)
7278 	    if (--wnr <= 0)
7279 		break;
7280     }
7281     else
7282 #endif
7283 #if defined(FEAT_WINDOWS) || defined(FEAT_AUTOCMD)
7284 	wp = curwin;
7285 #endif
7286 
7287 #ifdef FEAT_AUTOCMD
7288     apply_autocmds(EVENT_QUITPRE, NULL, NULL, FALSE, curbuf);
7289     /* Refuse to quit when locked or when the buffer in the last window is
7290      * being closed (can only happen in autocommands). */
7291     if (curbuf_locked()
7292 # ifdef FEAT_WINDOWS
7293 	    || !win_valid(wp)
7294 # endif
7295 	    || (wp->w_buffer->b_nwindows == 1 && wp->w_buffer->b_locked > 0))
7296 	return;
7297 #endif
7298 
7299 #ifdef FEAT_NETBEANS_INTG
7300     netbeansForcedQuit = eap->forceit;
7301 #endif
7302 
7303     /*
7304      * If there are more files or windows we won't exit.
7305      */
7306     if (check_more(FALSE, eap->forceit) == OK && only_one_window())
7307 	exiting = TRUE;
7308     if ((!buf_hide(curbuf)
7309 		&& check_changed(curbuf, (p_awa ? CCGD_AW : 0)
7310 				       | (eap->forceit ? CCGD_FORCEIT : 0)
7311 				       | CCGD_EXCMD))
7312 	    || check_more(TRUE, eap->forceit) == FAIL
7313 	    || (only_one_window() && check_changed_any(eap->forceit, TRUE)))
7314     {
7315 	not_exiting();
7316     }
7317     else
7318     {
7319 #ifdef FEAT_WINDOWS
7320 	/* quit last window
7321 	 * Note: only_one_window() returns true, even so a help window is
7322 	 * still open. In that case only quit, if no address has been
7323 	 * specified. Example:
7324 	 * :h|wincmd w|1q     - don't quit
7325 	 * :h|wincmd w|q      - quit
7326 	 */
7327 	if (only_one_window() && (ONE_WINDOW || eap->addr_count == 0))
7328 #endif
7329 	    getout(0);
7330 #ifdef FEAT_WINDOWS
7331 # ifdef FEAT_GUI
7332 	need_mouse_correct = TRUE;
7333 # endif
7334 	/* close window; may free buffer */
7335 	win_close(wp, !buf_hide(wp->w_buffer) || eap->forceit);
7336 #endif
7337     }
7338 }
7339 
7340 /*
7341  * ":cquit".
7342  */
7343     static void
7344 ex_cquit(exarg_T *eap UNUSED)
7345 {
7346     getout(1);	/* this does not always pass on the exit code to the Manx
7347 		   compiler. why? */
7348 }
7349 
7350 /*
7351  * ":qall": try to quit all windows
7352  */
7353     static void
7354 ex_quit_all(exarg_T *eap)
7355 {
7356 # ifdef FEAT_CMDWIN
7357     if (cmdwin_type != 0)
7358     {
7359 	if (eap->forceit)
7360 	    cmdwin_result = K_XF1;	/* ex_window() takes care of this */
7361 	else
7362 	    cmdwin_result = K_XF2;
7363 	return;
7364     }
7365 # endif
7366 
7367     /* Don't quit while editing the command line. */
7368     if (text_locked())
7369     {
7370 	text_locked_msg();
7371 	return;
7372     }
7373 #ifdef FEAT_AUTOCMD
7374     apply_autocmds(EVENT_QUITPRE, NULL, NULL, FALSE, curbuf);
7375     /* Refuse to quit when locked or when the buffer in the last window is
7376      * being closed (can only happen in autocommands). */
7377     if (curbuf_locked() || (curbuf->b_nwindows == 1 && curbuf->b_locked > 0))
7378 	return;
7379 #endif
7380 
7381     exiting = TRUE;
7382     if (eap->forceit || !check_changed_any(FALSE, FALSE))
7383 	getout(0);
7384     not_exiting();
7385 }
7386 
7387 #if defined(FEAT_WINDOWS) || defined(PROTO)
7388 /*
7389  * ":close": close current window, unless it is the last one
7390  */
7391     static void
7392 ex_close(exarg_T *eap)
7393 {
7394     win_T	*win;
7395     int		winnr = 0;
7396 # ifdef FEAT_CMDWIN
7397     if (cmdwin_type != 0)
7398 	cmdwin_result = Ctrl_C;
7399     else
7400 # endif
7401 	if (!text_locked()
7402 #ifdef FEAT_AUTOCMD
7403 		&& !curbuf_locked()
7404 #endif
7405 		)
7406 	{
7407 	    if (eap->addr_count == 0)
7408 		ex_win_close(eap->forceit, curwin, NULL);
7409 	    else {
7410 		FOR_ALL_WINDOWS(win)
7411 		{
7412 		    winnr++;
7413 		    if (winnr == eap->line2)
7414 			break;
7415 		}
7416 		if (win == NULL)
7417 		    win = lastwin;
7418 		ex_win_close(eap->forceit, win, NULL);
7419 	    }
7420 	}
7421 }
7422 
7423 # ifdef FEAT_QUICKFIX
7424 /*
7425  * ":pclose": Close any preview window.
7426  */
7427     static void
7428 ex_pclose(exarg_T *eap)
7429 {
7430     win_T	*win;
7431 
7432     FOR_ALL_WINDOWS(win)
7433 	if (win->w_p_pvw)
7434 	{
7435 	    ex_win_close(eap->forceit, win, NULL);
7436 	    break;
7437 	}
7438 }
7439 # endif
7440 
7441 /*
7442  * Close window "win" and take care of handling closing the last window for a
7443  * modified buffer.
7444  */
7445     static void
7446 ex_win_close(
7447     int		forceit,
7448     win_T	*win,
7449     tabpage_T	*tp)		/* NULL or the tab page "win" is in */
7450 {
7451     int		need_hide;
7452     buf_T	*buf = win->w_buffer;
7453 
7454     need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
7455     if (need_hide && !buf_hide(buf) && !forceit)
7456     {
7457 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
7458 	if ((p_confirm || cmdmod.confirm) && p_write)
7459 	{
7460 	    bufref_T bufref;
7461 
7462 	    set_bufref(&bufref, buf);
7463 	    dialog_changed(buf, FALSE);
7464 	    if (bufref_valid(&bufref) && bufIsChanged(buf))
7465 		return;
7466 	    need_hide = FALSE;
7467 	}
7468 	else
7469 # endif
7470 	{
7471 	    EMSG(_(e_nowrtmsg));
7472 	    return;
7473 	}
7474     }
7475 
7476 # ifdef FEAT_GUI
7477     need_mouse_correct = TRUE;
7478 # endif
7479 
7480     /* free buffer when not hiding it or when it's a scratch buffer */
7481     if (tp == NULL)
7482 	win_close(win, !need_hide && !buf_hide(buf));
7483     else
7484 	win_close_othertab(win, !need_hide && !buf_hide(buf), tp);
7485 }
7486 
7487 /*
7488  * Handle the argument for a tabpage related ex command.
7489  * Returns a tabpage number.
7490  * When an error is encountered then eap->errmsg is set.
7491  */
7492     static int
7493 get_tabpage_arg(exarg_T *eap)
7494 {
7495     int tab_number;
7496     int unaccept_arg0 = (eap->cmdidx == CMD_tabmove) ? 0 : 1;
7497 
7498     if (eap->arg && *eap->arg != NUL)
7499     {
7500 	char_u *p = eap->arg;
7501 	char_u *p_save;
7502 	int    relative = 0; /* argument +N/-N means: go to N places to the
7503 			      * right/left relative to the current position. */
7504 
7505 	if (*p == '-')
7506 	{
7507 	    relative = -1;
7508 	    p++;
7509 	}
7510 	else if (*p == '+')
7511 	{
7512 	    relative = 1;
7513 	    p++;
7514 	}
7515 
7516 	p_save = p;
7517 	tab_number = getdigits(&p);
7518 
7519 	if (relative == 0)
7520 	{
7521 	    if (STRCMP(p, "$") == 0)
7522 		tab_number = LAST_TAB_NR;
7523 	    else if (p == p_save || *p_save == '-' || *p != NUL
7524 		    || tab_number > LAST_TAB_NR)
7525 	    {
7526 		/* No numbers as argument. */
7527 		eap->errmsg = e_invarg;
7528 		goto theend;
7529 	    }
7530 	}
7531 	else
7532 	{
7533 	    if (*p_save == NUL)
7534 		tab_number = 1;
7535 	    else if (p == p_save || *p_save == '-' || *p != NUL
7536 		    || tab_number == 0)
7537 	    {
7538 		/* No numbers as argument. */
7539 		eap->errmsg = e_invarg;
7540 		goto theend;
7541 	    }
7542 	    tab_number = tab_number * relative + tabpage_index(curtab);
7543 	    if (!unaccept_arg0 && relative == -1)
7544 		--tab_number;
7545 	}
7546 	if (tab_number < unaccept_arg0 || tab_number > LAST_TAB_NR)
7547 	    eap->errmsg = e_invarg;
7548     }
7549     else if (eap->addr_count > 0)
7550     {
7551 	if (unaccept_arg0 && eap->line2 == 0)
7552 	{
7553 	    eap->errmsg = e_invrange;
7554 	    tab_number = 0;
7555 	}
7556 	else
7557 	{
7558 	    tab_number = eap->line2;
7559 	    if (!unaccept_arg0 && **eap->cmdlinep == '-')
7560 	    {
7561 		--tab_number;
7562 		if (tab_number < unaccept_arg0)
7563 		    eap->errmsg = e_invarg;
7564 	    }
7565 	}
7566     }
7567     else
7568     {
7569 	switch (eap->cmdidx)
7570 	{
7571 	case CMD_tabnext:
7572 	    tab_number = tabpage_index(curtab) + 1;
7573 	    if (tab_number > LAST_TAB_NR)
7574 		tab_number = 1;
7575 	    break;
7576 	case CMD_tabmove:
7577 	    tab_number = LAST_TAB_NR;
7578 	    break;
7579 	default:
7580 	    tab_number = tabpage_index(curtab);
7581 	}
7582     }
7583 
7584 theend:
7585     return tab_number;
7586 }
7587 
7588 /*
7589  * ":tabclose": close current tab page, unless it is the last one.
7590  * ":tabclose N": close tab page N.
7591  */
7592     static void
7593 ex_tabclose(exarg_T *eap)
7594 {
7595     tabpage_T	*tp;
7596     int		tab_number;
7597 
7598 # ifdef FEAT_CMDWIN
7599     if (cmdwin_type != 0)
7600 	cmdwin_result = K_IGNORE;
7601     else
7602 # endif
7603 	if (first_tabpage->tp_next == NULL)
7604 	    EMSG(_("E784: Cannot close last tab page"));
7605 	else
7606 	{
7607 	    tab_number = get_tabpage_arg(eap);
7608 	    if (eap->errmsg == NULL)
7609 	    {
7610 		tp = find_tabpage(tab_number);
7611 		if (tp == NULL)
7612 		{
7613 		    beep_flush();
7614 		    return;
7615 		}
7616 		if (tp != curtab)
7617 		{
7618 		    tabpage_close_other(tp, eap->forceit);
7619 		    return;
7620 		}
7621 		else if (!text_locked()
7622 #ifdef FEAT_AUTOCMD
7623 			&& !curbuf_locked()
7624 #endif
7625 		)
7626 		    tabpage_close(eap->forceit);
7627 	    }
7628 	}
7629 }
7630 
7631 /*
7632  * ":tabonly": close all tab pages except the current one
7633  */
7634     static void
7635 ex_tabonly(exarg_T *eap)
7636 {
7637     tabpage_T	*tp;
7638     int		done;
7639     int		tab_number;
7640 
7641 # ifdef FEAT_CMDWIN
7642     if (cmdwin_type != 0)
7643 	cmdwin_result = K_IGNORE;
7644     else
7645 # endif
7646 	if (first_tabpage->tp_next == NULL)
7647 	    MSG(_("Already only one tab page"));
7648 	else
7649 	{
7650 	    tab_number = get_tabpage_arg(eap);
7651 	    if (eap->errmsg == NULL)
7652 	    {
7653 		goto_tabpage(tab_number);
7654 		/* Repeat this up to a 1000 times, because autocommands may
7655 		 * mess up the lists. */
7656 		for (done = 0; done < 1000; ++done)
7657 		{
7658 		    FOR_ALL_TABPAGES(tp)
7659 			if (tp->tp_topframe != topframe)
7660 			{
7661 			    tabpage_close_other(tp, eap->forceit);
7662 			    /* if we failed to close it quit */
7663 			    if (valid_tabpage(tp))
7664 				done = 1000;
7665 			    /* start over, "tp" is now invalid */
7666 			    break;
7667 			}
7668 		    if (first_tabpage->tp_next == NULL)
7669 			break;
7670 		}
7671 	    }
7672 	}
7673 }
7674 
7675 /*
7676  * Close the current tab page.
7677  */
7678     void
7679 tabpage_close(int forceit)
7680 {
7681     /* First close all the windows but the current one.  If that worked then
7682      * close the last window in this tab, that will close it. */
7683     if (!ONE_WINDOW)
7684 	close_others(TRUE, forceit);
7685     if (ONE_WINDOW)
7686 	ex_win_close(forceit, curwin, NULL);
7687 # ifdef FEAT_GUI
7688     need_mouse_correct = TRUE;
7689 # endif
7690 }
7691 
7692 /*
7693  * Close tab page "tp", which is not the current tab page.
7694  * Note that autocommands may make "tp" invalid.
7695  * Also takes care of the tab pages line disappearing when closing the
7696  * last-but-one tab page.
7697  */
7698     void
7699 tabpage_close_other(tabpage_T *tp, int forceit)
7700 {
7701     int		done = 0;
7702     win_T	*wp;
7703     int		h = tabline_height();
7704 
7705     /* Limit to 1000 windows, autocommands may add a window while we close
7706      * one.  OK, so I'm paranoid... */
7707     while (++done < 1000)
7708     {
7709 	wp = tp->tp_firstwin;
7710 	ex_win_close(forceit, wp, tp);
7711 
7712 	/* Autocommands may delete the tab page under our fingers and we may
7713 	 * fail to close a window with a modified buffer. */
7714 	if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
7715 	    break;
7716     }
7717 
7718 #ifdef FEAT_AUTOCMD
7719     apply_autocmds(EVENT_TABCLOSED, NULL, NULL, FALSE, curbuf);
7720 #endif
7721 
7722     redraw_tabline = TRUE;
7723     if (h != tabline_height())
7724 	shell_new_rows();
7725 }
7726 
7727 /*
7728  * ":only".
7729  */
7730     static void
7731 ex_only(exarg_T *eap)
7732 {
7733     win_T   *wp;
7734     int	    wnr;
7735 # ifdef FEAT_GUI
7736     need_mouse_correct = TRUE;
7737 # endif
7738     if (eap->addr_count > 0)
7739     {
7740 	wnr = eap->line2;
7741 	for (wp = firstwin; --wnr > 0; )
7742 	{
7743 	    if (wp->w_next == NULL)
7744 		break;
7745 	    else
7746 		wp = wp->w_next;
7747 	}
7748 	win_goto(wp);
7749     }
7750     close_others(TRUE, eap->forceit);
7751 }
7752 
7753 /*
7754  * ":all" and ":sall".
7755  * Also used for ":tab drop file ..." after setting the argument list.
7756  */
7757     void
7758 ex_all(exarg_T *eap)
7759 {
7760     if (eap->addr_count == 0)
7761 	eap->line2 = 9999;
7762     do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
7763 }
7764 #endif /* FEAT_WINDOWS */
7765 
7766     static void
7767 ex_hide(exarg_T *eap UNUSED)
7768 {
7769     /* ":hide" or ":hide | cmd": hide current window */
7770 #ifdef FEAT_WINDOWS
7771     if (!eap->skip)
7772     {
7773 # ifdef FEAT_GUI
7774 	need_mouse_correct = TRUE;
7775 # endif
7776 	if (eap->addr_count == 0)
7777 	    win_close(curwin, FALSE);	/* don't free buffer */
7778 	else
7779 	{
7780 	    int	winnr = 0;
7781 	    win_T	*win;
7782 
7783 	    FOR_ALL_WINDOWS(win)
7784 	    {
7785 		winnr++;
7786 		if (winnr == eap->line2)
7787 		    break;
7788 	    }
7789 	    if (win == NULL)
7790 		win = lastwin;
7791 	    win_close(win, FALSE);
7792 	}
7793     }
7794 #endif
7795 }
7796 
7797 /*
7798  * ":stop" and ":suspend": Suspend Vim.
7799  */
7800     static void
7801 ex_stop(exarg_T *eap)
7802 {
7803     /*
7804      * Disallow suspending for "rvim".
7805      */
7806     if (!check_restricted())
7807     {
7808 	if (!eap->forceit)
7809 	    autowrite_all();
7810 	windgoto((int)Rows - 1, 0);
7811 	out_char('\n');
7812 	out_flush();
7813 	stoptermcap();
7814 	out_flush();		/* needed for SUN to restore xterm buffer */
7815 #ifdef FEAT_TITLE
7816 	mch_restore_title(3);	/* restore window titles */
7817 #endif
7818 	ui_suspend();		/* call machine specific function */
7819 #ifdef FEAT_TITLE
7820 	maketitle();
7821 	resettitle();		/* force updating the title */
7822 #endif
7823 	starttermcap();
7824 	scroll_start();		/* scroll screen before redrawing */
7825 	redraw_later_clear();
7826 	shell_resized();	/* may have resized window */
7827     }
7828 }
7829 
7830 /*
7831  * ":exit", ":xit" and ":wq": Write file and exit Vim.
7832  */
7833     static void
7834 ex_exit(exarg_T *eap)
7835 {
7836 #ifdef FEAT_CMDWIN
7837     if (cmdwin_type != 0)
7838     {
7839 	cmdwin_result = Ctrl_C;
7840 	return;
7841     }
7842 #endif
7843     /* Don't quit while editing the command line. */
7844     if (text_locked())
7845     {
7846 	text_locked_msg();
7847 	return;
7848     }
7849 #ifdef FEAT_AUTOCMD
7850     apply_autocmds(EVENT_QUITPRE, NULL, NULL, FALSE, curbuf);
7851     /* Refuse to quit when locked or when the buffer in the last window is
7852      * being closed (can only happen in autocommands). */
7853     if (curbuf_locked() || (curbuf->b_nwindows == 1 && curbuf->b_locked > 0))
7854 	return;
7855 #endif
7856 
7857     /*
7858      * if more files or windows we won't exit
7859      */
7860     if (check_more(FALSE, eap->forceit) == OK && only_one_window())
7861 	exiting = TRUE;
7862     if (       ((eap->cmdidx == CMD_wq
7863 		    || curbufIsChanged())
7864 		&& do_write(eap) == FAIL)
7865 	    || check_more(TRUE, eap->forceit) == FAIL
7866 	    || (only_one_window() && check_changed_any(eap->forceit, FALSE)))
7867     {
7868 	not_exiting();
7869     }
7870     else
7871     {
7872 #ifdef FEAT_WINDOWS
7873 	if (only_one_window())	    /* quit last window, exit Vim */
7874 #endif
7875 	    getout(0);
7876 #ifdef FEAT_WINDOWS
7877 # ifdef FEAT_GUI
7878 	need_mouse_correct = TRUE;
7879 # endif
7880 	/* Quit current window, may free the buffer. */
7881 	win_close(curwin, !buf_hide(curwin->w_buffer));
7882 #endif
7883     }
7884 }
7885 
7886 /*
7887  * ":print", ":list", ":number".
7888  */
7889     static void
7890 ex_print(exarg_T *eap)
7891 {
7892     if (curbuf->b_ml.ml_flags & ML_EMPTY)
7893 	EMSG(_(e_emptybuf));
7894     else
7895     {
7896 	for ( ;!got_int; ui_breakcheck())
7897 	{
7898 	    print_line(eap->line1,
7899 		    (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
7900 						 || (eap->flags & EXFLAG_NR)),
7901 		    eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
7902 	    if (++eap->line1 > eap->line2)
7903 		break;
7904 	    out_flush();	    /* show one line at a time */
7905 	}
7906 	setpcmark();
7907 	/* put cursor at last line */
7908 	curwin->w_cursor.lnum = eap->line2;
7909 	beginline(BL_SOL | BL_FIX);
7910     }
7911 
7912     ex_no_reprint = TRUE;
7913 }
7914 
7915 #ifdef FEAT_BYTEOFF
7916     static void
7917 ex_goto(exarg_T *eap)
7918 {
7919     goto_byte(eap->line2);
7920 }
7921 #endif
7922 
7923 /*
7924  * ":shell".
7925  */
7926     static void
7927 ex_shell(exarg_T *eap UNUSED)
7928 {
7929     do_shell(NULL, 0);
7930 }
7931 
7932 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
7933 	|| (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
7934 	|| defined(FEAT_GUI_MSWIN) \
7935 	|| defined(FEAT_GUI_MAC) \
7936 	|| defined(PROTO)
7937 
7938 /*
7939  * Handle a file drop. The code is here because a drop is *nearly* like an
7940  * :args command, but not quite (we have a list of exact filenames, so we
7941  * don't want to (a) parse a command line, or (b) expand wildcards. So the
7942  * code is very similar to :args and hence needs access to a lot of the static
7943  * functions in this file.
7944  *
7945  * The list should be allocated using alloc(), as should each item in the
7946  * list. This function takes over responsibility for freeing the list.
7947  *
7948  * XXX The list is made into the argument list. This is freed using
7949  * FreeWild(), which does a series of vim_free() calls.
7950  */
7951     void
7952 handle_drop(
7953     int		filec,		/* the number of files dropped */
7954     char_u	**filev,	/* the list of files dropped */
7955     int		split)		/* force splitting the window */
7956 {
7957     exarg_T	ea;
7958     int		save_msg_scroll = msg_scroll;
7959 
7960     /* Postpone this while editing the command line. */
7961     if (text_locked())
7962 	return;
7963 #ifdef FEAT_AUTOCMD
7964     if (curbuf_locked())
7965 	return;
7966 #endif
7967     /* When the screen is being updated we should not change buffers and
7968      * windows structures, it may cause freed memory to be used. */
7969     if (updating_screen)
7970 	return;
7971 
7972     /* Check whether the current buffer is changed. If so, we will need
7973      * to split the current window or data could be lost.
7974      * We don't need to check if the 'hidden' option is set, as in this
7975      * case the buffer won't be lost.
7976      */
7977     if (!buf_hide(curbuf) && !split)
7978     {
7979 	++emsg_off;
7980 	split = check_changed(curbuf, CCGD_AW);
7981 	--emsg_off;
7982     }
7983     if (split)
7984     {
7985 # ifdef FEAT_WINDOWS
7986 	if (win_split(0, 0) == FAIL)
7987 	    return;
7988 	RESET_BINDING(curwin);
7989 
7990 	/* When splitting the window, create a new alist.  Otherwise the
7991 	 * existing one is overwritten. */
7992 	alist_unlink(curwin->w_alist);
7993 	alist_new();
7994 # else
7995 	return;	    /* can't split, always fail */
7996 # endif
7997     }
7998 
7999     /*
8000      * Set up the new argument list.
8001      */
8002     alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
8003 
8004     /*
8005      * Move to the first file.
8006      */
8007     /* Fake up a minimal "next" command for do_argfile() */
8008     vim_memset(&ea, 0, sizeof(ea));
8009     ea.cmd = (char_u *)"next";
8010     do_argfile(&ea, 0);
8011 
8012     /* do_ecmd() may set need_start_insertmode, but since we never left Insert
8013      * mode that is not needed here. */
8014     need_start_insertmode = FALSE;
8015 
8016     /* Restore msg_scroll, otherwise a following command may cause scrolling
8017      * unexpectedly.  The screen will be redrawn by the caller, thus
8018      * msg_scroll being set by displaying a message is irrelevant. */
8019     msg_scroll = save_msg_scroll;
8020 }
8021 #endif
8022 
8023 /*
8024  * Clear an argument list: free all file names and reset it to zero entries.
8025  */
8026     void
8027 alist_clear(alist_T *al)
8028 {
8029     while (--al->al_ga.ga_len >= 0)
8030 	vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
8031     ga_clear(&al->al_ga);
8032 }
8033 
8034 /*
8035  * Init an argument list.
8036  */
8037     void
8038 alist_init(alist_T *al)
8039 {
8040     ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
8041 }
8042 
8043 #if defined(FEAT_WINDOWS) || defined(PROTO)
8044 
8045 /*
8046  * Remove a reference from an argument list.
8047  * Ignored when the argument list is the global one.
8048  * If the argument list is no longer used by any window, free it.
8049  */
8050     void
8051 alist_unlink(alist_T *al)
8052 {
8053     if (al != &global_alist && --al->al_refcount <= 0)
8054     {
8055 	alist_clear(al);
8056 	vim_free(al);
8057     }
8058 }
8059 
8060 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
8061 /*
8062  * Create a new argument list and use it for the current window.
8063  */
8064     void
8065 alist_new(void)
8066 {
8067     curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
8068     if (curwin->w_alist == NULL)
8069     {
8070 	curwin->w_alist = &global_alist;
8071 	++global_alist.al_refcount;
8072     }
8073     else
8074     {
8075 	curwin->w_alist->al_refcount = 1;
8076 	curwin->w_alist->id = ++max_alist_id;
8077 	alist_init(curwin->w_alist);
8078     }
8079 }
8080 # endif
8081 #endif
8082 
8083 #if !defined(UNIX) || defined(PROTO)
8084 /*
8085  * Expand the file names in the global argument list.
8086  * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
8087  * numbers to be re-used.
8088  */
8089     void
8090 alist_expand(int *fnum_list, int fnum_len)
8091 {
8092     char_u	**old_arg_files;
8093     int		old_arg_count;
8094     char_u	**new_arg_files;
8095     int		new_arg_file_count;
8096     char_u	*save_p_su = p_su;
8097     int		i;
8098 
8099     /* Don't use 'suffixes' here.  This should work like the shell did the
8100      * expansion.  Also, the vimrc file isn't read yet, thus the user
8101      * can't set the options. */
8102     p_su = empty_option;
8103     old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
8104     if (old_arg_files != NULL)
8105     {
8106 	for (i = 0; i < GARGCOUNT; ++i)
8107 	    old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
8108 	old_arg_count = GARGCOUNT;
8109 	if (expand_wildcards(old_arg_count, old_arg_files,
8110 		    &new_arg_file_count, &new_arg_files,
8111 		    EW_FILE|EW_NOTFOUND|EW_ADDSLASH|EW_NOERROR) == OK
8112 		&& new_arg_file_count > 0)
8113 	{
8114 	    alist_set(&global_alist, new_arg_file_count, new_arg_files,
8115 						   TRUE, fnum_list, fnum_len);
8116 	    FreeWild(old_arg_count, old_arg_files);
8117 	}
8118     }
8119     p_su = save_p_su;
8120 }
8121 #endif
8122 
8123 /*
8124  * Set the argument list for the current window.
8125  * Takes over the allocated files[] and the allocated fnames in it.
8126  */
8127     void
8128 alist_set(
8129     alist_T	*al,
8130     int		count,
8131     char_u	**files,
8132     int		use_curbuf,
8133     int		*fnum_list,
8134     int		fnum_len)
8135 {
8136     int		i;
8137 
8138     alist_clear(al);
8139     if (ga_grow(&al->al_ga, count) == OK)
8140     {
8141 	for (i = 0; i < count; ++i)
8142 	{
8143 	    if (got_int)
8144 	    {
8145 		/* When adding many buffers this can take a long time.  Allow
8146 		 * interrupting here. */
8147 		while (i < count)
8148 		    vim_free(files[i++]);
8149 		break;
8150 	    }
8151 
8152 	    /* May set buffer name of a buffer previously used for the
8153 	     * argument list, so that it's re-used by alist_add. */
8154 	    if (fnum_list != NULL && i < fnum_len)
8155 		buf_set_name(fnum_list[i], files[i]);
8156 
8157 	    alist_add(al, files[i], use_curbuf ? 2 : 1);
8158 	    ui_breakcheck();
8159 	}
8160 	vim_free(files);
8161     }
8162     else
8163 	FreeWild(count, files);
8164 #ifdef FEAT_WINDOWS
8165     if (al == &global_alist)
8166 #endif
8167 	arg_had_last = FALSE;
8168 }
8169 
8170 /*
8171  * Add file "fname" to argument list "al".
8172  * "fname" must have been allocated and "al" must have been checked for room.
8173  */
8174     void
8175 alist_add(
8176     alist_T	*al,
8177     char_u	*fname,
8178     int		set_fnum)	/* 1: set buffer number; 2: re-use curbuf */
8179 {
8180     if (fname == NULL)		/* don't add NULL file names */
8181 	return;
8182 #ifdef BACKSLASH_IN_FILENAME
8183     slash_adjust(fname);
8184 #endif
8185     AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
8186     if (set_fnum > 0)
8187 	AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
8188 	    buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
8189     ++al->al_ga.ga_len;
8190 }
8191 
8192 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
8193 /*
8194  * Adjust slashes in file names.  Called after 'shellslash' was set.
8195  */
8196     void
8197 alist_slash_adjust(void)
8198 {
8199     int		i;
8200 # ifdef FEAT_WINDOWS
8201     win_T	*wp;
8202     tabpage_T	*tp;
8203 # endif
8204 
8205     for (i = 0; i < GARGCOUNT; ++i)
8206 	if (GARGLIST[i].ae_fname != NULL)
8207 	    slash_adjust(GARGLIST[i].ae_fname);
8208 # ifdef FEAT_WINDOWS
8209     FOR_ALL_TAB_WINDOWS(tp, wp)
8210 	if (wp->w_alist != &global_alist)
8211 	    for (i = 0; i < WARGCOUNT(wp); ++i)
8212 		if (WARGLIST(wp)[i].ae_fname != NULL)
8213 		    slash_adjust(WARGLIST(wp)[i].ae_fname);
8214 # endif
8215 }
8216 #endif
8217 
8218 /*
8219  * ":preserve".
8220  */
8221     static void
8222 ex_preserve(exarg_T *eap UNUSED)
8223 {
8224     curbuf->b_flags |= BF_PRESERVED;
8225     ml_preserve(curbuf, TRUE);
8226 }
8227 
8228 /*
8229  * ":recover".
8230  */
8231     static void
8232 ex_recover(exarg_T *eap)
8233 {
8234     /* Set recoverymode right away to avoid the ATTENTION prompt. */
8235     recoverymode = TRUE;
8236     if (!check_changed(curbuf, (p_awa ? CCGD_AW : 0)
8237 			     | CCGD_MULTWIN
8238 			     | (eap->forceit ? CCGD_FORCEIT : 0)
8239 			     | CCGD_EXCMD)
8240 
8241 	    && (*eap->arg == NUL
8242 			     || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
8243 	ml_recover();
8244     recoverymode = FALSE;
8245 }
8246 
8247 /*
8248  * Command modifier used in a wrong way.
8249  */
8250     static void
8251 ex_wrongmodifier(exarg_T *eap)
8252 {
8253     eap->errmsg = e_invcmd;
8254 }
8255 
8256 #ifdef FEAT_WINDOWS
8257 /*
8258  * :sview [+command] file	split window with new file, read-only
8259  * :split [[+command] file]	split window with current or new file
8260  * :vsplit [[+command] file]	split window vertically with current or new file
8261  * :new [[+command] file]	split window with no or new file
8262  * :vnew [[+command] file]	split vertically window with no or new file
8263  * :sfind [+command] file	split window with file in 'path'
8264  *
8265  * :tabedit			open new Tab page with empty window
8266  * :tabedit [+command] file	open new Tab page and edit "file"
8267  * :tabnew [[+command] file]	just like :tabedit
8268  * :tabfind [+command] file	open new Tab page and find "file"
8269  */
8270     void
8271 ex_splitview(exarg_T *eap)
8272 {
8273     win_T	*old_curwin = curwin;
8274 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
8275     char_u	*fname = NULL;
8276 # endif
8277 # ifdef FEAT_BROWSE
8278     int		browse_flag = cmdmod.browse;
8279 # endif
8280 
8281 # ifdef FEAT_GUI
8282     need_mouse_correct = TRUE;
8283 # endif
8284 
8285 # ifdef FEAT_QUICKFIX
8286     /* A ":split" in the quickfix window works like ":new".  Don't want two
8287      * quickfix windows.  But it's OK when doing ":tab split". */
8288     if (bt_quickfix(curbuf) && cmdmod.tab == 0)
8289     {
8290 	if (eap->cmdidx == CMD_split)
8291 	    eap->cmdidx = CMD_new;
8292 	if (eap->cmdidx == CMD_vsplit)
8293 	    eap->cmdidx = CMD_vnew;
8294     }
8295 # endif
8296 
8297 # ifdef FEAT_SEARCHPATH
8298     if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
8299     {
8300 	fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
8301 					  FNAME_MESS, TRUE, curbuf->b_ffname);
8302 	if (fname == NULL)
8303 	    goto theend;
8304 	eap->arg = fname;
8305     }
8306 #  ifdef FEAT_BROWSE
8307     else
8308 #  endif
8309 # endif
8310 # ifdef FEAT_BROWSE
8311     if (cmdmod.browse
8312 	    && eap->cmdidx != CMD_vnew
8313 	    && eap->cmdidx != CMD_new)
8314     {
8315 # ifdef FEAT_AUTOCMD
8316 	if (
8317 #  ifdef FEAT_GUI
8318 	    !gui.in_use &&
8319 #  endif
8320 		au_has_group((char_u *)"FileExplorer"))
8321 	{
8322 	    /* No browsing supported but we do have the file explorer:
8323 	     * Edit the directory. */
8324 	    if (*eap->arg == NUL || !mch_isdir(eap->arg))
8325 		eap->arg = (char_u *)".";
8326 	}
8327 	else
8328 # endif
8329 	{
8330 	    fname = do_browse(0, (char_u *)_("Edit File in new window"),
8331 					  eap->arg, NULL, NULL, NULL, curbuf);
8332 	    if (fname == NULL)
8333 		goto theend;
8334 	    eap->arg = fname;
8335 	}
8336     }
8337     cmdmod.browse = FALSE;	/* Don't browse again in do_ecmd(). */
8338 # endif
8339 
8340     /*
8341      * Either open new tab page or split the window.
8342      */
8343     if (eap->cmdidx == CMD_tabedit
8344 	    || eap->cmdidx == CMD_tabfind
8345 	    || eap->cmdidx == CMD_tabnew)
8346     {
8347 	if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
8348 			 : eap->addr_count == 0 ? 0
8349 					       : (int)eap->line2 + 1) != FAIL)
8350 	{
8351 	    do_exedit(eap, old_curwin);
8352 
8353 	    /* set the alternate buffer for the window we came from */
8354 	    if (curwin != old_curwin
8355 		    && win_valid(old_curwin)
8356 		    && old_curwin->w_buffer != curbuf
8357 		    && !cmdmod.keepalt)
8358 		old_curwin->w_alt_fnum = curbuf->b_fnum;
8359 	}
8360     }
8361     else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
8362 				     *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
8363     {
8364 # ifdef FEAT_SCROLLBIND
8365 	/* Reset 'scrollbind' when editing another file, but keep it when
8366 	 * doing ":split" without arguments. */
8367 	if (*eap->arg != NUL
8368 #  ifdef FEAT_BROWSE
8369 		|| cmdmod.browse
8370 #  endif
8371 	   )
8372 	{
8373 	    RESET_BINDING(curwin);
8374 	}
8375 	else
8376 	    do_check_scrollbind(FALSE);
8377 # endif
8378 	do_exedit(eap, old_curwin);
8379     }
8380 
8381 # ifdef FEAT_BROWSE
8382     cmdmod.browse = browse_flag;
8383 # endif
8384 
8385 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
8386 theend:
8387     vim_free(fname);
8388 # endif
8389 }
8390 
8391 /*
8392  * Open a new tab page.
8393  */
8394     void
8395 tabpage_new(void)
8396 {
8397     exarg_T	ea;
8398 
8399     vim_memset(&ea, 0, sizeof(ea));
8400     ea.cmdidx = CMD_tabnew;
8401     ea.cmd = (char_u *)"tabn";
8402     ea.arg = (char_u *)"";
8403     ex_splitview(&ea);
8404 }
8405 
8406 /*
8407  * :tabnext command
8408  */
8409     static void
8410 ex_tabnext(exarg_T *eap)
8411 {
8412     int tab_number;
8413 
8414     switch (eap->cmdidx)
8415     {
8416 	case CMD_tabfirst:
8417 	case CMD_tabrewind:
8418 	    goto_tabpage(1);
8419 	    break;
8420 	case CMD_tablast:
8421 	    goto_tabpage(9999);
8422 	    break;
8423 	case CMD_tabprevious:
8424 	case CMD_tabNext:
8425 	    if (eap->arg && *eap->arg != NUL)
8426 	    {
8427 		char_u *p = eap->arg;
8428 		char_u *p_save = p;
8429 
8430 		tab_number = getdigits(&p);
8431 		if (p == p_save || *p_save == '-' || *p != NUL
8432 			    || tab_number == 0)
8433 		{
8434 		    /* No numbers as argument. */
8435 		    eap->errmsg = e_invarg;
8436 		    return;
8437 		}
8438 	    }
8439 	    else
8440 	    {
8441 		if (eap->addr_count == 0)
8442 		    tab_number = 1;
8443 		else
8444 		{
8445 		    tab_number = eap->line2;
8446 		    if (tab_number < 1)
8447 		    {
8448 			eap->errmsg = e_invrange;
8449 			return;
8450 		    }
8451 		}
8452 	    }
8453 	    goto_tabpage(-tab_number);
8454 	    break;
8455 	default: /* CMD_tabnext */
8456 	    tab_number = get_tabpage_arg(eap);
8457 	    if (eap->errmsg == NULL)
8458 		goto_tabpage(tab_number);
8459 	    break;
8460     }
8461 }
8462 
8463 /*
8464  * :tabmove command
8465  */
8466     static void
8467 ex_tabmove(exarg_T *eap)
8468 {
8469     int tab_number;
8470 
8471     tab_number = get_tabpage_arg(eap);
8472     if (eap->errmsg == NULL)
8473 	tabpage_move(tab_number);
8474 }
8475 
8476 /*
8477  * :tabs command: List tabs and their contents.
8478  */
8479     static void
8480 ex_tabs(exarg_T *eap UNUSED)
8481 {
8482     tabpage_T	*tp;
8483     win_T	*wp;
8484     int		tabcount = 1;
8485 
8486     msg_start();
8487     msg_scroll = TRUE;
8488     for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
8489     {
8490 	msg_putchar('\n');
8491 	vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
8492 	msg_outtrans_attr(IObuff, HL_ATTR(HLF_T));
8493 	out_flush();	    /* output one line at a time */
8494 	ui_breakcheck();
8495 
8496 	if (tp  == curtab)
8497 	    wp = firstwin;
8498 	else
8499 	    wp = tp->tp_firstwin;
8500 	for ( ; wp != NULL && !got_int; wp = wp->w_next)
8501 	{
8502 	    msg_putchar('\n');
8503 	    msg_putchar(wp == curwin ? '>' : ' ');
8504 	    msg_putchar(' ');
8505 	    msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
8506 	    msg_putchar(' ');
8507 	    if (buf_spname(wp->w_buffer) != NULL)
8508 		vim_strncpy(IObuff, buf_spname(wp->w_buffer), IOSIZE - 1);
8509 	    else
8510 		home_replace(wp->w_buffer, wp->w_buffer->b_fname,
8511 							IObuff, IOSIZE, TRUE);
8512 	    msg_outtrans(IObuff);
8513 	    out_flush();	    /* output one line at a time */
8514 	    ui_breakcheck();
8515 	}
8516     }
8517 }
8518 
8519 #endif /* FEAT_WINDOWS */
8520 
8521 /*
8522  * ":mode": Set screen mode.
8523  * If no argument given, just get the screen size and redraw.
8524  */
8525     static void
8526 ex_mode(exarg_T *eap)
8527 {
8528     if (*eap->arg == NUL)
8529 	shell_resized();
8530     else
8531 	mch_screenmode(eap->arg);
8532 }
8533 
8534 #ifdef FEAT_WINDOWS
8535 /*
8536  * ":resize".
8537  * set, increment or decrement current window height
8538  */
8539     static void
8540 ex_resize(exarg_T *eap)
8541 {
8542     int		n;
8543     win_T	*wp = curwin;
8544 
8545     if (eap->addr_count > 0)
8546     {
8547 	n = eap->line2;
8548 	for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
8549 	    ;
8550     }
8551 
8552 # ifdef FEAT_GUI
8553     need_mouse_correct = TRUE;
8554 # endif
8555     n = atol((char *)eap->arg);
8556     if (cmdmod.split & WSP_VERT)
8557     {
8558 	if (*eap->arg == '-' || *eap->arg == '+')
8559 	    n += W_WIDTH(curwin);
8560 	else if (n == 0 && eap->arg[0] == NUL)	/* default is very wide */
8561 	    n = 9999;
8562 	win_setwidth_win((int)n, wp);
8563     }
8564     else
8565     {
8566 	if (*eap->arg == '-' || *eap->arg == '+')
8567 	    n += curwin->w_height;
8568 	else if (n == 0 && eap->arg[0] == NUL)	/* default is very high */
8569 	    n = 9999;
8570 	win_setheight_win((int)n, wp);
8571     }
8572 }
8573 #endif
8574 
8575 /*
8576  * ":find [+command] <file>" command.
8577  */
8578     static void
8579 ex_find(exarg_T *eap)
8580 {
8581 #ifdef FEAT_SEARCHPATH
8582     char_u	*fname;
8583     int		count;
8584 
8585     fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
8586 						      TRUE, curbuf->b_ffname);
8587     if (eap->addr_count > 0)
8588     {
8589 	/* Repeat finding the file "count" times.  This matters when it
8590 	 * appears several times in the path. */
8591 	count = eap->line2;
8592 	while (fname != NULL && --count > 0)
8593 	{
8594 	    vim_free(fname);
8595 	    fname = find_file_in_path(NULL, 0, FNAME_MESS,
8596 						     FALSE, curbuf->b_ffname);
8597 	}
8598     }
8599 
8600     if (fname != NULL)
8601     {
8602 	eap->arg = fname;
8603 #endif
8604 	do_exedit(eap, NULL);
8605 #ifdef FEAT_SEARCHPATH
8606 	vim_free(fname);
8607     }
8608 #endif
8609 }
8610 
8611 /*
8612  * ":open" simulation: for now just work like ":visual".
8613  */
8614     static void
8615 ex_open(exarg_T *eap)
8616 {
8617     regmatch_T	regmatch;
8618     char_u	*p;
8619 
8620     curwin->w_cursor.lnum = eap->line2;
8621     beginline(BL_SOL | BL_FIX);
8622     if (*eap->arg == '/')
8623     {
8624 	/* ":open /pattern/": put cursor in column found with pattern */
8625 	++eap->arg;
8626 	p = skip_regexp(eap->arg, '/', p_magic, NULL);
8627 	*p = NUL;
8628 	regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
8629 	if (regmatch.regprog != NULL)
8630 	{
8631 	    regmatch.rm_ic = p_ic;
8632 	    p = ml_get_curline();
8633 	    if (vim_regexec(&regmatch, p, (colnr_T)0))
8634 		curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
8635 	    else
8636 		EMSG(_(e_nomatch));
8637 	    vim_regfree(regmatch.regprog);
8638 	}
8639 	/* Move to the NUL, ignore any other arguments. */
8640 	eap->arg += STRLEN(eap->arg);
8641     }
8642     check_cursor();
8643 
8644     eap->cmdidx = CMD_visual;
8645     do_exedit(eap, NULL);
8646 }
8647 
8648 /*
8649  * ":edit", ":badd", ":visual".
8650  */
8651     static void
8652 ex_edit(exarg_T *eap)
8653 {
8654     do_exedit(eap, NULL);
8655 }
8656 
8657 /*
8658  * ":edit <file>" command and alikes.
8659  */
8660     void
8661 do_exedit(
8662     exarg_T	*eap,
8663     win_T	*old_curwin)	    /* curwin before doing a split or NULL */
8664 {
8665     int		n;
8666 #ifdef FEAT_WINDOWS
8667     int		need_hide;
8668 #endif
8669     int		exmode_was = exmode_active;
8670 
8671     /*
8672      * ":vi" command ends Ex mode.
8673      */
8674     if (exmode_active && (eap->cmdidx == CMD_visual
8675 						|| eap->cmdidx == CMD_view))
8676     {
8677 	exmode_active = FALSE;
8678 	if (*eap->arg == NUL)
8679 	{
8680 	    /* Special case:  ":global/pat/visual\NLvi-commands" */
8681 	    if (global_busy)
8682 	    {
8683 		int	rd = RedrawingDisabled;
8684 		int	nwr = no_wait_return;
8685 		int	ms = msg_scroll;
8686 #ifdef FEAT_GUI
8687 		int	he = hold_gui_events;
8688 #endif
8689 
8690 		if (eap->nextcmd != NULL)
8691 		{
8692 		    stuffReadbuff(eap->nextcmd);
8693 		    eap->nextcmd = NULL;
8694 		}
8695 
8696 		if (exmode_was != EXMODE_VIM)
8697 		    settmode(TMODE_RAW);
8698 		RedrawingDisabled = 0;
8699 		no_wait_return = 0;
8700 		need_wait_return = FALSE;
8701 		msg_scroll = 0;
8702 #ifdef FEAT_GUI
8703 		hold_gui_events = 0;
8704 #endif
8705 		must_redraw = CLEAR;
8706 
8707 		main_loop(FALSE, TRUE);
8708 
8709 		RedrawingDisabled = rd;
8710 		no_wait_return = nwr;
8711 		msg_scroll = ms;
8712 #ifdef FEAT_GUI
8713 		hold_gui_events = he;
8714 #endif
8715 	    }
8716 	    return;
8717 	}
8718     }
8719 
8720     if ((eap->cmdidx == CMD_new
8721 		|| eap->cmdidx == CMD_tabnew
8722 		|| eap->cmdidx == CMD_tabedit
8723 #ifdef FEAT_WINDOWS
8724 		|| eap->cmdidx == CMD_vnew
8725 #endif
8726 		) && *eap->arg == NUL)
8727     {
8728 	/* ":new" or ":tabnew" without argument: edit an new empty buffer */
8729 	setpcmark();
8730 	(void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
8731 		      ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
8732 		      old_curwin == NULL ? curwin : NULL);
8733     }
8734     else if ((eap->cmdidx != CMD_split
8735 #ifdef FEAT_WINDOWS
8736 		&& eap->cmdidx != CMD_vsplit
8737 #endif
8738 		)
8739 	    || *eap->arg != NUL
8740 #ifdef FEAT_BROWSE
8741 	    || cmdmod.browse
8742 #endif
8743 	    )
8744     {
8745 #ifdef FEAT_AUTOCMD
8746 	/* Can't edit another file when "curbuf_lock" is set.  Only ":edit"
8747 	 * can bring us here, others are stopped earlier. */
8748 	if (*eap->arg != NUL && curbuf_locked())
8749 	    return;
8750 #endif
8751 	n = readonlymode;
8752 	if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
8753 	    readonlymode = TRUE;
8754 	else if (eap->cmdidx == CMD_enew)
8755 	    readonlymode = FALSE;   /* 'readonly' doesn't make sense in an
8756 				       empty buffer */
8757 	setpcmark();
8758 	if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
8759 		    NULL, eap,
8760 		    /* ":edit" goes to first line if Vi compatible */
8761 		    (*eap->arg == NUL && eap->do_ecmd_lnum == 0
8762 				      && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
8763 					       ? ECMD_ONE : eap->do_ecmd_lnum,
8764 		    (buf_hide(curbuf) ? ECMD_HIDE : 0)
8765 		    + (eap->forceit ? ECMD_FORCEIT : 0)
8766 		      /* after a split we can use an existing buffer */
8767 		    + (old_curwin != NULL ? ECMD_OLDBUF : 0)
8768 #ifdef FEAT_LISTCMDS
8769 		    + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
8770 #endif
8771 		    , old_curwin == NULL ? curwin : NULL) == FAIL)
8772 	{
8773 	    /* Editing the file failed.  If the window was split, close it. */
8774 #ifdef FEAT_WINDOWS
8775 	    if (old_curwin != NULL)
8776 	    {
8777 		need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
8778 		if (!need_hide || buf_hide(curbuf))
8779 		{
8780 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
8781 		    cleanup_T   cs;
8782 
8783 		    /* Reset the error/interrupt/exception state here so that
8784 		     * aborting() returns FALSE when closing a window. */
8785 		    enter_cleanup(&cs);
8786 # endif
8787 # ifdef FEAT_GUI
8788 		    need_mouse_correct = TRUE;
8789 # endif
8790 		    win_close(curwin, !need_hide && !buf_hide(curbuf));
8791 
8792 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
8793 		    /* Restore the error/interrupt/exception state if not
8794 		     * discarded by a new aborting error, interrupt, or
8795 		     * uncaught exception. */
8796 		    leave_cleanup(&cs);
8797 # endif
8798 		}
8799 	    }
8800 #endif
8801 	}
8802 	else if (readonlymode && curbuf->b_nwindows == 1)
8803 	{
8804 	    /* When editing an already visited buffer, 'readonly' won't be set
8805 	     * but the previous value is kept.  With ":view" and ":sview" we
8806 	     * want the  file to be readonly, except when another window is
8807 	     * editing the same buffer. */
8808 	    curbuf->b_p_ro = TRUE;
8809 	}
8810 	readonlymode = n;
8811     }
8812     else
8813     {
8814 	if (eap->do_ecmd_cmd != NULL)
8815 	    do_cmdline_cmd(eap->do_ecmd_cmd);
8816 #ifdef FEAT_TITLE
8817 	n = curwin->w_arg_idx_invalid;
8818 #endif
8819 	check_arg_idx(curwin);
8820 #ifdef FEAT_TITLE
8821 	if (n != curwin->w_arg_idx_invalid)
8822 	    maketitle();
8823 #endif
8824     }
8825 
8826 #ifdef FEAT_WINDOWS
8827     /*
8828      * if ":split file" worked, set alternate file name in old window to new
8829      * file
8830      */
8831     if (old_curwin != NULL
8832 	    && *eap->arg != NUL
8833 	    && curwin != old_curwin
8834 	    && win_valid(old_curwin)
8835 	    && old_curwin->w_buffer != curbuf
8836 	    && !cmdmod.keepalt)
8837 	old_curwin->w_alt_fnum = curbuf->b_fnum;
8838 #endif
8839 
8840     ex_no_reprint = TRUE;
8841 }
8842 
8843 #ifndef FEAT_GUI
8844 /*
8845  * ":gui" and ":gvim" when there is no GUI.
8846  */
8847     static void
8848 ex_nogui(exarg_T *eap)
8849 {
8850     eap->errmsg = e_nogvim;
8851 }
8852 #endif
8853 
8854 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
8855     static void
8856 ex_tearoff(exarg_T *eap)
8857 {
8858     gui_make_tearoff(eap->arg);
8859 }
8860 #endif
8861 
8862 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
8863     static void
8864 ex_popup(exarg_T *eap)
8865 {
8866     gui_make_popup(eap->arg, eap->forceit);
8867 }
8868 #endif
8869 
8870     static void
8871 ex_swapname(exarg_T *eap UNUSED)
8872 {
8873     if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
8874 	MSG(_("No swap file"));
8875     else
8876 	msg(curbuf->b_ml.ml_mfp->mf_fname);
8877 }
8878 
8879 /*
8880  * ":syncbind" forces all 'scrollbind' windows to have the same relative
8881  * offset.
8882  * (1998-11-02 16:21:01  R. Edward Ralston <[email protected]>)
8883  */
8884     static void
8885 ex_syncbind(exarg_T *eap UNUSED)
8886 {
8887 #ifdef FEAT_SCROLLBIND
8888     win_T	*wp;
8889     win_T	*save_curwin = curwin;
8890     buf_T	*save_curbuf = curbuf;
8891     long	topline;
8892     long	y;
8893     linenr_T	old_linenr = curwin->w_cursor.lnum;
8894 
8895     setpcmark();
8896 
8897     /*
8898      * determine max topline
8899      */
8900     if (curwin->w_p_scb)
8901     {
8902 	topline = curwin->w_topline;
8903 	FOR_ALL_WINDOWS(wp)
8904 	{
8905 	    if (wp->w_p_scb && wp->w_buffer)
8906 	    {
8907 		y = wp->w_buffer->b_ml.ml_line_count - p_so;
8908 		if (topline > y)
8909 		    topline = y;
8910 	    }
8911 	}
8912 	if (topline < 1)
8913 	    topline = 1;
8914     }
8915     else
8916     {
8917 	topline = 1;
8918     }
8919 
8920 
8921     /*
8922      * Set all scrollbind windows to the same topline.
8923      */
8924     FOR_ALL_WINDOWS(curwin)
8925     {
8926 	if (curwin->w_p_scb)
8927 	{
8928 	    curbuf = curwin->w_buffer;
8929 	    y = topline - curwin->w_topline;
8930 	    if (y > 0)
8931 		scrollup(y, TRUE);
8932 	    else
8933 		scrolldown(-y, TRUE);
8934 	    curwin->w_scbind_pos = topline;
8935 	    redraw_later(VALID);
8936 	    cursor_correct();
8937 #ifdef FEAT_WINDOWS
8938 	    curwin->w_redr_status = TRUE;
8939 #endif
8940 	}
8941     }
8942     curwin = save_curwin;
8943     curbuf = save_curbuf;
8944     if (curwin->w_p_scb)
8945     {
8946 	did_syncbind = TRUE;
8947 	checkpcmark();
8948 	if (old_linenr != curwin->w_cursor.lnum)
8949 	{
8950 	    char_u ctrl_o[2];
8951 
8952 	    ctrl_o[0] = Ctrl_O;
8953 	    ctrl_o[1] = 0;
8954 	    ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
8955 	}
8956     }
8957 #endif
8958 }
8959 
8960 
8961     static void
8962 ex_read(exarg_T *eap)
8963 {
8964     int		i;
8965     int		empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
8966     linenr_T	lnum;
8967 
8968     if (eap->usefilter)			/* :r!cmd */
8969 	do_bang(1, eap, FALSE, FALSE, TRUE);
8970     else
8971     {
8972 	if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
8973 	    return;
8974 
8975 #ifdef FEAT_BROWSE
8976 	if (cmdmod.browse)
8977 	{
8978 	    char_u *browseFile;
8979 
8980 	    browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
8981 						    NULL, NULL, NULL, curbuf);
8982 	    if (browseFile != NULL)
8983 	    {
8984 		i = readfile(browseFile, NULL,
8985 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
8986 		vim_free(browseFile);
8987 	    }
8988 	    else
8989 		i = OK;
8990 	}
8991 	else
8992 #endif
8993 	     if (*eap->arg == NUL)
8994 	{
8995 	    if (check_fname() == FAIL)	/* check for no file name */
8996 		return;
8997 	    i = readfile(curbuf->b_ffname, curbuf->b_fname,
8998 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
8999 	}
9000 	else
9001 	{
9002 	    if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
9003 		(void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
9004 	    i = readfile(eap->arg, NULL,
9005 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
9006 
9007 	}
9008 	if (i != OK)
9009 	{
9010 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
9011 	    if (!aborting())
9012 #endif
9013 		EMSG2(_(e_notopen), eap->arg);
9014 	}
9015 	else
9016 	{
9017 	    if (empty && exmode_active)
9018 	    {
9019 		/* Delete the empty line that remains.  Historically ex does
9020 		 * this but vi doesn't. */
9021 		if (eap->line2 == 0)
9022 		    lnum = curbuf->b_ml.ml_line_count;
9023 		else
9024 		    lnum = 1;
9025 		if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
9026 		{
9027 		    ml_delete(lnum, FALSE);
9028 		    if (curwin->w_cursor.lnum > 1
9029 					     && curwin->w_cursor.lnum >= lnum)
9030 			--curwin->w_cursor.lnum;
9031 		    deleted_lines_mark(lnum, 1L);
9032 		}
9033 	    }
9034 	    redraw_curbuf_later(VALID);
9035 	}
9036     }
9037 }
9038 
9039 static char_u	*prev_dir = NULL;
9040 
9041 #if defined(EXITFREE) || defined(PROTO)
9042     void
9043 free_cd_dir(void)
9044 {
9045     vim_free(prev_dir);
9046     prev_dir = NULL;
9047 
9048     vim_free(globaldir);
9049     globaldir = NULL;
9050 }
9051 #endif
9052 
9053 /*
9054  * Deal with the side effects of changing the current directory.
9055  * When "local" is TRUE then this was after an ":lcd" command.
9056  */
9057     void
9058 post_chdir(int local)
9059 {
9060     vim_free(curwin->w_localdir);
9061     curwin->w_localdir = NULL;
9062     if (local)
9063     {
9064 	/* If still in global directory, need to remember current
9065 	 * directory as global directory. */
9066 	if (globaldir == NULL && prev_dir != NULL)
9067 	    globaldir = vim_strsave(prev_dir);
9068 	/* Remember this local directory for the window. */
9069 	if (mch_dirname(NameBuff, MAXPATHL) == OK)
9070 	    curwin->w_localdir = vim_strsave(NameBuff);
9071     }
9072     else
9073     {
9074 	/* We are now in the global directory, no need to remember its
9075 	 * name. */
9076 	vim_free(globaldir);
9077 	globaldir = NULL;
9078     }
9079 
9080     shorten_fnames(TRUE);
9081 }
9082 
9083 
9084 /*
9085  * ":cd", ":lcd", ":chdir" and ":lchdir".
9086  */
9087     void
9088 ex_cd(exarg_T *eap)
9089 {
9090     char_u		*new_dir;
9091     char_u		*tofree;
9092 
9093     new_dir = eap->arg;
9094 #if !defined(UNIX) && !defined(VMS)
9095     /* for non-UNIX ":cd" means: print current directory */
9096     if (*new_dir == NUL)
9097 	ex_pwd(NULL);
9098     else
9099 #endif
9100     {
9101 #ifdef FEAT_AUTOCMD
9102 	if (allbuf_locked())
9103 	    return;
9104 #endif
9105 	if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
9106 							     && !eap->forceit)
9107 	{
9108 	    EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
9109 	    return;
9110 	}
9111 
9112 	/* ":cd -": Change to previous directory */
9113 	if (STRCMP(new_dir, "-") == 0)
9114 	{
9115 	    if (prev_dir == NULL)
9116 	    {
9117 		EMSG(_("E186: No previous directory"));
9118 		return;
9119 	    }
9120 	    new_dir = prev_dir;
9121 	}
9122 
9123 	/* Save current directory for next ":cd -" */
9124 	tofree = prev_dir;
9125 	if (mch_dirname(NameBuff, MAXPATHL) == OK)
9126 	    prev_dir = vim_strsave(NameBuff);
9127 	else
9128 	    prev_dir = NULL;
9129 
9130 #if defined(UNIX) || defined(VMS)
9131 	/* for UNIX ":cd" means: go to home directory */
9132 	if (*new_dir == NUL)
9133 	{
9134 	    /* use NameBuff for home directory name */
9135 # ifdef VMS
9136 	    char_u	*p;
9137 
9138 	    p = mch_getenv((char_u *)"SYS$LOGIN");
9139 	    if (p == NULL || *p == NUL)	/* empty is the same as not set */
9140 		NameBuff[0] = NUL;
9141 	    else
9142 		vim_strncpy(NameBuff, p, MAXPATHL - 1);
9143 # else
9144 	    expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
9145 # endif
9146 	    new_dir = NameBuff;
9147 	}
9148 #endif
9149 	if (new_dir == NULL || vim_chdir(new_dir))
9150 	    EMSG(_(e_failed));
9151 	else
9152 	{
9153 	    post_chdir(eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir);
9154 
9155 	    /* Echo the new current directory if the command was typed. */
9156 	    if (KeyTyped || p_verbose >= 5)
9157 		ex_pwd(eap);
9158 	}
9159 	vim_free(tofree);
9160     }
9161 }
9162 
9163 /*
9164  * ":pwd".
9165  */
9166     static void
9167 ex_pwd(exarg_T *eap UNUSED)
9168 {
9169     if (mch_dirname(NameBuff, MAXPATHL) == OK)
9170     {
9171 #ifdef BACKSLASH_IN_FILENAME
9172 	slash_adjust(NameBuff);
9173 #endif
9174 	msg(NameBuff);
9175     }
9176     else
9177 	EMSG(_("E187: Unknown"));
9178 }
9179 
9180 /*
9181  * ":=".
9182  */
9183     static void
9184 ex_equal(exarg_T *eap)
9185 {
9186     smsg((char_u *)"%ld", (long)eap->line2);
9187     ex_may_print(eap);
9188 }
9189 
9190     static void
9191 ex_sleep(exarg_T *eap)
9192 {
9193     int		n;
9194     long	len;
9195 
9196     if (cursor_valid())
9197     {
9198 	n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
9199 	if (n >= 0)
9200 	    windgoto((int)n, W_WINCOL(curwin) + curwin->w_wcol);
9201     }
9202 
9203     len = eap->line2;
9204     switch (*eap->arg)
9205     {
9206 	case 'm': break;
9207 	case NUL: len *= 1000L; break;
9208 	default: EMSG2(_(e_invarg2), eap->arg); return;
9209     }
9210     do_sleep(len);
9211 }
9212 
9213 /*
9214  * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
9215  */
9216     void
9217 do_sleep(long msec)
9218 {
9219     long	done;
9220     long	wait_now;
9221 
9222     cursor_on();
9223     out_flush();
9224     for (done = 0; !got_int && done < msec; done += wait_now)
9225     {
9226 	wait_now = msec - done > 1000L ? 1000L : msec - done;
9227 #ifdef FEAT_TIMERS
9228 	{
9229 	    long    due_time = check_due_timer();
9230 
9231 	    if (due_time > 0 && due_time < wait_now)
9232 		wait_now = due_time;
9233 	}
9234 #endif
9235 #ifdef FEAT_JOB_CHANNEL
9236 	if (has_any_channel() && wait_now > 100L)
9237 	    wait_now = 100L;
9238 #endif
9239 	ui_delay(wait_now, TRUE);
9240 #ifdef FEAT_JOB_CHANNEL
9241 	if (has_any_channel())
9242 	    ui_breakcheck_force(TRUE);
9243 	else
9244 #endif
9245 	    ui_breakcheck();
9246 #ifdef MESSAGE_QUEUE
9247 	/* Process the netbeans and clientserver messages that may have been
9248 	 * received in the call to ui_breakcheck() when the GUI is in use. This
9249 	 * may occur when running a test case. */
9250 	parse_queued_messages();
9251 #endif
9252     }
9253 }
9254 
9255     static void
9256 do_exmap(exarg_T *eap, int isabbrev)
9257 {
9258     int	    mode;
9259     char_u  *cmdp;
9260 
9261     cmdp = eap->cmd;
9262     mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
9263 
9264     switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
9265 						    eap->arg, mode, isabbrev))
9266     {
9267 	case 1: EMSG(_(e_invarg));
9268 		break;
9269 	case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
9270 		break;
9271     }
9272 }
9273 
9274 /*
9275  * ":winsize" command (obsolete).
9276  */
9277     static void
9278 ex_winsize(exarg_T *eap)
9279 {
9280     int		w, h;
9281     char_u	*arg = eap->arg;
9282     char_u	*p;
9283 
9284     w = getdigits(&arg);
9285     arg = skipwhite(arg);
9286     p = arg;
9287     h = getdigits(&arg);
9288     if (*p != NUL && *arg == NUL)
9289 	set_shellsize(w, h, TRUE);
9290     else
9291 	EMSG(_("E465: :winsize requires two number arguments"));
9292 }
9293 
9294 #ifdef FEAT_WINDOWS
9295     static void
9296 ex_wincmd(exarg_T *eap)
9297 {
9298     int		xchar = NUL;
9299     char_u	*p;
9300 
9301     if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
9302     {
9303 	/* CTRL-W g and CTRL-W CTRL-G  have an extra command character */
9304 	if (eap->arg[1] == NUL)
9305 	{
9306 	    EMSG(_(e_invarg));
9307 	    return;
9308 	}
9309 	xchar = eap->arg[1];
9310 	p = eap->arg + 2;
9311     }
9312     else
9313 	p = eap->arg + 1;
9314 
9315     eap->nextcmd = check_nextcmd(p);
9316     p = skipwhite(p);
9317     if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
9318 	EMSG(_(e_invarg));
9319     else if (!eap->skip)
9320     {
9321 	/* Pass flags on for ":vertical wincmd ]". */
9322 	postponed_split_flags = cmdmod.split;
9323 	postponed_split_tab = cmdmod.tab;
9324 	do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
9325 	postponed_split_flags = 0;
9326 	postponed_split_tab = 0;
9327     }
9328 }
9329 #endif
9330 
9331 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
9332 /*
9333  * ":winpos".
9334  */
9335     static void
9336 ex_winpos(exarg_T *eap)
9337 {
9338     int		x, y;
9339     char_u	*arg = eap->arg;
9340     char_u	*p;
9341 
9342     if (*arg == NUL)
9343     {
9344 # if defined(FEAT_GUI) || defined(MSWIN)
9345 #  ifdef FEAT_GUI
9346 	if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
9347 #  else
9348 	if (mch_get_winpos(&x, &y) != FAIL)
9349 #  endif
9350 	{
9351 	    sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
9352 	    msg(IObuff);
9353 	}
9354 	else
9355 # endif
9356 	    EMSG(_("E188: Obtaining window position not implemented for this platform"));
9357     }
9358     else
9359     {
9360 	x = getdigits(&arg);
9361 	arg = skipwhite(arg);
9362 	p = arg;
9363 	y = getdigits(&arg);
9364 	if (*p == NUL || *arg != NUL)
9365 	{
9366 	    EMSG(_("E466: :winpos requires two number arguments"));
9367 	    return;
9368 	}
9369 # ifdef FEAT_GUI
9370 	if (gui.in_use)
9371 	    gui_mch_set_winpos(x, y);
9372 	else if (gui.starting)
9373 	{
9374 	    /* Remember the coordinates for when the window is opened. */
9375 	    gui_win_x = x;
9376 	    gui_win_y = y;
9377 	}
9378 #  ifdef HAVE_TGETENT
9379 	else
9380 #  endif
9381 # else
9382 #  ifdef MSWIN
9383 	    mch_set_winpos(x, y);
9384 #  endif
9385 # endif
9386 # ifdef HAVE_TGETENT
9387 	if (*T_CWP)
9388 	    term_set_winpos(x, y);
9389 # endif
9390     }
9391 }
9392 #endif
9393 
9394 /*
9395  * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
9396  */
9397     static void
9398 ex_operators(exarg_T *eap)
9399 {
9400     oparg_T	oa;
9401 
9402     clear_oparg(&oa);
9403     oa.regname = eap->regname;
9404     oa.start.lnum = eap->line1;
9405     oa.end.lnum = eap->line2;
9406     oa.line_count = eap->line2 - eap->line1 + 1;
9407     oa.motion_type = MLINE;
9408 #ifdef FEAT_VIRTUALEDIT
9409     virtual_op = FALSE;
9410 #endif
9411     if (eap->cmdidx != CMD_yank)	/* position cursor for undo */
9412     {
9413 	setpcmark();
9414 	curwin->w_cursor.lnum = eap->line1;
9415 	beginline(BL_SOL | BL_FIX);
9416     }
9417 
9418     if (VIsual_active)
9419 	end_visual_mode();
9420 
9421     switch (eap->cmdidx)
9422     {
9423 	case CMD_delete:
9424 	    oa.op_type = OP_DELETE;
9425 	    op_delete(&oa);
9426 	    break;
9427 
9428 	case CMD_yank:
9429 	    oa.op_type = OP_YANK;
9430 	    (void)op_yank(&oa, FALSE, TRUE);
9431 	    break;
9432 
9433 	default:    /* CMD_rshift or CMD_lshift */
9434 	    if (
9435 #ifdef FEAT_RIGHTLEFT
9436 		(eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl
9437 #else
9438 		eap->cmdidx == CMD_rshift
9439 #endif
9440 						)
9441 		oa.op_type = OP_RSHIFT;
9442 	    else
9443 		oa.op_type = OP_LSHIFT;
9444 	    op_shift(&oa, FALSE, eap->amount);
9445 	    break;
9446     }
9447 #ifdef FEAT_VIRTUALEDIT
9448     virtual_op = MAYBE;
9449 #endif
9450     ex_may_print(eap);
9451 }
9452 
9453 /*
9454  * ":put".
9455  */
9456     static void
9457 ex_put(exarg_T *eap)
9458 {
9459     /* ":0put" works like ":1put!". */
9460     if (eap->line2 == 0)
9461     {
9462 	eap->line2 = 1;
9463 	eap->forceit = TRUE;
9464     }
9465     curwin->w_cursor.lnum = eap->line2;
9466     do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
9467 						       PUT_LINE|PUT_CURSLINE);
9468 }
9469 
9470 /*
9471  * Handle ":copy" and ":move".
9472  */
9473     static void
9474 ex_copymove(exarg_T *eap)
9475 {
9476     long	n;
9477 
9478     n = get_address(eap, &eap->arg, eap->addr_type, FALSE, FALSE, 1);
9479     if (eap->arg == NULL)	    /* error detected */
9480     {
9481 	eap->nextcmd = NULL;
9482 	return;
9483     }
9484     get_flags(eap);
9485 
9486     /*
9487      * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
9488      */
9489     if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
9490     {
9491 	EMSG(_(e_invaddr));
9492 	return;
9493     }
9494 
9495     if (eap->cmdidx == CMD_move)
9496     {
9497 	if (do_move(eap->line1, eap->line2, n) == FAIL)
9498 	    return;
9499     }
9500     else
9501 	ex_copy(eap->line1, eap->line2, n);
9502     u_clearline();
9503     beginline(BL_SOL | BL_FIX);
9504     ex_may_print(eap);
9505 }
9506 
9507 /*
9508  * Print the current line if flags were given to the Ex command.
9509  */
9510     void
9511 ex_may_print(exarg_T *eap)
9512 {
9513     if (eap->flags != 0)
9514     {
9515 	print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
9516 						  (eap->flags & EXFLAG_LIST));
9517 	ex_no_reprint = TRUE;
9518     }
9519 }
9520 
9521 /*
9522  * ":smagic" and ":snomagic".
9523  */
9524     static void
9525 ex_submagic(exarg_T *eap)
9526 {
9527     int		magic_save = p_magic;
9528 
9529     p_magic = (eap->cmdidx == CMD_smagic);
9530     do_sub(eap);
9531     p_magic = magic_save;
9532 }
9533 
9534 /*
9535  * ":join".
9536  */
9537     static void
9538 ex_join(exarg_T *eap)
9539 {
9540     curwin->w_cursor.lnum = eap->line1;
9541     if (eap->line1 == eap->line2)
9542     {
9543 	if (eap->addr_count >= 2)   /* :2,2join does nothing */
9544 	    return;
9545 	if (eap->line2 == curbuf->b_ml.ml_line_count)
9546 	{
9547 	    beep_flush();
9548 	    return;
9549 	}
9550 	++eap->line2;
9551     }
9552     (void)do_join(eap->line2 - eap->line1 + 1, !eap->forceit, TRUE, TRUE, TRUE);
9553     beginline(BL_WHITE | BL_FIX);
9554     ex_may_print(eap);
9555 }
9556 
9557 /*
9558  * ":[addr]@r" or ":[addr]*r": execute register
9559  */
9560     static void
9561 ex_at(exarg_T *eap)
9562 {
9563     int		c;
9564     int		prev_len = typebuf.tb_len;
9565 
9566     curwin->w_cursor.lnum = eap->line2;
9567     check_cursor_col();
9568 
9569 #ifdef USE_ON_FLY_SCROLL
9570     dont_scroll = TRUE;		/* disallow scrolling here */
9571 #endif
9572 
9573     /* get the register name.  No name means to use the previous one */
9574     c = *eap->arg;
9575     if (c == NUL || (c == '*' && *eap->cmd == '*'))
9576 	c = '@';
9577     /* Put the register in the typeahead buffer with the "silent" flag. */
9578     if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
9579 								      == FAIL)
9580     {
9581 	beep_flush();
9582     }
9583     else
9584     {
9585 	int	save_efr = exec_from_reg;
9586 
9587 	exec_from_reg = TRUE;
9588 
9589 	/*
9590 	 * Execute from the typeahead buffer.
9591 	 * Continue until the stuff buffer is empty and all added characters
9592 	 * have been consumed.
9593 	 */
9594 	while (!stuff_empty() || typebuf.tb_len > prev_len)
9595 	    (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
9596 
9597 	exec_from_reg = save_efr;
9598     }
9599 }
9600 
9601 /*
9602  * ":!".
9603  */
9604     static void
9605 ex_bang(exarg_T *eap)
9606 {
9607     do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
9608 }
9609 
9610 /*
9611  * ":undo".
9612  */
9613     static void
9614 ex_undo(exarg_T *eap)
9615 {
9616     if (eap->addr_count == 1)	    /* :undo 123 */
9617 	undo_time(eap->line2, FALSE, FALSE, TRUE);
9618     else
9619 	u_undo(1);
9620 }
9621 
9622 #ifdef FEAT_PERSISTENT_UNDO
9623     static void
9624 ex_wundo(exarg_T *eap)
9625 {
9626     char_u hash[UNDO_HASH_SIZE];
9627 
9628     u_compute_hash(hash);
9629     u_write_undo(eap->arg, eap->forceit, curbuf, hash);
9630 }
9631 
9632     static void
9633 ex_rundo(exarg_T *eap)
9634 {
9635     char_u hash[UNDO_HASH_SIZE];
9636 
9637     u_compute_hash(hash);
9638     u_read_undo(eap->arg, hash, NULL);
9639 }
9640 #endif
9641 
9642 /*
9643  * ":redo".
9644  */
9645     static void
9646 ex_redo(exarg_T *eap UNUSED)
9647 {
9648     u_redo(1);
9649 }
9650 
9651 /*
9652  * ":earlier" and ":later".
9653  */
9654     static void
9655 ex_later(exarg_T *eap)
9656 {
9657     long	count = 0;
9658     int		sec = FALSE;
9659     int		file = FALSE;
9660     char_u	*p = eap->arg;
9661 
9662     if (*p == NUL)
9663 	count = 1;
9664     else if (isdigit(*p))
9665     {
9666 	count = getdigits(&p);
9667 	switch (*p)
9668 	{
9669 	    case 's': ++p; sec = TRUE; break;
9670 	    case 'm': ++p; sec = TRUE; count *= 60; break;
9671 	    case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
9672 	    case 'd': ++p; sec = TRUE; count *= 24 * 60 * 60; break;
9673 	    case 'f': ++p; file = TRUE; break;
9674 	}
9675     }
9676 
9677     if (*p != NUL)
9678 	EMSG2(_(e_invarg2), eap->arg);
9679     else
9680 	undo_time(eap->cmdidx == CMD_earlier ? -count : count,
9681 							    sec, file, FALSE);
9682 }
9683 
9684 /*
9685  * ":redir": start/stop redirection.
9686  */
9687     static void
9688 ex_redir(exarg_T *eap)
9689 {
9690     char	*mode;
9691     char_u	*fname;
9692     char_u	*arg = eap->arg;
9693 
9694 #ifdef FEAT_EVAL
9695     if (redir_execute)
9696     {
9697 	EMSG(_("E930: Cannot use :redir inside execute()"));
9698 	return;
9699     }
9700 #endif
9701 
9702     if (STRICMP(eap->arg, "END") == 0)
9703 	close_redir();
9704     else
9705     {
9706 	if (*arg == '>')
9707 	{
9708 	    ++arg;
9709 	    if (*arg == '>')
9710 	    {
9711 		++arg;
9712 		mode = "a";
9713 	    }
9714 	    else
9715 		mode = "w";
9716 	    arg = skipwhite(arg);
9717 
9718 	    close_redir();
9719 
9720 	    /* Expand environment variables and "~/". */
9721 	    fname = expand_env_save(arg);
9722 	    if (fname == NULL)
9723 		return;
9724 #ifdef FEAT_BROWSE
9725 	    if (cmdmod.browse)
9726 	    {
9727 		char_u	*browseFile;
9728 
9729 		browseFile = do_browse(BROWSE_SAVE,
9730 			(char_u *)_("Save Redirection"),
9731 			fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
9732 		if (browseFile == NULL)
9733 		    return;		/* operation cancelled */
9734 		vim_free(fname);
9735 		fname = browseFile;
9736 		eap->forceit = TRUE;	/* since dialog already asked */
9737 	    }
9738 #endif
9739 
9740 	    redir_fd = open_exfile(fname, eap->forceit, mode);
9741 	    vim_free(fname);
9742 	}
9743 #ifdef FEAT_EVAL
9744 	else if (*arg == '@')
9745 	{
9746 	    /* redirect to a register a-z (resp. A-Z for appending) */
9747 	    close_redir();
9748 	    ++arg;
9749 	    if (ASCII_ISALPHA(*arg)
9750 # ifdef FEAT_CLIPBOARD
9751 		    || *arg == '*'
9752 		    || *arg == '+'
9753 # endif
9754 		    || *arg == '"')
9755 	    {
9756 		redir_reg = *arg++;
9757 		if (*arg == '>' && arg[1] == '>')  /* append */
9758 		    arg += 2;
9759 		else
9760 		{
9761 		    /* Can use both "@a" and "@a>". */
9762 		    if (*arg == '>')
9763 			arg++;
9764 		    /* Make register empty when not using @A-@Z and the
9765 		     * command is valid. */
9766 		    if (*arg == NUL && !isupper(redir_reg))
9767 			write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
9768 		}
9769 	    }
9770 	    if (*arg != NUL)
9771 	    {
9772 		redir_reg = 0;
9773 		EMSG2(_(e_invarg2), eap->arg);
9774 	    }
9775 	}
9776 	else if (*arg == '=' && arg[1] == '>')
9777 	{
9778 	    int append;
9779 
9780 	    /* redirect to a variable */
9781 	    close_redir();
9782 	    arg += 2;
9783 
9784 	    if (*arg == '>')
9785 	    {
9786 		++arg;
9787 		append = TRUE;
9788 	    }
9789 	    else
9790 		append = FALSE;
9791 
9792 	    if (var_redir_start(skipwhite(arg), append) == OK)
9793 		redir_vname = 1;
9794 	}
9795 #endif
9796 
9797 	/* TODO: redirect to a buffer */
9798 
9799 	else
9800 	    EMSG2(_(e_invarg2), eap->arg);
9801     }
9802 
9803     /* Make sure redirection is not off.  Can happen for cmdline completion
9804      * that indirectly invokes a command to catch its output. */
9805     if (redir_fd != NULL
9806 #ifdef FEAT_EVAL
9807 			  || redir_reg || redir_vname
9808 #endif
9809 							)
9810 	redir_off = FALSE;
9811 }
9812 
9813 /*
9814  * ":redraw": force redraw
9815  */
9816     void
9817 ex_redraw(exarg_T *eap)
9818 {
9819     int		r = RedrawingDisabled;
9820     int		p = p_lz;
9821 
9822     RedrawingDisabled = 0;
9823     p_lz = FALSE;
9824     validate_cursor();
9825     update_topline();
9826     update_screen(eap->forceit ? CLEAR : VIsual_active ? INVERTED : 0);
9827 #ifdef FEAT_TITLE
9828     if (need_maketitle)
9829 	maketitle();
9830 #endif
9831     RedrawingDisabled = r;
9832     p_lz = p;
9833 
9834     /* Reset msg_didout, so that a message that's there is overwritten. */
9835     msg_didout = FALSE;
9836     msg_col = 0;
9837 
9838     /* No need to wait after an intentional redraw. */
9839     need_wait_return = FALSE;
9840 
9841     out_flush();
9842 }
9843 
9844 /*
9845  * ":redrawstatus": force redraw of status line(s)
9846  */
9847     static void
9848 ex_redrawstatus(exarg_T *eap UNUSED)
9849 {
9850 #if defined(FEAT_WINDOWS)
9851     int		r = RedrawingDisabled;
9852     int		p = p_lz;
9853 
9854     RedrawingDisabled = 0;
9855     p_lz = FALSE;
9856     if (eap->forceit)
9857 	status_redraw_all();
9858     else
9859 	status_redraw_curbuf();
9860     update_screen(VIsual_active ? INVERTED : 0);
9861     RedrawingDisabled = r;
9862     p_lz = p;
9863     out_flush();
9864 #endif
9865 }
9866 
9867     static void
9868 close_redir(void)
9869 {
9870     if (redir_fd != NULL)
9871     {
9872 	fclose(redir_fd);
9873 	redir_fd = NULL;
9874     }
9875 #ifdef FEAT_EVAL
9876     redir_reg = 0;
9877     if (redir_vname)
9878     {
9879 	var_redir_stop();
9880 	redir_vname = 0;
9881     }
9882 #endif
9883 }
9884 
9885 #if defined(FEAT_SESSION) && defined(USE_CRNL)
9886 # define MKSESSION_NL
9887 static int mksession_nl = FALSE;    /* use NL only in put_eol() */
9888 #endif
9889 
9890 /*
9891  * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
9892  */
9893     static void
9894 ex_mkrc(
9895     exarg_T	*eap)
9896 {
9897     FILE	*fd;
9898     int		failed = FALSE;
9899     char_u	*fname;
9900 #ifdef FEAT_BROWSE
9901     char_u	*browseFile = NULL;
9902 #endif
9903 #ifdef FEAT_SESSION
9904     int		view_session = FALSE;
9905     int		using_vdir = FALSE;	/* using 'viewdir'? */
9906     char_u	*viewFile = NULL;
9907     unsigned	*flagp;
9908 #endif
9909 
9910     if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
9911     {
9912 #ifdef FEAT_SESSION
9913 	view_session = TRUE;
9914 #else
9915 	ex_ni(eap);
9916 	return;
9917 #endif
9918     }
9919 
9920 #ifdef FEAT_SESSION
9921     /* Use the short file name until ":lcd" is used.  We also don't use the
9922      * short file name when 'acd' is set, that is checked later. */
9923     did_lcd = FALSE;
9924 
9925     /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
9926     if (eap->cmdidx == CMD_mkview
9927 	    && (*eap->arg == NUL
9928 		|| (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
9929     {
9930 	eap->forceit = TRUE;
9931 	fname = get_view_file(*eap->arg);
9932 	if (fname == NULL)
9933 	    return;
9934 	viewFile = fname;
9935 	using_vdir = TRUE;
9936     }
9937     else
9938 #endif
9939 	if (*eap->arg != NUL)
9940 	fname = eap->arg;
9941     else if (eap->cmdidx == CMD_mkvimrc)
9942 	fname = (char_u *)VIMRC_FILE;
9943 #ifdef FEAT_SESSION
9944     else if (eap->cmdidx == CMD_mksession)
9945 	fname = (char_u *)SESSION_FILE;
9946 #endif
9947     else
9948 	fname = (char_u *)EXRC_FILE;
9949 
9950 #ifdef FEAT_BROWSE
9951     if (cmdmod.browse)
9952     {
9953 	browseFile = do_browse(BROWSE_SAVE,
9954 # ifdef FEAT_SESSION
9955 		eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
9956 		eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
9957 # endif
9958 		(char_u *)_("Save Setup"),
9959 		fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
9960 	if (browseFile == NULL)
9961 	    goto theend;
9962 	fname = browseFile;
9963 	eap->forceit = TRUE;	/* since dialog already asked */
9964     }
9965 #endif
9966 
9967 #if defined(FEAT_SESSION) && defined(vim_mkdir)
9968     /* When using 'viewdir' may have to create the directory. */
9969     if (using_vdir && !mch_isdir(p_vdir))
9970 	vim_mkdir_emsg(p_vdir, 0755);
9971 #endif
9972 
9973     fd = open_exfile(fname, eap->forceit, WRITEBIN);
9974     if (fd != NULL)
9975     {
9976 #ifdef FEAT_SESSION
9977 	if (eap->cmdidx == CMD_mkview)
9978 	    flagp = &vop_flags;
9979 	else
9980 	    flagp = &ssop_flags;
9981 #endif
9982 
9983 #ifdef MKSESSION_NL
9984 	/* "unix" in 'sessionoptions': use NL line separator */
9985 	if (view_session && (*flagp & SSOP_UNIX))
9986 	    mksession_nl = TRUE;
9987 #endif
9988 
9989 	/* Write the version command for :mkvimrc */
9990 	if (eap->cmdidx == CMD_mkvimrc)
9991 	    (void)put_line(fd, "version 6.0");
9992 
9993 #ifdef FEAT_SESSION
9994 	if (eap->cmdidx == CMD_mksession)
9995 	{
9996 	    if (put_line(fd, "let SessionLoad = 1") == FAIL)
9997 		failed = TRUE;
9998 	}
9999 
10000 	if (eap->cmdidx != CMD_mkview)
10001 #endif
10002 	{
10003 	    /* Write setting 'compatible' first, because it has side effects.
10004 	     * For that same reason only do it when needed. */
10005 	    if (p_cp)
10006 		(void)put_line(fd, "if !&cp | set cp | endif");
10007 	    else
10008 		(void)put_line(fd, "if &cp | set nocp | endif");
10009 	}
10010 
10011 #ifdef FEAT_SESSION
10012 	if (!view_session
10013 		|| (eap->cmdidx == CMD_mksession
10014 		    && (*flagp & SSOP_OPTIONS)))
10015 #endif
10016 	    failed |= (makemap(fd, NULL) == FAIL
10017 				   || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
10018 
10019 #ifdef FEAT_SESSION
10020 	if (!failed && view_session)
10021 	{
10022 	    if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
10023 		failed = TRUE;
10024 	    if (eap->cmdidx == CMD_mksession)
10025 	    {
10026 		char_u *dirnow;	 /* current directory */
10027 
10028 		dirnow = alloc(MAXPATHL);
10029 		if (dirnow == NULL)
10030 		    failed = TRUE;
10031 		else
10032 		{
10033 		    /*
10034 		     * Change to session file's dir.
10035 		     */
10036 		    if (mch_dirname(dirnow, MAXPATHL) == FAIL
10037 					    || mch_chdir((char *)dirnow) != 0)
10038 			*dirnow = NUL;
10039 		    if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
10040 		    {
10041 			if (vim_chdirfile(fname) == OK)
10042 			    shorten_fnames(TRUE);
10043 		    }
10044 		    else if (*dirnow != NUL
10045 			   && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
10046 		    {
10047 			if (mch_chdir((char *)globaldir) == 0)
10048 			    shorten_fnames(TRUE);
10049 		    }
10050 
10051 		    failed |= (makeopens(fd, dirnow) == FAIL);
10052 
10053 		    /* restore original dir */
10054 		    if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
10055 			|| ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
10056 		    {
10057 			if (mch_chdir((char *)dirnow) != 0)
10058 			    EMSG(_(e_prev_dir));
10059 			shorten_fnames(TRUE);
10060 		    }
10061 		    vim_free(dirnow);
10062 		}
10063 	    }
10064 	    else
10065 	    {
10066 		failed |= (put_view(fd, curwin, !using_vdir, flagp,
10067 								 -1) == FAIL);
10068 	    }
10069 	    if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
10070 								      == FAIL)
10071 		failed = TRUE;
10072 	    if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
10073 		failed = TRUE;
10074 	    if (eap->cmdidx == CMD_mksession)
10075 	    {
10076 		if (put_line(fd, "unlet SessionLoad") == FAIL)
10077 		    failed = TRUE;
10078 	    }
10079 	}
10080 #endif
10081 	if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
10082 	    failed = TRUE;
10083 
10084 	failed |= fclose(fd);
10085 
10086 	if (failed)
10087 	    EMSG(_(e_write));
10088 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
10089 	else if (eap->cmdidx == CMD_mksession)
10090 	{
10091 	    /* successful session write - set this_session var */
10092 	    char_u	*tbuf;
10093 
10094 	    tbuf = alloc(MAXPATHL);
10095 	    if (tbuf != NULL)
10096 	    {
10097 		if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
10098 		    set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
10099 		vim_free(tbuf);
10100 	    }
10101 	}
10102 #endif
10103 #ifdef MKSESSION_NL
10104 	mksession_nl = FALSE;
10105 #endif
10106     }
10107 
10108 #ifdef FEAT_BROWSE
10109 theend:
10110     vim_free(browseFile);
10111 #endif
10112 #ifdef FEAT_SESSION
10113     vim_free(viewFile);
10114 #endif
10115 }
10116 
10117 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
10118 	|| defined(PROTO)
10119     int
10120 vim_mkdir_emsg(char_u *name, int prot)
10121 {
10122     if (vim_mkdir(name, prot) != 0)
10123     {
10124 	EMSG2(_("E739: Cannot create directory: %s"), name);
10125 	return FAIL;
10126     }
10127     return OK;
10128 }
10129 #endif
10130 
10131 /*
10132  * Open a file for writing for an Ex command, with some checks.
10133  * Return file descriptor, or NULL on failure.
10134  */
10135     FILE *
10136 open_exfile(
10137     char_u	*fname,
10138     int		forceit,
10139     char	*mode)	    /* "w" for create new file or "a" for append */
10140 {
10141     FILE	*fd;
10142 
10143 #ifdef UNIX
10144     /* with Unix it is possible to open a directory */
10145     if (mch_isdir(fname))
10146     {
10147 	EMSG2(_(e_isadir2), fname);
10148 	return NULL;
10149     }
10150 #endif
10151     if (!forceit && *mode != 'a' && vim_fexists(fname))
10152     {
10153 	EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
10154 	return NULL;
10155     }
10156 
10157     if ((fd = mch_fopen((char *)fname, mode)) == NULL)
10158 	EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
10159 
10160     return fd;
10161 }
10162 
10163 /*
10164  * ":mark" and ":k".
10165  */
10166     static void
10167 ex_mark(exarg_T *eap)
10168 {
10169     pos_T	pos;
10170 
10171     if (*eap->arg == NUL)		/* No argument? */
10172 	EMSG(_(e_argreq));
10173     else if (eap->arg[1] != NUL)	/* more than one character? */
10174 	EMSG(_(e_trailing));
10175     else
10176     {
10177 	pos = curwin->w_cursor;		/* save curwin->w_cursor */
10178 	curwin->w_cursor.lnum = eap->line2;
10179 	beginline(BL_WHITE | BL_FIX);
10180 	if (setmark(*eap->arg) == FAIL)	/* set mark */
10181 	    EMSG(_("E191: Argument must be a letter or forward/backward quote"));
10182 	curwin->w_cursor = pos;		/* restore curwin->w_cursor */
10183     }
10184 }
10185 
10186 /*
10187  * Update w_topline, w_leftcol and the cursor position.
10188  */
10189     void
10190 update_topline_cursor(void)
10191 {
10192     check_cursor();		/* put cursor on valid line */
10193     update_topline();
10194     if (!curwin->w_p_wrap)
10195 	validate_cursor();
10196     update_curswant();
10197 }
10198 
10199 /*
10200  * ":normal[!] {commands}": Execute normal mode commands.
10201  */
10202     void
10203 ex_normal(exarg_T *eap)
10204 {
10205     int		save_msg_scroll = msg_scroll;
10206     int		save_restart_edit = restart_edit;
10207     int		save_msg_didout = msg_didout;
10208     int		save_State = State;
10209     tasave_T	tabuf;
10210     int		save_insertmode = p_im;
10211     int		save_finish_op = finish_op;
10212     int		save_opcount = opcount;
10213 #ifdef FEAT_MBYTE
10214     char_u	*arg = NULL;
10215     int		l;
10216     char_u	*p;
10217 #endif
10218 
10219     if (ex_normal_lock > 0)
10220     {
10221 	EMSG(_(e_secure));
10222 	return;
10223     }
10224     if (ex_normal_busy >= p_mmd)
10225     {
10226 	EMSG(_("E192: Recursive use of :normal too deep"));
10227 	return;
10228     }
10229     ++ex_normal_busy;
10230 
10231     msg_scroll = FALSE;	    /* no msg scrolling in Normal mode */
10232     restart_edit = 0;	    /* don't go to Insert mode */
10233     p_im = FALSE;	    /* don't use 'insertmode' */
10234 
10235 #ifdef FEAT_MBYTE
10236     /*
10237      * vgetc() expects a CSI and K_SPECIAL to have been escaped.  Don't do
10238      * this for the K_SPECIAL leading byte, otherwise special keys will not
10239      * work.
10240      */
10241     if (has_mbyte)
10242     {
10243 	int	len = 0;
10244 
10245 	/* Count the number of characters to be escaped. */
10246 	for (p = eap->arg; *p != NUL; ++p)
10247 	{
10248 # ifdef FEAT_GUI
10249 	    if (*p == CSI)  /* leadbyte CSI */
10250 		len += 2;
10251 # endif
10252 	    for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
10253 		if (*++p == K_SPECIAL	  /* trailbyte K_SPECIAL or CSI */
10254 # ifdef FEAT_GUI
10255 			|| *p == CSI
10256 # endif
10257 			)
10258 		    len += 2;
10259 	}
10260 	if (len > 0)
10261 	{
10262 	    arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
10263 	    if (arg != NULL)
10264 	    {
10265 		len = 0;
10266 		for (p = eap->arg; *p != NUL; ++p)
10267 		{
10268 		    arg[len++] = *p;
10269 # ifdef FEAT_GUI
10270 		    if (*p == CSI)
10271 		    {
10272 			arg[len++] = KS_EXTRA;
10273 			arg[len++] = (int)KE_CSI;
10274 		    }
10275 # endif
10276 		    for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
10277 		    {
10278 			arg[len++] = *++p;
10279 			if (*p == K_SPECIAL)
10280 			{
10281 			    arg[len++] = KS_SPECIAL;
10282 			    arg[len++] = KE_FILLER;
10283 			}
10284 # ifdef FEAT_GUI
10285 			else if (*p == CSI)
10286 			{
10287 			    arg[len++] = KS_EXTRA;
10288 			    arg[len++] = (int)KE_CSI;
10289 			}
10290 # endif
10291 		    }
10292 		    arg[len] = NUL;
10293 		}
10294 	    }
10295 	}
10296     }
10297 #endif
10298 
10299     /*
10300      * Save the current typeahead.  This is required to allow using ":normal"
10301      * from an event handler and makes sure we don't hang when the argument
10302      * ends with half a command.
10303      */
10304     save_typeahead(&tabuf);
10305     if (tabuf.typebuf_valid)
10306     {
10307 	/*
10308 	 * Repeat the :normal command for each line in the range.  When no
10309 	 * range given, execute it just once, without positioning the cursor
10310 	 * first.
10311 	 */
10312 	do
10313 	{
10314 	    if (eap->addr_count != 0)
10315 	    {
10316 		curwin->w_cursor.lnum = eap->line1++;
10317 		curwin->w_cursor.col = 0;
10318 		check_cursor_moved(curwin);
10319 	    }
10320 
10321 	    exec_normal_cmd(
10322 #ifdef FEAT_MBYTE
10323 		    arg != NULL ? arg :
10324 #endif
10325 		    eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
10326 	}
10327 	while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
10328     }
10329 
10330     /* Might not return to the main loop when in an event handler. */
10331     update_topline_cursor();
10332 
10333     /* Restore the previous typeahead. */
10334     restore_typeahead(&tabuf);
10335 
10336     --ex_normal_busy;
10337     msg_scroll = save_msg_scroll;
10338     restart_edit = save_restart_edit;
10339     p_im = save_insertmode;
10340     finish_op = save_finish_op;
10341     opcount = save_opcount;
10342     msg_didout |= save_msg_didout;	/* don't reset msg_didout now */
10343 
10344     /* Restore the state (needed when called from a function executed for
10345      * 'indentexpr'). Update the mouse and cursor, they may have changed. */
10346     State = save_State;
10347 #ifdef FEAT_MOUSE
10348     setmouse();
10349 #endif
10350 #ifdef CURSOR_SHAPE
10351     ui_cursor_shape();		/* may show different cursor shape */
10352 #endif
10353 
10354 #ifdef FEAT_MBYTE
10355     vim_free(arg);
10356 #endif
10357 }
10358 
10359 /*
10360  * ":startinsert", ":startreplace" and ":startgreplace"
10361  */
10362     static void
10363 ex_startinsert(exarg_T *eap)
10364 {
10365     if (eap->forceit)
10366     {
10367 	coladvance((colnr_T)MAXCOL);
10368 	curwin->w_curswant = MAXCOL;
10369 	curwin->w_set_curswant = FALSE;
10370     }
10371 
10372     /* Ignore the command when already in Insert mode.  Inserting an
10373      * expression register that invokes a function can do this. */
10374     if (State & INSERT)
10375 	return;
10376 
10377     if (eap->cmdidx == CMD_startinsert)
10378 	restart_edit = 'a';
10379     else if (eap->cmdidx == CMD_startreplace)
10380 	restart_edit = 'R';
10381     else
10382 	restart_edit = 'V';
10383 
10384     if (!eap->forceit)
10385     {
10386 	if (eap->cmdidx == CMD_startinsert)
10387 	    restart_edit = 'i';
10388 	curwin->w_curswant = 0;	    /* avoid MAXCOL */
10389     }
10390 }
10391 
10392 /*
10393  * ":stopinsert"
10394  */
10395     static void
10396 ex_stopinsert(exarg_T *eap UNUSED)
10397 {
10398     restart_edit = 0;
10399     stop_insert_mode = TRUE;
10400     clearmode();
10401 }
10402 
10403 /*
10404  * Execute normal mode command "cmd".
10405  * "remap" can be REMAP_NONE or REMAP_YES.
10406  */
10407     void
10408 exec_normal_cmd(char_u *cmd, int remap, int silent)
10409 {
10410     /* Stuff the argument into the typeahead buffer. */
10411     ins_typebuf(cmd, remap, 0, TRUE, silent);
10412     exec_normal(FALSE);
10413 }
10414 
10415 /*
10416  * Execute normal_cmd() until there is no typeahead left.
10417  */
10418     void
10419 exec_normal(int was_typed)
10420 {
10421     oparg_T	oa;
10422 
10423     clear_oparg(&oa);
10424     finish_op = FALSE;
10425     while ((!stuff_empty() || ((was_typed || !typebuf_typed())
10426 		    && typebuf.tb_len > 0)) && !got_int)
10427     {
10428 	update_topline_cursor();
10429 	normal_cmd(&oa, TRUE);	/* execute a Normal mode cmd */
10430     }
10431 }
10432 
10433 #ifdef FEAT_FIND_ID
10434     static void
10435 ex_checkpath(exarg_T *eap)
10436 {
10437     find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
10438 				   eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
10439 					      (linenr_T)1, (linenr_T)MAXLNUM);
10440 }
10441 
10442 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
10443 /*
10444  * ":psearch"
10445  */
10446     static void
10447 ex_psearch(exarg_T *eap)
10448 {
10449     g_do_tagpreview = p_pvh;
10450     ex_findpat(eap);
10451     g_do_tagpreview = 0;
10452 }
10453 #endif
10454 
10455     static void
10456 ex_findpat(exarg_T *eap)
10457 {
10458     int		whole = TRUE;
10459     long	n;
10460     char_u	*p;
10461     int		action;
10462 
10463     switch (cmdnames[eap->cmdidx].cmd_name[2])
10464     {
10465 	case 'e':	/* ":psearch", ":isearch" and ":dsearch" */
10466 		if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
10467 		    action = ACTION_GOTO;
10468 		else
10469 		    action = ACTION_SHOW;
10470 		break;
10471 	case 'i':	/* ":ilist" and ":dlist" */
10472 		action = ACTION_SHOW_ALL;
10473 		break;
10474 	case 'u':	/* ":ijump" and ":djump" */
10475 		action = ACTION_GOTO;
10476 		break;
10477 	default:	/* ":isplit" and ":dsplit" */
10478 		action = ACTION_SPLIT;
10479 		break;
10480     }
10481 
10482     n = 1;
10483     if (vim_isdigit(*eap->arg))	/* get count */
10484     {
10485 	n = getdigits(&eap->arg);
10486 	eap->arg = skipwhite(eap->arg);
10487     }
10488     if (*eap->arg == '/')   /* Match regexp, not just whole words */
10489     {
10490 	whole = FALSE;
10491 	++eap->arg;
10492 	p = skip_regexp(eap->arg, '/', p_magic, NULL);
10493 	if (*p)
10494 	{
10495 	    *p++ = NUL;
10496 	    p = skipwhite(p);
10497 
10498 	    /* Check for trailing illegal characters */
10499 	    if (!ends_excmd(*p))
10500 		eap->errmsg = e_trailing;
10501 	    else
10502 		eap->nextcmd = check_nextcmd(p);
10503 	}
10504     }
10505     if (!eap->skip)
10506 	find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
10507 			    whole, !eap->forceit,
10508 			    *eap->cmd == 'd' ?	FIND_DEFINE : FIND_ANY,
10509 			    n, action, eap->line1, eap->line2);
10510 }
10511 #endif
10512 
10513 #ifdef FEAT_WINDOWS
10514 
10515 # ifdef FEAT_QUICKFIX
10516 /*
10517  * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
10518  */
10519     static void
10520 ex_ptag(exarg_T *eap)
10521 {
10522     g_do_tagpreview = p_pvh;  /* will be reset to 0 in ex_tag_cmd() */
10523     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
10524 }
10525 
10526 /*
10527  * ":pedit"
10528  */
10529     static void
10530 ex_pedit(exarg_T *eap)
10531 {
10532     win_T	*curwin_save = curwin;
10533 
10534     g_do_tagpreview = p_pvh;
10535     prepare_tagpreview(TRUE);
10536     keep_help_flag = bt_help(curwin_save->w_buffer);
10537     do_exedit(eap, NULL);
10538     keep_help_flag = FALSE;
10539     if (curwin != curwin_save && win_valid(curwin_save))
10540     {
10541 	/* Return cursor to where we were */
10542 	validate_cursor();
10543 	redraw_later(VALID);
10544 	win_enter(curwin_save, TRUE);
10545     }
10546     g_do_tagpreview = 0;
10547 }
10548 # endif
10549 
10550 /*
10551  * ":stag", ":stselect" and ":stjump".
10552  */
10553     static void
10554 ex_stag(exarg_T *eap)
10555 {
10556     postponed_split = -1;
10557     postponed_split_flags = cmdmod.split;
10558     postponed_split_tab = cmdmod.tab;
10559     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
10560     postponed_split_flags = 0;
10561     postponed_split_tab = 0;
10562 }
10563 #endif
10564 
10565 /*
10566  * ":tag", ":tselect", ":tjump", ":tnext", etc.
10567  */
10568     static void
10569 ex_tag(exarg_T *eap)
10570 {
10571     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
10572 }
10573 
10574     static void
10575 ex_tag_cmd(exarg_T *eap, char_u *name)
10576 {
10577     int		cmd;
10578 
10579     switch (name[1])
10580     {
10581 	case 'j': cmd = DT_JUMP;	/* ":tjump" */
10582 		  break;
10583 	case 's': cmd = DT_SELECT;	/* ":tselect" */
10584 		  break;
10585 	case 'p': cmd = DT_PREV;	/* ":tprevious" */
10586 		  break;
10587 	case 'N': cmd = DT_PREV;	/* ":tNext" */
10588 		  break;
10589 	case 'n': cmd = DT_NEXT;	/* ":tnext" */
10590 		  break;
10591 	case 'o': cmd = DT_POP;		/* ":pop" */
10592 		  break;
10593 	case 'f':			/* ":tfirst" */
10594 	case 'r': cmd = DT_FIRST;	/* ":trewind" */
10595 		  break;
10596 	case 'l': cmd = DT_LAST;	/* ":tlast" */
10597 		  break;
10598 	default:			/* ":tag" */
10599 #ifdef FEAT_CSCOPE
10600 		  if (p_cst && *eap->arg != NUL)
10601 		  {
10602 		      ex_cstag(eap);
10603 		      return;
10604 		  }
10605 #endif
10606 		  cmd = DT_TAG;
10607 		  break;
10608     }
10609 
10610     if (name[0] == 'l')
10611     {
10612 #ifndef FEAT_QUICKFIX
10613 	ex_ni(eap);
10614 	return;
10615 #else
10616 	cmd = DT_LTAG;
10617 #endif
10618     }
10619 
10620     do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
10621 							  eap->forceit, TRUE);
10622 }
10623 
10624 /*
10625  * Check "str" for starting with a special cmdline variable.
10626  * If found return one of the SPEC_ values and set "*usedlen" to the length of
10627  * the variable.  Otherwise return -1 and "*usedlen" is unchanged.
10628  */
10629     int
10630 find_cmdline_var(char_u *src, int *usedlen)
10631 {
10632     int		len;
10633     int		i;
10634     static char *(spec_str[]) = {
10635 		    "%",
10636 #define SPEC_PERC   0
10637 		    "#",
10638 #define SPEC_HASH   1
10639 		    "<cword>",		/* cursor word */
10640 #define SPEC_CWORD  2
10641 		    "<cWORD>",		/* cursor WORD */
10642 #define SPEC_CCWORD 3
10643 		    "<cfile>",		/* cursor path name */
10644 #define SPEC_CFILE  4
10645 		    "<sfile>",		/* ":so" file name */
10646 #define SPEC_SFILE  5
10647 		    "<slnum>",		/* ":so" file line number */
10648 #define SPEC_SLNUM  6
10649 #ifdef FEAT_AUTOCMD
10650 		    "<afile>",		/* autocommand file name */
10651 # define SPEC_AFILE 7
10652 		    "<abuf>",		/* autocommand buffer number */
10653 # define SPEC_ABUF  8
10654 		    "<amatch>",		/* autocommand match name */
10655 # define SPEC_AMATCH 9
10656 #endif
10657 #ifdef FEAT_CLIENTSERVER
10658 		    "<client>"
10659 # ifdef FEAT_AUTOCMD
10660 #  define SPEC_CLIENT 10
10661 # else
10662 #  define SPEC_CLIENT 7
10663 # endif
10664 #endif
10665     };
10666 
10667     for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i)
10668     {
10669 	len = (int)STRLEN(spec_str[i]);
10670 	if (STRNCMP(src, spec_str[i], len) == 0)
10671 	{
10672 	    *usedlen = len;
10673 	    return i;
10674 	}
10675     }
10676     return -1;
10677 }
10678 
10679 /*
10680  * Evaluate cmdline variables.
10681  *
10682  * change '%'	    to curbuf->b_ffname
10683  *	  '#'	    to curwin->w_altfile
10684  *	  '<cword>' to word under the cursor
10685  *	  '<cWORD>' to WORD under the cursor
10686  *	  '<cfile>' to path name under the cursor
10687  *	  '<sfile>' to sourced file name
10688  *	  '<slnum>' to sourced file line number
10689  *	  '<afile>' to file name for autocommand
10690  *	  '<abuf>'  to buffer number for autocommand
10691  *	  '<amatch>' to matching name for autocommand
10692  *
10693  * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
10694  * "" for error without a message) and NULL is returned.
10695  * Returns an allocated string if a valid match was found.
10696  * Returns NULL if no match was found.	"usedlen" then still contains the
10697  * number of characters to skip.
10698  */
10699     char_u *
10700 eval_vars(
10701     char_u	*src,		/* pointer into commandline */
10702     char_u	*srcstart,	/* beginning of valid memory for src */
10703     int		*usedlen,	/* characters after src that are used */
10704     linenr_T	*lnump,		/* line number for :e command, or NULL */
10705     char_u	**errormsg,	/* pointer to error message */
10706     int		*escaped)	/* return value has escaped white space (can
10707 				 * be NULL) */
10708 {
10709     int		i;
10710     char_u	*s;
10711     char_u	*result;
10712     char_u	*resultbuf = NULL;
10713     int		resultlen;
10714     buf_T	*buf;
10715     int		valid = VALID_HEAD + VALID_PATH;    /* assume valid result */
10716     int		spec_idx;
10717 #ifdef FEAT_MODIFY_FNAME
10718     int		skip_mod = FALSE;
10719 #endif
10720     char_u	strbuf[30];
10721 
10722     *errormsg = NULL;
10723     if (escaped != NULL)
10724 	*escaped = FALSE;
10725 
10726     /*
10727      * Check if there is something to do.
10728      */
10729     spec_idx = find_cmdline_var(src, usedlen);
10730     if (spec_idx < 0)	/* no match */
10731     {
10732 	*usedlen = 1;
10733 	return NULL;
10734     }
10735 
10736     /*
10737      * Skip when preceded with a backslash "\%" and "\#".
10738      * Note: In "\\%" the % is also not recognized!
10739      */
10740     if (src > srcstart && src[-1] == '\\')
10741     {
10742 	*usedlen = 0;
10743 	STRMOVE(src - 1, src);	/* remove backslash */
10744 	return NULL;
10745     }
10746 
10747     /*
10748      * word or WORD under cursor
10749      */
10750     if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
10751     {
10752 	resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
10753 				      (FIND_IDENT|FIND_STRING) : FIND_STRING);
10754 	if (resultlen == 0)
10755 	{
10756 	    *errormsg = (char_u *)"";
10757 	    return NULL;
10758 	}
10759     }
10760 
10761     /*
10762      * '#': Alternate file name
10763      * '%': Current file name
10764      *	    File name under the cursor
10765      *	    File name for autocommand
10766      *	and following modifiers
10767      */
10768     else
10769     {
10770 	switch (spec_idx)
10771 	{
10772 	case SPEC_PERC:		/* '%': current file */
10773 		if (curbuf->b_fname == NULL)
10774 		{
10775 		    result = (char_u *)"";
10776 		    valid = 0;	    /* Must have ":p:h" to be valid */
10777 		}
10778 		else
10779 		    result = curbuf->b_fname;
10780 		break;
10781 
10782 	case SPEC_HASH:		/* '#' or "#99": alternate file */
10783 		if (src[1] == '#')  /* "##": the argument list */
10784 		{
10785 		    result = arg_all();
10786 		    resultbuf = result;
10787 		    *usedlen = 2;
10788 		    if (escaped != NULL)
10789 			*escaped = TRUE;
10790 #ifdef FEAT_MODIFY_FNAME
10791 		    skip_mod = TRUE;
10792 #endif
10793 		    break;
10794 		}
10795 		s = src + 1;
10796 		if (*s == '<')		/* "#<99" uses v:oldfiles */
10797 		    ++s;
10798 		i = (int)getdigits(&s);
10799 		*usedlen = (int)(s - src); /* length of what we expand */
10800 
10801 		if (src[1] == '<')
10802 		{
10803 		    if (*usedlen < 2)
10804 		    {
10805 			/* Should we give an error message for #<text? */
10806 			*usedlen = 1;
10807 			return NULL;
10808 		    }
10809 #ifdef FEAT_EVAL
10810 		    result = list_find_str(get_vim_var_list(VV_OLDFILES),
10811 								     (long)i);
10812 		    if (result == NULL)
10813 		    {
10814 			*errormsg = (char_u *)"";
10815 			return NULL;
10816 		    }
10817 #else
10818 		    *errormsg = (char_u *)_("E809: #< is not available without the +eval feature");
10819 		    return NULL;
10820 #endif
10821 		}
10822 		else
10823 		{
10824 		    buf = buflist_findnr(i);
10825 		    if (buf == NULL)
10826 		    {
10827 			*errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
10828 			return NULL;
10829 		    }
10830 		    if (lnump != NULL)
10831 			*lnump = ECMD_LAST;
10832 		    if (buf->b_fname == NULL)
10833 		    {
10834 			result = (char_u *)"";
10835 			valid = 0;	    /* Must have ":p:h" to be valid */
10836 		    }
10837 		    else
10838 			result = buf->b_fname;
10839 		}
10840 		break;
10841 
10842 #ifdef FEAT_SEARCHPATH
10843 	case SPEC_CFILE:	/* file name under cursor */
10844 		result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
10845 		if (result == NULL)
10846 		{
10847 		    *errormsg = (char_u *)"";
10848 		    return NULL;
10849 		}
10850 		resultbuf = result;	    /* remember allocated string */
10851 		break;
10852 #endif
10853 
10854 #ifdef FEAT_AUTOCMD
10855 	case SPEC_AFILE:	/* file name for autocommand */
10856 		result = autocmd_fname;
10857 		if (result != NULL && !autocmd_fname_full)
10858 		{
10859 		    /* Still need to turn the fname into a full path.  It is
10860 		     * postponed to avoid a delay when <afile> is not used. */
10861 		    autocmd_fname_full = TRUE;
10862 		    result = FullName_save(autocmd_fname, FALSE);
10863 		    vim_free(autocmd_fname);
10864 		    autocmd_fname = result;
10865 		}
10866 		if (result == NULL)
10867 		{
10868 		    *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
10869 		    return NULL;
10870 		}
10871 		result = shorten_fname1(result);
10872 		break;
10873 
10874 	case SPEC_ABUF:		/* buffer number for autocommand */
10875 		if (autocmd_bufnr <= 0)
10876 		{
10877 		    *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
10878 		    return NULL;
10879 		}
10880 		sprintf((char *)strbuf, "%d", autocmd_bufnr);
10881 		result = strbuf;
10882 		break;
10883 
10884 	case SPEC_AMATCH:	/* match name for autocommand */
10885 		result = autocmd_match;
10886 		if (result == NULL)
10887 		{
10888 		    *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
10889 		    return NULL;
10890 		}
10891 		break;
10892 
10893 #endif
10894 	case SPEC_SFILE:	/* file name for ":so" command */
10895 		result = sourcing_name;
10896 		if (result == NULL)
10897 		{
10898 		    *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
10899 		    return NULL;
10900 		}
10901 		break;
10902 	case SPEC_SLNUM:	/* line in file for ":so" command */
10903 		if (sourcing_name == NULL || sourcing_lnum == 0)
10904 		{
10905 		    *errormsg = (char_u *)_("E842: no line number to use for \"<slnum>\"");
10906 		    return NULL;
10907 		}
10908 		sprintf((char *)strbuf, "%ld", (long)sourcing_lnum);
10909 		result = strbuf;
10910 		break;
10911 #if defined(FEAT_CLIENTSERVER)
10912 	case SPEC_CLIENT:	/* Source of last submitted input */
10913 		sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
10914 							(long_u)clientWindow);
10915 		result = strbuf;
10916 		break;
10917 #endif
10918 	default:
10919 		result = (char_u *)""; /* avoid gcc warning */
10920 		break;
10921 	}
10922 
10923 	resultlen = (int)STRLEN(result);	/* length of new string */
10924 	if (src[*usedlen] == '<')	/* remove the file name extension */
10925 	{
10926 	    ++*usedlen;
10927 	    if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
10928 		resultlen = (int)(s - result);
10929 	}
10930 #ifdef FEAT_MODIFY_FNAME
10931 	else if (!skip_mod)
10932 	{
10933 	    valid |= modify_fname(src, usedlen, &result, &resultbuf,
10934 								  &resultlen);
10935 	    if (result == NULL)
10936 	    {
10937 		*errormsg = (char_u *)"";
10938 		return NULL;
10939 	    }
10940 	}
10941 #endif
10942     }
10943 
10944     if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
10945     {
10946 	if (valid != VALID_HEAD + VALID_PATH)
10947 	    /* xgettext:no-c-format */
10948 	    *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
10949 	else
10950 	    *errormsg = (char_u *)_("E500: Evaluates to an empty string");
10951 	result = NULL;
10952     }
10953     else
10954 	result = vim_strnsave(result, resultlen);
10955     vim_free(resultbuf);
10956     return result;
10957 }
10958 
10959 /*
10960  * Concatenate all files in the argument list, separated by spaces, and return
10961  * it in one allocated string.
10962  * Spaces and backslashes in the file names are escaped with a backslash.
10963  * Returns NULL when out of memory.
10964  */
10965     static char_u *
10966 arg_all(void)
10967 {
10968     int		len;
10969     int		idx;
10970     char_u	*retval = NULL;
10971     char_u	*p;
10972 
10973     /*
10974      * Do this loop two times:
10975      * first time: compute the total length
10976      * second time: concatenate the names
10977      */
10978     for (;;)
10979     {
10980 	len = 0;
10981 	for (idx = 0; idx < ARGCOUNT; ++idx)
10982 	{
10983 	    p = alist_name(&ARGLIST[idx]);
10984 	    if (p != NULL)
10985 	    {
10986 		if (len > 0)
10987 		{
10988 		    /* insert a space in between names */
10989 		    if (retval != NULL)
10990 			retval[len] = ' ';
10991 		    ++len;
10992 		}
10993 		for ( ; *p != NUL; ++p)
10994 		{
10995 		    if (*p == ' '
10996 #ifndef BACKSLASH_IN_FILENAME
10997 			    || *p == '\\'
10998 #endif
10999 			    )
11000 		    {
11001 			/* insert a backslash */
11002 			if (retval != NULL)
11003 			    retval[len] = '\\';
11004 			++len;
11005 		    }
11006 		    if (retval != NULL)
11007 			retval[len] = *p;
11008 		    ++len;
11009 		}
11010 	    }
11011 	}
11012 
11013 	/* second time: break here */
11014 	if (retval != NULL)
11015 	{
11016 	    retval[len] = NUL;
11017 	    break;
11018 	}
11019 
11020 	/* allocate memory */
11021 	retval = alloc((unsigned)len + 1);
11022 	if (retval == NULL)
11023 	    break;
11024     }
11025 
11026     return retval;
11027 }
11028 
11029 #if defined(FEAT_AUTOCMD) || defined(PROTO)
11030 /*
11031  * Expand the <sfile> string in "arg".
11032  *
11033  * Returns an allocated string, or NULL for any error.
11034  */
11035     char_u *
11036 expand_sfile(char_u *arg)
11037 {
11038     char_u	*errormsg;
11039     int		len;
11040     char_u	*result;
11041     char_u	*newres;
11042     char_u	*repl;
11043     int		srclen;
11044     char_u	*p;
11045 
11046     result = vim_strsave(arg);
11047     if (result == NULL)
11048 	return NULL;
11049 
11050     for (p = result; *p; )
11051     {
11052 	if (STRNCMP(p, "<sfile>", 7) != 0)
11053 	    ++p;
11054 	else
11055 	{
11056 	    /* replace "<sfile>" with the sourced file name, and do ":" stuff */
11057 	    repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
11058 	    if (errormsg != NULL)
11059 	    {
11060 		if (*errormsg)
11061 		    emsg(errormsg);
11062 		vim_free(result);
11063 		return NULL;
11064 	    }
11065 	    if (repl == NULL)		/* no match (cannot happen) */
11066 	    {
11067 		p += srclen;
11068 		continue;
11069 	    }
11070 	    len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
11071 	    newres = alloc(len);
11072 	    if (newres == NULL)
11073 	    {
11074 		vim_free(repl);
11075 		vim_free(result);
11076 		return NULL;
11077 	    }
11078 	    mch_memmove(newres, result, (size_t)(p - result));
11079 	    STRCPY(newres + (p - result), repl);
11080 	    len = (int)STRLEN(newres);
11081 	    STRCAT(newres, p + srclen);
11082 	    vim_free(repl);
11083 	    vim_free(result);
11084 	    result = newres;
11085 	    p = newres + len;		/* continue after the match */
11086 	}
11087     }
11088 
11089     return result;
11090 }
11091 #endif
11092 
11093 #ifdef FEAT_SESSION
11094 static int ses_winsizes(FILE *fd, int restore_size,
11095 							win_T *tab_firstwin);
11096 static int ses_win_rec(FILE *fd, frame_T *fr);
11097 static frame_T *ses_skipframe(frame_T *fr);
11098 static int ses_do_frame(frame_T *fr);
11099 static int ses_do_win(win_T *wp);
11100 static int ses_arglist(FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp);
11101 static int ses_put_fname(FILE *fd, char_u *name, unsigned *flagp);
11102 static int ses_fname(FILE *fd, buf_T *buf, unsigned *flagp);
11103 
11104 /*
11105  * Write openfile commands for the current buffers to an .exrc file.
11106  * Return FAIL on error, OK otherwise.
11107  */
11108     static int
11109 makeopens(
11110     FILE	*fd,
11111     char_u	*dirnow)	/* Current directory name */
11112 {
11113     buf_T	*buf;
11114     int		only_save_windows = TRUE;
11115     int		nr;
11116     int		restore_size = TRUE;
11117     win_T	*wp;
11118     char_u	*sname;
11119     win_T	*edited_win = NULL;
11120     int		tabnr;
11121     int		restore_stal = FALSE;
11122     win_T	*tab_firstwin;
11123     frame_T	*tab_topframe;
11124     int		cur_arg_idx = 0;
11125     int		next_arg_idx = 0;
11126 
11127     if (ssop_flags & SSOP_BUFFERS)
11128 	only_save_windows = FALSE;		/* Save ALL buffers */
11129 
11130     /*
11131      * Begin by setting the this_session variable, and then other
11132      * sessionable variables.
11133      */
11134 #ifdef FEAT_EVAL
11135     if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
11136 	return FAIL;
11137     if (ssop_flags & SSOP_GLOBALS)
11138 	if (store_session_globals(fd) == FAIL)
11139 	    return FAIL;
11140 #endif
11141 
11142     /*
11143      * Close all windows but one.
11144      */
11145     if (put_line(fd, "silent only") == FAIL)
11146 	return FAIL;
11147 
11148     /*
11149      * Now a :cd command to the session directory or the current directory
11150      */
11151     if (ssop_flags & SSOP_SESDIR)
11152     {
11153 	if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
11154 								      == FAIL)
11155 	    return FAIL;
11156     }
11157     else if (ssop_flags & SSOP_CURDIR)
11158     {
11159 	sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
11160 	if (sname == NULL
11161 		|| fputs("cd ", fd) < 0
11162 		|| ses_put_fname(fd, sname, &ssop_flags) == FAIL
11163 		|| put_eol(fd) == FAIL)
11164 	{
11165 	    vim_free(sname);
11166 	    return FAIL;
11167 	}
11168 	vim_free(sname);
11169     }
11170 
11171     /*
11172      * If there is an empty, unnamed buffer we will wipe it out later.
11173      * Remember the buffer number.
11174      */
11175     if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
11176 	return FAIL;
11177     if (put_line(fd, "  let s:wipebuf = bufnr('%')") == FAIL)
11178 	return FAIL;
11179     if (put_line(fd, "endif") == FAIL)
11180 	return FAIL;
11181 
11182     /*
11183      * Now save the current files, current buffer first.
11184      */
11185     if (put_line(fd, "set shortmess=aoO") == FAIL)
11186 	return FAIL;
11187 
11188     /* Now put the other buffers into the buffer list */
11189     FOR_ALL_BUFFERS(buf)
11190     {
11191 	if (!(only_save_windows && buf->b_nwindows == 0)
11192 		&& !(buf->b_help && !(ssop_flags & SSOP_HELP))
11193 		&& buf->b_fname != NULL
11194 		&& buf->b_p_bl)
11195 	{
11196 	    if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
11197 					   : buf->b_wininfo->wi_fpos.lnum) < 0
11198 		    || ses_fname(fd, buf, &ssop_flags) == FAIL)
11199 		return FAIL;
11200 	}
11201     }
11202 
11203     /* the global argument list */
11204     if (ses_arglist(fd, "argglobal", &global_alist.al_ga,
11205 			    !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
11206 	return FAIL;
11207 
11208     if (ssop_flags & SSOP_RESIZE)
11209     {
11210 	/* Note: after the restore we still check it worked!*/
11211 	if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
11212 		|| put_eol(fd) == FAIL)
11213 	    return FAIL;
11214     }
11215 
11216 #ifdef FEAT_GUI
11217     if (gui.in_use && (ssop_flags & SSOP_WINPOS))
11218     {
11219 	int	x, y;
11220 
11221 	if (gui_mch_get_winpos(&x, &y) == OK)
11222 	{
11223 	    /* Note: after the restore we still check it worked!*/
11224 	    if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
11225 		return FAIL;
11226 	}
11227     }
11228 #endif
11229 
11230     /*
11231      * When there are two or more tabpages and 'showtabline' is 1 the tabline
11232      * will be displayed when creating the next tab.  That resizes the windows
11233      * in the first tab, which may cause problems.  Set 'showtabline' to 2
11234      * temporarily to avoid that.
11235      */
11236     if (p_stal == 1 && first_tabpage->tp_next != NULL)
11237     {
11238 	if (put_line(fd, "set stal=2") == FAIL)
11239 	    return FAIL;
11240 	restore_stal = TRUE;
11241     }
11242 
11243     /*
11244      * May repeat putting Windows for each tab, when "tabpages" is in
11245      * 'sessionoptions'.
11246      * Don't use goto_tabpage(), it may change directory and trigger
11247      * autocommands.
11248      */
11249     tab_firstwin = firstwin;	/* first window in tab page "tabnr" */
11250     tab_topframe = topframe;
11251     for (tabnr = 1; ; ++tabnr)
11252     {
11253 	int	need_tabnew = FALSE;
11254 	int	cnr = 1;
11255 
11256 	if ((ssop_flags & SSOP_TABPAGES))
11257 	{
11258 	    tabpage_T *tp = find_tabpage(tabnr);
11259 
11260 	    if (tp == NULL)
11261 		break;		/* done all tab pages */
11262 	    if (tp == curtab)
11263 	    {
11264 		tab_firstwin = firstwin;
11265 		tab_topframe = topframe;
11266 	    }
11267 	    else
11268 	    {
11269 		tab_firstwin = tp->tp_firstwin;
11270 		tab_topframe = tp->tp_topframe;
11271 	    }
11272 	    if (tabnr > 1)
11273 		need_tabnew = TRUE;
11274 	}
11275 
11276 	/*
11277 	 * Before creating the window layout, try loading one file.  If this
11278 	 * is aborted we don't end up with a number of useless windows.
11279 	 * This may have side effects! (e.g., compressed or network file).
11280 	 */
11281 	for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
11282 	{
11283 	    if (ses_do_win(wp)
11284 		    && wp->w_buffer->b_ffname != NULL
11285 		    && !bt_help(wp->w_buffer)
11286 #ifdef FEAT_QUICKFIX
11287 		    && !bt_nofile(wp->w_buffer)
11288 #endif
11289 		    )
11290 	    {
11291 		if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
11292 			|| ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
11293 		    return FAIL;
11294 		need_tabnew = FALSE;
11295 		if (!wp->w_arg_idx_invalid)
11296 		    edited_win = wp;
11297 		break;
11298 	    }
11299 	}
11300 
11301 	/* If no file got edited create an empty tab page. */
11302 	if (need_tabnew && put_line(fd, "tabnew") == FAIL)
11303 	    return FAIL;
11304 
11305 	/*
11306 	 * Save current window layout.
11307 	 */
11308 	if (put_line(fd, "set splitbelow splitright") == FAIL)
11309 	    return FAIL;
11310 	if (ses_win_rec(fd, tab_topframe) == FAIL)
11311 	    return FAIL;
11312 	if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
11313 	    return FAIL;
11314 	if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
11315 	    return FAIL;
11316 
11317 	/*
11318 	 * Check if window sizes can be restored (no windows omitted).
11319 	 * Remember the window number of the current window after restoring.
11320 	 */
11321 	nr = 0;
11322 	for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
11323 	{
11324 	    if (ses_do_win(wp))
11325 		++nr;
11326 	    else
11327 		restore_size = FALSE;
11328 	    if (curwin == wp)
11329 		cnr = nr;
11330 	}
11331 
11332 	/* Go to the first window. */
11333 	if (put_line(fd, "wincmd t") == FAIL)
11334 	    return FAIL;
11335 
11336 	/*
11337 	 * If more than one window, see if sizes can be restored.
11338 	 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
11339 	 * resized when moving between windows.
11340 	 * Do this before restoring the view, so that the topline and the
11341 	 * cursor can be set.  This is done again below.
11342 	 * winminheight and winminwidth need to be set to avoid an error if the
11343 	 * user has set winheight or winwidth.
11344 	 */
11345 	if (put_line(fd, "set winminheight=1 winheight=1 winminwidth=1 winwidth=1") == FAIL)
11346 	    return FAIL;
11347 	if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
11348 	    return FAIL;
11349 
11350 	/*
11351 	 * Restore the view of the window (options, file, cursor, etc.).
11352 	 */
11353 	for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
11354 	{
11355 	    if (!ses_do_win(wp))
11356 		continue;
11357 	    if (put_view(fd, wp, wp != edited_win, &ssop_flags,
11358 							 cur_arg_idx) == FAIL)
11359 		return FAIL;
11360 	    if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
11361 		return FAIL;
11362 	    next_arg_idx = wp->w_arg_idx;
11363 	}
11364 
11365 	/* The argument index in the first tab page is zero, need to set it in
11366 	 * each window.  For further tab pages it's the window where we do
11367 	 * "tabedit". */
11368 	cur_arg_idx = next_arg_idx;
11369 
11370 	/*
11371 	 * Restore cursor to the current window if it's not the first one.
11372 	 */
11373 	if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
11374 						      || put_eol(fd) == FAIL))
11375 	    return FAIL;
11376 
11377 	/*
11378 	 * Restore window sizes again after jumping around in windows, because
11379 	 * the current window has a minimum size while others may not.
11380 	 */
11381 	if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
11382 	    return FAIL;
11383 
11384 	/* Don't continue in another tab page when doing only the current one
11385 	 * or when at the last tab page. */
11386 	if (!(ssop_flags & SSOP_TABPAGES))
11387 	    break;
11388     }
11389 
11390     if (ssop_flags & SSOP_TABPAGES)
11391     {
11392 	if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
11393 		|| put_eol(fd) == FAIL)
11394 	    return FAIL;
11395     }
11396     if (restore_stal && put_line(fd, "set stal=1") == FAIL)
11397 	return FAIL;
11398 
11399     /*
11400      * Wipe out an empty unnamed buffer we started in.
11401      */
11402     if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
11403 	return FAIL;
11404     if (put_line(fd, "  silent exe 'bwipe ' . s:wipebuf") == FAIL)
11405 	return FAIL;
11406     if (put_line(fd, "endif") == FAIL)
11407 	return FAIL;
11408     if (put_line(fd, "unlet! s:wipebuf") == FAIL)
11409 	return FAIL;
11410 
11411     /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
11412     if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
11413 			       p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
11414 	return FAIL;
11415     /* Re-apply 'winminheight' and 'winminwidth'. */
11416     if (fprintf(fd, "set winminheight=%ld winminwidth=%ld",
11417 				      p_wmh, p_wmw) < 0 || put_eol(fd) == FAIL)
11418 	return FAIL;
11419 
11420     /*
11421      * Lastly, execute the x.vim file if it exists.
11422      */
11423     if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
11424 	    || put_line(fd, "if file_readable(s:sx)") == FAIL
11425 	    || put_line(fd, "  exe \"source \" . fnameescape(s:sx)") == FAIL
11426 	    || put_line(fd, "endif") == FAIL)
11427 	return FAIL;
11428 
11429     return OK;
11430 }
11431 
11432     static int
11433 ses_winsizes(
11434     FILE	*fd,
11435     int		restore_size,
11436     win_T	*tab_firstwin)
11437 {
11438     int		n = 0;
11439     win_T	*wp;
11440 
11441     if (restore_size && (ssop_flags & SSOP_WINSIZE))
11442     {
11443 	for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
11444 	{
11445 	    if (!ses_do_win(wp))
11446 		continue;
11447 	    ++n;
11448 
11449 	    /* restore height when not full height */
11450 	    if (wp->w_height + wp->w_status_height < topframe->fr_height
11451 		    && (fprintf(fd,
11452 			  "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
11453 			    n, (long)wp->w_height, Rows / 2, Rows) < 0
11454 						  || put_eol(fd) == FAIL))
11455 		return FAIL;
11456 
11457 	    /* restore width when not full width */
11458 	    if (wp->w_width < Columns && (fprintf(fd,
11459 		   "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
11460 			    n, (long)wp->w_width, Columns / 2, Columns) < 0
11461 						  || put_eol(fd) == FAIL))
11462 		return FAIL;
11463 	}
11464     }
11465     else
11466     {
11467 	/* Just equalise window sizes */
11468 	if (put_line(fd, "wincmd =") == FAIL)
11469 	    return FAIL;
11470     }
11471     return OK;
11472 }
11473 
11474 /*
11475  * Write commands to "fd" to recursively create windows for frame "fr",
11476  * horizontally and vertically split.
11477  * After the commands the last window in the frame is the current window.
11478  * Returns FAIL when writing the commands to "fd" fails.
11479  */
11480     static int
11481 ses_win_rec(FILE *fd, frame_T *fr)
11482 {
11483     frame_T	*frc;
11484     int		count = 0;
11485 
11486     if (fr->fr_layout != FR_LEAF)
11487     {
11488 	/* Find first frame that's not skipped and then create a window for
11489 	 * each following one (first frame is already there). */
11490 	frc = ses_skipframe(fr->fr_child);
11491 	if (frc != NULL)
11492 	    while ((frc = ses_skipframe(frc->fr_next)) != NULL)
11493 	    {
11494 		/* Make window as big as possible so that we have lots of room
11495 		 * to split. */
11496 		if (put_line(fd, "wincmd _ | wincmd |") == FAIL
11497 			|| put_line(fd, fr->fr_layout == FR_COL
11498 						? "split" : "vsplit") == FAIL)
11499 		    return FAIL;
11500 		++count;
11501 	    }
11502 
11503 	/* Go back to the first window. */
11504 	if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
11505 			? "%dwincmd k" : "%dwincmd h", count) < 0
11506 						      || put_eol(fd) == FAIL))
11507 	    return FAIL;
11508 
11509 	/* Recursively create frames/windows in each window of this column or
11510 	 * row. */
11511 	frc = ses_skipframe(fr->fr_child);
11512 	while (frc != NULL)
11513 	{
11514 	    ses_win_rec(fd, frc);
11515 	    frc = ses_skipframe(frc->fr_next);
11516 	    /* Go to next window. */
11517 	    if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
11518 		return FAIL;
11519 	}
11520     }
11521     return OK;
11522 }
11523 
11524 /*
11525  * Skip frames that don't contain windows we want to save in the Session.
11526  * Returns NULL when there none.
11527  */
11528     static frame_T *
11529 ses_skipframe(frame_T *fr)
11530 {
11531     frame_T	*frc;
11532 
11533     for (frc = fr; frc != NULL; frc = frc->fr_next)
11534 	if (ses_do_frame(frc))
11535 	    break;
11536     return frc;
11537 }
11538 
11539 /*
11540  * Return TRUE if frame "fr" has a window somewhere that we want to save in
11541  * the Session.
11542  */
11543     static int
11544 ses_do_frame(frame_T *fr)
11545 {
11546     frame_T	*frc;
11547 
11548     if (fr->fr_layout == FR_LEAF)
11549 	return ses_do_win(fr->fr_win);
11550     for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
11551 	if (ses_do_frame(frc))
11552 	    return TRUE;
11553     return FALSE;
11554 }
11555 
11556 /*
11557  * Return non-zero if window "wp" is to be stored in the Session.
11558  */
11559     static int
11560 ses_do_win(win_T *wp)
11561 {
11562     if (wp->w_buffer->b_fname == NULL
11563 #ifdef FEAT_QUICKFIX
11564 	    /* When 'buftype' is "nofile" can't restore the window contents. */
11565 	    || bt_nofile(wp->w_buffer)
11566 #endif
11567        )
11568 	return (ssop_flags & SSOP_BLANK);
11569     if (bt_help(wp->w_buffer))
11570 	return (ssop_flags & SSOP_HELP);
11571     return TRUE;
11572 }
11573 
11574 /*
11575  * Write commands to "fd" to restore the view of a window.
11576  * Caller must make sure 'scrolloff' is zero.
11577  */
11578     static int
11579 put_view(
11580     FILE	*fd,
11581     win_T	*wp,
11582     int		add_edit,	/* add ":edit" command to view */
11583     unsigned	*flagp,		/* vop_flags or ssop_flags */
11584     int		current_arg_idx) /* current argument index of the window, use
11585 				  * -1 if unknown */
11586 {
11587     win_T	*save_curwin;
11588     int		f;
11589     int		do_cursor;
11590     int		did_next = FALSE;
11591 
11592     /* Always restore cursor position for ":mksession".  For ":mkview" only
11593      * when 'viewoptions' contains "cursor". */
11594     do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
11595 
11596     /*
11597      * Local argument list.
11598      */
11599     if (wp->w_alist == &global_alist)
11600     {
11601 	if (put_line(fd, "argglobal") == FAIL)
11602 	    return FAIL;
11603     }
11604     else
11605     {
11606 	if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
11607 			flagp == &vop_flags
11608 			|| !(*flagp & SSOP_CURDIR)
11609 			|| wp->w_localdir != NULL, flagp) == FAIL)
11610 	    return FAIL;
11611     }
11612 
11613     /* Only when part of a session: restore the argument index.  Some
11614      * arguments may have been deleted, check if the index is valid. */
11615     if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx < WARGCOUNT(wp)
11616 						      && flagp == &ssop_flags)
11617     {
11618 	if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
11619 		|| put_eol(fd) == FAIL)
11620 	    return FAIL;
11621 	did_next = TRUE;
11622     }
11623 
11624     /* Edit the file.  Skip this when ":next" already did it. */
11625     if (add_edit && (!did_next || wp->w_arg_idx_invalid))
11626     {
11627 	/*
11628 	 * Load the file.
11629 	 */
11630 	if (wp->w_buffer->b_ffname != NULL
11631 #ifdef FEAT_QUICKFIX
11632 		&& !bt_nofile(wp->w_buffer)
11633 #endif
11634 		)
11635 	{
11636 	    /*
11637 	     * Editing a file in this buffer: use ":edit file".
11638 	     * This may have side effects! (e.g., compressed or network file).
11639 	     */
11640 	    if (fputs("edit ", fd) < 0
11641 		    || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
11642 		return FAIL;
11643 	}
11644 	else
11645 	{
11646 	    /* No file in this buffer, just make it empty. */
11647 	    if (put_line(fd, "enew") == FAIL)
11648 		return FAIL;
11649 #ifdef FEAT_QUICKFIX
11650 	    if (wp->w_buffer->b_ffname != NULL)
11651 	    {
11652 		/* The buffer does have a name, but it's not a file name. */
11653 		if (fputs("file ", fd) < 0
11654 			|| ses_fname(fd, wp->w_buffer, flagp) == FAIL)
11655 		    return FAIL;
11656 	    }
11657 #endif
11658 	    do_cursor = FALSE;
11659 	}
11660     }
11661 
11662     /*
11663      * Local mappings and abbreviations.
11664      */
11665     if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
11666 					 && makemap(fd, wp->w_buffer) == FAIL)
11667 	return FAIL;
11668 
11669     /*
11670      * Local options.  Need to go to the window temporarily.
11671      * Store only local values when using ":mkview" and when ":mksession" is
11672      * used and 'sessionoptions' doesn't include "options".
11673      * Some folding options are always stored when "folds" is included,
11674      * otherwise the folds would not be restored correctly.
11675      */
11676     save_curwin = curwin;
11677     curwin = wp;
11678     curbuf = curwin->w_buffer;
11679     if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
11680 	f = makeset(fd, OPT_LOCAL,
11681 			     flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
11682 #ifdef FEAT_FOLDING
11683     else if (*flagp & SSOP_FOLDS)
11684 	f = makefoldset(fd);
11685 #endif
11686     else
11687 	f = OK;
11688     curwin = save_curwin;
11689     curbuf = curwin->w_buffer;
11690     if (f == FAIL)
11691 	return FAIL;
11692 
11693 #ifdef FEAT_FOLDING
11694     /*
11695      * Save Folds when 'buftype' is empty and for help files.
11696      */
11697     if ((*flagp & SSOP_FOLDS)
11698 	    && wp->w_buffer->b_ffname != NULL
11699 	    && (*wp->w_buffer->b_p_bt == NUL || bt_help(wp->w_buffer)))
11700     {
11701 	if (put_folds(fd, wp) == FAIL)
11702 	    return FAIL;
11703     }
11704 #endif
11705 
11706     /*
11707      * Set the cursor after creating folds, since that moves the cursor.
11708      */
11709     if (do_cursor)
11710     {
11711 
11712 	/* Restore the cursor line in the file and relatively in the
11713 	 * window.  Don't use "G", it changes the jumplist. */
11714 	if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
11715 		    (long)wp->w_cursor.lnum,
11716 		    (long)(wp->w_cursor.lnum - wp->w_topline),
11717 		    (long)wp->w_height / 2, (long)wp->w_height) < 0
11718 		|| put_eol(fd) == FAIL
11719 		|| put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
11720 		|| put_line(fd, "exe s:l") == FAIL
11721 		|| put_line(fd, "normal! zt") == FAIL
11722 		|| fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
11723 		|| put_eol(fd) == FAIL)
11724 	    return FAIL;
11725 	/* Restore the cursor column and left offset when not wrapping. */
11726 	if (wp->w_cursor.col == 0)
11727 	{
11728 	    if (put_line(fd, "normal! 0") == FAIL)
11729 		return FAIL;
11730 	}
11731 	else
11732 	{
11733 	    if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
11734 	    {
11735 		if (fprintf(fd,
11736 			  "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
11737 			    (long)wp->w_virtcol + 1,
11738 			    (long)(wp->w_virtcol - wp->w_leftcol),
11739 			    (long)wp->w_width / 2, (long)wp->w_width) < 0
11740 			|| put_eol(fd) == FAIL
11741 			|| put_line(fd, "if s:c > 0") == FAIL
11742 			|| fprintf(fd,
11743 			    "  exe 'normal! ' . s:c . '|zs' . %ld . '|'",
11744 			    (long)wp->w_virtcol + 1) < 0
11745 			|| put_eol(fd) == FAIL
11746 			|| put_line(fd, "else") == FAIL
11747 			|| fprintf(fd, "  normal! 0%d|", wp->w_virtcol + 1) < 0
11748 			|| put_eol(fd) == FAIL
11749 			|| put_line(fd, "endif") == FAIL)
11750 		    return FAIL;
11751 	    }
11752 	    else
11753 	    {
11754 		if (fprintf(fd, "normal! 0%d|", wp->w_virtcol + 1) < 0
11755 			|| put_eol(fd) == FAIL)
11756 		    return FAIL;
11757 	    }
11758 	}
11759     }
11760 
11761     /*
11762      * Local directory.
11763      */
11764     if (wp->w_localdir != NULL)
11765     {
11766 	if (fputs("lcd ", fd) < 0
11767 		|| ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
11768 		|| put_eol(fd) == FAIL)
11769 	    return FAIL;
11770 	did_lcd = TRUE;
11771     }
11772 
11773     return OK;
11774 }
11775 
11776 /*
11777  * Write an argument list to the session file.
11778  * Returns FAIL if writing fails.
11779  */
11780     static int
11781 ses_arglist(
11782     FILE	*fd,
11783     char	*cmd,
11784     garray_T	*gap,
11785     int		fullname,	/* TRUE: use full path name */
11786     unsigned	*flagp)
11787 {
11788     int		i;
11789     char_u	*buf = NULL;
11790     char_u	*s;
11791 
11792     if (fputs(cmd, fd) < 0 || put_eol(fd) == FAIL)
11793 	return FAIL;
11794     if (put_line(fd, "silent! argdel *") == FAIL)
11795 	return FAIL;
11796     for (i = 0; i < gap->ga_len; ++i)
11797     {
11798 	/* NULL file names are skipped (only happens when out of memory). */
11799 	s = alist_name(&((aentry_T *)gap->ga_data)[i]);
11800 	if (s != NULL)
11801 	{
11802 	    if (fullname)
11803 	    {
11804 		buf = alloc(MAXPATHL);
11805 		if (buf != NULL)
11806 		{
11807 		    (void)vim_FullName(s, buf, MAXPATHL, FALSE);
11808 		    s = buf;
11809 		}
11810 	    }
11811 	    if (fputs("$argadd ", fd) < 0
11812 		    || ses_put_fname(fd, s, flagp) == FAIL
11813 		    || put_eol(fd) == FAIL)
11814 	    {
11815 		vim_free(buf);
11816 		return FAIL;
11817 	    }
11818 	    vim_free(buf);
11819 	}
11820     }
11821     return OK;
11822 }
11823 
11824 /*
11825  * Write a buffer name to the session file.
11826  * Also ends the line.
11827  * Returns FAIL if writing fails.
11828  */
11829     static int
11830 ses_fname(FILE *fd, buf_T *buf, unsigned *flagp)
11831 {
11832     char_u	*name;
11833 
11834     /* Use the short file name if the current directory is known at the time
11835      * the session file will be sourced.
11836      * Don't do this for ":mkview", we don't know the current directory.
11837      * Don't do this after ":lcd", we don't keep track of what the current
11838      * directory is. */
11839     if (buf->b_sfname != NULL
11840 	    && flagp == &ssop_flags
11841 	    && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
11842 #ifdef FEAT_AUTOCHDIR
11843 	    && !p_acd
11844 #endif
11845 	    && !did_lcd)
11846 	name = buf->b_sfname;
11847     else
11848 	name = buf->b_ffname;
11849     if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
11850 	return FAIL;
11851     return OK;
11852 }
11853 
11854 /*
11855  * Write a file name to the session file.
11856  * Takes care of the "slash" option in 'sessionoptions' and escapes special
11857  * characters.
11858  * Returns FAIL if writing fails or out of memory.
11859  */
11860     static int
11861 ses_put_fname(FILE *fd, char_u *name, unsigned *flagp)
11862 {
11863     char_u	*sname;
11864     char_u	*p;
11865     int		retval = OK;
11866 
11867     sname = home_replace_save(NULL, name);
11868     if (sname == NULL)
11869 	return FAIL;
11870 
11871     if (*flagp & SSOP_SLASH)
11872     {
11873 	/* change all backslashes to forward slashes */
11874 	for (p = sname; *p != NUL; MB_PTR_ADV(p))
11875 	    if (*p == '\\')
11876 		*p = '/';
11877     }
11878 
11879     /* escape special characters */
11880     p = vim_strsave_fnameescape(sname, FALSE);
11881     vim_free(sname);
11882     if (p == NULL)
11883 	return FAIL;
11884 
11885     /* write the result */
11886     if (fputs((char *)p, fd) < 0)
11887 	retval = FAIL;
11888 
11889     vim_free(p);
11890     return retval;
11891 }
11892 
11893 /*
11894  * ":loadview [nr]"
11895  */
11896     static void
11897 ex_loadview(exarg_T *eap)
11898 {
11899     char_u	*fname;
11900 
11901     fname = get_view_file(*eap->arg);
11902     if (fname != NULL)
11903     {
11904 	do_source(fname, FALSE, DOSO_NONE);
11905 	vim_free(fname);
11906     }
11907 }
11908 
11909 /*
11910  * Get the name of the view file for the current buffer.
11911  */
11912     static char_u *
11913 get_view_file(int c)
11914 {
11915     int		len = 0;
11916     char_u	*p, *s;
11917     char_u	*retval;
11918     char_u	*sname;
11919 
11920     if (curbuf->b_ffname == NULL)
11921     {
11922 	EMSG(_(e_noname));
11923 	return NULL;
11924     }
11925     sname = home_replace_save(NULL, curbuf->b_ffname);
11926     if (sname == NULL)
11927 	return NULL;
11928 
11929     /*
11930      * We want a file name without separators, because we're not going to make
11931      * a directory.
11932      * "normal" path separator	-> "=+"
11933      * "="			-> "=="
11934      * ":" path separator	-> "=-"
11935      */
11936     for (p = sname; *p; ++p)
11937 	if (*p == '=' || vim_ispathsep(*p))
11938 	    ++len;
11939     retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
11940     if (retval != NULL)
11941     {
11942 	STRCPY(retval, p_vdir);
11943 	add_pathsep(retval);
11944 	s = retval + STRLEN(retval);
11945 	for (p = sname; *p; ++p)
11946 	{
11947 	    if (*p == '=')
11948 	    {
11949 		*s++ = '=';
11950 		*s++ = '=';
11951 	    }
11952 	    else if (vim_ispathsep(*p))
11953 	    {
11954 		*s++ = '=';
11955 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(VMS)
11956 		if (*p == ':')
11957 		    *s++ = '-';
11958 		else
11959 #endif
11960 		    *s++ = '+';
11961 	    }
11962 	    else
11963 		*s++ = *p;
11964 	}
11965 	*s++ = '=';
11966 	*s++ = c;
11967 	STRCPY(s, ".vim");
11968     }
11969 
11970     vim_free(sname);
11971     return retval;
11972 }
11973 
11974 #endif /* FEAT_SESSION */
11975 
11976 /*
11977  * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
11978  * Return FAIL for a write error.
11979  */
11980     int
11981 put_eol(FILE *fd)
11982 {
11983     if (
11984 #ifdef USE_CRNL
11985 	    (
11986 # ifdef MKSESSION_NL
11987 	     !mksession_nl &&
11988 # endif
11989 	     (putc('\r', fd) < 0)) ||
11990 #endif
11991 	    (putc('\n', fd) < 0))
11992 	return FAIL;
11993     return OK;
11994 }
11995 
11996 /*
11997  * Write a line to "fd".
11998  * Return FAIL for a write error.
11999  */
12000     int
12001 put_line(FILE *fd, char *s)
12002 {
12003     if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
12004 	return FAIL;
12005     return OK;
12006 }
12007 
12008 #ifdef FEAT_VIMINFO
12009 /*
12010  * ":rviminfo" and ":wviminfo".
12011  */
12012     static void
12013 ex_viminfo(
12014     exarg_T	*eap)
12015 {
12016     char_u	*save_viminfo;
12017 
12018     save_viminfo = p_viminfo;
12019     if (*p_viminfo == NUL)
12020 	p_viminfo = (char_u *)"'100";
12021     if (eap->cmdidx == CMD_rviminfo)
12022     {
12023 	if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
12024 				  | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
12025 	    EMSG(_("E195: Cannot open viminfo file for reading"));
12026     }
12027     else
12028 	write_viminfo(eap->arg, eap->forceit);
12029     p_viminfo = save_viminfo;
12030 }
12031 #endif
12032 
12033 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
12034 /*
12035  * Make a dialog message in "buff[DIALOG_MSG_SIZE]".
12036  * "format" must contain "%s".
12037  */
12038     void
12039 dialog_msg(char_u *buff, char *format, char_u *fname)
12040 {
12041     if (fname == NULL)
12042 	fname = (char_u *)_("Untitled");
12043     vim_snprintf((char *)buff, DIALOG_MSG_SIZE, format, fname);
12044 }
12045 #endif
12046 
12047 /*
12048  * ":behave {mswin,xterm}"
12049  */
12050     static void
12051 ex_behave(exarg_T *eap)
12052 {
12053     if (STRCMP(eap->arg, "mswin") == 0)
12054     {
12055 	set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
12056 	set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
12057 	set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
12058 	set_option_value((char_u *)"keymodel", 0L,
12059 					     (char_u *)"startsel,stopsel", 0);
12060     }
12061     else if (STRCMP(eap->arg, "xterm") == 0)
12062     {
12063 	set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
12064 	set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
12065 	set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
12066 	set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
12067     }
12068     else
12069 	EMSG2(_(e_invarg2), eap->arg);
12070 }
12071 
12072 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
12073 /*
12074  * Function given to ExpandGeneric() to obtain the possible arguments of the
12075  * ":behave {mswin,xterm}" command.
12076  */
12077     char_u *
12078 get_behave_arg(expand_T *xp UNUSED, int idx)
12079 {
12080     if (idx == 0)
12081 	return (char_u *)"mswin";
12082     if (idx == 1)
12083 	return (char_u *)"xterm";
12084     return NULL;
12085 }
12086 
12087 /*
12088  * Function given to ExpandGeneric() to obtain the possible arguments of the
12089  * ":messages {clear}" command.
12090  */
12091     char_u *
12092 get_messages_arg(expand_T *xp UNUSED, int idx)
12093 {
12094     if (idx == 0)
12095 	return (char_u *)"clear";
12096     return NULL;
12097 }
12098 #endif
12099 
12100     char_u *
12101 get_mapclear_arg(expand_T *xp UNUSED, int idx)
12102 {
12103     if (idx == 0)
12104 	return (char_u *)"<buffer>";
12105     return NULL;
12106 }
12107 
12108 #ifdef FEAT_AUTOCMD
12109 static int filetype_detect = FALSE;
12110 static int filetype_plugin = FALSE;
12111 static int filetype_indent = FALSE;
12112 
12113 /*
12114  * ":filetype [plugin] [indent] {on,off,detect}"
12115  * on: Load the filetype.vim file to install autocommands for file types.
12116  * off: Load the ftoff.vim file to remove all autocommands for file types.
12117  * plugin on: load filetype.vim and ftplugin.vim
12118  * plugin off: load ftplugof.vim
12119  * indent on: load filetype.vim and indent.vim
12120  * indent off: load indoff.vim
12121  */
12122     static void
12123 ex_filetype(exarg_T *eap)
12124 {
12125     char_u	*arg = eap->arg;
12126     int		plugin = FALSE;
12127     int		indent = FALSE;
12128 
12129     if (*eap->arg == NUL)
12130     {
12131 	/* Print current status. */
12132 	smsg((char_u *)"filetype detection:%s  plugin:%s  indent:%s",
12133 		filetype_detect ? "ON" : "OFF",
12134 		filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
12135 		filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
12136 	return;
12137     }
12138 
12139     /* Accept "plugin" and "indent" in any order. */
12140     for (;;)
12141     {
12142 	if (STRNCMP(arg, "plugin", 6) == 0)
12143 	{
12144 	    plugin = TRUE;
12145 	    arg = skipwhite(arg + 6);
12146 	    continue;
12147 	}
12148 	if (STRNCMP(arg, "indent", 6) == 0)
12149 	{
12150 	    indent = TRUE;
12151 	    arg = skipwhite(arg + 6);
12152 	    continue;
12153 	}
12154 	break;
12155     }
12156     if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
12157     {
12158 	if (*arg == 'o' || !filetype_detect)
12159 	{
12160 	    source_runtime((char_u *)FILETYPE_FILE, DIP_ALL);
12161 	    filetype_detect = TRUE;
12162 	    if (plugin)
12163 	    {
12164 		source_runtime((char_u *)FTPLUGIN_FILE, DIP_ALL);
12165 		filetype_plugin = TRUE;
12166 	    }
12167 	    if (indent)
12168 	    {
12169 		source_runtime((char_u *)INDENT_FILE, DIP_ALL);
12170 		filetype_indent = TRUE;
12171 	    }
12172 	}
12173 	if (*arg == 'd')
12174 	{
12175 	    (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE, NULL);
12176 	    do_modelines(0);
12177 	}
12178     }
12179     else if (STRCMP(arg, "off") == 0)
12180     {
12181 	if (plugin || indent)
12182 	{
12183 	    if (plugin)
12184 	    {
12185 		source_runtime((char_u *)FTPLUGOF_FILE, DIP_ALL);
12186 		filetype_plugin = FALSE;
12187 	    }
12188 	    if (indent)
12189 	    {
12190 		source_runtime((char_u *)INDOFF_FILE, DIP_ALL);
12191 		filetype_indent = FALSE;
12192 	    }
12193 	}
12194 	else
12195 	{
12196 	    source_runtime((char_u *)FTOFF_FILE, DIP_ALL);
12197 	    filetype_detect = FALSE;
12198 	}
12199     }
12200     else
12201 	EMSG2(_(e_invarg2), arg);
12202 }
12203 
12204 /*
12205  * ":setfiletype [FALLBACK] {name}"
12206  */
12207     static void
12208 ex_setfiletype(exarg_T *eap)
12209 {
12210     if (!did_filetype)
12211     {
12212 	char_u *arg = eap->arg;
12213 
12214 	if (STRNCMP(arg, "FALLBACK ", 9) == 0)
12215 	    arg += 9;
12216 
12217 	set_option_value((char_u *)"filetype", 0L, arg, OPT_LOCAL);
12218 	if (arg != eap->arg)
12219 	    did_filetype = FALSE;
12220     }
12221 }
12222 #endif
12223 
12224     static void
12225 ex_digraphs(exarg_T *eap UNUSED)
12226 {
12227 #ifdef FEAT_DIGRAPHS
12228     if (*eap->arg != NUL)
12229 	putdigraph(eap->arg);
12230     else
12231 	listdigraphs();
12232 #else
12233     EMSG(_("E196: No digraphs in this version"));
12234 #endif
12235 }
12236 
12237     static void
12238 ex_set(exarg_T *eap)
12239 {
12240     int		flags = 0;
12241 
12242     if (eap->cmdidx == CMD_setlocal)
12243 	flags = OPT_LOCAL;
12244     else if (eap->cmdidx == CMD_setglobal)
12245 	flags = OPT_GLOBAL;
12246 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
12247     if (cmdmod.browse && flags == 0)
12248 	ex_options(eap);
12249     else
12250 #endif
12251 	(void)do_set(eap->arg, flags);
12252 }
12253 
12254 #ifdef FEAT_SEARCH_EXTRA
12255 /*
12256  * ":nohlsearch"
12257  */
12258     static void
12259 ex_nohlsearch(exarg_T *eap UNUSED)
12260 {
12261     SET_NO_HLSEARCH(TRUE);
12262     redraw_all_later(SOME_VALID);
12263 }
12264 
12265 /*
12266  * ":[N]match {group} {pattern}"
12267  * Sets nextcmd to the start of the next command, if any.  Also called when
12268  * skipping commands to find the next command.
12269  */
12270     static void
12271 ex_match(exarg_T *eap)
12272 {
12273     char_u	*p;
12274     char_u	*g = NULL;
12275     char_u	*end;
12276     int		c;
12277     int		id;
12278 
12279     if (eap->line2 <= 3)
12280 	id = eap->line2;
12281     else
12282     {
12283 	EMSG(e_invcmd);
12284 	return;
12285     }
12286 
12287     /* First clear any old pattern. */
12288     if (!eap->skip)
12289 	match_delete(curwin, id, FALSE);
12290 
12291     if (ends_excmd(*eap->arg))
12292 	end = eap->arg;
12293     else if ((STRNICMP(eap->arg, "none", 4) == 0
12294 		&& (VIM_ISWHITE(eap->arg[4]) || ends_excmd(eap->arg[4]))))
12295 	end = eap->arg + 4;
12296     else
12297     {
12298 	p = skiptowhite(eap->arg);
12299 	if (!eap->skip)
12300 	    g = vim_strnsave(eap->arg, (int)(p - eap->arg));
12301 	p = skipwhite(p);
12302 	if (*p == NUL)
12303 	{
12304 	    /* There must be two arguments. */
12305 	    vim_free(g);
12306 	    EMSG2(_(e_invarg2), eap->arg);
12307 	    return;
12308 	}
12309 	end = skip_regexp(p + 1, *p, TRUE, NULL);
12310 	if (!eap->skip)
12311 	{
12312 	    if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
12313 	    {
12314 		vim_free(g);
12315 		eap->errmsg = e_trailing;
12316 		return;
12317 	    }
12318 	    if (*end != *p)
12319 	    {
12320 		vim_free(g);
12321 		EMSG2(_(e_invarg2), p);
12322 		return;
12323 	    }
12324 
12325 	    c = *end;
12326 	    *end = NUL;
12327 	    match_add(curwin, g, p + 1, 10, id, NULL, NULL);
12328 	    vim_free(g);
12329 	    *end = c;
12330 	}
12331     }
12332     eap->nextcmd = find_nextcmd(end);
12333 }
12334 #endif
12335 
12336 #ifdef FEAT_CRYPT
12337 /*
12338  * ":X": Get crypt key
12339  */
12340     static void
12341 ex_X(exarg_T *eap UNUSED)
12342 {
12343     crypt_check_current_method();
12344     (void)crypt_get_key(TRUE, TRUE);
12345 }
12346 #endif
12347 
12348 #ifdef FEAT_FOLDING
12349     static void
12350 ex_fold(exarg_T *eap)
12351 {
12352     if (foldManualAllowed(TRUE))
12353 	foldCreate(eap->line1, eap->line2);
12354 }
12355 
12356     static void
12357 ex_foldopen(exarg_T *eap)
12358 {
12359     opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
12360 							 eap->forceit, FALSE);
12361 }
12362 
12363     static void
12364 ex_folddo(exarg_T *eap)
12365 {
12366     linenr_T	lnum;
12367 
12368 #ifdef FEAT_CLIPBOARD
12369     start_global_changes();
12370 #endif
12371 
12372     /* First set the marks for all lines closed/open. */
12373     for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
12374 	if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
12375 	    ml_setmarked(lnum);
12376 
12377     /* Execute the command on the marked lines. */
12378     global_exe(eap->arg);
12379     ml_clearmarked();	   /* clear rest of the marks */
12380 #ifdef FEAT_CLIPBOARD
12381     end_global_changes();
12382 #endif
12383 }
12384 #endif
12385