xref: /vim-8.2.3635/src/ex_docmd.c (revision 15d0a8c7)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * ex_docmd.c: functions for executing an Ex command line.
12  */
13 
14 #include "vim.h"
15 
16 #ifdef HAVE_FCNTL_H
17 # include <fcntl.h>	    /* for chdir() */
18 #endif
19 
20 static int	quitmore = 0;
21 static int	ex_pressedreturn = FALSE;
22 #ifndef FEAT_PRINTER
23 # define ex_hardcopy	ex_ni
24 #endif
25 
26 #ifdef FEAT_USR_CMDS
27 typedef struct ucmd
28 {
29     char_u	*uc_name;	/* The command name */
30     long_u	uc_argt;	/* The argument type */
31     char_u	*uc_rep;	/* The command's replacement string */
32     long	uc_def;		/* The default value for a range/count */
33     scid_T	uc_scriptID;	/* SID where the command was defined */
34     int		uc_compl;	/* completion type */
35 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
36     char_u	*uc_compl_arg;	/* completion argument if any */
37 # endif
38 } ucmd_T;
39 
40 #define UC_BUFFER	1	/* -buffer: local to current buffer */
41 
42 garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL};
43 
44 #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
45 #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
46 
47 static void do_ucmd __ARGS((exarg_T *eap));
48 static void ex_command __ARGS((exarg_T *eap));
49 static void ex_comclear __ARGS((exarg_T *eap));
50 static void ex_delcommand __ARGS((exarg_T *eap));
51 # ifdef FEAT_CMDL_COMPL
52 static char_u *get_user_command_name __ARGS((int idx));
53 # endif
54 
55 #else
56 # define ex_command	ex_ni
57 # define ex_comclear	ex_ni
58 # define ex_delcommand	ex_ni
59 #endif
60 
61 #ifdef FEAT_EVAL
62 static char_u	*do_one_cmd __ARGS((char_u **, int, struct condstack *, char_u *(*getline)(int, void *, int), void *cookie));
63 #else
64 static char_u	*do_one_cmd __ARGS((char_u **, int, char_u *(*getline)(int, void *, int), void *cookie));
65 static int	if_level = 0;		/* depth in :if */
66 #endif
67 static int	checkforcmd __ARGS((char_u **pp, char *cmd, int len));
68 static char_u	*find_command __ARGS((exarg_T *eap, int *full));
69 
70 static void	ex_abbreviate __ARGS((exarg_T *eap));
71 static void	ex_map __ARGS((exarg_T *eap));
72 static void	ex_unmap __ARGS((exarg_T *eap));
73 static void	ex_mapclear __ARGS((exarg_T *eap));
74 static void	ex_abclear __ARGS((exarg_T *eap));
75 #ifndef FEAT_MENU
76 # define ex_emenu		ex_ni
77 # define ex_menu		ex_ni
78 # define ex_menutranslate	ex_ni
79 #endif
80 #ifdef FEAT_AUTOCMD
81 static void	ex_autocmd __ARGS((exarg_T *eap));
82 static void	ex_doautocmd __ARGS((exarg_T *eap));
83 #else
84 # define ex_autocmd		ex_ni
85 # define ex_doautocmd		ex_ni
86 # define ex_doautoall		ex_ni
87 #endif
88 #ifdef FEAT_LISTCMDS
89 static void	ex_bunload __ARGS((exarg_T *eap));
90 static void	ex_buffer __ARGS((exarg_T *eap));
91 static void	ex_bmodified __ARGS((exarg_T *eap));
92 static void	ex_bnext __ARGS((exarg_T *eap));
93 static void	ex_bprevious __ARGS((exarg_T *eap));
94 static void	ex_brewind __ARGS((exarg_T *eap));
95 static void	ex_blast __ARGS((exarg_T *eap));
96 #else
97 # define ex_bunload		ex_ni
98 # define ex_buffer		ex_ni
99 # define ex_bmodified		ex_ni
100 # define ex_bnext		ex_ni
101 # define ex_bprevious		ex_ni
102 # define ex_brewind		ex_ni
103 # define ex_blast		ex_ni
104 # define buflist_list		ex_ni
105 # define ex_checktime		ex_ni
106 #endif
107 #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS)
108 # define ex_buffer_all		ex_ni
109 #endif
110 static char_u	*getargcmd __ARGS((char_u **));
111 static char_u	*skip_cmd_arg __ARGS((char_u *p, int rembs));
112 static int	getargopt __ARGS((exarg_T *eap));
113 #ifndef FEAT_QUICKFIX
114 # define ex_make		ex_ni
115 # define ex_cc			ex_ni
116 # define ex_cnext		ex_ni
117 # define ex_cfile		ex_ni
118 # define qf_list		ex_ni
119 # define qf_age			ex_ni
120 # define ex_helpgrep		ex_ni
121 #endif
122 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS)
123 # define ex_cclose		ex_ni
124 # define ex_copen		ex_ni
125 # define ex_cwindow		ex_ni
126 #endif
127 
128 static int	check_more __ARGS((int, int));
129 static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file));
130 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
131 	|| !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME)
132 static void	ex_script_ni __ARGS((exarg_T *eap));
133 #endif
134 static char_u	*invalid_range __ARGS((exarg_T *eap));
135 static void	correct_range __ARGS((exarg_T *eap));
136 static char_u	*repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep));
137 static void	ex_highlight __ARGS((exarg_T *eap));
138 static void	ex_colorscheme __ARGS((exarg_T *eap));
139 static void	ex_quit __ARGS((exarg_T *eap));
140 static void	ex_cquit __ARGS((exarg_T *eap));
141 static void	ex_quit_all __ARGS((exarg_T *eap));
142 #ifdef FEAT_WINDOWS
143 static void	ex_close __ARGS((exarg_T *eap));
144 static void	ex_win_close __ARGS((exarg_T *eap, win_T *win));
145 static void	ex_only __ARGS((exarg_T *eap));
146 static void	ex_all __ARGS((exarg_T *eap));
147 static void	ex_resize __ARGS((exarg_T *eap));
148 static void	ex_stag __ARGS((exarg_T *eap));
149 #else
150 # define ex_close		ex_ni
151 # define ex_only		ex_ni
152 # define ex_all			ex_ni
153 # define ex_resize		ex_ni
154 # define ex_splitview		ex_ni
155 # define ex_stag		ex_ni
156 #endif
157 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
158 static void	ex_pclose __ARGS((exarg_T *eap));
159 static void	ex_ptag __ARGS((exarg_T *eap));
160 static void	ex_pedit __ARGS((exarg_T *eap));
161 #else
162 # define ex_pclose		ex_ni
163 # define ex_ptag		ex_ni
164 # define ex_pedit		ex_ni
165 #endif
166 static void	ex_hide __ARGS((exarg_T *eap));
167 static void	ex_stop __ARGS((exarg_T *eap));
168 static void	ex_exit __ARGS((exarg_T *eap));
169 static void	ex_print __ARGS((exarg_T *eap));
170 #ifdef FEAT_BYTEOFF
171 static void	ex_goto __ARGS((exarg_T *eap));
172 #else
173 # define ex_goto		ex_ni
174 #endif
175 static void	ex_shell __ARGS((exarg_T *eap));
176 static void	ex_preserve __ARGS((exarg_T *eap));
177 static void	ex_recover __ARGS((exarg_T *eap));
178 #ifndef FEAT_LISTCMDS
179 # define ex_argedit		ex_ni
180 # define ex_argadd		ex_ni
181 # define ex_argdelete		ex_ni
182 # define ex_listdo		ex_ni
183 #endif
184 static void	ex_mode __ARGS((exarg_T *eap));
185 static void	ex_wrongmodifier __ARGS((exarg_T *eap));
186 static void	ex_find __ARGS((exarg_T *eap));
187 static void	ex_edit __ARGS((exarg_T *eap));
188 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
189 # define ex_drop		ex_ni
190 #endif
191 #ifndef FEAT_GUI
192 # define ex_gui			ex_nogui
193 static void	ex_nogui __ARGS((exarg_T *eap));
194 #endif
195 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
196 static void	ex_tearoff __ARGS((exarg_T *eap));
197 #else
198 # define ex_tearoff		ex_ni
199 #endif
200 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_KDE) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
201 static void	ex_popup __ARGS((exarg_T *eap));
202 #else
203 # define ex_popup		ex_ni
204 #endif
205 #ifndef FEAT_GUI_MSWIN
206 # define ex_simalt		ex_ni
207 #endif
208 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF) && !defined(FEAT_GUI_KDE)
209 # define gui_mch_find_dialog	ex_ni
210 # define gui_mch_replace_dialog ex_ni
211 #endif
212 #if !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_KDE)
213 # define ex_helpfind		ex_ni
214 #endif
215 #ifndef FEAT_CSCOPE
216 # define do_cscope		ex_ni
217 # define do_scscope		ex_ni
218 # define do_cstag		ex_ni
219 #endif
220 #ifndef FEAT_SYN_HL
221 # define ex_syntax		ex_ni
222 #endif
223 #ifndef FEAT_MZSCHEME
224 # define ex_mzscheme		ex_script_ni
225 # define ex_mzfile		ex_ni
226 #endif
227 #ifndef FEAT_PERL
228 # define ex_perl		ex_script_ni
229 # define ex_perldo		ex_ni
230 #endif
231 #ifndef FEAT_PYTHON
232 # define ex_python		ex_script_ni
233 # define ex_pyfile		ex_ni
234 #endif
235 #ifndef FEAT_TCL
236 # define ex_tcl			ex_script_ni
237 # define ex_tcldo		ex_ni
238 # define ex_tclfile		ex_ni
239 #endif
240 #ifndef FEAT_RUBY
241 # define ex_ruby		ex_script_ni
242 # define ex_rubydo		ex_ni
243 # define ex_rubyfile		ex_ni
244 #endif
245 #ifndef FEAT_SNIFF
246 # define ex_sniff		ex_ni
247 #endif
248 #ifndef FEAT_KEYMAP
249 # define ex_loadkeymap		ex_ni
250 #endif
251 static void	ex_swapname __ARGS((exarg_T *eap));
252 static void	ex_syncbind __ARGS((exarg_T *eap));
253 static void	ex_read __ARGS((exarg_T *eap));
254 static void	ex_cd __ARGS((exarg_T *eap));
255 static void	ex_pwd __ARGS((exarg_T *eap));
256 static void	ex_equal __ARGS((exarg_T *eap));
257 static void	ex_sleep __ARGS((exarg_T *eap));
258 static void	do_exmap __ARGS((exarg_T *eap, int isabbrev));
259 static void	ex_winsize __ARGS((exarg_T *eap));
260 #ifdef FEAT_WINDOWS
261 static void	ex_wincmd __ARGS((exarg_T *eap));
262 #else
263 # define ex_wincmd	    ex_ni
264 #endif
265 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
266 static void	ex_winpos __ARGS((exarg_T *eap));
267 #else
268 # define ex_winpos	    ex_ni
269 #endif
270 static void	ex_operators __ARGS((exarg_T *eap));
271 static void	ex_put __ARGS((exarg_T *eap));
272 static void	ex_copymove __ARGS((exarg_T *eap));
273 static void	ex_submagic __ARGS((exarg_T *eap));
274 static void	ex_join __ARGS((exarg_T *eap));
275 static void	ex_at __ARGS((exarg_T *eap));
276 static void	ex_bang __ARGS((exarg_T *eap));
277 static void	ex_undo __ARGS((exarg_T *eap));
278 static void	ex_redo __ARGS((exarg_T *eap));
279 static void	ex_redir __ARGS((exarg_T *eap));
280 static void	ex_redraw __ARGS((exarg_T *eap));
281 static void	ex_redrawstatus __ARGS((exarg_T *eap));
282 static void	close_redir __ARGS((void));
283 static void	ex_mkrc __ARGS((exarg_T *eap));
284 static void	ex_mark __ARGS((exarg_T *eap));
285 #ifdef FEAT_USR_CMDS
286 static char_u	*uc_fun_cmd __ARGS((void));
287 #endif
288 #ifdef FEAT_EX_EXTRA
289 static void	ex_normal __ARGS((exarg_T *eap));
290 static void	ex_startinsert __ARGS((exarg_T *eap));
291 static void	ex_stopinsert __ARGS((exarg_T *eap));
292 #else
293 # define ex_normal		ex_ni
294 # define ex_align		ex_ni
295 # define ex_retab		ex_ni
296 # define ex_startinsert		ex_ni
297 # define ex_stopinsert		ex_ni
298 # define ex_helptags		ex_ni
299 #endif
300 #ifdef FEAT_FIND_ID
301 static void	ex_checkpath __ARGS((exarg_T *eap));
302 static void	ex_findpat __ARGS((exarg_T *eap));
303 #else
304 # define ex_findpat		ex_ni
305 # define ex_checkpath		ex_ni
306 #endif
307 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
308 static void	ex_psearch __ARGS((exarg_T *eap));
309 #else
310 # define ex_psearch		ex_ni
311 #endif
312 static void	ex_tag __ARGS((exarg_T *eap));
313 static void	ex_tag_cmd __ARGS((exarg_T *eap, char_u *name));
314 #ifndef FEAT_EVAL
315 # define ex_scriptnames		ex_ni
316 # define ex_finish		ex_ni
317 # define ex_echo		ex_ni
318 # define ex_echohl		ex_ni
319 # define ex_execute		ex_ni
320 # define ex_call		ex_ni
321 # define ex_if			ex_ni
322 # define ex_endif		ex_ni
323 # define ex_else		ex_ni
324 # define ex_while		ex_ni
325 # define ex_continue		ex_ni
326 # define ex_break		ex_ni
327 # define ex_endwhile		ex_ni
328 # define ex_throw		ex_ni
329 # define ex_try			ex_ni
330 # define ex_catch		ex_ni
331 # define ex_finally		ex_ni
332 # define ex_endtry		ex_ni
333 # define ex_endfunction		ex_ni
334 # define ex_let			ex_ni
335 # define ex_unlet		ex_ni
336 # define ex_function		ex_ni
337 # define ex_delfunction		ex_ni
338 # define ex_return		ex_ni
339 #endif
340 static char_u	*arg_all __ARGS((void));
341 #ifdef FEAT_SESSION
342 static int	makeopens __ARGS((FILE *fd, char_u *dirnow));
343 static int	put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp));
344 static void	ex_loadview __ARGS((exarg_T *eap));
345 static char_u	*get_view_file __ARGS((int c));
346 #else
347 # define ex_loadview		ex_ni
348 #endif
349 #ifndef FEAT_EVAL
350 # define ex_compiler		ex_ni
351 #endif
352 #ifdef FEAT_VIMINFO
353 static void	ex_viminfo __ARGS((exarg_T *eap));
354 #else
355 # define ex_viminfo		ex_ni
356 #endif
357 static void	ex_behave __ARGS((exarg_T *eap));
358 #ifdef FEAT_AUTOCMD
359 static void	ex_filetype __ARGS((exarg_T *eap));
360 static void	ex_setfiletype  __ARGS((exarg_T *eap));
361 #else
362 # define ex_filetype		ex_ni
363 # define ex_setfiletype		ex_ni
364 #endif
365 #ifndef FEAT_DIFF
366 # define ex_diffoff		ex_ni
367 # define ex_diffpatch		ex_ni
368 # define ex_diffgetput		ex_ni
369 # define ex_diffsplit		ex_ni
370 # define ex_diffthis		ex_ni
371 # define ex_diffupdate		ex_ni
372 #endif
373 static void	ex_digraphs __ARGS((exarg_T *eap));
374 static void	ex_set __ARGS((exarg_T *eap));
375 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
376 # define ex_options		ex_ni
377 #endif
378 #ifdef FEAT_SEARCH_EXTRA
379 static void	ex_nohlsearch __ARGS((exarg_T *eap));
380 static void	ex_match __ARGS((exarg_T *eap));
381 #else
382 # define ex_nohlsearch		ex_ni
383 # define ex_match		ex_ni
384 #endif
385 #ifdef FEAT_CRYPT
386 static void	ex_X __ARGS((exarg_T *eap));
387 #else
388 # define ex_X			ex_ni
389 #endif
390 #ifdef FEAT_FOLDING
391 static void	ex_fold __ARGS((exarg_T *eap));
392 static void	ex_foldopen __ARGS((exarg_T *eap));
393 static void	ex_folddo __ARGS((exarg_T *eap));
394 #else
395 # define ex_fold		ex_ni
396 # define ex_foldopen		ex_ni
397 # define ex_folddo		ex_ni
398 #endif
399 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
400 	&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
401 # define ex_language		ex_ni
402 #endif
403 #ifndef FEAT_SIGNS
404 # define ex_sign		ex_ni
405 #endif
406 #ifndef FEAT_SUN_WORKSHOP
407 # define ex_wsverb		ex_ni
408 #endif
409 
410 #ifndef FEAT_EVAL
411 # define ex_debug		ex_ni
412 # define ex_breakadd		ex_ni
413 # define ex_debuggreedy		ex_ni
414 # define ex_breakdel		ex_ni
415 # define ex_breaklist		ex_ni
416 #endif
417 
418 #ifndef FEAT_CMDHIST
419 # define ex_history		ex_ni
420 #endif
421 #ifndef FEAT_JUMPLIST
422 # define ex_jumps		ex_ni
423 # define ex_changes		ex_ni
424 #endif
425 
426 /*
427  * Declare cmdnames[].
428  */
429 #define DO_DECLARE_EXCMD
430 #include "ex_cmds.h"
431 
432 /*
433  * Table used to quickly search for a command, based on its first character.
434  */
435 cmdidx_T cmdidxs[27] =
436 {
437 	CMD_append,
438 	CMD_buffer,
439 	CMD_change,
440 	CMD_delete,
441 	CMD_edit,
442 	CMD_file,
443 	CMD_global,
444 	CMD_help,
445 	CMD_insert,
446 	CMD_join,
447 	CMD_k,
448 	CMD_list,
449 	CMD_move,
450 	CMD_next,
451 	CMD_open,
452 	CMD_print,
453 	CMD_quit,
454 	CMD_read,
455 	CMD_substitute,
456 	CMD_t,
457 	CMD_undo,
458 	CMD_vglobal,
459 	CMD_write,
460 	CMD_xit,
461 	CMD_yank,
462 	CMD_z,
463 	CMD_bang
464 };
465 
466 static char_u dollar_command[2] = {'$', 0};
467 
468 
469 #ifdef FEAT_EVAL
470 /* Struct for storing a line inside a while loop */
471 typedef struct
472 {
473     char_u	*line;		/* command line */
474     linenr_T	lnum;		/* sourcing_lnum of the line */
475 } wcmd_T;
476 
477 /*
478  * Structure used to store info for line position in a while loop.
479  * This is required, because do_one_cmd() may invoke ex_function(), which
480  * reads more lines that may come from the while loop.
481  */
482 struct while_cookie
483 {
484     garray_T	*lines_gap;		/* growarray with line info */
485     int		current_line;		/* last read line from growarray */
486     int		repeating;		/* TRUE when looping a second time */
487     /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
488     char_u	*(*getline) __ARGS((int, void *, int));
489     void	*cookie;
490 };
491 
492 static char_u	*get_while_line __ARGS((int c, void *cookie, int indent));
493 static int	store_while_line __ARGS((garray_T *gap, char_u *line));
494 static void	free_cmdlines __ARGS((garray_T *gap));
495 
496 /* Struct to save a few things while debugging.  Used in do_cmdline() only. */
497 struct dbg_stuff
498 {
499     int		trylevel;
500     int		force_abort;
501     except_T	*caught_stack;
502     char_u	*vv_exception;
503     char_u	*vv_throwpoint;
504     int		did_emsg;
505     int		got_int;
506     int		did_throw;
507     int		need_rethrow;
508     int		check_cstack;
509     except_T	*current_exception;
510 };
511 
512 static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp));
513 static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp));
514 
515     static void
516 save_dbg_stuff(dsp)
517     struct dbg_stuff *dsp;
518 {
519     dsp->trylevel	= trylevel;		trylevel = 0;
520     dsp->force_abort	= force_abort;		force_abort = FALSE;
521     dsp->caught_stack	= caught_stack;		caught_stack = NULL;
522     dsp->vv_exception	= v_exception(NULL);
523     dsp->vv_throwpoint	= v_throwpoint(NULL);
524 
525     /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
526     dsp->did_emsg	= did_emsg;		did_emsg     = FALSE;
527     dsp->got_int	= got_int;		got_int	     = FALSE;
528     dsp->did_throw	= did_throw;		did_throw    = FALSE;
529     dsp->need_rethrow	= need_rethrow;		need_rethrow = FALSE;
530     dsp->check_cstack	= check_cstack;		check_cstack = FALSE;
531     dsp->current_exception = current_exception;	current_exception = NULL;
532 }
533 
534     static void
535 restore_dbg_stuff(dsp)
536     struct dbg_stuff *dsp;
537 {
538     suppress_errthrow = FALSE;
539     trylevel = dsp->trylevel;
540     force_abort = dsp->force_abort;
541     caught_stack = dsp->caught_stack;
542     (void)v_exception(dsp->vv_exception);
543     (void)v_throwpoint(dsp->vv_throwpoint);
544     did_emsg = dsp->did_emsg;
545     got_int = dsp->got_int;
546     did_throw = dsp->did_throw;
547     need_rethrow = dsp->need_rethrow;
548     check_cstack = dsp->check_cstack;
549     current_exception = dsp->current_exception;
550 }
551 #endif
552 
553 
554 /*
555  * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
556  * command is given.
557  */
558     void
559 do_exmode(improved)
560     int		improved;	    /* TRUE for "improved Ex" mode */
561 {
562     int		save_msg_scroll;
563     int		prev_msg_row;
564     linenr_T	prev_line;
565 
566     save_msg_scroll = msg_scroll;
567     ++RedrawingDisabled;	    /* don't redisplay the window */
568     ++no_wait_return;		    /* don't wait for return */
569     if (improved)
570 	exmode_active = EXMODE_VIM;
571     else
572     {
573 	settmode(TMODE_COOK);
574 	exmode_active = EXMODE_NORMAL;
575     }
576 
577     State = NORMAL;
578 #ifdef FEAT_GUI
579     /* Ignore scrollbar and mouse events in Ex mode */
580     ++hold_gui_events;
581 #endif
582 #ifdef FEAT_SNIFF
583     want_sniff_request = 0;    /* No K_SNIFF wanted */
584 #endif
585 
586     MSG(_("Entering Ex mode.  Type \"visual\" to go to Normal mode."));
587     while (exmode_active)
588     {
589 	msg_scroll = TRUE;
590 	need_wait_return = FALSE;
591 	ex_pressedreturn = FALSE;
592 	ex_no_reprint = FALSE;
593 	prev_msg_row = msg_row;
594 	prev_line = curwin->w_cursor.lnum;
595 #ifdef FEAT_SNIFF
596 	ProcessSniffRequests();
597 #endif
598 	if (improved)
599 	{
600 	    cmdline_row = msg_row;
601 	    do_cmdline(NULL, getexline, NULL, 0);
602 	}
603 	else
604 	    do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
605 	lines_left = Rows - 1;
606 
607 	if (prev_line != curwin->w_cursor.lnum && !ex_no_reprint)
608 	{
609 	    if (ex_pressedreturn)
610 	    {
611 		/* go up one line, to overwrite the ":<CR>" line, so the
612 		 * output doensn't contain empty lines. */
613 		msg_row = prev_msg_row;
614 		if (prev_msg_row == Rows - 1)
615 		    msg_row--;
616 	    }
617 	    msg_col = 0;
618 	    print_line_no_prefix(curwin->w_cursor.lnum, FALSE);
619 	    msg_clr_eos();
620 	}
621 	else if (ex_pressedreturn)	/* must be at EOF */
622 	    EMSG(_("E501: At end-of-file"));
623     }
624 
625 #ifdef FEAT_GUI
626     --hold_gui_events;
627 #endif
628     if (!improved)
629 	settmode(TMODE_RAW);
630     --RedrawingDisabled;
631     --no_wait_return;
632     update_screen(CLEAR);
633     need_wait_return = FALSE;
634     msg_scroll = save_msg_scroll;
635 }
636 
637 /*
638  * Execute a simple command line.  Used for translated commands like "*".
639  */
640     int
641 do_cmdline_cmd(cmd)
642     char_u	*cmd;
643 {
644     return do_cmdline(cmd, NULL, NULL,
645 				   DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
646 }
647 
648 /*
649  * do_cmdline(): execute one Ex command line
650  *
651  * 1. Execute "cmdline" when it is not NULL.
652  *    If "cmdline" is NULL, or more lines are needed, getline() is used.
653  * 2. Split up in parts separated with '|'.
654  *
655  * This function can be called recursively!
656  *
657  * flags:
658  * DOCMD_VERBOSE  - The command will be included in the error message.
659  * DOCMD_NOWAIT   - Don't call wait_return() and friends.
660  * DOCMD_REPEAT   - Repeat execution until getline() returns NULL.
661  * DOCMD_KEYTYPED - Don't reset KeyTyped.
662  * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
663  * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
664  *
665  * return FAIL if cmdline could not be executed, OK otherwise
666  */
667     int
668 do_cmdline(cmdline, getline, cookie, flags)
669     char_u	*cmdline;
670     char_u	*(*getline) __ARGS((int, void *, int));
671     void	*cookie;		/* argument for getline() */
672     int		flags;
673 {
674     char_u	*next_cmdline;		/* next cmd to execute */
675     char_u	*cmdline_copy = NULL;	/* copy of cmd line */
676     int		used_getline = FALSE;	/* used "getline" to obtain command */
677     static int	recursive = 0;		/* recursive depth */
678     int		msg_didout_before_start = 0;
679     int		count = 0;		/* line number count */
680     int		did_inc = FALSE;	/* incremented RedrawingDisabled */
681     int		retval = OK;
682 #ifdef FEAT_EVAL
683     struct condstack cstack;		/* conditional stack */
684     garray_T	lines_ga;		/* keep lines for ":while" */
685     int		current_line = 0;	/* active line in lines_ga */
686     char_u	*fname = NULL;		/* function or script name */
687     linenr_T	*breakpoint = NULL;	/* ptr to breakpoint field in cookie */
688     int		*dbg_tick = NULL;	/* ptr to dbg_tick field in cookie */
689     struct dbg_stuff debug_saved;	/* saved things for debug mode */
690     int		initial_trylevel;
691     struct msglist	**saved_msg_list = NULL;
692     struct msglist	*private_msg_list;
693 
694     /* "getline" and "cookie" passed to do_one_cmd() */
695     char_u	*(*cmd_getline) __ARGS((int, void *, int));
696     void	*cmd_cookie;
697     struct while_cookie cmd_while_cookie;
698     void	*real_cookie;
699 #else
700 # define cmd_getline getline
701 # define cmd_cookie cookie
702 #endif
703     static int	call_depth = 0;		/* recursiveness */
704 
705 #ifdef FEAT_EVAL
706     /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
707      * location for storing error messages to be converted to an exception.
708      * This ensures that the do_errthrow() call in do_one_cmd() does not combine
709      * the messages stored by an earlier invocation of do_one_cmd() with the
710      * command name of the later one.  This would happen when BufWritePost
711      * autocommands are executed after a write error. */
712     saved_msg_list = msg_list;
713     msg_list = &private_msg_list;
714     private_msg_list = NULL;
715 #endif
716 
717     /* It's possible to create an endless loop with ":execute", catch that
718      * here.  The value of 200 allows nested function calls, ":source", etc. */
719     if (call_depth == 200)
720     {
721 	EMSG(_("E169: Command too recursive"));
722 #ifdef FEAT_EVAL
723 	/* When converting to an exception, we do not include the command name
724 	 * since this is not an error of the specific command. */
725 	do_errthrow((struct condstack *)NULL, (char_u *)NULL);
726 	msg_list = saved_msg_list;
727 #endif
728 	return FAIL;
729     }
730     ++call_depth;
731 
732 #ifdef FEAT_EVAL
733     cstack.cs_idx = -1;
734     cstack.cs_whilelevel = 0;
735     cstack.cs_trylevel = 0;
736     cstack.cs_emsg_silent_list = NULL;
737     cstack.cs_had_while = FALSE;
738     cstack.cs_had_endwhile = FALSE;
739     cstack.cs_had_continue = FALSE;
740     cstack.cs_had_finally = FALSE;
741     ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
742 
743     real_cookie = getline_cookie(getline, cookie);
744 
745     /* Inside a function use a higher nesting level. */
746     if (getline_equal(getline, cookie, get_func_line)
747 			       && ex_nesting_level == func_level(real_cookie))
748 	++ex_nesting_level;
749 
750     /* Get the function or script name and the address where the next breakpoint
751      * line and the debug tick for a function or script are stored. */
752     if (getline_equal(getline, cookie, get_func_line))
753     {
754 	fname = func_name(real_cookie);
755 	breakpoint = func_breakpoint(real_cookie);
756 	dbg_tick = func_dbg_tick(real_cookie);
757     }
758     else if (getline_equal(getline, cookie, getsourceline))
759     {
760 	fname = sourcing_name;
761 	breakpoint = source_breakpoint(real_cookie);
762 	dbg_tick = source_dbg_tick(real_cookie);
763     }
764 
765     /*
766      * Initialize "force_abort"  and "suppress_errthrow" at the top level.
767      */
768     if (!recursive)
769     {
770 	force_abort = FALSE;
771 	suppress_errthrow = FALSE;
772     }
773 
774     /*
775      * If requested, store and reset the global values controlling the
776      * exception handling (used when debugging).
777      */
778     else if (flags & DOCMD_EXCRESET)
779 	save_dbg_stuff(&debug_saved);
780 
781     initial_trylevel = trylevel;
782 
783     /*
784      * "did_throw" will be set to TRUE when an exception is being thrown.
785      */
786     did_throw = FALSE;
787 #endif
788     /*
789      * "did_emsg" will be set to TRUE when emsg() is used, in which case we
790      * cancel the whole command line, and any if/endif while/endwhile loop.
791      * If force_abort is set, we cancel everything.
792      */
793     did_emsg = FALSE;
794 
795     /*
796      * KeyTyped is only set when calling vgetc().  Reset it here when not
797      * calling vgetc() (sourced command lines).
798      */
799     if (!(flags & DOCMD_KEYTYPED) && !getline_equal(getline, cookie, getexline))
800 	KeyTyped = FALSE;
801 
802     /*
803      * Continue executing command lines:
804      * - when inside an ":if" or ":while"
805      * - for multiple commands on one line, separated with '|'
806      * - when repeating until there are no more lines (for ":source")
807      */
808     next_cmdline = cmdline;
809     do
810     {
811 	/* stop skipping cmds for an error msg after all endifs and endwhiles */
812 	if (next_cmdline == NULL
813 #ifdef FEAT_EVAL
814 		&& !force_abort
815 		&& cstack.cs_idx < 0
816 		&& !(getline_equal(getline, cookie, get_func_line)
817 					       && func_has_abort(real_cookie))
818 #endif
819 							)
820 	    did_emsg = FALSE;
821 
822 	/*
823 	 * 1. If repeating a line with ":while", get a line from lines_ga.
824 	 * 2. If no line given: Get an allocated line with getline().
825 	 * 3. If a line is given: Make a copy, so we can mess with it.
826 	 */
827 
828 #ifdef FEAT_EVAL
829 	/* 1. If repeating, get a previous line from lines_ga. */
830 	if (cstack.cs_whilelevel && current_line < lines_ga.ga_len)
831 	{
832 	    /* Each '|' separated command is stored separately in lines_ga, to
833 	     * be able to jump to it.  Don't use next_cmdline now. */
834 	    vim_free(cmdline_copy);
835 	    cmdline_copy = NULL;
836 
837 	    /* Check if a function has returned or, unless it has an unclosed
838 	     * try conditional, aborted. */
839 	    if (getline_equal(getline, cookie, get_func_line)
840 					       && func_has_ended(real_cookie))
841 	    {
842 		retval = FAIL;
843 		break;
844 	    }
845 
846 	    /* Check if a sourced file hit a ":finish" command. */
847 	    if (source_finished(getline, cookie))
848 	    {
849 		retval = FAIL;
850 		break;
851 	    }
852 
853 	    /* If breakpoints have been added/deleted need to check for it. */
854 	    if (breakpoint != NULL && dbg_tick != NULL
855 						   && *dbg_tick != debug_tick)
856 	    {
857 		*breakpoint = dbg_find_breakpoint(
858 				getline_equal(getline, cookie, getsourceline),
859 							fname, sourcing_lnum);
860 		*dbg_tick = debug_tick;
861 	    }
862 
863 	    next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
864 	    sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
865 
866 	    /* Did we encounter a breakpoint? */
867 	    if (breakpoint != NULL && *breakpoint != 0
868 					      && *breakpoint <= sourcing_lnum)
869 	    {
870 		dbg_breakpoint(fname, sourcing_lnum);
871 		/* Find next breakpoint. */
872 		*breakpoint = dbg_find_breakpoint(
873 				getline_equal(getline, cookie, getsourceline),
874 							fname, sourcing_lnum);
875 		*dbg_tick = debug_tick;
876 	    }
877 	}
878 
879 	if (cstack.cs_whilelevel)
880 	{
881 	    /* Inside a while loop we need to store the lines and use them
882 	     * again.  Pass a different "getline" function to do_one_cmd()
883 	     * below, so that it stores lines in or reads them from
884 	     * "lines_ga".  Makes it possible to define a function inside a
885 	     * while loop. */
886 	    cmd_getline = get_while_line;
887 	    cmd_cookie = (void *)&cmd_while_cookie;
888 	    cmd_while_cookie.lines_gap = &lines_ga;
889 	    cmd_while_cookie.current_line = current_line;
890 	    cmd_while_cookie.getline = getline;
891 	    cmd_while_cookie.cookie = cookie;
892 	    cmd_while_cookie.repeating = (current_line < lines_ga.ga_len);
893 	}
894 	else
895 	{
896 	    cmd_getline = getline;
897 	    cmd_cookie = cookie;
898 	}
899 #endif
900 
901 	/* 2. If no line given, get an allocated line with getline(). */
902 	if (next_cmdline == NULL)
903 	{
904 	    /*
905 	     * Need to set msg_didout for the first line after an ":if",
906 	     * otherwise the ":if" will be overwritten.
907 	     */
908 	    if (count == 1 && getline_equal(getline, cookie, getexline))
909 		msg_didout = TRUE;
910 	    if (getline == NULL || (next_cmdline = getline(':', cookie,
911 #ifdef FEAT_EVAL
912 		    cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
913 #else
914 		    0
915 #endif
916 			    )) == NULL)
917 	    {
918 		/* Don't call wait_return for aborted command line.  The NULL
919 		 * returned for the end of a sourced file or executed function
920 		 * doesn't do this. */
921 		if (KeyTyped && !(flags & DOCMD_REPEAT))
922 		    need_wait_return = FALSE;
923 		retval = FAIL;
924 		break;
925 	    }
926 	    used_getline = TRUE;
927 
928 	    /*
929 	     * Keep the first typed line.  Clear it when more lines are typed.
930 	     */
931 	    if (flags & DOCMD_KEEPLINE)
932 	    {
933 		vim_free(repeat_cmdline);
934 		if (count == 0)
935 		    repeat_cmdline = vim_strsave(next_cmdline);
936 		else
937 		    repeat_cmdline = NULL;
938 	    }
939 	}
940 
941 	/* 3. Make a copy of the command so we can mess with it. */
942 	else if (cmdline_copy == NULL)
943 	{
944 	    next_cmdline = vim_strsave(next_cmdline);
945 	    if (next_cmdline == NULL)
946 	    {
947 		EMSG(_(e_outofmem));
948 		retval = FAIL;
949 		break;
950 	    }
951 	}
952 	cmdline_copy = next_cmdline;
953 
954 #ifdef FEAT_EVAL
955 	/*
956 	 * Save the current line when inside a ":while", and when the command
957 	 * looks like a ":while", because we may need it later.
958 	 * When there is a '|' and another command, it is stored separately,
959 	 * because we need to be able to jump back to it from an :endwhile.
960 	 */
961 	if (	   current_line == lines_ga.ga_len
962 		&& (cstack.cs_whilelevel || has_while_cmd(next_cmdline)))
963 	{
964 	    if (store_while_line(&lines_ga, next_cmdline) == FAIL)
965 	    {
966 		retval = FAIL;
967 		break;
968 	    }
969 	}
970 	did_endif = FALSE;
971 #endif
972 
973 	if (count++ == 0)
974 	{
975 	    /*
976 	     * All output from the commands is put below each other, without
977 	     * waiting for a return. Don't do this when executing commands
978 	     * from a script or when being called recursive (e.g. for ":e
979 	     * +command file").
980 	     */
981 	    if (!(flags & DOCMD_NOWAIT) && !recursive)
982 	    {
983 		msg_didout_before_start = msg_didout;
984 		msg_didany = FALSE; /* no output yet */
985 		msg_start();
986 		msg_scroll = TRUE;  /* put messages below each other */
987 		++no_wait_return;   /* dont wait for return until finished */
988 		++RedrawingDisabled;
989 		did_inc = TRUE;
990 	    }
991 	}
992 
993 	if (p_verbose >= 15 && sourcing_name != NULL)
994 	{
995 	    int	c = -1;
996 
997 	    ++no_wait_return;
998 	    msg_scroll = TRUE;	    /* always scroll up, don't overwrite */
999 	    /* Truncate long lines, smsg() can't handle that. */
1000 	    if (STRLEN(cmdline_copy) > 200)
1001 	    {
1002 		c = cmdline_copy[200];
1003 		cmdline_copy[200] = NUL;
1004 	    }
1005 	    smsg((char_u *)_("line %ld: %s"),
1006 					   (long)sourcing_lnum, cmdline_copy);
1007 	    msg_puts((char_u *)"\n");   /* don't overwrite this either */
1008 	    if (c >= 0)
1009 		cmdline_copy[200] = c;
1010 	    cmdline_row = msg_row;
1011 	    --no_wait_return;
1012 	}
1013 
1014 	/*
1015 	 * 2. Execute one '|' separated command.
1016 	 *    do_one_cmd() will return NULL if there is no trailing '|'.
1017 	 *    "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1018 	 */
1019 	++recursive;
1020 	next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1021 #ifdef FEAT_EVAL
1022 				&cstack,
1023 #endif
1024 				cmd_getline, cmd_cookie);
1025 	--recursive;
1026 
1027 #ifdef FEAT_EVAL
1028 	if (cmd_cookie == (void *)&cmd_while_cookie)
1029 	    /* Use "current_line" from "cmd_while_cookie", it may have been
1030 	     * incremented when defining a function. */
1031 	    current_line = cmd_while_cookie.current_line;
1032 #endif
1033 
1034 	if (next_cmdline == NULL)
1035 	{
1036 	    vim_free(cmdline_copy);
1037 	    cmdline_copy = NULL;
1038 #ifdef FEAT_CMDHIST
1039 	    /*
1040 	     * If the command was typed, remember it for the ':' register.
1041 	     * Do this AFTER executing the command to make :@: work.
1042 	     */
1043 	    if (getline_equal(getline, cookie, getexline)
1044 						  && new_last_cmdline != NULL)
1045 	    {
1046 		vim_free(last_cmdline);
1047 		last_cmdline = new_last_cmdline;
1048 		new_last_cmdline = NULL;
1049 	    }
1050 #endif
1051 	}
1052 	else
1053 	{
1054 	    /* need to copy the command after the '|' to cmdline_copy, for the
1055 	     * next do_one_cmd() */
1056 	    mch_memmove(cmdline_copy, next_cmdline, STRLEN(next_cmdline) + 1);
1057 	    next_cmdline = cmdline_copy;
1058 	}
1059 
1060 
1061 #ifdef FEAT_EVAL
1062 	/* reset did_emsg for a function that is not aborted by an error */
1063 	if (did_emsg && !force_abort
1064 		&& getline_equal(getline, cookie, get_func_line)
1065 					      && !func_has_abort(real_cookie))
1066 	    did_emsg = FALSE;
1067 
1068 	if (cstack.cs_whilelevel)
1069 	{
1070 	    ++current_line;
1071 
1072 	    /*
1073 	     * An ":endwhile" and ":continue" is handled here.
1074 	     * If we were executing commands, jump back to the ":while".
1075 	     * If we were not executing commands, decrement whilelevel.
1076 	     */
1077 	    if (cstack.cs_had_endwhile || cstack.cs_had_continue)
1078 	    {
1079 		if (cstack.cs_had_endwhile)
1080 		    cstack.cs_had_endwhile = FALSE;
1081 		else
1082 		    cstack.cs_had_continue = FALSE;
1083 
1084 		/* Jump back to the matching ":while".  Be careful not to use
1085 		 * a cs_line[] from an entry that isn't a ":while": It would
1086 		 * make "current_line" invalid and can cause a crash. */
1087 		if (!did_emsg && !got_int && !did_throw
1088 			&& cstack.cs_idx >= 0
1089 			&& (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1090 			&& cstack.cs_line[cstack.cs_idx] >= 0
1091 			&& (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1092 		{
1093 		    current_line = cstack.cs_line[cstack.cs_idx];
1094 		    cstack.cs_had_while = TRUE;	/* note we jumped there */
1095 		    line_breakcheck();		/* check if CTRL-C typed */
1096 
1097 		    /* Check for the next breakpoint at or after the ":while".*/
1098 		    if (breakpoint != NULL)
1099 		    {
1100 			*breakpoint = dbg_find_breakpoint(
1101 				getline_equal(getline, cookie, getsourceline),
1102 									fname,
1103 			   ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1104 			*dbg_tick = debug_tick;
1105 		    }
1106 		}
1107 		else /* can only get here with ":endwhile" */
1108 		{
1109 		    --cstack.cs_whilelevel;
1110 		    if (cstack.cs_idx >= 0)
1111 			--cstack.cs_idx;
1112 		}
1113 	    }
1114 
1115 	    /*
1116 	     * For a ":while" we need to remember the line number.
1117 	     */
1118 	    else if (cstack.cs_had_while)
1119 	    {
1120 		cstack.cs_had_while = FALSE;
1121 		cstack.cs_line[cstack.cs_idx] = current_line - 1;
1122 	    }
1123 	}
1124 
1125 	/*
1126 	 * When not inside any ":while" loop, clear remembered lines.
1127 	 */
1128 	if (!cstack.cs_whilelevel)
1129 	{
1130 	    if (lines_ga.ga_len > 0)
1131 	    {
1132 		sourcing_lnum =
1133 		       ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1134 		free_cmdlines(&lines_ga);
1135 	    }
1136 	    current_line = 0;
1137 	}
1138 
1139 	/*
1140 	 * A ":finally" makes did_emsg, got_int, and did_throw pending for being
1141 	 * restored at the ":endtry".  Reset them here and set the ACTIVE and
1142 	 * FINALLY flags, so that the finally clause gets executed.  This
1143 	 * includes the case where a missing ":endif" or ":endwhile" was
1144 	 * detected by the ":finally" itself.
1145 	 */
1146 	if (cstack.cs_had_finally)
1147 	{
1148 	    cstack.cs_had_finally = FALSE;
1149 	    report_make_pending(cstack.cs_pending[cstack.cs_idx] &
1150 		    (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1151 		    did_throw ? (void *)current_exception : NULL);
1152 	    did_emsg = got_int = did_throw = FALSE;
1153 	    cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1154 	}
1155 
1156 	/* Update global "trylevel" for recursive calls to do_cmdline() from
1157 	 * within this loop. */
1158 	trylevel = initial_trylevel + cstack.cs_trylevel;
1159 
1160 	/*
1161 	 * If the outermost try conditional (accross function calls and sourced
1162 	 * files) is aborted because of an error, an interrupt, or an uncaught
1163 	 * exception, cancel everything.  If it is left normally, reset
1164 	 * force_abort to get the non-EH compatible abortion behavior for
1165 	 * the rest of the script.
1166 	 */
1167 	if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1168 	    force_abort = FALSE;
1169 
1170 	/* Convert an interrupt to an exception if appropriate. */
1171 	(void)do_intthrow(&cstack);
1172 #endif /* FEAT_EVAL */
1173 
1174     }
1175     /*
1176      * Continue executing command lines when:
1177      * - no CTRL-C typed, no aborting error, no exception thrown or try
1178      *   conditionals need to be checked for executing finally clauses or
1179      *   catching an interrupt exception
1180      * - didn't get an error message or lines are not typed
1181      * - there is a command after '|', inside a :if, :while, or :try, or
1182      *   looping for ":source" command or function call.
1183      */
1184     while (!((got_int
1185 #ifdef FEAT_EVAL
1186 		    || (did_emsg && force_abort) || did_throw
1187 #endif
1188 	     )
1189 #ifdef FEAT_EVAL
1190 		&& cstack.cs_trylevel == 0
1191 #endif
1192 	    )
1193 	    && !(did_emsg && used_getline
1194 			  && (getline_equal(getline, cookie, getexmodeline)
1195 				|| getline_equal(getline, cookie, getexline)))
1196 	    && (next_cmdline != NULL
1197 #ifdef FEAT_EVAL
1198 			|| cstack.cs_idx >= 0
1199 #endif
1200 			|| (flags & DOCMD_REPEAT)));
1201 
1202     vim_free(cmdline_copy);
1203 #ifdef FEAT_EVAL
1204     free_cmdlines(&lines_ga);
1205     ga_clear(&lines_ga);
1206 
1207     if (cstack.cs_idx >= 0)
1208     {
1209 	/*
1210 	 * If a sourced file or executed function ran to its end, report the
1211 	 * unclosed conditional.
1212 	 */
1213 	if (!got_int && !did_throw
1214 		&& ((getline_equal(getline, cookie, getsourceline)
1215 			&& !source_finished(getline, cookie))
1216 		    || (getline_equal(getline, cookie, get_func_line)
1217 					    && !func_has_ended(real_cookie))))
1218 	{
1219 	    if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1220 		EMSG(_(e_endtry));
1221 	    else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1222 		EMSG(_(e_endwhile));
1223 	    else
1224 		EMSG(_(e_endif));
1225 	}
1226 
1227 	/*
1228 	 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1229 	 * ":endtry" in a sourced file or executed function.  If the try
1230 	 * conditional is in its finally clause, ignore anything pending.
1231 	 * If it is in a catch clause, finish the caught exception.
1232 	 */
1233 	do
1234 	    cstack.cs_idx = cleanup_conditionals(&cstack, 0, TRUE);
1235 	while (--cstack.cs_idx >= 0);
1236 	trylevel = initial_trylevel;
1237     }
1238 
1239     /* If a missing ":endtry", ":endwhile", or ":endif" or a memory lack
1240      * was reported above and the error message is to be converted to an
1241      * exception, do this now after rewinding the cstack. */
1242     do_errthrow(&cstack, getline_equal(getline, cookie, get_func_line)
1243 				  ? (char_u *)"endfunction" : (char_u *)NULL);
1244 
1245     if (trylevel == 0)
1246     {
1247 	/*
1248 	 * When an exception is being thrown out of the outermost try
1249 	 * conditional, discard the uncaught exception, disable the conversion
1250 	 * of interrupts or errors to exceptions, and ensure that no more
1251 	 * commands are executed.
1252 	 */
1253 	if (did_throw)
1254 	{
1255 	    void	*p = NULL;
1256 	    char_u	*saved_sourcing_name;
1257 	    int		saved_sourcing_lnum;
1258 	    struct msglist	*messages = NULL, *next;
1259 
1260 	    /*
1261 	     * If the uncaught exception is a user exception, report it as an
1262 	     * error.  If it is an error exception, display the saved error
1263 	     * message now.  For an interrupt exception, do nothing; the
1264 	     * interrupt message is given elsewhere.
1265 	     */
1266 	    switch (current_exception->type)
1267 	    {
1268 		case ET_USER:
1269 		    sprintf((char *)IObuff, _("E605: Exception not caught: %s"),
1270 			    current_exception->value);
1271 		    p = vim_strsave(IObuff);
1272 		    break;
1273 		case ET_ERROR:
1274 		    messages = current_exception->messages;
1275 		    current_exception->messages = NULL;
1276 		    break;
1277 		case ET_INTERRUPT:
1278 		    break;
1279 		default:
1280 		    p = vim_strsave((char_u *)_(e_internal));
1281 	    }
1282 
1283 	    saved_sourcing_name = sourcing_name;
1284 	    saved_sourcing_lnum = sourcing_lnum;
1285 	    sourcing_name = current_exception->throw_name;
1286 	    sourcing_lnum = current_exception->throw_lnum;
1287 	    current_exception->throw_name = NULL;
1288 
1289 	    discard_current_exception();	/* uses IObuff if 'verbose' */
1290 	    suppress_errthrow = TRUE;
1291 	    force_abort = TRUE;
1292 
1293 	    if (messages != NULL)
1294 	    {
1295 		do
1296 		{
1297 		    next = messages->next;
1298 		    emsg(messages->msg);
1299 		    vim_free(messages->msg);
1300 		    vim_free(messages);
1301 		    messages = next;
1302 		}
1303 		while (messages != NULL);
1304 	    }
1305 	    else if (p != NULL)
1306 	    {
1307 		emsg(p);
1308 		vim_free(p);
1309 	    }
1310 	    vim_free(sourcing_name);
1311 	    sourcing_name = saved_sourcing_name;
1312 	    sourcing_lnum = saved_sourcing_lnum;
1313 	}
1314 
1315 	/*
1316 	 * On an interrupt or an aborting error not converted to an exception,
1317 	 * disable the conversion of errors to exceptions.  (Interrupts are not
1318 	 * converted any more, here.) This enables also the interrupt message
1319 	 * when force_abort is set and did_emsg unset in case of an interrupt
1320 	 * from a finally clause after an error.
1321 	 */
1322 	else if (got_int || (did_emsg && force_abort))
1323 	    suppress_errthrow = TRUE;
1324     }
1325 
1326     /*
1327      * The current cstack will be freed when do_cmdline() returns.  An uncaught
1328      * exception will have to be rethrown in the previous cstack.  If a function
1329      * has just returned or a script file was just finished and the previous
1330      * cstack belongs to the same function or, respectively, script file, it
1331      * will have to be checked for finally clauses to be executed due to the
1332      * ":return" or ":finish".  This is done in do_one_cmd().
1333      */
1334     if (did_throw)
1335 	need_rethrow = TRUE;
1336     if ((getline_equal(getline, cookie, getsourceline)
1337 		&& ex_nesting_level > source_level(real_cookie))
1338 	    || (getline_equal(getline, cookie, get_func_line)
1339 		&& ex_nesting_level > func_level(real_cookie) + 1))
1340     {
1341 	if (!did_throw)
1342 	    check_cstack = TRUE;
1343     }
1344     else
1345     {
1346 	/* When leaving a function, reduce nesting level. */
1347 	if (getline_equal(getline, cookie, get_func_line))
1348 	    --ex_nesting_level;
1349 	/*
1350 	 * Go to debug mode when returning from a function in which we are
1351 	 * single-stepping.
1352 	 */
1353 	if ((getline_equal(getline, cookie, getsourceline)
1354 		    || getline_equal(getline, cookie, get_func_line))
1355 		&& ex_nesting_level + 1 <= debug_break_level)
1356 	    do_debug(getline_equal(getline, cookie, getsourceline)
1357 		    ? (char_u *)_("End of sourced file")
1358 		    : (char_u *)_("End of function"));
1359     }
1360 
1361     /*
1362      * Restore the exception environment (done after returning from the
1363      * debugger).
1364      */
1365     if (flags & DOCMD_EXCRESET)
1366 	restore_dbg_stuff(&debug_saved);
1367 
1368     msg_list = saved_msg_list;
1369 #endif /* FEAT_EVAL */
1370 
1371     /*
1372      * If there was too much output to fit on the command line, ask the user to
1373      * hit return before redrawing the screen. With the ":global" command we do
1374      * this only once after the command is finished.
1375      */
1376     if (did_inc)
1377     {
1378 	--RedrawingDisabled;
1379 	--no_wait_return;
1380 	msg_scroll = FALSE;
1381 
1382 	/*
1383 	 * When just finished an ":if"-":else" which was typed, no need to
1384 	 * wait for hit-return.  Also for an error situation.
1385 	 */
1386 	if (retval == FAIL
1387 #ifdef FEAT_EVAL
1388 		|| (did_endif && KeyTyped && !did_emsg)
1389 #endif
1390 					    )
1391 	{
1392 	    need_wait_return = FALSE;
1393 	    msg_didany = FALSE;		/* don't wait when restarting edit */
1394 	}
1395 	else if (need_wait_return)
1396 	{
1397 	    /*
1398 	     * The msg_start() above clears msg_didout. The wait_return we do
1399 	     * here should not overwrite the command that may be shown before
1400 	     * doing that.
1401 	     */
1402 	    msg_didout |= msg_didout_before_start;
1403 	    wait_return(FALSE);
1404 	}
1405     }
1406 
1407 #ifndef FEAT_EVAL
1408     /*
1409      * Reset if_level, in case a sourced script file contains more ":if" than
1410      * ":endif" (could be ":if x | foo | endif").
1411      */
1412     if_level = 0;
1413 #endif
1414 
1415     --call_depth;
1416     return retval;
1417 }
1418 
1419 #ifdef FEAT_EVAL
1420 /*
1421  * Obtain a line when inside a ":while" loop.
1422  */
1423     static char_u *
1424 get_while_line(c, cookie, indent)
1425     int		c;
1426     void	*cookie;
1427     int		indent;
1428 {
1429     struct while_cookie *cp = (struct while_cookie *)cookie;
1430     wcmd_T		*wp;
1431     char_u		*line;
1432 
1433     if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1434     {
1435 	if (cp->repeating)
1436 	    return NULL;	/* trying to read past the ":endwhile" */
1437 
1438 	/* First time inside the ":while": get line normally. */
1439 	if (cp->getline == NULL)
1440 	    line = getcmdline(c, 0L, indent);
1441 	else
1442 	    line = cp->getline(c, cp->cookie, indent);
1443 	if (store_while_line(cp->lines_gap, line) == OK)
1444 	    ++cp->current_line;
1445 
1446 	return line;
1447     }
1448 
1449     KeyTyped = FALSE;
1450     ++cp->current_line;
1451     wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1452     sourcing_lnum = wp->lnum;
1453     return vim_strsave(wp->line);
1454 }
1455 
1456 /*
1457  * Store a line in "gap" so that a ":while" loop can execute it again.
1458  */
1459     static int
1460 store_while_line(gap, line)
1461     garray_T	*gap;
1462     char_u	*line;
1463 {
1464     if (ga_grow(gap, 1) == FAIL)
1465 	return FAIL;
1466     ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1467     ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1468     ++gap->ga_len;
1469     --gap->ga_room;
1470     return OK;
1471 }
1472 
1473 /*
1474  * Free the lines stored for a ":while" loop.
1475  */
1476     static void
1477 free_cmdlines(gap)
1478     garray_T	*gap;
1479 {
1480     while (gap->ga_len > 0)
1481     {
1482 	vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1483 	--gap->ga_len;
1484 	++gap->ga_room;
1485     }
1486 }
1487 #endif
1488 
1489 /*
1490  * If "getline" is get_while_line(), return TRUE if the getline it uses equals
1491  * "func".  * Otherwise return TRUE when "getline" equals "func".
1492  */
1493 /*ARGSUSED*/
1494     int
1495 getline_equal(getline, cookie, func)
1496     char_u	*(*getline) __ARGS((int, void *, int));
1497     void	*cookie;		/* argument for getline() */
1498     char_u	*(*func) __ARGS((int, void *, int));
1499 {
1500 #ifdef FEAT_EVAL
1501     char_u		*(*gp) __ARGS((int, void *, int));
1502     struct while_cookie *cp;
1503 
1504     /* When "getline" is "get_while_line()" use the "cookie" to find the
1505      * function that's orignally used to obtain the lines.  This may be nested
1506      * several levels. */
1507     gp = getline;
1508     cp = (struct while_cookie *)cookie;
1509     while (gp == get_while_line)
1510     {
1511 	gp = cp->getline;
1512 	cp = cp->cookie;
1513     }
1514     return gp == func;
1515 #else
1516     return getline == func;
1517 #endif
1518 }
1519 
1520 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1521 /*
1522  * If "getline" is get_while_line(), return the cookie used by the original
1523  * getline function.  Otherwise return "cookie".
1524  */
1525 /*ARGSUSED*/
1526     void *
1527 getline_cookie(getline, cookie)
1528     char_u	*(*getline) __ARGS((int, void *, int));
1529     void	*cookie;		/* argument for getline() */
1530 {
1531 # ifdef FEAT_EVAL
1532     char_u		*(*gp) __ARGS((int, void *, int));
1533     struct while_cookie *cp;
1534 
1535     /* When "getline" is "get_while_line()" use the "cookie" to find the
1536      * cookie that's orignally used to obtain the lines.  This may be nested
1537      * several levels. */
1538     gp = getline;
1539     cp = (struct while_cookie *)cookie;
1540     while (gp == get_while_line)
1541     {
1542 	gp = cp->getline;
1543 	cp = cp->cookie;
1544     }
1545     return cp;
1546 # else
1547     return cookie;
1548 # endif
1549 }
1550 #endif
1551 
1552 /*
1553  * Execute one Ex command.
1554  *
1555  * If 'sourcing' is TRUE, the command will be included in the error message.
1556  *
1557  * 1. skip comment lines and leading space
1558  * 2. handle command modifiers
1559  * 3. parse range
1560  * 4. parse command
1561  * 5. parse arguments
1562  * 6. switch on command name
1563  *
1564  * Note: "getline" can be NULL.
1565  *
1566  * This function may be called recursively!
1567  */
1568 #if (_MSC_VER == 1200)
1569 /*
1570  * Avoid optimisation bug in VC++ version 6.0
1571  */
1572 # pragma optimize( "g", off )
1573 #endif
1574     static char_u *
1575 do_one_cmd(cmdlinep, sourcing,
1576 #ifdef FEAT_EVAL
1577 			    cstack,
1578 #endif
1579 				    getline, cookie)
1580     char_u		**cmdlinep;
1581     int			sourcing;
1582 #ifdef FEAT_EVAL
1583     struct condstack	*cstack;
1584 #endif
1585     char_u		*(*getline) __ARGS((int, void *, int));
1586     void		*cookie;		/* argument for getline() */
1587 {
1588     char_u		*p;
1589     linenr_T		lnum;
1590     long		n;
1591     char_u		*errormsg = NULL;	/* error message */
1592     exarg_T		ea;			/* Ex command arguments */
1593     long		verbose_save = -1;
1594     int			save_msg_scroll = 0;
1595     int			did_silent = 0;
1596     int			did_esilent = 0;
1597     cmdmod_T		save_cmdmod;
1598     int			ni;			/* set when Not Implemented */
1599 
1600     vim_memset(&ea, 0, sizeof(ea));
1601     ea.line1 = 1;
1602     ea.line2 = 1;
1603 #ifdef FEAT_EVAL
1604     ++ex_nesting_level;
1605 #endif
1606 
1607 	/* when not editing the last file :q has to be typed twice */
1608     if (quitmore
1609 #ifdef FEAT_EVAL
1610 	    /* avoid that a function call in 'statusline' does this */
1611 	    && !getline_equal(getline, cookie, get_func_line)
1612 #endif
1613 	    )
1614 	--quitmore;
1615 
1616     /*
1617      * Reset browse, confirm, etc..  They are restored when returning, for
1618      * recursive calls.
1619      */
1620     save_cmdmod = cmdmod;
1621     vim_memset(&cmdmod, 0, sizeof(cmdmod));
1622 
1623     /*
1624      * Repeat until no more command modifiers are found.
1625      */
1626     ea.cmd = *cmdlinep;
1627     for (;;)
1628     {
1629 /*
1630  * 1. skip comment lines and leading white space and colons
1631  */
1632 	while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1633 	    ++ea.cmd;
1634 
1635 	/* in ex mode, an empty line works like :+ */
1636 	if (*ea.cmd == NUL && exmode_active
1637 			&& (getline_equal(getline, cookie, getexmodeline)
1638 			    || getline_equal(getline, cookie, getexline)))
1639 	{
1640 	    ea.cmd = (char_u *)"+";
1641 	    ex_pressedreturn = TRUE;
1642 	}
1643 
1644 	/* ignore comment and empty lines */
1645 	if (*ea.cmd == '"' || *ea.cmd == NUL)
1646 	    goto doend;
1647 
1648 /*
1649  * 2. handle command modifiers.
1650  */
1651 	p = ea.cmd;
1652 	if (VIM_ISDIGIT(*ea.cmd))
1653 	    p = skipwhite(skipdigits(ea.cmd));
1654 	switch (*p)
1655 	{
1656 	    /* When adding an entry, also modify cmd_exists(). */
1657 	    case 'a':	if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1658 			    break;
1659 #ifdef FEAT_WINDOWS
1660 			cmdmod.split |= WSP_ABOVE;
1661 #endif
1662 			continue;
1663 
1664 	    case 'b':	if (checkforcmd(&ea.cmd, "belowright", 3))
1665 			{
1666 #ifdef FEAT_WINDOWS
1667 			    cmdmod.split |= WSP_BELOW;
1668 #endif
1669 			    continue;
1670 			}
1671 			if (checkforcmd(&ea.cmd, "browse", 3))
1672 			{
1673 #ifdef FEAT_BROWSE
1674 			    cmdmod.browse = TRUE;
1675 #endif
1676 			    continue;
1677 			}
1678 			if (!checkforcmd(&ea.cmd, "botright", 2))
1679 			    break;
1680 #ifdef FEAT_WINDOWS
1681 			cmdmod.split |= WSP_BOT;
1682 #endif
1683 			continue;
1684 
1685 	    case 'c':	if (!checkforcmd(&ea.cmd, "confirm", 4))
1686 			    break;
1687 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1688 			cmdmod.confirm = TRUE;
1689 #endif
1690 			continue;
1691 
1692 	    case 'k':	if (checkforcmd(&ea.cmd, "keepmarks", 3))
1693 			{
1694 			    cmdmod.keepmarks = TRUE;
1695 			    continue;
1696 			}
1697 			if (checkforcmd(&ea.cmd, "keepalt", 5))
1698 			{
1699 			    cmdmod.keepalt = TRUE;
1700 			    continue;
1701 			}
1702 			if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1703 			    break;
1704 			cmdmod.keepjumps = TRUE;
1705 			continue;
1706 
1707 			/* ":hide" and ":hide | cmd" are not modifiers */
1708 	    case 'h':	if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1709 					       || *p == NUL || ends_excmd(*p))
1710 			    break;
1711 			ea.cmd = p;
1712 			cmdmod.hide = TRUE;
1713 			continue;
1714 
1715 	    case 'l':	if (checkforcmd(&ea.cmd, "lockmarks", 3))
1716 			{
1717 			    cmdmod.lockmarks = TRUE;
1718 			    continue;
1719 			}
1720 
1721 			if (!checkforcmd(&ea.cmd, "leftabove", 5))
1722 			    break;
1723 #ifdef FEAT_WINDOWS
1724 			cmdmod.split |= WSP_ABOVE;
1725 #endif
1726 			continue;
1727 
1728 	    case 'r':	if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1729 			    break;
1730 #ifdef FEAT_WINDOWS
1731 			cmdmod.split |= WSP_BELOW;
1732 #endif
1733 			continue;
1734 
1735 	    case 's':	if (!checkforcmd(&ea.cmd, "silent", 3))
1736 			    break;
1737 			++did_silent;
1738 			++msg_silent;
1739 			save_msg_scroll = msg_scroll;
1740 			if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1]))
1741 			{
1742 			    /* ":silent!", but not "silent !cmd" */
1743 			    ea.cmd = skipwhite(ea.cmd + 1);
1744 			    ++emsg_silent;
1745 			    ++did_esilent;
1746 			}
1747 			continue;
1748 
1749 	    case 't':	if (!checkforcmd(&ea.cmd, "topleft", 2))
1750 			    break;
1751 #ifdef FEAT_WINDOWS
1752 			cmdmod.split |= WSP_TOP;
1753 #endif
1754 			continue;
1755 
1756 	    case 'v':	if (checkforcmd(&ea.cmd, "vertical", 4))
1757 			{
1758 #ifdef FEAT_VERTSPLIT
1759 			    cmdmod.split |= WSP_VERT;
1760 #endif
1761 			    continue;
1762 			}
1763 			if (!checkforcmd(&p, "verbose", 4))
1764 			    break;
1765 			if (verbose_save < 0)
1766 			    verbose_save = p_verbose;
1767 			if (vim_isdigit(*ea.cmd))
1768 			    p_verbose = atoi((char *)ea.cmd);
1769 			else
1770 			    p_verbose = 1;
1771 			ea.cmd = p;
1772 			continue;
1773 	}
1774 	break;
1775     }
1776 
1777 #ifdef FEAT_EVAL
1778     ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
1779 			 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
1780 #else
1781     ea.skip = (if_level > 0);
1782 #endif
1783 
1784 #ifdef FEAT_EVAL
1785     /* May go to debug mode.  If this happens and the ">quit" debug command is
1786      * used, throw an interrupt exception and skip the next command. */
1787     dbg_check_breakpoint(&ea);
1788     if (!ea.skip && got_int)
1789     {
1790 	ea.skip = TRUE;
1791 	(void)do_intthrow(cstack);
1792     }
1793 #endif
1794 
1795 /*
1796  * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
1797  *
1798  * where 'addr' is:
1799  *
1800  * %	      (entire file)
1801  * $  [+-NUM]
1802  * 'x [+-NUM] (where x denotes a currently defined mark)
1803  * .  [+-NUM]
1804  * [+-NUM]..
1805  * NUM
1806  *
1807  * The ea.cmd pointer is updated to point to the first character following the
1808  * range spec. If an initial address is found, but no second, the upper bound
1809  * is equal to the lower.
1810  */
1811 
1812     /* repeat for all ',' or ';' separated addresses */
1813     for (;;)
1814     {
1815 	ea.line1 = ea.line2;
1816 	ea.line2 = curwin->w_cursor.lnum;   /* default is current line number */
1817 	ea.cmd = skipwhite(ea.cmd);
1818 	lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0);
1819 	if (ea.cmd == NULL)		    /* error detected */
1820 	    goto doend;
1821 	if (lnum == MAXLNUM)
1822 	{
1823 	    if (*ea.cmd == '%')		    /* '%' - all lines */
1824 	    {
1825 		++ea.cmd;
1826 		ea.line1 = 1;
1827 		ea.line2 = curbuf->b_ml.ml_line_count;
1828 		++ea.addr_count;
1829 	    }
1830 					    /* '*' - visual area */
1831 	    else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
1832 	    {
1833 		pos_T	    *fp;
1834 
1835 		++ea.cmd;
1836 		if (!ea.skip)
1837 		{
1838 		    fp = getmark('<', FALSE);
1839 		    if (check_mark(fp) == FAIL)
1840 			goto doend;
1841 		    ea.line1 = fp->lnum;
1842 		    fp = getmark('>', FALSE);
1843 		    if (check_mark(fp) == FAIL)
1844 			goto doend;
1845 		    ea.line2 = fp->lnum;
1846 		    ++ea.addr_count;
1847 		}
1848 	    }
1849 	}
1850 	else
1851 	    ea.line2 = lnum;
1852 	ea.addr_count++;
1853 
1854 	if (*ea.cmd == ';')
1855 	{
1856 	    if (!ea.skip)
1857 		curwin->w_cursor.lnum = ea.line2;
1858 	}
1859 	else if (*ea.cmd != ',')
1860 	    break;
1861 	++ea.cmd;
1862     }
1863 
1864     /* One address given: set start and end lines */
1865     if (ea.addr_count == 1)
1866     {
1867 	ea.line1 = ea.line2;
1868 	    /* ... but only implicit: really no address given */
1869 	if (lnum == MAXLNUM)
1870 	    ea.addr_count = 0;
1871     }
1872 
1873     /* Don't leave the cursor on an illegal line (caused by ';') */
1874     check_cursor_lnum();
1875 
1876 /*
1877  * 4. parse command
1878  */
1879 
1880     /*
1881      * Skip ':' and any white space
1882      */
1883     ea.cmd = skipwhite(ea.cmd);
1884     while (*ea.cmd == ':')
1885 	ea.cmd = skipwhite(ea.cmd + 1);
1886 
1887     /*
1888      * If we got a line, but no command, then go to the line.
1889      * If we find a '|' or '\n' we set ea.nextcmd.
1890      */
1891     if (*ea.cmd == NUL || *ea.cmd == '"' ||
1892 			       (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
1893     {
1894 	/*
1895 	 * strange vi behaviour:
1896 	 * ":3"		jumps to line 3
1897 	 * ":3|..."	prints line 3
1898 	 * ":|"		prints current line
1899 	 */
1900 	if (ea.skip)	    /* skip this if inside :if */
1901 	    goto doend;
1902 	if (*ea.cmd == '|')
1903 	{
1904 	    ea.cmdidx = CMD_print;
1905 	    ea.argt = RANGE+COUNT+TRLBAR;
1906 	    if ((errormsg = invalid_range(&ea)) == NULL)
1907 	    {
1908 		correct_range(&ea);
1909 		ex_print(&ea);
1910 	    }
1911 	}
1912 	else if (ea.addr_count != 0)
1913 	{
1914 	    if (ea.line2 < 0)
1915 		errormsg = invalid_range(&ea);
1916 	    else
1917 	    {
1918 		if (ea.line2 == 0)
1919 		    curwin->w_cursor.lnum = 1;
1920 		else if (ea.line2 > curbuf->b_ml.ml_line_count)
1921 		    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1922 		else
1923 		    curwin->w_cursor.lnum = ea.line2;
1924 		beginline(BL_SOL | BL_FIX);
1925 	    }
1926 	}
1927 	goto doend;
1928     }
1929 
1930     /* Find the command and let "p" point to after it. */
1931     p = find_command(&ea, NULL);
1932 
1933 #ifdef FEAT_USR_CMDS
1934     if (p == NULL)
1935     {
1936 	if (!ea.skip)
1937 	    errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
1938 	goto doend;
1939     }
1940     /* Check for wrong commands. */
1941     if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78)
1942     {
1943 	errormsg = uc_fun_cmd();
1944 	goto doend;
1945     }
1946 #endif
1947     if (ea.cmdidx == CMD_SIZE)
1948     {
1949 	if (!ea.skip)
1950 	{
1951 	    STRCPY(IObuff, _("E492: Not an editor command"));
1952 	    if (!sourcing)
1953 	    {
1954 		STRCAT(IObuff, ": ");
1955 		STRNCAT(IObuff, *cmdlinep, 40);
1956 	    }
1957 	    errormsg = IObuff;
1958 	}
1959 	goto doend;
1960     }
1961 
1962     ni = (
1963 #ifdef FEAT_USR_CMDS
1964 	    !USER_CMDIDX(ea.cmdidx) &&
1965 #endif
1966 	    cmdnames[ea.cmdidx].cmd_func == ex_ni);
1967 
1968 #ifndef FEAT_EVAL
1969     /*
1970      * When the expression evaluation is disabled, recognize the ":if" and
1971      * ":endif" commands and ignore everything in between it.
1972      */
1973     if (ea.cmdidx == CMD_if)
1974 	++if_level;
1975     if (if_level)
1976     {
1977 	if (ea.cmdidx == CMD_endif)
1978 	    --if_level;
1979 	goto doend;
1980     }
1981 
1982 #endif
1983 
1984     if (*p == '!' && ea.cmdidx != CMD_substitute)    /* forced commands */
1985     {
1986 	++p;
1987 	ea.forceit = TRUE;
1988     }
1989     else
1990 	ea.forceit = FALSE;
1991 
1992 /*
1993  * 5. parse arguments
1994  */
1995 #ifdef FEAT_USR_CMDS
1996     if (!USER_CMDIDX(ea.cmdidx))
1997 #endif
1998 	ea.argt = cmdnames[(int)ea.cmdidx].cmd_argt;
1999 
2000     if (!ea.skip)
2001     {
2002 #ifdef HAVE_SANDBOX
2003 	if (sandbox != 0 && !(ea.argt & SBOXOK))
2004 	{
2005 	    /* Command not allowed in sandbox. */
2006 	    errormsg = (char_u *)_(e_sandbox);
2007 	    goto doend;
2008 	}
2009 #endif
2010 	if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2011 	{
2012 	    /* Command not allowed in non-'modifiable' buffer */
2013 	    errormsg = (char_u *)_(e_modifiable);
2014 	    goto doend;
2015 	}
2016 #ifdef FEAT_CMDWIN
2017 	if (cmdwin_type != 0 && !(ea.argt & CMDWIN)
2018 # ifdef FEAT_USR_CMDS
2019 		&& !USER_CMDIDX(ea.cmdidx)
2020 # endif
2021 	   )
2022 	{
2023 	    /* Command not allowed in cmdline window. */
2024 	    errormsg = (char_u *)_(e_cmdwin);
2025 	    goto doend;
2026 	}
2027 #endif
2028 
2029 	if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2030 	{
2031 	    /* no range allowed */
2032 	    errormsg = (char_u *)_(e_norange);
2033 	    goto doend;
2034 	}
2035     }
2036 
2037     if (!ni && !(ea.argt & BANG) && ea.forceit)	/* no <!> allowed */
2038     {
2039 	errormsg = (char_u *)_(e_nobang);
2040 	goto doend;
2041     }
2042 
2043     /*
2044      * Don't complain about the range if it is not used
2045      * (could happen if line_count is accidentally set to 0).
2046      */
2047     if (!ea.skip && !ni)
2048     {
2049 	/*
2050 	 * If the range is backwards, ask for confirmation and, if given, swap
2051 	 * ea.line1 & ea.line2 so it's forwards again.
2052 	 * When global command is busy, don't ask, will fail below.
2053 	 */
2054 	if (!global_busy && ea.line1 > ea.line2)
2055 	{
2056 	    if (sourcing)
2057 	    {
2058 		errormsg = (char_u *)_("E493: Backwards range given");
2059 		goto doend;
2060 	    }
2061 	    else
2062 	    {
2063 		int	msg_silent_save = msg_silent;
2064 
2065 		msg_silent = 0;
2066 		if (ask_yesno((char_u *)
2067 			_("Backwards range given, OK to swap"), FALSE) != 'y')
2068 		goto doend;
2069 		msg_silent = msg_silent_save;
2070 	    }
2071 	    lnum = ea.line1;
2072 	    ea.line1 = ea.line2;
2073 	    ea.line2 = lnum;
2074 	}
2075 	if ((errormsg = invalid_range(&ea)) != NULL)
2076 	    goto doend;
2077     }
2078 
2079     if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2080 	ea.line2 = 1;
2081 
2082     correct_range(&ea);
2083 
2084 #ifdef FEAT_FOLDING
2085     if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy)
2086     {
2087 	/* Put the first line at the start of a closed fold, put the last line
2088 	 * at the end of a closed fold. */
2089 	(void)hasFolding(ea.line1, &ea.line1, NULL);
2090 	(void)hasFolding(ea.line2, NULL, &ea.line2);
2091     }
2092 #endif
2093 
2094 #ifdef FEAT_QUICKFIX
2095     /*
2096      * For the :make and :grep commands we insert the 'makeprg'/'grepprg'
2097      * option here, so things like % get expanded.
2098      */
2099     if (ea.cmdidx == CMD_make || ea.cmdidx == CMD_grep
2100 						  || ea.cmdidx == CMD_grepadd)
2101     {
2102 	char_u		*new_cmdline;
2103 	char_u		*program;
2104 	char_u		*pos;
2105 	char_u		*ptr;
2106 	int		len;
2107 	int		i;
2108 
2109 	if (ea.cmdidx == CMD_grep || ea.cmdidx == CMD_grepadd)
2110 	{
2111 	    if (*curbuf->b_p_gp == NUL)
2112 		program = p_gp;
2113 	    else
2114 		program = curbuf->b_p_gp;
2115 	}
2116 	else
2117 	{
2118 	    if (*curbuf->b_p_mp == NUL)
2119 		program = p_mp;
2120 	    else
2121 		program = curbuf->b_p_mp;
2122 	}
2123 
2124 	p = skipwhite(p);
2125 
2126 	if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
2127 	{				/* replace $* by given arguments */
2128 	    i = 1;
2129 	    while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
2130 		++i;
2131 	    len = (int)STRLEN(p);
2132 	    new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
2133 	    if (new_cmdline == NULL)
2134 		goto doend;		    /* out of memory */
2135 	    ptr = new_cmdline;
2136 	    while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
2137 	    {
2138 		i = (int)(pos - program);
2139 		STRNCPY(ptr, program, i);
2140 		STRCPY(ptr += i, p);
2141 		ptr += len;
2142 		program = pos + 2;
2143 	    }
2144 	    STRCPY(ptr, program);
2145 	}
2146 	else
2147 	{
2148 	    new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
2149 	    if (new_cmdline == NULL)
2150 		goto doend;		    /* out of memory */
2151 	    STRCPY(new_cmdline, program);
2152 	    STRCAT(new_cmdline, " ");
2153 	    STRCAT(new_cmdline, p);
2154 	}
2155 	msg_make(p);
2156 	/* 'ea.cmd' is not set here, because it is not used at CMD_make */
2157 	vim_free(*cmdlinep);
2158 	*cmdlinep = new_cmdline;
2159 	p = new_cmdline;
2160     }
2161 #endif
2162 
2163     /*
2164      * Skip to start of argument.
2165      * Don't do this for the ":!" command, because ":!! -l" needs the space.
2166      */
2167     if (ea.cmdidx == CMD_bang)
2168 	ea.arg = p;
2169     else
2170 	ea.arg = skipwhite(p);
2171 
2172     /*
2173      * Check for "++opt=val" argument.
2174      * Must be first, allow ":w ++enc=utf8 !cmd"
2175      */
2176     if (ea.argt & ARGOPT)
2177 	while (ea.arg[0] == '+' && ea.arg[1] == '+')
2178 	    if (getargopt(&ea) == FAIL && !ni)
2179 	    {
2180 		errormsg = (char_u *)_(e_invarg);
2181 		goto doend;
2182 	    }
2183 
2184     if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2185     {
2186 	if (*ea.arg == '>')			/* append */
2187 	{
2188 	    if (*++ea.arg != '>')		/* typed wrong */
2189 	    {
2190 		errormsg = (char_u *)_("E494: Use w or w>>");
2191 		goto doend;
2192 	    }
2193 	    ea.arg = skipwhite(ea.arg + 1);
2194 	    ea.append = TRUE;
2195 	}
2196 	else if (*ea.arg == '!' && ea.cmdidx == CMD_write)  /* :w !filter */
2197 	{
2198 	    ++ea.arg;
2199 	    ea.usefilter = TRUE;
2200 	}
2201     }
2202 
2203     if (ea.cmdidx == CMD_read)
2204     {
2205 	if (ea.forceit)
2206 	{
2207 	    ea.usefilter = TRUE;		/* :r! filter if ea.forceit */
2208 	    ea.forceit = FALSE;
2209 	}
2210 	else if (*ea.arg == '!')		/* :r !filter */
2211 	{
2212 	    ++ea.arg;
2213 	    ea.usefilter = TRUE;
2214 	}
2215     }
2216 
2217     if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2218     {
2219 	ea.amount = 1;
2220 	while (*ea.arg == *ea.cmd)		/* count number of '>' or '<' */
2221 	{
2222 	    ++ea.arg;
2223 	    ++ea.amount;
2224 	}
2225 	ea.arg = skipwhite(ea.arg);
2226     }
2227 
2228     /*
2229      * Check for "+command" argument, before checking for next command.
2230      * Don't do this for ":read !cmd" and ":write !cmd".
2231      */
2232     if ((ea.argt & EDITCMD) && !ea.usefilter)
2233 	ea.do_ecmd_cmd = getargcmd(&ea.arg);
2234 
2235     /*
2236      * Check for '|' to separate commands and '"' to start comments.
2237      * Don't do this for ":read !cmd" and ":write !cmd".
2238      */
2239     if ((ea.argt & TRLBAR) && !ea.usefilter)
2240 	separate_nextcmd(&ea);
2241 
2242     /*
2243      * Check for <newline> to end a shell command.
2244      * Also do this for ":read !cmd" and ":write !cmd".
2245      */
2246     else if (ea.cmdidx == CMD_bang || ea.usefilter)
2247     {
2248 	for (p = ea.arg; *p; ++p)
2249 	{
2250 	    /* Remove one backslash before a newline, so that it's possible to
2251 	     * pass a newline to the shell and also a newline that is preceded
2252 	     * with a backslash.  This makes it impossible to end a shell
2253 	     * command in a backslash, but that doesn't appear useful.
2254 	     * Halving the number of backslashes is incompatible with previous
2255 	     * versions. */
2256 	    if (*p == '\\' && p[1] == '\n')
2257 		mch_memmove(p, p + 1, STRLEN(p));
2258 	    else if (*p == '\n')
2259 	    {
2260 		ea.nextcmd = p + 1;
2261 		*p = NUL;
2262 		break;
2263 	    }
2264 	}
2265     }
2266 
2267     if ((ea.argt & DFLALL) && ea.addr_count == 0)
2268     {
2269 	ea.line1 = 1;
2270 	ea.line2 = curbuf->b_ml.ml_line_count;
2271     }
2272 
2273     /* accept numbered register only when no count allowed (:put) */
2274     if (       (ea.argt & REGSTR)
2275 	    && *ea.arg != NUL
2276 #ifdef FEAT_USR_CMDS
2277 	    && valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2278 						   && USER_CMDIDX(ea.cmdidx)))
2279 	    /* Do not allow register = for user commands */
2280 	    && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2281 #else
2282 	    && valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put)
2283 #endif
2284 	    && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2285     {
2286 	ea.regname = *ea.arg++;
2287 #ifdef FEAT_EVAL
2288 	/* for '=' register: accept the rest of the line as an expression */
2289 	if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2290 	{
2291 	    set_expr_line(vim_strsave(ea.arg));
2292 	    ea.arg += STRLEN(ea.arg);
2293 	}
2294 #endif
2295 	ea.arg = skipwhite(ea.arg);
2296     }
2297 
2298     /*
2299      * Check for a count.  When accepting a BUFNAME, don't use "123foo" as a
2300      * count, it's a buffer name.
2301      */
2302     if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2303 	    && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2304 							  || vim_iswhite(*p)))
2305     {
2306 	n = getdigits(&ea.arg);
2307 	ea.arg = skipwhite(ea.arg);
2308 	if (n <= 0 && !ni)
2309 	{
2310 	    errormsg = (char_u *)_(e_zerocount);
2311 	    goto doend;
2312 	}
2313 	if (ea.argt & NOTADR)	/* e.g. :buffer 2, :sleep 3 */
2314 	{
2315 	    ea.line2 = n;
2316 	    if (ea.addr_count == 0)
2317 		ea.addr_count = 1;
2318 	}
2319 	else
2320 	{
2321 	    ea.line1 = ea.line2;
2322 	    ea.line2 += n - 1;
2323 	    ++ea.addr_count;
2324 	    /*
2325 	     * Be vi compatible: no error message for out of range.
2326 	     */
2327 	    if (ea.line2 > curbuf->b_ml.ml_line_count)
2328 		ea.line2 = curbuf->b_ml.ml_line_count;
2329 	}
2330     }
2331 						/* no arguments allowed */
2332     if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2333 			      && vim_strchr((char_u *)"|\"", *ea.arg) == NULL)
2334     {
2335 	errormsg = (char_u *)_(e_trailing);
2336 	goto doend;
2337     }
2338 
2339     if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2340     {
2341 	errormsg = (char_u *)_(e_argreq);
2342 	goto doend;
2343     }
2344 
2345 #ifdef FEAT_EVAL
2346     /*
2347      * Skip the command when it's not going to be executed.
2348      * The commands like :if, :endif, etc. always need to be executed.
2349      * Also make an exception for commands that handle a trailing command
2350      * themselves.
2351      */
2352     if (ea.skip)
2353     {
2354 	switch (ea.cmdidx)
2355 	{
2356 	    /* commands that need evaluation */
2357 	    case CMD_while:
2358 	    case CMD_endwhile:
2359 	    case CMD_if:
2360 	    case CMD_elseif:
2361 	    case CMD_else:
2362 	    case CMD_endif:
2363 	    case CMD_try:
2364 	    case CMD_catch:
2365 	    case CMD_finally:
2366 	    case CMD_endtry:
2367 	    case CMD_function:
2368 				break;
2369 
2370 	    /* Commands that handle '|' themselves.  Check: A command should
2371 	     * either have the TRLBAR flag, appear in this list or appear in
2372 	     * the list at ":help :bar". */
2373 	    case CMD_aboveleft:
2374 	    case CMD_and:
2375 	    case CMD_belowright:
2376 	    case CMD_botright:
2377 	    case CMD_browse:
2378 	    case CMD_call:
2379 	    case CMD_confirm:
2380 	    case CMD_delfunction:
2381 	    case CMD_djump:
2382 	    case CMD_dlist:
2383 	    case CMD_dsearch:
2384 	    case CMD_dsplit:
2385 	    case CMD_echo:
2386 	    case CMD_echoerr:
2387 	    case CMD_echomsg:
2388 	    case CMD_echon:
2389 	    case CMD_execute:
2390 	    case CMD_help:
2391 	    case CMD_hide:
2392 	    case CMD_ijump:
2393 	    case CMD_ilist:
2394 	    case CMD_isearch:
2395 	    case CMD_isplit:
2396 	    case CMD_keepalt:
2397 	    case CMD_keepjumps:
2398 	    case CMD_keepmarks:
2399 	    case CMD_leftabove:
2400 	    case CMD_let:
2401 	    case CMD_lockmarks:
2402 	    case CMD_match:
2403 	    case CMD_mzscheme:
2404 	    case CMD_perl:
2405 	    case CMD_psearch:
2406 	    case CMD_python:
2407 	    case CMD_return:
2408 	    case CMD_rightbelow:
2409 	    case CMD_ruby:
2410 	    case CMD_silent:
2411 	    case CMD_smagic:
2412 	    case CMD_snomagic:
2413 	    case CMD_substitute:
2414 	    case CMD_syntax:
2415 	    case CMD_tcl:
2416 	    case CMD_throw:
2417 	    case CMD_tilde:
2418 	    case CMD_topleft:
2419 	    case CMD_unlet:
2420 	    case CMD_verbose:
2421 	    case CMD_vertical:
2422 				break;
2423 
2424 	    default:		goto doend;
2425 	}
2426     }
2427 #endif
2428 
2429     if (ea.argt & XFILE)
2430     {
2431 	if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2432 	    goto doend;
2433     }
2434 
2435 #ifdef FEAT_LISTCMDS
2436     /*
2437      * Accept buffer name.  Cannot be used at the same time with a buffer
2438      * number.  Don't do this for a user command.
2439      */
2440     if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2441 # ifdef FEAT_USR_CMDS
2442 	    && !USER_CMDIDX(ea.cmdidx)
2443 # endif
2444 	    )
2445     {
2446 	/*
2447 	 * :bdelete, :bwipeout and :bunload take several arguments, separated
2448 	 * by spaces: find next space (skipping over escaped characters).
2449 	 * The others take one argument: ignore trailing spaces.
2450 	 */
2451 	if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2452 						  || ea.cmdidx == CMD_bunload)
2453 	    p = skiptowhite_esc(ea.arg);
2454 	else
2455 	{
2456 	    p = ea.arg + STRLEN(ea.arg);
2457 	    while (p > ea.arg && vim_iswhite(p[-1]))
2458 		--p;
2459 	}
2460 	ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE);
2461 	if (ea.line2 < 0)	    /* failed */
2462 	    goto doend;
2463 	ea.addr_count = 1;
2464 	ea.arg = skipwhite(p);
2465     }
2466 #endif
2467 
2468 /*
2469  * 6. switch on command name
2470  *
2471  * The "ea" structure holds the arguments that can be used.
2472  */
2473     ea.cmdlinep = cmdlinep;
2474     ea.getline = getline;
2475     ea.cookie = cookie;
2476 #ifdef FEAT_EVAL
2477     ea.cstack = cstack;
2478 #endif
2479 
2480 #ifdef FEAT_USR_CMDS
2481     if (USER_CMDIDX(ea.cmdidx))
2482     {
2483 	/*
2484 	 * Execute a user-defined command.
2485 	 */
2486 	do_ucmd(&ea);
2487     }
2488     else
2489 #endif
2490     {
2491 	/*
2492 	 * Call the function to execute the command.
2493 	 */
2494 	ea.errmsg = NULL;
2495 	(cmdnames[ea.cmdidx].cmd_func)(&ea);
2496 	if (ea.errmsg != NULL)
2497 	    errormsg = (char_u *)_(ea.errmsg);
2498     }
2499 
2500 #ifdef FEAT_EVAL
2501     /*
2502      * If the command just executed called do_cmdline(), any throw or ":return"
2503      * or ":finish" encountered there must also check the cstack of the still
2504      * active do_cmdline() that called this do_one_cmd().  Rethrow an uncaught
2505      * exception, or reanimate a returned function or finished script file and
2506      * return or finish it again.
2507      */
2508     if (need_rethrow)
2509 	do_throw(cstack);
2510     else if (check_cstack)
2511     {
2512 	if (source_finished(getline, cookie))
2513 	    do_finish(&ea, TRUE);
2514 	else if (getline_equal(getline, cookie, get_func_line)
2515 						   && current_func_returned())
2516 	    do_return(&ea, TRUE, FALSE, NULL);
2517     }
2518     need_rethrow = check_cstack = FALSE;
2519 #endif
2520 
2521 doend:
2522     if (curwin->w_cursor.lnum == 0)	/* can happen with zero line number */
2523 	curwin->w_cursor.lnum = 1;
2524 
2525     if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2526     {
2527 	if (sourcing)
2528 	{
2529 	    if (errormsg != IObuff)
2530 	    {
2531 		STRCPY(IObuff, errormsg);
2532 		errormsg = IObuff;
2533 	    }
2534 	    STRCAT(errormsg, ": ");
2535 	    STRNCAT(errormsg, *cmdlinep, IOSIZE - STRLEN(IObuff));
2536 	}
2537 	emsg(errormsg);
2538     }
2539 #ifdef FEAT_EVAL
2540     do_errthrow(cstack,
2541 	    (ea.cmdidx != CMD_SIZE
2542 # ifdef FEAT_USR_CMDS
2543 	     && !USER_CMDIDX(ea.cmdidx)
2544 # endif
2545 	    ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
2546 #endif
2547 
2548     if (verbose_save >= 0)
2549 	p_verbose = verbose_save;
2550 
2551     cmdmod = save_cmdmod;
2552 
2553     if (did_silent > 0)
2554     {
2555 	/* messages could be enabled for a serious error, need to check if the
2556 	 * counters don't become negative */
2557 	msg_silent -= did_silent;
2558 	if (msg_silent < 0)
2559 	    msg_silent = 0;
2560 	emsg_silent -= did_esilent;
2561 	if (emsg_silent < 0)
2562 	    emsg_silent = 0;
2563 	/* Restore msg_scroll, it's set by file I/O commands, even when no
2564 	 * message is actually displayed. */
2565 	msg_scroll = save_msg_scroll;
2566     }
2567 
2568     if (ea.nextcmd && *ea.nextcmd == NUL)	/* not really a next command */
2569 	ea.nextcmd = NULL;
2570 
2571 #ifdef FEAT_EVAL
2572     --ex_nesting_level;
2573 #endif
2574 
2575     return ea.nextcmd;
2576 }
2577 #if (_MSC_VER == 1200)
2578 # pragma optimize( "", on )
2579 #endif
2580 
2581 /*
2582  * Check for a command modifier command with optional tail.
2583  * If there is a match advance "pp" to the argument and return TRUE.
2584  */
2585     static int
2586 checkforcmd(pp, cmd, len)
2587     char_u	**pp;		/* start of command line */
2588     char	*cmd;		/* name of command */
2589     int		len;		/* required length */
2590 {
2591     int		i;
2592 
2593     for (i = 0; cmd[i] != NUL; ++i)
2594 	if (cmd[i] != (*pp)[i])
2595 	    break;
2596     if (i >= len && !isalpha((*pp)[i]))
2597     {
2598 	*pp = skipwhite(*pp + i);
2599 	return TRUE;
2600     }
2601     return FALSE;
2602 }
2603 
2604 /*
2605  * Find an Ex command by its name, either built-in or user.
2606  * Name can be found at eap->cmd.
2607  * Returns pointer to char after the command name.
2608  * Returns NULL for an ambiguous user command.
2609  */
2610 /*ARGSUSED*/
2611     static char_u *
2612 find_command(eap, full)
2613     exarg_T	*eap;
2614     int		*full;
2615 {
2616     int		len;
2617     char_u	*p;
2618 
2619     /*
2620      * Isolate the command and search for it in the command table.
2621      * Exeptions:
2622      * - the 'k' command can directly be followed by any character.
2623      * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2624      *	    but :sre[wind] is another command, as are :scrip[tnames],
2625      *	    :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
2626      */
2627     p = eap->cmd;
2628     if (*p == 'k')
2629     {
2630 	eap->cmdidx = CMD_k;
2631 	++p;
2632     }
2633     else if (p[0] == 's'
2634 	    && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r' && p[3] != 'i' && p[4] != 'p')
2635 		|| p[1] == 'g'
2636 		|| (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
2637 		|| p[1] == 'I'
2638 		|| (p[1] == 'r' && p[2] != 'e')))
2639     {
2640 	eap->cmdidx = CMD_substitute;
2641 	++p;
2642     }
2643     else
2644     {
2645 	while (ASCII_ISALPHA(*p))
2646 	    ++p;
2647 	/* check for non-alpha command */
2648 	if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2649 	    ++p;
2650 	len = (int)(p - eap->cmd);
2651 
2652 	if (ASCII_ISLOWER(*eap->cmd))
2653 	    eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)];
2654 	else
2655 	    eap->cmdidx = cmdidxs[26];
2656 
2657 	for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
2658 			       eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
2659 	    if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
2660 							    (size_t)len) == 0)
2661 	    {
2662 #ifdef FEAT_EVAL
2663 		if (full != NULL
2664 			   && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
2665 		    *full = TRUE;
2666 #endif
2667 		break;
2668 	    }
2669 
2670 #ifdef FEAT_USR_CMDS
2671 	/* Look for a user defined command as a last resort */
2672 	if (eap->cmdidx == CMD_SIZE && *eap->cmd >= 'A' && *eap->cmd <= 'Z')
2673 	{
2674 	    ucmd_T	*cmd;
2675 	    int		j, k, matchlen = 0;
2676 	    int		found = FALSE, possible = FALSE;
2677 	    char_u	*cp, *np;	/* Point into typed cmd and test name */
2678 	    garray_T	*gap;
2679 	    int		amb_local = FALSE; /* Found ambiguous buffer-local
2680 					      command, only full match global
2681 					      is accepted. */
2682 
2683 	    /* User defined commands may contain numbers */
2684 	    while (ASCII_ISALNUM(*p))
2685 		++p;
2686 	    len = (int)(p - eap->cmd);
2687 
2688 	    /*
2689 	     * Look for buffer-local user commands first, then global ones.
2690 	     */
2691 	    gap = &curbuf->b_ucmds;
2692 	    for (;;)
2693 	    {
2694 		for (j = 0; j < gap->ga_len; ++j)
2695 		{
2696 		    cmd = USER_CMD_GA(gap, j);
2697 		    cp = eap->cmd;
2698 		    np = cmd->uc_name;
2699 		    k = 0;
2700 		    while (k < len && *np != NUL && *cp++ == *np++)
2701 			k++;
2702 		    if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
2703 		    {
2704 			/* If finding a second match, the command is
2705 			 * ambiguous.  But not if a buffer-local command
2706 			 * wasn't a full match and a global command is a full
2707 			 * match. */
2708 			if (k == len && found && *np != NUL)
2709 			{
2710 			    if (gap == &ucmds)
2711 				return NULL;
2712 			    amb_local = TRUE;
2713 			}
2714 
2715 			if (!found || (k == len && *np == NUL))
2716 			{
2717 			    /* If we matched up to a digit, then there could
2718 			     * be another command including the digit that we
2719 			     * should use instead.
2720 			     */
2721 			    if (k == len)
2722 				found = TRUE;
2723 			    else
2724 				possible = TRUE;
2725 
2726 			    if (gap == &ucmds)
2727 				eap->cmdidx = CMD_USER;
2728 			    else
2729 				eap->cmdidx = CMD_USER_BUF;
2730 			    eap->argt = cmd->uc_argt;
2731 			    eap->useridx = j;
2732 
2733 			    /* Do not search for further abbreviations
2734 			     * if this is an exact match. */
2735 			    matchlen = k;
2736 			    if (k == len && *np == NUL)
2737 			    {
2738 				if (full != NULL)
2739 				    *full = TRUE;
2740 				amb_local = FALSE;
2741 				break;
2742 			    }
2743 			}
2744 		    }
2745 		}
2746 
2747 		/* Stop if we found a full match or searched all. */
2748 		if (j < gap->ga_len || gap == &ucmds)
2749 		    break;
2750 		gap = &ucmds;
2751 	    }
2752 
2753 	    /* Only found ambiguous matches. */
2754 	    if (amb_local)
2755 		return NULL;
2756 
2757 	    /* The match we found may be followed immediately by a
2758 	     * number.  Move *p back to point to it.
2759 	     */
2760 	    if (found || possible)
2761 		p += matchlen - len;
2762 	}
2763 #endif
2764 
2765 	if (len == 0)
2766 	    eap->cmdidx = CMD_SIZE;
2767     }
2768 
2769     return p;
2770 }
2771 
2772 #if defined(FEAT_EVAL) || defined(PROTO)
2773 /*
2774  * Return > 0 if an Ex command "name" exists.
2775  * Return 2 if there is an exact match.
2776  * Return 3 if there is an ambiguous match.
2777  */
2778     int
2779 cmd_exists(name)
2780     char_u	*name;
2781 {
2782     exarg_T	ea;
2783     int		full = FALSE;
2784     int		i;
2785     int		j;
2786     static struct cmdmod
2787     {
2788 	char	*name;
2789 	int	minlen;
2790     } cmdmods[] = {
2791 	{"aboveleft", 3},
2792 	{"belowright", 3},
2793 	{"botright", 2},
2794 	{"browse", 3},
2795 	{"confirm", 4},
2796 	{"hide", 3},
2797 	{"keepalt", 5},
2798 	{"keepjumps", 5},
2799 	{"keepmarks", 3},
2800 	{"leftabove", 5},
2801 	{"lockmarks", 3},
2802 	{"rightbelow", 6},
2803 	{"silent", 3},
2804 	{"topleft", 2},
2805 	{"verbose", 4},
2806 	{"vertical", 4},
2807     };
2808 
2809     /* Check command modifiers. */
2810     for (i = 0; i < sizeof(cmdmods) / sizeof(struct cmdmod); ++i)
2811     {
2812 	for (j = 0; name[j] != NUL; ++j)
2813 	    if (name[j] != cmdmods[i].name[j])
2814 		break;
2815 	if (name[j] == NUL && j >= cmdmods[i].minlen)
2816 	    return (cmdmods[i].name[j] == NUL ? 2 : 1);
2817     }
2818 
2819     /* Check built-in commands and user defined commands. */
2820     ea.cmd = name;
2821     ea.cmdidx = (cmdidx_T)0;
2822     if (find_command(&ea, &full) == NULL)
2823 	return 3;
2824     return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
2825 }
2826 #endif
2827 
2828 /*
2829  * This is all pretty much copied from do_one_cmd(), with all the extra stuff
2830  * we don't need/want deleted.	Maybe this could be done better if we didn't
2831  * repeat all this stuff.  The only problem is that they may not stay
2832  * perfectly compatible with each other, but then the command line syntax
2833  * probably won't change that much -- webb.
2834  */
2835     char_u *
2836 set_one_cmd_context(xp, buff)
2837     expand_T	*xp;
2838     char_u	*buff;	    /* buffer for command string */
2839 {
2840     char_u		*p;
2841     char_u		*cmd, *arg;
2842     int			i = 0;
2843     cmdidx_T		cmdidx;
2844     long_u		argt = 0;
2845 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
2846     int			compl = EXPAND_NOTHING;
2847 #endif
2848 #ifdef FEAT_CMDL_COMPL
2849     int			delim;
2850 #endif
2851     int			forceit = FALSE;
2852     int			usefilter = FALSE;  /* filter instead of file name */
2853 
2854     xp->xp_pattern = buff;
2855     xp->xp_context = EXPAND_COMMANDS;	/* Default until we get past command */
2856     xp->xp_backslash = XP_BS_NONE;
2857 #if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
2858     xp->xp_arg = NULL;
2859 #endif
2860 
2861 /*
2862  * 2. skip comment lines and leading space, colons or bars
2863  */
2864     for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
2865 	;
2866     xp->xp_pattern = cmd;
2867 
2868     if (*cmd == NUL)
2869 	return NULL;
2870     if (*cmd == '"')	    /* ignore comment lines */
2871     {
2872 	xp->xp_context = EXPAND_NOTHING;
2873 	return NULL;
2874     }
2875 
2876 /*
2877  * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
2878  */
2879     cmd = skip_range(cmd, &xp->xp_context);
2880 
2881 /*
2882  * 4. parse command
2883  */
2884 
2885     cmd = skipwhite(cmd);
2886     xp->xp_pattern = cmd;
2887     if (*cmd == NUL)
2888 	return NULL;
2889     if (*cmd == '"')
2890     {
2891 	xp->xp_context = EXPAND_NOTHING;
2892 	return NULL;
2893     }
2894 
2895     if (*cmd == '|' || *cmd == '\n')
2896 	return cmd + 1;			/* There's another command */
2897 
2898     /*
2899      * Isolate the command and search for it in the command table.
2900      * Exceptions:
2901      * - the 'k' command can directly be followed by any character, but
2902      *   do accept "keepmarks", "keepalt" and "keepjumps".
2903      * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2904      */
2905     if (*cmd == 'k' && cmd[1] != 'e')
2906     {
2907 	cmdidx = CMD_k;
2908 	p = cmd + 1;
2909     }
2910     else
2911     {
2912 	p = cmd;
2913 	while (ASCII_ISALPHA(*p) || *p == '*')    /* Allow * wild card */
2914 	    ++p;
2915 	/* check for non-alpha command */
2916 	if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2917 	    ++p;
2918 	i = (int)(p - cmd);
2919 
2920 	if (i == 0)
2921 	{
2922 	    xp->xp_context = EXPAND_UNSUCCESSFUL;
2923 	    return NULL;
2924 	}
2925 	for (cmdidx = (cmdidx_T)0; (int)cmdidx < (int)CMD_SIZE;
2926 					 cmdidx = (cmdidx_T)((int)cmdidx + 1))
2927 	    if (STRNCMP(cmdnames[(int)cmdidx].cmd_name, cmd, (size_t)i) == 0)
2928 		break;
2929 
2930 #ifdef FEAT_USR_CMDS
2931 	if (cmd[0] >= 'A' && cmd[0] <= 'Z')
2932 	{
2933 	    while (ASCII_ISALNUM(*p) || *p == '*')	/* Allow * wild card */
2934 		++p;
2935 	    i = (int)(p - cmd);
2936 	}
2937 #endif
2938     }
2939 
2940     /*
2941      * If the cursor is touching the command, and it ends in an alpha-numeric
2942      * character, complete the command name.
2943      */
2944     if (*p == NUL && ASCII_ISALNUM(p[-1]))
2945 	return NULL;
2946 
2947     if (cmdidx == CMD_SIZE)
2948     {
2949 	if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
2950 	{
2951 	    cmdidx = CMD_substitute;
2952 	    p = cmd + 1;
2953 	}
2954 #ifdef FEAT_USR_CMDS
2955 	else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
2956 	{
2957 	    /* Look for a user defined command as a last resort */
2958 	    ucmd_T	*uc;
2959 	    int		j, k, matchlen = 0;
2960 	    int		found = FALSE, possible = FALSE;
2961 	    char_u	*cp, *np;	/* Point into typed cmd and test name */
2962 	    garray_T	*gap;
2963 
2964 	    gap = &curbuf->b_ucmds;
2965 	    for (;;)
2966 	    {
2967 		uc = USER_CMD_GA(gap, 0);
2968 		for (j = 0; j < gap->ga_len; ++j, ++uc)
2969 		{
2970 		    cp = cmd;
2971 		    np = uc->uc_name;
2972 		    k = 0;
2973 		    while (k < i && *np != NUL && *cp++ == *np++)
2974 			k++;
2975 		    if (k == i || (*np == NUL && VIM_ISDIGIT(cmd[k])))
2976 		    {
2977 			if (k == i && found)
2978 			{
2979 			    /* Ambiguous abbreviation */
2980 			    xp->xp_context = EXPAND_UNSUCCESSFUL;
2981 			    return NULL;
2982 			}
2983 			if (!found)
2984 			{
2985 			    /* If we matched up to a digit, then there could
2986 			     * be another command including the digit that we
2987 			     * should use instead.
2988 			     */
2989 			    if (k == i)
2990 				found = TRUE;
2991 			    else
2992 				possible = TRUE;
2993 
2994 			    if (gap == &ucmds)
2995 				cmdidx = CMD_USER;
2996 			    else
2997 				cmdidx = CMD_USER_BUF;
2998 			    argt = uc->uc_argt;
2999 #ifdef FEAT_CMDL_COMPL
3000 			    compl = uc->uc_compl;
3001 # ifdef FEAT_EVAL
3002 			    xp->xp_arg = uc->uc_compl_arg;
3003 			    xp->xp_scriptID = uc->uc_scriptID;
3004 # endif
3005 #endif
3006 			    /* Do not search for further abbreviations
3007 			     * if this is an exact match
3008 			     */
3009 			    matchlen = k;
3010 			    if (k == i && *np == NUL)
3011 				break;
3012 			}
3013 		    }
3014 		}
3015 		if (gap == &ucmds || j < gap->ga_len)
3016 		    break;
3017 		gap = &ucmds;
3018 	    }
3019 
3020 	    /* The match we found may be followed immediately by a
3021 	     * number.  Move *p back to point to it.
3022 	     */
3023 	    if (found || possible)
3024 		p += matchlen - i;
3025 	}
3026 #endif
3027     }
3028     if (cmdidx == CMD_SIZE)
3029     {
3030 	/* Not still touching the command and it was an illegal one */
3031 	xp->xp_context = EXPAND_UNSUCCESSFUL;
3032 	return NULL;
3033     }
3034 
3035     xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3036 
3037     if (*p == '!')		    /* forced commands */
3038     {
3039 	forceit = TRUE;
3040 	++p;
3041     }
3042 
3043 /*
3044  * 5. parse arguments
3045  */
3046 #ifdef FEAT_USR_CMDS
3047     if (!USER_CMDIDX(cmdidx))
3048 #endif
3049 	argt = cmdnames[(int)cmdidx].cmd_argt;
3050 
3051     arg = skipwhite(p);
3052 
3053     if (cmdidx == CMD_write || cmdidx == CMD_update)
3054     {
3055 	if (*arg == '>')			/* append */
3056 	{
3057 	    if (*++arg == '>')
3058 		++arg;
3059 	    arg = skipwhite(arg);
3060 	}
3061 	else if (*arg == '!' && cmdidx == CMD_write)	/* :w !filter */
3062 	{
3063 	    ++arg;
3064 	    usefilter = TRUE;
3065 	}
3066     }
3067 
3068     if (cmdidx == CMD_read)
3069     {
3070 	usefilter = forceit;			/* :r! filter if forced */
3071 	if (*arg == '!')			/* :r !filter */
3072 	{
3073 	    ++arg;
3074 	    usefilter = TRUE;
3075 	}
3076     }
3077 
3078     if (cmdidx == CMD_lshift || cmdidx == CMD_rshift)
3079     {
3080 	while (*arg == *cmd)	    /* allow any number of '>' or '<' */
3081 	    ++arg;
3082 	arg = skipwhite(arg);
3083     }
3084 
3085     /* Does command allow "+command"? */
3086     if ((argt & EDITCMD) && !usefilter && *arg == '+')
3087     {
3088 	/* Check if we're in the +command */
3089 	p = arg + 1;
3090 	arg = skip_cmd_arg(arg, FALSE);
3091 
3092 	/* Still touching the command after '+'? */
3093 	if (*arg == NUL)
3094 	    return p;
3095 
3096 	/* Skip space(s) after +command to get to the real argument */
3097 	arg = skipwhite(arg);
3098     }
3099 
3100     /*
3101      * Check for '|' to separate commands and '"' to start comments.
3102      * Don't do this for ":read !cmd" and ":write !cmd".
3103      */
3104     if ((argt & TRLBAR) && !usefilter)
3105     {
3106 	p = arg;
3107 	/* ":redir @" is not the start of a comment */
3108 	if (cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3109 	    p += 2;
3110 	while (*p)
3111 	{
3112 	    if (*p == Ctrl_V)
3113 	    {
3114 		if (p[1] != NUL)
3115 		    ++p;
3116 	    }
3117 	    else if ( (*p == '"' && !(argt & NOTRLCOM))
3118 		    || *p == '|' || *p == '\n')
3119 	    {
3120 		if (*(p - 1) != '\\')
3121 		{
3122 		    if (*p == '|' || *p == '\n')
3123 			return p + 1;
3124 		    return NULL;    /* It's a comment */
3125 		}
3126 	    }
3127 #ifdef FEAT_MBYTE
3128 	    if (has_mbyte)
3129 		p += (*mb_ptr2len_check)(p);
3130 	    else
3131 #endif
3132 		++p;
3133 	}
3134     }
3135 
3136 						/* no arguments allowed */
3137     if (!(argt & EXTRA) && *arg != NUL &&
3138 				    vim_strchr((char_u *)"|\"", *arg) == NULL)
3139 	return NULL;
3140 
3141     /* Find start of last argument (argument just before cursor): */
3142     p = buff + STRLEN(buff);
3143     while (p != arg && *p != ' ' && *p != TAB)
3144 	p--;
3145     if (*p == ' ' || *p == TAB)
3146 	p++;
3147     xp->xp_pattern = p;
3148 
3149     if (argt & XFILE)
3150     {
3151 	int in_quote = FALSE;
3152 	char_u *bow = NULL;	/* Beginning of word */
3153 
3154 	/*
3155 	 * Allow spaces within back-quotes to count as part of the argument
3156 	 * being expanded.
3157 	 */
3158 	xp->xp_pattern = skipwhite(arg);
3159 	for (p = xp->xp_pattern; *p; )
3160 	{
3161 	    if (*p == '\\' && p[1])
3162 		++p;
3163 #ifdef SPACE_IN_FILENAME
3164 	    else if (vim_iswhite(*p) && (!(argt & NOSPC) || usefilter))
3165 #else
3166 	    else if (vim_iswhite(*p))
3167 #endif
3168 	    {
3169 		p = skipwhite(p);
3170 		if (in_quote)
3171 		    bow = p;
3172 		else
3173 		    xp->xp_pattern = p;
3174 		--p;
3175 	    }
3176 	    else if (*p == '`')
3177 	    {
3178 		if (!in_quote)
3179 		{
3180 		    xp->xp_pattern = p;
3181 		    bow = p + 1;
3182 		}
3183 		in_quote = !in_quote;
3184 	    }
3185 #ifdef FEAT_MBYTE
3186 	    if (has_mbyte)
3187 		p += (*mb_ptr2len_check)(p);
3188 	    else
3189 #endif
3190 		++p;
3191 	}
3192 
3193 	/*
3194 	 * If we are still inside the quotes, and we passed a space, just
3195 	 * expand from there.
3196 	 */
3197 	if (bow != NULL && in_quote)
3198 	    xp->xp_pattern = bow;
3199 	xp->xp_context = EXPAND_FILES;
3200 
3201 	/* Check for environment variable */
3202 	if (*xp->xp_pattern == '$'
3203 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3204 		|| *xp->xp_pattern == '%'
3205 #endif
3206 		)
3207 	{
3208 	    for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3209 		if (!vim_isIDc(*p))
3210 		    break;
3211 	    if (*p == NUL)
3212 	    {
3213 		xp->xp_context = EXPAND_ENV_VARS;
3214 		++xp->xp_pattern;
3215 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3216 		/* Avoid that the assignment uses EXPAND_FILES again. */
3217 		if (compl != EXPAND_USER_DEFINED)
3218 		    compl = EXPAND_ENV_VARS;
3219 #endif
3220 	    }
3221 	}
3222     }
3223 
3224 /*
3225  * 6. switch on command name
3226  */
3227     switch (cmdidx)
3228     {
3229 	case CMD_cd:
3230 	case CMD_chdir:
3231 	case CMD_lcd:
3232 	case CMD_lchdir:
3233 	    if (xp->xp_context == EXPAND_FILES)
3234 		xp->xp_context = EXPAND_DIRECTORIES;
3235 	    break;
3236 	case CMD_help:
3237 	    xp->xp_context = EXPAND_HELP;
3238 	    xp->xp_pattern = arg;
3239 	    break;
3240 
3241 	/* Command modifiers: return the argument. */
3242 	case CMD_aboveleft:
3243 	case CMD_belowright:
3244 	case CMD_botright:
3245 	case CMD_browse:
3246 	case CMD_confirm:
3247 	case CMD_folddoclosed:
3248 	case CMD_folddoopen:
3249 	case CMD_hide:
3250 	case CMD_keepalt:
3251 	case CMD_keepjumps:
3252 	case CMD_keepmarks:
3253 	case CMD_leftabove:
3254 	case CMD_lockmarks:
3255 	case CMD_rightbelow:
3256 	case CMD_silent:
3257 	case CMD_topleft:
3258 	case CMD_verbose:
3259 	case CMD_vertical:
3260 	    return arg;
3261 
3262 #ifdef FEAT_SEARCH_EXTRA
3263 	case CMD_match:
3264 	    if (*arg == NUL || !ends_excmd(*arg))
3265 	    {
3266 		/* Dummy call to clear variables. */
3267 		set_context_in_highlight_cmd(xp, (char_u *)"link n");
3268 		xp->xp_context = EXPAND_HIGHLIGHT;
3269 		xp->xp_pattern = arg;
3270 		arg = skipwhite(skiptowhite(arg));
3271 		if (*arg != NUL)
3272 		{
3273 		    xp->xp_context = EXPAND_NOTHING;
3274 		    arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3275 		}
3276 	    }
3277 	    return find_nextcmd(arg);
3278 #endif
3279 
3280 #ifdef FEAT_CMDL_COMPL
3281 /*
3282  * All completion for the +cmdline_compl feature goes here.
3283  */
3284 
3285 # ifdef FEAT_USR_CMDS
3286 	case CMD_command:
3287 	    /* Check for attributes */
3288 	    while (*arg == '-')
3289 	    {
3290 		arg++;	    /* Skip "-" */
3291 		p = skiptowhite(arg);
3292 		if (*p == NUL)
3293 		{
3294 		    /* Cursor is still in the attribute */
3295 		    p = vim_strchr(arg, '=');
3296 		    if (p == NULL)
3297 		    {
3298 			/* No "=", so complete attribute names */
3299 			xp->xp_context = EXPAND_USER_CMD_FLAGS;
3300 			xp->xp_pattern = arg;
3301 			return NULL;
3302 		    }
3303 
3304 		    /* For the -complete and -nargs attributes, we complete
3305 		     * their arguments as well.
3306 		     */
3307 		    if (STRNICMP(arg, "complete", p - arg) == 0)
3308 		    {
3309 			xp->xp_context = EXPAND_USER_COMPLETE;
3310 			xp->xp_pattern = p + 1;
3311 			return NULL;
3312 		    }
3313 		    else if (STRNICMP(arg, "nargs", p - arg) == 0)
3314 		    {
3315 			xp->xp_context = EXPAND_USER_NARGS;
3316 			xp->xp_pattern = p + 1;
3317 			return NULL;
3318 		    }
3319 		    return NULL;
3320 		}
3321 		arg = skipwhite(p);
3322 	    }
3323 
3324 	    /* After the attributes comes the new command name */
3325 	    p = skiptowhite(arg);
3326 	    if (*p == NUL)
3327 	    {
3328 		xp->xp_context = EXPAND_USER_COMMANDS;
3329 		xp->xp_pattern = arg;
3330 		break;
3331 	    }
3332 
3333 	    /* And finally comes a normal command */
3334 	    return skipwhite(p);
3335 
3336 	case CMD_delcommand:
3337 	    xp->xp_context = EXPAND_USER_COMMANDS;
3338 	    xp->xp_pattern = arg;
3339 	    break;
3340 # endif
3341 
3342 	case CMD_global:
3343 	case CMD_vglobal:
3344 	    delim = *arg;	    /* get the delimiter */
3345 	    if (delim)
3346 		++arg;		    /* skip delimiter if there is one */
3347 
3348 	    while (arg[0] != NUL && arg[0] != delim)
3349 	    {
3350 		if (arg[0] == '\\' && arg[1] != NUL)
3351 		    ++arg;
3352 		++arg;
3353 	    }
3354 	    if (arg[0] != NUL)
3355 		return arg + 1;
3356 	    break;
3357 	case CMD_and:
3358 	case CMD_substitute:
3359 	    delim = *arg;
3360 	    if (delim)
3361 	    {
3362 		/* skip "from" part */
3363 		++arg;
3364 		arg = skip_regexp(arg, delim, p_magic, NULL);
3365 	    }
3366 	    /* skip "to" part */
3367 	    while (arg[0] != NUL && arg[0] != delim)
3368 	    {
3369 		if (arg[0] == '\\' && arg[1] != NUL)
3370 		    ++arg;
3371 		++arg;
3372 	    }
3373 	    if (arg[0] != NUL)	/* skip delimiter */
3374 		++arg;
3375 	    while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
3376 		++arg;
3377 	    if (arg[0] != NUL)
3378 		return arg;
3379 	    break;
3380 	case CMD_isearch:
3381 	case CMD_dsearch:
3382 	case CMD_ilist:
3383 	case CMD_dlist:
3384 	case CMD_ijump:
3385 	case CMD_psearch:
3386 	case CMD_djump:
3387 	case CMD_isplit:
3388 	case CMD_dsplit:
3389 	    arg = skipwhite(skipdigits(arg));	    /* skip count */
3390 	    if (*arg == '/')	/* Match regexp, not just whole words */
3391 	    {
3392 		for (++arg; *arg && *arg != '/'; arg++)
3393 		    if (*arg == '\\' && arg[1] != NUL)
3394 			arg++;
3395 		if (*arg)
3396 		{
3397 		    arg = skipwhite(arg + 1);
3398 
3399 		    /* Check for trailing illegal characters */
3400 		    if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
3401 			xp->xp_context = EXPAND_NOTHING;
3402 		    else
3403 			return arg;
3404 		}
3405 	    }
3406 	    break;
3407 #ifdef FEAT_AUTOCMD
3408 	case CMD_autocmd:
3409 	    return set_context_in_autocmd(xp, arg, FALSE);
3410 
3411 	case CMD_doautocmd:
3412 	    return set_context_in_autocmd(xp, arg, TRUE);
3413 #endif
3414 	case CMD_set:
3415 	    set_context_in_set_cmd(xp, arg, 0);
3416 	    break;
3417 	case CMD_setglobal:
3418 	    set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
3419 	    break;
3420 	case CMD_setlocal:
3421 	    set_context_in_set_cmd(xp, arg, OPT_LOCAL);
3422 	    break;
3423 	case CMD_tag:
3424 	case CMD_stag:
3425 	case CMD_ptag:
3426 	case CMD_tselect:
3427 	case CMD_stselect:
3428 	case CMD_ptselect:
3429 	case CMD_tjump:
3430 	case CMD_stjump:
3431 	case CMD_ptjump:
3432 	    xp->xp_context = EXPAND_TAGS;
3433 	    xp->xp_pattern = arg;
3434 	    break;
3435 	case CMD_augroup:
3436 	    xp->xp_context = EXPAND_AUGROUP;
3437 	    xp->xp_pattern = arg;
3438 	    break;
3439 #ifdef FEAT_SYN_HL
3440 	case CMD_syntax:
3441 	    set_context_in_syntax_cmd(xp, arg);
3442 	    break;
3443 #endif
3444 #ifdef FEAT_EVAL
3445 	case CMD_let:
3446 	case CMD_if:
3447 	case CMD_elseif:
3448 	case CMD_while:
3449 	case CMD_echo:
3450 	case CMD_echon:
3451 	case CMD_execute:
3452 	case CMD_echomsg:
3453 	case CMD_echoerr:
3454 	case CMD_call:
3455 	case CMD_return:
3456 	    set_context_for_expression(xp, arg, cmdidx);
3457 	    break;
3458 
3459 	case CMD_unlet:
3460 	    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3461 		arg = xp->xp_pattern + 1;
3462 	    xp->xp_context = EXPAND_USER_VARS;
3463 	    xp->xp_pattern = arg;
3464 	    break;
3465 
3466 	case CMD_function:
3467 	case CMD_delfunction:
3468 	    xp->xp_context = EXPAND_USER_FUNC;
3469 	    xp->xp_pattern = arg;
3470 	    break;
3471 
3472 	case CMD_echohl:
3473 	    xp->xp_context = EXPAND_HIGHLIGHT;
3474 	    xp->xp_pattern = arg;
3475 	    break;
3476 #endif
3477 	case CMD_highlight:
3478 	    set_context_in_highlight_cmd(xp, arg);
3479 	    break;
3480 #ifdef FEAT_LISTCMDS
3481 	case CMD_bdelete:
3482 	case CMD_bwipeout:
3483 	case CMD_bunload:
3484 	    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3485 		arg = xp->xp_pattern + 1;
3486 	    /*FALLTHROUGH*/
3487 	case CMD_buffer:
3488 	case CMD_sbuffer:
3489 	case CMD_checktime:
3490 	    xp->xp_context = EXPAND_BUFFERS;
3491 	    xp->xp_pattern = arg;
3492 	    break;
3493 #endif
3494 #ifdef FEAT_USR_CMDS
3495 	case CMD_USER:
3496 	case CMD_USER_BUF:
3497 	    if (compl != EXPAND_NOTHING)
3498 	    {
3499 		/* XFILE: file names are handled above */
3500 		if (!(argt & XFILE))
3501 		{
3502 # ifdef FEAT_MENU
3503 		    if (compl == EXPAND_MENUS)
3504 			return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3505 # endif
3506 		    if (compl == EXPAND_COMMANDS)
3507 			return arg;
3508 		    if (compl == EXPAND_MAPPINGS)
3509 			return set_context_in_map_cmd(xp, (char_u *)"map",
3510 					 arg, forceit, FALSE, FALSE, CMD_map);
3511 		    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3512 			arg = xp->xp_pattern + 1;
3513 		    xp->xp_pattern = arg;
3514 		}
3515 		xp->xp_context = compl;
3516 	    }
3517 	    break;
3518 #endif
3519 	case CMD_map:	    case CMD_noremap:
3520 	case CMD_nmap:	    case CMD_nnoremap:
3521 	case CMD_vmap:	    case CMD_vnoremap:
3522 	case CMD_omap:	    case CMD_onoremap:
3523 	case CMD_imap:	    case CMD_inoremap:
3524 	case CMD_cmap:	    case CMD_cnoremap:
3525 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
3526 							FALSE, FALSE, cmdidx);
3527 	case CMD_unmap:
3528 	case CMD_nunmap:
3529 	case CMD_vunmap:
3530 	case CMD_ounmap:
3531 	case CMD_iunmap:
3532 	case CMD_cunmap:
3533 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
3534 							 FALSE, TRUE, cmdidx);
3535 	case CMD_abbreviate:	case CMD_noreabbrev:
3536 	case CMD_cabbrev:	case CMD_cnoreabbrev:
3537 	case CMD_iabbrev:	case CMD_inoreabbrev:
3538 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
3539 							 TRUE, FALSE, cmdidx);
3540 	case CMD_unabbreviate:
3541 	case CMD_cunabbrev:
3542 	case CMD_iunabbrev:
3543 	    return set_context_in_map_cmd(xp, cmd, arg, forceit,
3544 							  TRUE, TRUE, cmdidx);
3545 #ifdef FEAT_MENU
3546 	case CMD_menu:	    case CMD_noremenu:	    case CMD_unmenu:
3547 	case CMD_amenu:	    case CMD_anoremenu:	    case CMD_aunmenu:
3548 	case CMD_nmenu:	    case CMD_nnoremenu:	    case CMD_nunmenu:
3549 	case CMD_vmenu:	    case CMD_vnoremenu:	    case CMD_vunmenu:
3550 	case CMD_omenu:	    case CMD_onoremenu:	    case CMD_ounmenu:
3551 	case CMD_imenu:	    case CMD_inoremenu:	    case CMD_iunmenu:
3552 	case CMD_cmenu:	    case CMD_cnoremenu:	    case CMD_cunmenu:
3553 	case CMD_tmenu:				    case CMD_tunmenu:
3554 	case CMD_popup:	    case CMD_tearoff:	    case CMD_emenu:
3555 	    return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3556 #endif
3557 
3558 	case CMD_colorscheme:
3559 	    xp->xp_context = EXPAND_COLORS;
3560 	    xp->xp_pattern = arg;
3561 	    break;
3562 
3563 	case CMD_compiler:
3564 	    xp->xp_context = EXPAND_COMPILER;
3565 	    xp->xp_pattern = arg;
3566 	    break;
3567 
3568 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
3569 	&& (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
3570 	case CMD_language:
3571 	    if (*skiptowhite(arg) == NUL)
3572 	    {
3573 		xp->xp_context = EXPAND_LANGUAGE;
3574 		xp->xp_pattern = arg;
3575 	    }
3576 	    else
3577 		xp->xp_context = EXPAND_NOTHING;
3578 	    break;
3579 #endif
3580 
3581 #endif /* FEAT_CMDL_COMPL */
3582 
3583 	default:
3584 	    break;
3585     }
3586     return NULL;
3587 }
3588 
3589 /*
3590  * skip a range specifier of the form: addr [,addr] [;addr] ..
3591  *
3592  * Backslashed delimiters after / or ? will be skipped, and commands will
3593  * not be expanded between /'s and ?'s or after "'".
3594  *
3595  * Returns the "cmd" pointer advanced to beyond the range.
3596  */
3597     char_u *
3598 skip_range(cmd, ctx)
3599     char_u	*cmd;
3600     int		*ctx;	/* pointer to xp_context or NULL */
3601 {
3602     int		delim;
3603 
3604     while (*cmd != NUL && (vim_isspace(*cmd) || VIM_ISDIGIT(*cmd) ||
3605 			    vim_strchr((char_u *)".$%'/?-+,;", *cmd) != NULL))
3606     {
3607 	if (*cmd == '\'')
3608 	{
3609 	    if (*++cmd == NUL && ctx != NULL)
3610 		*ctx = EXPAND_NOTHING;
3611 	}
3612 	else if (*cmd == '/' || *cmd == '?')
3613 	{
3614 	    delim = *cmd++;
3615 	    while (*cmd != NUL && *cmd != delim)
3616 		if (*cmd++ == '\\' && *cmd != NUL)
3617 		    ++cmd;
3618 	    if (*cmd == NUL && ctx != NULL)
3619 		*ctx = EXPAND_NOTHING;
3620 	}
3621 	if (*cmd != NUL)
3622 	    ++cmd;
3623     }
3624     return cmd;
3625 }
3626 
3627 /*
3628  * get a single EX address
3629  *
3630  * Set ptr to the next character after the part that was interpreted.
3631  * Set ptr to NULL when an error is encountered.
3632  *
3633  * Return MAXLNUM when no Ex address was found.
3634  */
3635     static linenr_T
3636 get_address(ptr, skip, to_other_file)
3637     char_u	**ptr;
3638     int		skip;	    /* only skip the address, don't use it */
3639     int		to_other_file;  /* flag: may jump to other file */
3640 {
3641     int		c;
3642     int		i;
3643     long	n;
3644     char_u	*cmd;
3645     pos_T	pos;
3646     pos_T	*fp;
3647     linenr_T	lnum;
3648 
3649     cmd = skipwhite(*ptr);
3650     lnum = MAXLNUM;
3651     do
3652     {
3653 	switch (*cmd)
3654 	{
3655 	    case '.':			    /* '.' - Cursor position */
3656 			++cmd;
3657 			lnum = curwin->w_cursor.lnum;
3658 			break;
3659 
3660 	    case '$':			    /* '$' - last line */
3661 			++cmd;
3662 			lnum = curbuf->b_ml.ml_line_count;
3663 			break;
3664 
3665 	    case '\'':			    /* ''' - mark */
3666 			if (*++cmd == NUL)
3667 			{
3668 			    cmd = NULL;
3669 			    goto error;
3670 			}
3671 			if (skip)
3672 			    ++cmd;
3673 			else
3674 			{
3675 			    /* Only accept a mark in another file when it is
3676 			     * used by itself: ":'M". */
3677 			    fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
3678 			    ++cmd;
3679 			    if (fp == (pos_T *)-1)
3680 				/* Jumped to another file. */
3681 				lnum = curwin->w_cursor.lnum;
3682 			    else
3683 			    {
3684 				if (check_mark(fp) == FAIL)
3685 				{
3686 				    cmd = NULL;
3687 				    goto error;
3688 				}
3689 				lnum = fp->lnum;
3690 			    }
3691 			}
3692 			break;
3693 
3694 	    case '/':
3695 	    case '?':			/* '/' or '?' - search */
3696 			c = *cmd++;
3697 			if (skip)	/* skip "/pat/" */
3698 			{
3699 			    cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
3700 			    if (*cmd == c)
3701 				++cmd;
3702 			}
3703 			else
3704 			{
3705 			    pos = curwin->w_cursor; /* save curwin->w_cursor */
3706 			    /*
3707 			     * When '/' or '?' follows another address, start
3708 			     * from there.
3709 			     */
3710 			    if (lnum != MAXLNUM)
3711 				curwin->w_cursor.lnum = lnum;
3712 			    /*
3713 			     * Start a forward search at the end of the line.
3714 			     * Start a backward search at the start of the line.
3715 			     * This makes sure we never match in the current
3716 			     * line, and can match anywhere in the
3717 			     * next/previous line.
3718 			     */
3719 			    if (c == '/')
3720 				curwin->w_cursor.col = MAXCOL;
3721 			    else
3722 				curwin->w_cursor.col = 0;
3723 			    searchcmdlen = 0;
3724 			    if (!do_search(NULL, c, cmd, 1L,
3725 				      SEARCH_HIS + SEARCH_MSG + SEARCH_START))
3726 			    {
3727 				curwin->w_cursor = pos;
3728 				cmd = NULL;
3729 				goto error;
3730 			    }
3731 			    lnum = curwin->w_cursor.lnum;
3732 			    curwin->w_cursor = pos;
3733 			    /* adjust command string pointer */
3734 			    cmd += searchcmdlen;
3735 			}
3736 			break;
3737 
3738 	    case '\\':		    /* "\?", "\/" or "\&", repeat search */
3739 			++cmd;
3740 			if (*cmd == '&')
3741 			    i = RE_SUBST;
3742 			else if (*cmd == '?' || *cmd == '/')
3743 			    i = RE_SEARCH;
3744 			else
3745 			{
3746 			    EMSG(_(e_backslash));
3747 			    cmd = NULL;
3748 			    goto error;
3749 			}
3750 
3751 			if (!skip)
3752 			{
3753 			    /*
3754 			     * When search follows another address, start from
3755 			     * there.
3756 			     */
3757 			    if (lnum != MAXLNUM)
3758 				pos.lnum = lnum;
3759 			    else
3760 				pos.lnum = curwin->w_cursor.lnum;
3761 
3762 			    /*
3763 			     * Start the search just like for the above
3764 			     * do_search().
3765 			     */
3766 			    if (*cmd != '?')
3767 				pos.col = MAXCOL;
3768 			    else
3769 				pos.col = 0;
3770 			    if (searchit(curwin, curbuf, &pos,
3771 					*cmd == '?' ? BACKWARD : FORWARD,
3772 					(char_u *)"", 1L,
3773 					SEARCH_MSG + SEARCH_START, i) != FAIL)
3774 				lnum = pos.lnum;
3775 			    else
3776 			    {
3777 				cmd = NULL;
3778 				goto error;
3779 			    }
3780 			}
3781 			++cmd;
3782 			break;
3783 
3784 	    default:
3785 			if (VIM_ISDIGIT(*cmd))	/* absolute line number */
3786 			    lnum = getdigits(&cmd);
3787 	}
3788 
3789 	for (;;)
3790 	{
3791 	    cmd = skipwhite(cmd);
3792 	    if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
3793 		break;
3794 
3795 	    if (lnum == MAXLNUM)
3796 		lnum = curwin->w_cursor.lnum;	/* "+1" is same as ".+1" */
3797 	    if (VIM_ISDIGIT(*cmd))
3798 		i = '+';		/* "number" is same as "+number" */
3799 	    else
3800 		i = *cmd++;
3801 	    if (!VIM_ISDIGIT(*cmd))	/* '+' is '+1', but '+0' is not '+1' */
3802 		n = 1;
3803 	    else
3804 		n = getdigits(&cmd);
3805 	    if (i == '-')
3806 		lnum -= n;
3807 	    else
3808 		lnum += n;
3809 	}
3810     } while (*cmd == '/' || *cmd == '?');
3811 
3812 error:
3813     *ptr = cmd;
3814     return lnum;
3815 }
3816 
3817 /*
3818  * Function called for command which is Not Implemented.  NI!
3819  */
3820     void
3821 ex_ni(eap)
3822     exarg_T	*eap;
3823 {
3824     if (!eap->skip)
3825 	eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
3826 }
3827 
3828 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
3829 	|| !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME)
3830 /*
3831  * Function called for script command which is Not Implemented.  NI!
3832  * Skips over ":perl <<EOF" constructs.
3833  */
3834     static void
3835 ex_script_ni(eap)
3836     exarg_T	*eap;
3837 {
3838     if (!eap->skip)
3839 	ex_ni(eap);
3840     else
3841 	vim_free(script_get(eap, eap->arg));
3842 }
3843 #endif
3844 
3845 /*
3846  * Check range in Ex command for validity.
3847  * Return NULL when valid, error message when invalid.
3848  */
3849     static char_u *
3850 invalid_range(eap)
3851     exarg_T	*eap;
3852 {
3853     if (       eap->line1 < 0
3854 	    || eap->line2 < 0
3855 	    || eap->line1 > eap->line2
3856 	    || ((eap->argt & RANGE)
3857 		&& !(eap->argt & NOTADR)
3858 		&& eap->line2 > curbuf->b_ml.ml_line_count
3859 #ifdef FEAT_DIFF
3860 			+ (eap->cmdidx == CMD_diffget)
3861 #endif
3862 		))
3863 	return (char_u *)_(e_invrange);
3864     return NULL;
3865 }
3866 
3867 /*
3868  * Correct the range for zero line number, if required.
3869  */
3870     static void
3871 correct_range(eap)
3872     exarg_T	*eap;
3873 {
3874     if (!(eap->argt & ZEROR))	    /* zero in range not allowed */
3875     {
3876 	if (eap->line1 == 0)
3877 	    eap->line1 = 1;
3878 	if (eap->line2 == 0)
3879 	    eap->line2 = 1;
3880     }
3881 }
3882 
3883 /*
3884  * Expand file name in Ex command argument.
3885  * Return FAIL for failure, OK otherwise.
3886  */
3887     int
3888 expand_filename(eap, cmdlinep, errormsgp)
3889     exarg_T	*eap;
3890     char_u	**cmdlinep;
3891     char_u	**errormsgp;
3892 {
3893     int		has_wildcards;	/* need to expand wildcards */
3894     char_u	*repl;
3895     int		srclen;
3896     char_u	*p;
3897     int		n;
3898 
3899     /*
3900      * Decide to expand wildcards *before* replacing '%', '#', etc.  If
3901      * the file name contains a wildcard it should not cause expanding.
3902      * (it will be expanded anyway if there is a wildcard before replacing).
3903      */
3904     has_wildcards = mch_has_wildcard(eap->arg);
3905     for (p = eap->arg; *p; )
3906     {
3907 #ifdef FEAT_EVAL
3908 	/* Skip over `=expr`, wildcards in it are not expanded. */
3909 	if (p[0] == '`' && p[1] == '=')
3910 	{
3911 	    p += 2;
3912 	    (void)skip_expr(&p);
3913 	    if (*p == '`')
3914 		++p;
3915 	    continue;
3916 	}
3917 #endif
3918 	/*
3919 	 * Quick check if this cannot be the start of a special string.
3920 	 * Also removes backslash before '%', '#' and '<'.
3921 	 */
3922 	if (vim_strchr((char_u *)"%#<", *p) == NULL)
3923 	{
3924 	    ++p;
3925 	    continue;
3926 	}
3927 
3928 	/*
3929 	 * Try to find a match at this position.
3930 	 */
3931 	repl = eval_vars(p, &srclen, &(eap->do_ecmd_lnum), errormsgp, eap->arg);
3932 	if (*errormsgp != NULL)		/* error detected */
3933 	    return FAIL;
3934 	if (repl == NULL)		/* no match found */
3935 	{
3936 	    p += srclen;
3937 	    continue;
3938 	}
3939 
3940 	/* Need to escape white space et al. with a backslash.  Don't do this
3941 	 * for shell commands (may have to use quotes instead).  Don't do this
3942 	 * for non-unix systems when there is a single argument (spaces don't
3943 	 * separate arguments then). */
3944 	if (!eap->usefilter
3945 		&& eap->cmdidx != CMD_bang
3946 		&& eap->cmdidx != CMD_make
3947 		&& eap->cmdidx != CMD_grep
3948 		&& eap->cmdidx != CMD_grepadd
3949 #ifndef UNIX
3950 		&& !(eap->argt & NOSPC)
3951 #endif
3952 		)
3953 	{
3954 	    char_u	*l;
3955 #ifdef BACKSLASH_IN_FILENAME
3956 	    /* Don't escape a backslash here, because rem_backslash() doesn't
3957 	     * remove it later. */
3958 	    static char_u *nobslash = (char_u *)" \t\"|";
3959 # define ESCAPE_CHARS nobslash
3960 #else
3961 # define ESCAPE_CHARS escape_chars
3962 #endif
3963 
3964 	    for (l = repl; *l; ++l)
3965 		if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
3966 		{
3967 		    l = vim_strsave_escaped(repl, ESCAPE_CHARS);
3968 		    if (l != NULL)
3969 		    {
3970 			vim_free(repl);
3971 			repl = l;
3972 		    }
3973 		    break;
3974 		}
3975 	}
3976 
3977 	/* For a shell command a '!' must be escaped. */
3978 	if ((eap->usefilter || eap->cmdidx == CMD_bang)
3979 		&& vim_strchr(repl, '!') != NULL)
3980 	{
3981 	    char_u	*l;
3982 
3983 	    l = vim_strsave_escaped(repl, (char_u *)"!");
3984 	    if (l != NULL)
3985 	    {
3986 		vim_free(repl);
3987 		repl = l;
3988 		/* For a sh-like shell escape it another time. */
3989 		if (strstr((char *)p_sh, "sh") != NULL)
3990 		{
3991 		    l = vim_strsave_escaped(repl, (char_u *)"!");
3992 		    if (l != NULL)
3993 		    {
3994 			vim_free(repl);
3995 			repl = l;
3996 		    }
3997 		}
3998 	    }
3999 	}
4000 
4001 	p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4002 	vim_free(repl);
4003 	if (p == NULL)
4004 	    return FAIL;
4005     }
4006 
4007     /*
4008      * One file argument: Expand wildcards.
4009      * Don't do this with ":r !command" or ":w !command".
4010      */
4011     if ((eap->argt & NOSPC) && !eap->usefilter)
4012     {
4013 	/*
4014 	 * May do this twice:
4015 	 * 1. Replace environment variables.
4016 	 * 2. Replace any other wildcards, remove backslashes.
4017 	 */
4018 	for (n = 1; n <= 2; ++n)
4019 	{
4020 	    if (n == 2)
4021 	    {
4022 #ifdef UNIX
4023 		/*
4024 		 * Only for Unix we check for more than one file name.
4025 		 * For other systems spaces are considered to be part
4026 		 * of the file name.
4027 		 * Only check here if there is no wildcard, otherwise
4028 		 * ExpandOne() will check for errors. This allows
4029 		 * ":e `ls ve*.c`" on Unix.
4030 		 */
4031 		if (!has_wildcards)
4032 		    for (p = eap->arg; *p; ++p)
4033 		    {
4034 			/* skip escaped characters */
4035 			if (p[1] && (*p == '\\' || *p == Ctrl_V))
4036 			    ++p;
4037 			else if (vim_iswhite(*p))
4038 			{
4039 			    *errormsgp = (char_u *)_("E172: Only one file name allowed");
4040 			    return FAIL;
4041 			}
4042 		    }
4043 #endif
4044 
4045 		/*
4046 		 * Halve the number of backslashes (this is Vi compatible).
4047 		 * For Unix and OS/2, when wildcards are expanded, this is
4048 		 * done by ExpandOne() below.
4049 		 */
4050 #if defined(UNIX) || defined(OS2)
4051 		if (!has_wildcards)
4052 #endif
4053 		    backslash_halve(eap->arg);
4054 #ifdef MACOS_CLASSIC
4055 		/*
4056 		 * translate unix-like path components
4057 		 */
4058 		slash_n_colon_adjust(eap->arg);
4059 #endif
4060 	    }
4061 
4062 	    if (has_wildcards)
4063 	    {
4064 		if (n == 1)
4065 		{
4066 		    /*
4067 		     * First loop: May expand environment variables.  This
4068 		     * can be done much faster with expand_env() than with
4069 		     * something else (e.g., calling a shell).
4070 		     * After expanding environment variables, check again
4071 		     * if there are still wildcards present.
4072 		     */
4073 		    if (vim_strchr(eap->arg, '$') != NULL
4074 			    || vim_strchr(eap->arg, '~') != NULL)
4075 		    {
4076 			expand_env_esc(eap->arg, NameBuff, MAXPATHL, TRUE);
4077 			has_wildcards = mch_has_wildcard(NameBuff);
4078 			p = NameBuff;
4079 		    }
4080 		    else
4081 			p = NULL;
4082 		}
4083 		else /* n == 2 */
4084 		{
4085 		    expand_T	xpc;
4086 
4087 		    ExpandInit(&xpc);
4088 		    xpc.xp_context = EXPAND_FILES;
4089 		    p = ExpandOne(&xpc, eap->arg, NULL,
4090 					    WILD_LIST_NOTFOUND|WILD_ADD_SLASH,
4091 						   WILD_EXPAND_FREE);
4092 		    ExpandCleanup(&xpc);
4093 		    if (p == NULL)
4094 			return FAIL;
4095 		}
4096 		if (p != NULL)
4097 		{
4098 		    (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
4099 								 p, cmdlinep);
4100 		    if (n == 2)	/* p came from ExpandOne() */
4101 			vim_free(p);
4102 		}
4103 	    }
4104 	}
4105     }
4106     return OK;
4107 }
4108 
4109 /*
4110  * Replace part of the command line, keeping eap->cmd, eap->arg and
4111  * eap->nextcmd correct.
4112  * "src" points to the part that is to be replaced, of length "srclen".
4113  * "repl" is the replacement string.
4114  * Returns a pointer to the character after the replaced string.
4115  * Returns NULL for failure.
4116  */
4117     static char_u *
4118 repl_cmdline(eap, src, srclen, repl, cmdlinep)
4119     exarg_T	*eap;
4120     char_u	*src;
4121     int		srclen;
4122     char_u	*repl;
4123     char_u	**cmdlinep;
4124 {
4125     int		len;
4126     int		i;
4127     char_u	*new_cmdline;
4128 
4129     /*
4130      * The new command line is build in new_cmdline[].
4131      * First allocate it.
4132      * Careful: a "+cmd" argument may have been NUL terminated.
4133      */
4134     len = (int)STRLEN(repl);
4135     i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
4136     if (eap->nextcmd)
4137 	i += (int)STRLEN(eap->nextcmd);/* add space for next command */
4138     if ((new_cmdline = alloc((unsigned)i)) == NULL)
4139 	return NULL;			/* out of memory! */
4140 
4141     /*
4142      * Copy the stuff before the expanded part.
4143      * Copy the expanded stuff.
4144      * Copy what came after the expanded part.
4145      * Copy the next commands, if there are any.
4146      */
4147     i = (int)(src - *cmdlinep);	/* length of part before match */
4148     mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
4149     mch_memmove(new_cmdline + i, repl, (size_t)len);
4150     i += len;				/* remember the end of the string */
4151     STRCPY(new_cmdline + i, src + srclen);
4152     src = new_cmdline + i;		/* remember where to continue */
4153 
4154     if (eap->nextcmd)			/* append next command */
4155     {
4156 	i = (int)STRLEN(new_cmdline) + 1;
4157 	STRCPY(new_cmdline + i, eap->nextcmd);
4158 	eap->nextcmd = new_cmdline + i;
4159     }
4160     eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4161     eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4162     if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
4163 	eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4164     vim_free(*cmdlinep);
4165     *cmdlinep = new_cmdline;
4166 
4167     return src;
4168 }
4169 
4170 /*
4171  * Check for '|' to separate commands and '"' to start comments.
4172  */
4173     void
4174 separate_nextcmd(eap)
4175     exarg_T	*eap;
4176 {
4177     char_u	*p;
4178 
4179     for (p = eap->arg; *p; ++p)
4180     {
4181 	if (*p == Ctrl_V)
4182 	{
4183 	    if (eap->argt & (USECTRLV | XFILE))
4184 		++p;		/* skip CTRL-V and next char */
4185 	    else
4186 		STRCPY(p, p + 1);	/* remove CTRL-V and skip next char */
4187 	    if (*p == NUL)		/* stop at NUL after CTRL-V */
4188 		break;
4189 	}
4190 
4191 #ifdef FEAT_EVAL
4192 	/* Skip over `=expr` when wildcards are expanded. */
4193 	else if (p[0] == '`' && p[1] == '=')
4194 	{
4195 	    p += 2;
4196 	    (void)skip_expr(&p);
4197 	    if (*p == '`')
4198 		++p;
4199 	}
4200 #endif
4201 
4202 	/* Check for '"': start of comment or '|': next command */
4203 	/* :@" and :*" do not start a comment!
4204 	 * :redir @" doesn't either. */
4205 	else if ((*p == '"' && !(eap->argt & NOTRLCOM)
4206 		    && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
4207 			|| p != eap->arg)
4208 		    && (eap->cmdidx != CMD_redir
4209 			|| p != eap->arg + 1 || p[-1] != '@'))
4210 		|| *p == '|' || *p == '\n')
4211 	{
4212 	    /*
4213 	     * We remove the '\' before the '|', unless USECTRLV is used
4214 	     * AND 'b' is present in 'cpoptions'.
4215 	     */
4216 	    if ((vim_strchr(p_cpo, CPO_BAR) == NULL
4217 			      || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
4218 	    {
4219 		mch_memmove(p - 1, p, STRLEN(p) + 1);	/* remove the '\' */
4220 		--p;
4221 	    }
4222 	    else
4223 	    {
4224 		eap->nextcmd = check_nextcmd(p);
4225 		*p = NUL;
4226 		break;
4227 	    }
4228 	}
4229 #ifdef FEAT_MBYTE
4230 	else if (has_mbyte)
4231 	    p += (*mb_ptr2len_check)(p) - 1; /* skip bytes of multi-byte char */
4232 #endif
4233     }
4234     if (!(eap->argt & NOTRLCOM))	/* remove trailing spaces */
4235 	del_trailing_spaces(eap->arg);
4236 }
4237 
4238 /*
4239  * get + command from ex argument
4240  */
4241     static char_u *
4242 getargcmd(argp)
4243     char_u **argp;
4244 {
4245     char_u *arg = *argp;
4246     char_u *command = NULL;
4247 
4248     if (*arg == '+')	    /* +[command] */
4249     {
4250 	++arg;
4251 	if (vim_isspace(*arg))
4252 	    command = dollar_command;
4253 	else
4254 	{
4255 	    command = arg;
4256 	    arg = skip_cmd_arg(command, TRUE);
4257 	    if (*arg != NUL)
4258 		*arg++ = NUL;		/* terminate command with NUL */
4259 	}
4260 
4261 	arg = skipwhite(arg);	/* skip over spaces */
4262 	*argp = arg;
4263     }
4264     return command;
4265 }
4266 
4267 /*
4268  * Find end of "+command" argument.  Skip over "\ " and "\\".
4269  */
4270     static char_u *
4271 skip_cmd_arg(p, rembs)
4272     char_u *p;
4273     int	   rembs;	/* TRUE to halve the number of backslashes */
4274 {
4275     while (*p && !vim_isspace(*p))
4276     {
4277 	if (*p == '\\' && p[1] != NUL)
4278 	{
4279 	    if (rembs)
4280 		mch_memmove(p, p + 1, STRLEN(p));
4281 	    else
4282 		++p;
4283 	}
4284 #ifdef FEAT_MBYTE
4285 	if (has_mbyte)
4286 	    p += (*mb_ptr2len_check)(p);
4287 	else
4288 #endif
4289 	    ++p;
4290     }
4291     return p;
4292 }
4293 
4294 /*
4295  * Get "++opt=arg" argument.
4296  * Return FAIL or OK.
4297  */
4298     static int
4299 getargopt(eap)
4300     exarg_T	*eap;
4301 {
4302     char_u	*arg = eap->arg + 2;
4303     int		*pp = NULL;
4304 #ifdef FEAT_MBYTE
4305     char_u	*p;
4306 #endif
4307 
4308     /* ":edit ++[no]bin[ary] file" */
4309     if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4310     {
4311 	if (*arg == 'n')
4312 	{
4313 	    arg += 2;
4314 	    eap->force_bin = FORCE_NOBIN;
4315 	}
4316 	else
4317 	    eap->force_bin = FORCE_BIN;
4318 	if (!checkforcmd(&arg, "binary", 3))
4319 	    return FAIL;
4320 	eap->arg = skipwhite(arg);
4321 	return OK;
4322     }
4323 
4324     if (STRNCMP(arg, "ff", 2) == 0)
4325     {
4326 	arg += 2;
4327 	pp = &eap->force_ff;
4328     }
4329     else if (STRNCMP(arg, "fileformat", 10) == 0)
4330     {
4331 	arg += 10;
4332 	pp = &eap->force_ff;
4333     }
4334 #ifdef FEAT_MBYTE
4335     else if (STRNCMP(arg, "enc", 3) == 0)
4336     {
4337 	arg += 3;
4338 	pp = &eap->force_enc;
4339     }
4340     else if (STRNCMP(arg, "encoding", 8) == 0)
4341     {
4342 	arg += 8;
4343 	pp = &eap->force_enc;
4344     }
4345 #endif
4346 
4347     if (pp == NULL || *arg != '=')
4348 	return FAIL;
4349 
4350     ++arg;
4351     *pp = (int)(arg - eap->cmd);
4352     arg = skip_cmd_arg(arg, FALSE);
4353     eap->arg = skipwhite(arg);
4354     *arg = NUL;
4355 
4356 #ifdef FEAT_MBYTE
4357     if (pp == &eap->force_ff)
4358     {
4359 #endif
4360 	if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4361 	    return FAIL;
4362 #ifdef FEAT_MBYTE
4363     }
4364     else
4365     {
4366 	/* Make 'fileencoding' lower case. */
4367 	for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4368 	    *p = TOLOWER_ASC(*p);
4369     }
4370 #endif
4371 
4372     return OK;
4373 }
4374 
4375 /*
4376  * ":abbreviate" and friends.
4377  */
4378     static void
4379 ex_abbreviate(eap)
4380     exarg_T	*eap;
4381 {
4382     do_exmap(eap, TRUE);	/* almost the same as mapping */
4383 }
4384 
4385 /*
4386  * ":map" and friends.
4387  */
4388     static void
4389 ex_map(eap)
4390     exarg_T	*eap;
4391 {
4392     /*
4393      * If we are sourcing .exrc or .vimrc in current directory we
4394      * print the mappings for security reasons.
4395      */
4396     if (secure)
4397     {
4398 	secure = 2;
4399 	msg_outtrans(eap->cmd);
4400 	msg_putchar('\n');
4401     }
4402     do_exmap(eap, FALSE);
4403 }
4404 
4405 /*
4406  * ":unmap" and friends.
4407  */
4408     static void
4409 ex_unmap(eap)
4410     exarg_T	*eap;
4411 {
4412     do_exmap(eap, FALSE);
4413 }
4414 
4415 /*
4416  * ":mapclear" and friends.
4417  */
4418     static void
4419 ex_mapclear(eap)
4420     exarg_T	*eap;
4421 {
4422     map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4423 }
4424 
4425 /*
4426  * ":abclear" and friends.
4427  */
4428     static void
4429 ex_abclear(eap)
4430     exarg_T	*eap;
4431 {
4432     map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4433 }
4434 
4435 #ifdef FEAT_AUTOCMD
4436     static void
4437 ex_autocmd(eap)
4438     exarg_T	*eap;
4439 {
4440     /*
4441      * Disallow auto commands from .exrc and .vimrc in current
4442      * directory for security reasons.
4443      */
4444     if (secure)
4445     {
4446 	secure = 2;
4447 	eap->errmsg = e_curdir;
4448     }
4449     else if (eap->cmdidx == CMD_autocmd)
4450 	do_autocmd(eap->arg, eap->forceit);
4451     else
4452 	do_augroup(eap->arg, eap->forceit);
4453 }
4454 
4455 /*
4456  * ":doautocmd": Apply the automatic commands to the current buffer.
4457  */
4458     static void
4459 ex_doautocmd(eap)
4460     exarg_T	*eap;
4461 {
4462     (void)do_doautocmd(eap->arg, TRUE);
4463     do_modelines(FALSE);
4464 }
4465 #endif
4466 
4467 #ifdef FEAT_LISTCMDS
4468 /*
4469  * :[N]bunload[!] [N] [bufname] unload buffer
4470  * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4471  * :[N]bwipeout[!] [N] [bufname] delete buffer really
4472  */
4473     static void
4474 ex_bunload(eap)
4475     exarg_T	*eap;
4476 {
4477     eap->errmsg = do_bufdel(
4478 	    eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4479 		: eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4480 		: DOBUF_UNLOAD, eap->arg,
4481 	    eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4482 }
4483 
4484 /*
4485  * :[N]buffer [N]	to buffer N
4486  * :[N]sbuffer [N]	to buffer N
4487  */
4488     static void
4489 ex_buffer(eap)
4490     exarg_T	*eap;
4491 {
4492     if (*eap->arg)
4493 	eap->errmsg = e_trailing;
4494     else
4495     {
4496 	if (eap->addr_count == 0)	/* default is current buffer */
4497 	    goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4498 	else
4499 	    goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4500     }
4501 }
4502 
4503 /*
4504  * :[N]bmodified [N]	to next mod. buffer
4505  * :[N]sbmodified [N]	to next mod. buffer
4506  */
4507     static void
4508 ex_bmodified(eap)
4509     exarg_T	*eap;
4510 {
4511     goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4512 }
4513 
4514 /*
4515  * :[N]bnext [N]	to next buffer
4516  * :[N]sbnext [N]	split and to next buffer
4517  */
4518     static void
4519 ex_bnext(eap)
4520     exarg_T	*eap;
4521 {
4522     goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4523 }
4524 
4525 /*
4526  * :[N]bNext [N]	to previous buffer
4527  * :[N]bprevious [N]	to previous buffer
4528  * :[N]sbNext [N]	split and to previous buffer
4529  * :[N]sbprevious [N]	split and to previous buffer
4530  */
4531     static void
4532 ex_bprevious(eap)
4533     exarg_T	*eap;
4534 {
4535     goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4536 }
4537 
4538 /*
4539  * :brewind		to first buffer
4540  * :bfirst		to first buffer
4541  * :sbrewind		split and to first buffer
4542  * :sbfirst		split and to first buffer
4543  */
4544     static void
4545 ex_brewind(eap)
4546     exarg_T	*eap;
4547 {
4548     goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4549 }
4550 
4551 /*
4552  * :blast		to last buffer
4553  * :sblast		split and to last buffer
4554  */
4555     static void
4556 ex_blast(eap)
4557     exarg_T	*eap;
4558 {
4559     goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4560 }
4561 #endif
4562 
4563     int
4564 ends_excmd(c)
4565     int	    c;
4566 {
4567     return (c == NUL || c == '|' || c == '"' || c == '\n');
4568 }
4569 
4570 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
4571 	|| defined(PROTO)
4572 /*
4573  * Return the next command, after the first '|' or '\n'.
4574  * Return NULL if not found.
4575  */
4576     char_u *
4577 find_nextcmd(p)
4578     char_u	*p;
4579 {
4580     while (*p != '|' && *p != '\n')
4581     {
4582 	if (*p == NUL)
4583 	    return NULL;
4584 	++p;
4585     }
4586     return (p + 1);
4587 }
4588 #endif
4589 
4590 /*
4591  * Check if *p is a separator between Ex commands.
4592  * Return NULL if it isn't, (p + 1) if it is.
4593  */
4594     char_u *
4595 check_nextcmd(p)
4596     char_u	*p;
4597 {
4598     p = skipwhite(p);
4599     if (*p == '|' || *p == '\n')
4600 	return (p + 1);
4601     else
4602 	return NULL;
4603 }
4604 
4605 /*
4606  * - if there are more files to edit
4607  * - and this is the last window
4608  * - and forceit not used
4609  * - and not repeated twice on a row
4610  *    return FAIL and give error message if 'message' TRUE
4611  * return OK otherwise
4612  */
4613     static int
4614 check_more(message, forceit)
4615     int message;	    /* when FALSE check only, no messages */
4616     int forceit;
4617 {
4618     int	    n = ARGCOUNT - curwin->w_arg_idx - 1;
4619 
4620     if (!forceit && only_one_window() && ARGCOUNT > 1 && !arg_had_last
4621 						   && n >= 0 && quitmore == 0)
4622     {
4623 	if (message)
4624 	{
4625 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
4626 	    if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
4627 	    {
4628 		char_u	buff[IOSIZE];
4629 
4630 		if (n == 1)
4631 		    STRCPY(buff, _("1 more file to edit.  Quit anyway?"));
4632 		else
4633 		    sprintf((char *)buff,
4634 			      _("%d more files to edit.  Quit anyway?"), n);
4635 		if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
4636 		    return OK;
4637 		return FAIL;
4638 	    }
4639 #endif
4640 	    if (n == 1)
4641 		EMSG(_("E173: 1 more file to edit"));
4642 	    else
4643 		EMSGN(_("E173: %ld more files to edit"), n);
4644 	    quitmore = 2;	    /* next try to quit is allowed */
4645 	}
4646 	return FAIL;
4647     }
4648     return OK;
4649 }
4650 
4651 #ifdef FEAT_CMDL_COMPL
4652 /*
4653  * Function given to ExpandGeneric() to obtain the list of command names.
4654  */
4655 /*ARGSUSED*/
4656     char_u *
4657 get_command_name(xp, idx)
4658     expand_T	*xp;
4659     int		idx;
4660 {
4661     if (idx >= (int)CMD_SIZE)
4662 # ifdef FEAT_USR_CMDS
4663 	return get_user_command_name(idx);
4664 # else
4665 	return NULL;
4666 # endif
4667     return cmdnames[idx].cmd_name;
4668 }
4669 #endif
4670 
4671 #if defined(FEAT_USR_CMDS) || defined(PROTO)
4672 static int	uc_add_command __ARGS((char_u *name, size_t name_len, char_u *rep, long argt, long def, int flags, int compl, char_u *compl_arg, int force));
4673 static void	uc_list __ARGS((char_u *name, size_t name_len));
4674 static int	uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
4675 static char_u	*uc_split_args __ARGS((char_u *arg, size_t *lenp));
4676 static size_t	uc_check_code __ARGS((char_u *code, size_t len, char_u *buf, ucmd_T *cmd, exarg_T *eap, char_u **split_buf, size_t *split_len));
4677 
4678     static int
4679 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
4680     char_u	*name;
4681     size_t	name_len;
4682     char_u	*rep;
4683     long	argt;
4684     long	def;
4685     int		flags;
4686     int		compl;
4687     char_u	*compl_arg;
4688     int		force;
4689 {
4690     ucmd_T	*cmd = NULL;
4691     char_u	*p;
4692     int		i;
4693     int		cmp = 1;
4694     char_u	*rep_buf = NULL;
4695     garray_T	*gap;
4696 
4697     replace_termcodes(rep, &rep_buf, FALSE, FALSE);
4698     if (rep_buf == NULL)
4699     {
4700 	/* Can't replace termcodes - try using the string as is */
4701 	rep_buf = vim_strsave(rep);
4702 
4703 	/* Give up if out of memory */
4704 	if (rep_buf == NULL)
4705 	    return FAIL;
4706     }
4707 
4708     /* get address of growarray: global or in curbuf */
4709     if (flags & UC_BUFFER)
4710     {
4711 	gap = &curbuf->b_ucmds;
4712 	if (gap->ga_itemsize == 0)
4713 	    ga_init2(gap, (int)sizeof(ucmd_T), 4);
4714     }
4715     else
4716 	gap = &ucmds;
4717 
4718     /* Search for the command in the already defined commands. */
4719     for (i = 0; i < gap->ga_len; ++i)
4720     {
4721 	size_t len;
4722 
4723 	cmd = USER_CMD_GA(gap, i);
4724 	len = STRLEN(cmd->uc_name);
4725 	cmp = STRNCMP(name, cmd->uc_name, name_len);
4726 	if (cmp == 0)
4727 	{
4728 	    if (name_len < len)
4729 		cmp = -1;
4730 	    else if (name_len > len)
4731 		cmp = 1;
4732 	}
4733 
4734 	if (cmp == 0)
4735 	{
4736 	    if (!force)
4737 	    {
4738 		EMSG(_("E174: Command already exists: add ! to replace it"));
4739 		goto fail;
4740 	    }
4741 
4742 	    vim_free(cmd->uc_rep);
4743 	    cmd->uc_rep = 0;
4744 	    break;
4745 	}
4746 
4747 	/* Stop as soon as we pass the name to add */
4748 	if (cmp < 0)
4749 	    break;
4750     }
4751 
4752     /* Extend the array unless we're replacing an existing command */
4753     if (cmp != 0)
4754     {
4755 	if (ga_grow(gap, 1) != OK)
4756 	    goto fail;
4757 	if ((p = vim_strnsave(name, (int)name_len)) == NULL)
4758 	    goto fail;
4759 
4760 	cmd = USER_CMD_GA(gap, i);
4761 	mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
4762 
4763 	++gap->ga_len;
4764 	--gap->ga_room;
4765 
4766 	cmd->uc_name = p;
4767     }
4768 
4769     cmd->uc_rep = rep_buf;
4770     cmd->uc_argt = argt;
4771     cmd->uc_def = def;
4772     cmd->uc_compl = compl;
4773 #ifdef FEAT_EVAL
4774     cmd->uc_scriptID = current_SID;
4775 # ifdef FEAT_CMDL_COMPL
4776     cmd->uc_compl_arg = compl_arg;
4777 # endif
4778 #endif
4779 
4780     return OK;
4781 
4782 fail:
4783     vim_free(rep_buf);
4784 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
4785     vim_free(compl_arg);
4786 #endif
4787     return FAIL;
4788 }
4789 
4790 /*
4791  * List of names for completion for ":command" with the EXPAND_ flag.
4792  * Must be alphabetical for completion.
4793  */
4794 static struct
4795 {
4796     int	    expand;
4797     char    *name;
4798 } command_complete[] =
4799 {
4800     {EXPAND_AUGROUP, "augroup"},
4801     {EXPAND_BUFFERS, "buffer"},
4802     {EXPAND_COMMANDS, "command"},
4803 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
4804     {EXPAND_USER_DEFINED, "custom"},
4805 #endif
4806     {EXPAND_DIRECTORIES, "dir"},
4807     {EXPAND_ENV_VARS, "environment"},
4808     {EXPAND_EVENTS, "event"},
4809     {EXPAND_EXPRESSION, "expression"},
4810     {EXPAND_FILES, "file"},
4811     {EXPAND_FUNCTIONS, "function"},
4812     {EXPAND_HELP, "help"},
4813     {EXPAND_HIGHLIGHT, "highlight"},
4814     {EXPAND_MAPPINGS, "mapping"},
4815     {EXPAND_MENUS, "menu"},
4816     {EXPAND_SETTINGS, "option"},
4817     {EXPAND_TAGS, "tag"},
4818     {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
4819     {EXPAND_USER_VARS, "var"},
4820     {0, NULL}
4821 };
4822 
4823     static void
4824 uc_list(name, name_len)
4825     char_u	*name;
4826     size_t	name_len;
4827 {
4828     int		i, j;
4829     int		found = FALSE;
4830     ucmd_T	*cmd;
4831     int		len;
4832     long	a;
4833     garray_T	*gap;
4834 
4835     gap = &curbuf->b_ucmds;
4836     for (;;)
4837     {
4838 	for (i = 0; i < gap->ga_len; ++i)
4839 	{
4840 	    cmd = USER_CMD_GA(gap, i);
4841 	    a = cmd->uc_argt;
4842 
4843 	    /* Skip commands which don't match the requested prefix */
4844 	    if (STRNCMP(name, cmd->uc_name, name_len) != 0)
4845 		continue;
4846 
4847 	    /* Put out the title first time */
4848 	    if (!found)
4849 		MSG_PUTS_TITLE(_("\n    Name        Args Range Complete  Definition"));
4850 	    found = TRUE;
4851 	    msg_putchar('\n');
4852 	    if (got_int)
4853 		break;
4854 
4855 	    /* Special cases */
4856 	    msg_putchar(a & BANG ? '!' : ' ');
4857 	    msg_putchar(a & REGSTR ? '"' : ' ');
4858 	    msg_putchar(gap != &ucmds ? 'b' : ' ');
4859 	    msg_putchar(' ');
4860 
4861 	    msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
4862 	    len = (int)STRLEN(cmd->uc_name) + 4;
4863 
4864 	    do {
4865 		msg_putchar(' ');
4866 		++len;
4867 	    } while (len < 16);
4868 
4869 	    len = 0;
4870 
4871 	    /* Arguments */
4872 	    switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
4873 	    {
4874 	    case 0:			IObuff[len++] = '0'; break;
4875 	    case (EXTRA):		IObuff[len++] = '*'; break;
4876 	    case (EXTRA|NOSPC):		IObuff[len++] = '?'; break;
4877 	    case (EXTRA|NEEDARG):	IObuff[len++] = '+'; break;
4878 	    case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
4879 	    }
4880 
4881 	    do {
4882 		IObuff[len++] = ' ';
4883 	    } while (len < 5);
4884 
4885 	    /* Range */
4886 	    if (a & (RANGE|COUNT))
4887 	    {
4888 		if (a & COUNT)
4889 		{
4890 		    /* -count=N */
4891 		    sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
4892 		    len += (int)STRLEN(IObuff + len);
4893 		}
4894 		else if (a & DFLALL)
4895 		    IObuff[len++] = '%';
4896 		else if (cmd->uc_def >= 0)
4897 		{
4898 		    /* -range=N */
4899 		    sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
4900 		    len += (int)STRLEN(IObuff + len);
4901 		}
4902 		else
4903 		    IObuff[len++] = '.';
4904 	    }
4905 
4906 	    do {
4907 		IObuff[len++] = ' ';
4908 	    } while (len < 11);
4909 
4910 	    /* Completion */
4911 	    for (j = 0; command_complete[j].expand != 0; ++j)
4912 		if (command_complete[j].expand == cmd->uc_compl)
4913 		{
4914 		    STRCPY(IObuff + len, command_complete[j].name);
4915 		    len += (int)STRLEN(IObuff + len);
4916 		    break;
4917 		}
4918 
4919 	    do {
4920 		IObuff[len++] = ' ';
4921 	    } while (len < 21);
4922 
4923 	    IObuff[len] = '\0';
4924 	    msg_outtrans(IObuff);
4925 
4926 	    msg_outtrans_special(cmd->uc_rep, FALSE);
4927 	    out_flush();
4928 	    ui_breakcheck();
4929 	    if (got_int)
4930 		break;
4931 	}
4932 	if (gap == &ucmds || i < gap->ga_len)
4933 	    break;
4934 	gap = &ucmds;
4935     }
4936 
4937     if (!found)
4938 	MSG(_("No user-defined commands found"));
4939 }
4940 
4941     static char_u *
4942 uc_fun_cmd()
4943 {
4944     static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
4945 			    0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
4946 			    0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
4947 			    0xb9, 0x7f, 0};
4948     int		i;
4949 
4950     for (i = 0; fcmd[i]; ++i)
4951 	IObuff[i] = fcmd[i] - 0x40;
4952     IObuff[i] = 0;
4953     return IObuff;
4954 }
4955 
4956     static int
4957 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
4958     char_u	*attr;
4959     size_t	len;
4960     long	*argt;
4961     long	*def;
4962     int		*flags;
4963     int		*compl;
4964     char_u	**compl_arg;
4965 {
4966     char_u	*p;
4967 
4968     if (len == 0)
4969     {
4970 	EMSG(_("E175: No attribute specified"));
4971 	return FAIL;
4972     }
4973 
4974     /* First, try the simple attributes (no arguments) */
4975     if (STRNICMP(attr, "bang", len) == 0)
4976 	*argt |= BANG;
4977     else if (STRNICMP(attr, "buffer", len) == 0)
4978 	*flags |= UC_BUFFER;
4979     else if (STRNICMP(attr, "register", len) == 0)
4980 	*argt |= REGSTR;
4981     else if (STRNICMP(attr, "bar", len) == 0)
4982 	*argt |= TRLBAR;
4983     else
4984     {
4985 	int	i;
4986 	char_u	*val = NULL;
4987 	size_t	vallen = 0;
4988 	size_t	attrlen = len;
4989 
4990 	/* Look for the attribute name - which is the part before any '=' */
4991 	for (i = 0; i < (int)len; ++i)
4992 	{
4993 	    if (attr[i] == '=')
4994 	    {
4995 		val = &attr[i + 1];
4996 		vallen = len - i - 1;
4997 		attrlen = i;
4998 		break;
4999 	    }
5000 	}
5001 
5002 	if (STRNICMP(attr, "nargs", attrlen) == 0)
5003 	{
5004 	    if (vallen == 1)
5005 	    {
5006 		if (*val == '0')
5007 		    /* Do nothing - this is the default */;
5008 		else if (*val == '1')
5009 		    *argt |= (EXTRA | NOSPC | NEEDARG);
5010 		else if (*val == '*')
5011 		    *argt |= EXTRA;
5012 		else if (*val == '?')
5013 		    *argt |= (EXTRA | NOSPC);
5014 		else if (*val == '+')
5015 		    *argt |= (EXTRA | NEEDARG);
5016 		else
5017 		    goto wrong_nargs;
5018 	    }
5019 	    else
5020 	    {
5021 wrong_nargs:
5022 		EMSG(_("E176: Invalid number of arguments"));
5023 		return FAIL;
5024 	    }
5025 	}
5026 	else if (STRNICMP(attr, "range", attrlen) == 0)
5027 	{
5028 	    *argt |= RANGE;
5029 	    if (vallen == 1 && *val == '%')
5030 		*argt |= DFLALL;
5031 	    else if (val != NULL)
5032 	    {
5033 		p = val;
5034 		if (*def >= 0)
5035 		{
5036 two_count:
5037 		    EMSG(_("E177: Count cannot be specified twice"));
5038 		    return FAIL;
5039 		}
5040 
5041 		*def = getdigits(&p);
5042 		*argt |= (ZEROR | NOTADR);
5043 
5044 		if (p != val + vallen || vallen == 0)
5045 		{
5046 invalid_count:
5047 		    EMSG(_("E178: Invalid default value for count"));
5048 		    return FAIL;
5049 		}
5050 	    }
5051 	}
5052 	else if (STRNICMP(attr, "count", attrlen) == 0)
5053 	{
5054 	    *argt |= (COUNT | ZEROR | NOTADR);
5055 
5056 	    if (val != NULL)
5057 	    {
5058 		p = val;
5059 		if (*def >= 0)
5060 		    goto two_count;
5061 
5062 		*def = getdigits(&p);
5063 
5064 		if (p != val + vallen)
5065 		    goto invalid_count;
5066 	    }
5067 
5068 	    if (*def < 0)
5069 		*def = 0;
5070 	}
5071 	else if (STRNICMP(attr, "complete", attrlen) == 0)
5072 	{
5073 	    char_u	*arg = NULL;
5074 	    size_t	arglen = 0;
5075 
5076 	    if (val == NULL)
5077 	    {
5078 		EMSG(_("E179: argument required for complete"));
5079 		return FAIL;
5080 	    }
5081 	    /* Look for any argument part - which is the part after any ',' */
5082 	    for (i = 0; i < (int)vallen; ++i)
5083 	    {
5084 		if (val[i] == ',')
5085 		{
5086 		    arg = &val[i + 1];
5087 		    arglen = vallen - i - 1;
5088 		    vallen = i;
5089 		    break;
5090 		}
5091 	    }
5092 
5093 	    for (i = 0; command_complete[i].expand != 0; ++i)
5094 	    {
5095 		if (STRLEN(command_complete[i].name) == vallen
5096 			&& STRNCMP(val, command_complete[i].name, vallen) == 0)
5097 		{
5098 		    *compl = command_complete[i].expand;
5099 		    if (command_complete[i].expand == EXPAND_BUFFERS)
5100 			*argt |= BUFNAME;
5101 		    else if (command_complete[i].expand == EXPAND_DIRECTORIES
5102 			    || command_complete[i].expand == EXPAND_FILES)
5103 			*argt |= XFILE;
5104 		    break;
5105 		}
5106 	    }
5107 
5108 	    if (command_complete[i].expand == 0)
5109 	    {
5110 		EMSG2(_("E180: Invalid complete value: %s"), val);
5111 		return FAIL;
5112 	    }
5113 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5114 	    if (*compl != EXPAND_USER_DEFINED && arg != NULL)
5115 #else
5116 	    if (arg != NULL)
5117 #endif
5118 	    {
5119 		EMSG(_("E468: Completion argument only allowed for custom completion"));
5120 		return FAIL;
5121 	    }
5122 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5123 	    if (*compl == EXPAND_USER_DEFINED && arg == NULL)
5124 	    {
5125 		EMSG(_("E467: Custom completion requires a function argument"));
5126 		return FAIL;
5127 	    }
5128 	    if (arg != NULL)
5129 		*compl_arg = vim_strnsave(arg, (int)arglen);
5130 #endif
5131 	}
5132 	else
5133 	{
5134 	    char_u ch = attr[len];
5135 	    attr[len] = '\0';
5136 	    EMSG2(_("E181: Invalid attribute: %s"), attr);
5137 	    attr[len] = ch;
5138 	    return FAIL;
5139 	}
5140     }
5141 
5142     return OK;
5143 }
5144 
5145     static void
5146 ex_command(eap)
5147     exarg_T   *eap;
5148 {
5149     char_u  *name;
5150     char_u  *end;
5151     char_u  *p;
5152     long    argt = 0;
5153     long    def = -1;
5154     int	    flags = 0;
5155     int	    compl = EXPAND_NOTHING;
5156     char_u  *compl_arg = NULL;
5157     int	    has_attr = (eap->arg[0] == '-');
5158 
5159     p = eap->arg;
5160 
5161     /* Check for attributes */
5162     while (*p == '-')
5163     {
5164 	++p;
5165 	end = skiptowhite(p);
5166 	if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5167 		== FAIL)
5168 	    return;
5169 	p = skipwhite(end);
5170     }
5171 
5172     /* Get the name (if any) and skip to the following argument */
5173     name = p;
5174     if (ASCII_ISALPHA(*p))
5175 	while (ASCII_ISALNUM(*p))
5176 	    ++p;
5177     if (!ends_excmd(*p) && !vim_iswhite(*p))
5178     {
5179 	EMSG(_("E182: Invalid command name"));
5180 	return;
5181     }
5182     end = p;
5183 
5184     /* If there is nothing after the name, and no attributes were specified,
5185      * we are listing commands
5186      */
5187     p = skipwhite(end);
5188     if (!has_attr && ends_excmd(*p))
5189     {
5190 	uc_list(name, end - name);
5191     }
5192     else if (!ASCII_ISUPPER(*name))
5193     {
5194 	EMSG(_("E183: User defined commands must start with an uppercase letter"));
5195 	return;
5196     }
5197     else
5198 	uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5199 								eap->forceit);
5200 }
5201 
5202 /*
5203  * ":comclear"
5204  */
5205 /*ARGSUSED*/
5206 /*
5207  * Clear all user commands, global and for current buffer.
5208  */
5209     static void
5210 ex_comclear(eap)
5211     exarg_T	*eap;
5212 {
5213     uc_clear(&ucmds);
5214     uc_clear(&curbuf->b_ucmds);
5215 }
5216 
5217 /*
5218  * Clear all user commands for "gap".
5219  */
5220     void
5221 uc_clear(gap)
5222     garray_T	*gap;
5223 {
5224     int		i;
5225     ucmd_T	*cmd;
5226 
5227     for (i = 0; i < gap->ga_len; ++i)
5228     {
5229 	cmd = USER_CMD_GA(gap, i);
5230 	vim_free(cmd->uc_name);
5231 	vim_free(cmd->uc_rep);
5232 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5233 	vim_free(cmd->uc_compl_arg);
5234 # endif
5235     }
5236     ga_clear(gap);
5237 }
5238 
5239     static void
5240 ex_delcommand(eap)
5241     exarg_T	*eap;
5242 {
5243     int		i = 0;
5244     ucmd_T	*cmd = NULL;
5245     int		cmp = -1;
5246     garray_T	*gap;
5247 
5248     gap = &curbuf->b_ucmds;
5249     for (;;)
5250     {
5251 	for (i = 0; i < gap->ga_len; ++i)
5252 	{
5253 	    cmd = USER_CMD_GA(gap, i);
5254 	    cmp = STRCMP(eap->arg, cmd->uc_name);
5255 	    if (cmp <= 0)
5256 		break;
5257 	}
5258 	if (gap == &ucmds || cmp == 0)
5259 	    break;
5260 	gap = &ucmds;
5261     }
5262 
5263     if (cmp != 0)
5264     {
5265 	EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5266 	return;
5267     }
5268 
5269     vim_free(cmd->uc_name);
5270     vim_free(cmd->uc_rep);
5271 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5272     vim_free(cmd->uc_compl_arg);
5273 # endif
5274 
5275     --gap->ga_len;
5276     ++gap->ga_room;
5277 
5278     if (i < gap->ga_len)
5279 	mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5280 }
5281 
5282     static char_u *
5283 uc_split_args(arg, lenp)
5284     char_u *arg;
5285     size_t *lenp;
5286 {
5287     char_u *buf;
5288     char_u *p;
5289     char_u *q;
5290     int len;
5291 
5292     /* Precalculate length */
5293     p = arg;
5294     len = 2; /* Initial and final quotes */
5295 
5296     while (*p)
5297     {
5298 	if (p[0] == '\\' && vim_iswhite(p[1]))
5299 	{
5300 	    len += 1;
5301 	    p += 2;
5302 	}
5303 	else if (*p == '\\' || *p == '"')
5304 	{
5305 	    len += 2;
5306 	    p += 1;
5307 	}
5308 	else if (vim_iswhite(*p))
5309 	{
5310 	    p = skipwhite(p);
5311 	    if (*p == NUL)
5312 		break;
5313 	    len += 3; /* "," */
5314 	}
5315 	else
5316 	{
5317 	    ++len;
5318 	    ++p;
5319 	}
5320     }
5321 
5322     buf = alloc(len + 1);
5323     if (buf == NULL)
5324     {
5325 	*lenp = 0;
5326 	return buf;
5327     }
5328 
5329     p = arg;
5330     q = buf;
5331     *q++ = '"';
5332     while (*p)
5333     {
5334 	if (p[0] == '\\' && vim_iswhite(p[1]))
5335 	{
5336 	    *q++ = p[1];
5337 	    p += 2;
5338 	}
5339 	else if (*p == '\\' || *p == '"')
5340 	{
5341 	    *q++ = '\\';
5342 	    *q++ = *p++;
5343 	}
5344 	else if (vim_iswhite(*p))
5345 	{
5346 	    p = skipwhite(p);
5347 	    if (*p == NUL)
5348 		break;
5349 	    *q++ = '"';
5350 	    *q++ = ',';
5351 	    *q++ = '"';
5352 	}
5353 	else
5354 	{
5355 	    *q++ = *p++;
5356 	}
5357     }
5358     *q++ = '"';
5359     *q = 0;
5360 
5361     *lenp = len;
5362     return buf;
5363 }
5364 
5365 /*
5366  * Check for a <> code in a user command.
5367  * "code" points to the '<'.  "len" the length of the <> (inclusive).
5368  * "buf" is where the result is to be added.
5369  * "split_buf" points to a buffer used for splitting, caller should free it.
5370  * "split_len" is the length of what "split_buf" contains.
5371  * Returns the length of the replacement, which has been added to "buf".
5372  * Returns -1 if there was no match, and only the "<" has been copied.
5373  */
5374     static size_t
5375 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5376     char_u	*code;
5377     size_t	len;
5378     char_u	*buf;
5379     ucmd_T	*cmd;		/* the user command we're expanding */
5380     exarg_T	*eap;		/* ex arguments */
5381     char_u	**split_buf;
5382     size_t	*split_len;
5383 {
5384     size_t	result = 0;
5385     char_u	*p = code + 1;
5386     size_t	l = len - 2;
5387     int		quote = 0;
5388     enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5389 	ct_LT, ct_NONE } type = ct_NONE;
5390 
5391     if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5392     {
5393 	quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5394 	p += 2;
5395 	l -= 2;
5396     }
5397 
5398     if (l < 1)
5399 	type = ct_NONE;
5400     else if (STRNICMP(p, "args", l) == 0)
5401 	type = ct_ARGS;
5402     else if (STRNICMP(p, "bang", l) == 0)
5403 	type = ct_BANG;
5404     else if (STRNICMP(p, "count", l) == 0)
5405 	type = ct_COUNT;
5406     else if (STRNICMP(p, "line1", l) == 0)
5407 	type = ct_LINE1;
5408     else if (STRNICMP(p, "line2", l) == 0)
5409 	type = ct_LINE2;
5410     else if (STRNICMP(p, "lt", l) == 0)
5411 	type = ct_LT;
5412     else if (STRNICMP(p, "register", l) == 0)
5413 	type = ct_REGISTER;
5414 
5415     switch (type)
5416     {
5417     case ct_ARGS:
5418 	/* Simple case first */
5419 	if (*eap->arg == NUL)
5420 	{
5421 	    if (quote == 1)
5422 	    {
5423 		result = 2;
5424 		if (buf != NULL)
5425 		    STRCPY(buf, "''");
5426 	    }
5427 	    else
5428 		result = 0;
5429 	    break;
5430 	}
5431 
5432 	/* When specified there is a single argument don't split it.
5433 	 * Works for ":Cmd %" when % is "a b c". */
5434 	if ((eap->argt & NOSPC) && quote == 2)
5435 	    quote = 1;
5436 
5437 	switch (quote)
5438 	{
5439 	case 0: /* No quoting, no splitting */
5440 	    result = STRLEN(eap->arg);
5441 	    if (buf != NULL)
5442 		STRCPY(buf, eap->arg);
5443 	    break;
5444 	case 1: /* Quote, but don't split */
5445 	    result = STRLEN(eap->arg) + 2;
5446 	    for (p = eap->arg; *p; ++p)
5447 	    {
5448 		if (*p == '\\' || *p == '"')
5449 		    ++result;
5450 	    }
5451 
5452 	    if (buf != NULL)
5453 	    {
5454 		*buf++ = '"';
5455 		for (p = eap->arg; *p; ++p)
5456 		{
5457 		    if (*p == '\\' || *p == '"')
5458 			*buf++ = '\\';
5459 		    *buf++ = *p;
5460 		}
5461 		*buf = '"';
5462 	    }
5463 
5464 	    break;
5465 	case 2: /* Quote and split */
5466 	    /* This is hard, so only do it once, and cache the result */
5467 	    if (*split_buf == NULL)
5468 		*split_buf = uc_split_args(eap->arg, split_len);
5469 
5470 	    result = *split_len;
5471 	    if (buf != NULL && result != 0)
5472 		STRCPY(buf, *split_buf);
5473 
5474 	    break;
5475 	}
5476 	break;
5477 
5478     case ct_BANG:
5479 	result = eap->forceit ? 1 : 0;
5480 	if (quote)
5481 	    result += 2;
5482 	if (buf != NULL)
5483 	{
5484 	    if (quote)
5485 		*buf++ = '"';
5486 	    if (eap->forceit)
5487 		*buf++ = '!';
5488 	    if (quote)
5489 		*buf = '"';
5490 	}
5491 	break;
5492 
5493     case ct_LINE1:
5494     case ct_LINE2:
5495     case ct_COUNT:
5496     {
5497 	char num_buf[20];
5498 	long num = (type == ct_LINE1) ? eap->line1 :
5499 		   (type == ct_LINE2) ? eap->line2 :
5500 		   (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5501 	size_t num_len;
5502 
5503 	sprintf(num_buf, "%ld", num);
5504 	num_len = STRLEN(num_buf);
5505 	result = num_len;
5506 
5507 	if (quote)
5508 	    result += 2;
5509 
5510 	if (buf != NULL)
5511 	{
5512 	    if (quote)
5513 		*buf++ = '"';
5514 	    STRCPY(buf, num_buf);
5515 	    buf += num_len;
5516 	    if (quote)
5517 		*buf = '"';
5518 	}
5519 
5520 	break;
5521     }
5522 
5523     case ct_REGISTER:
5524 	result = eap->regname ? 1 : 0;
5525 	if (quote)
5526 	    result += 2;
5527 	if (buf != NULL)
5528 	{
5529 	    if (quote)
5530 		*buf++ = '\'';
5531 	    if (eap->regname)
5532 		*buf++ = eap->regname;
5533 	    if (quote)
5534 		*buf = '\'';
5535 	}
5536 	break;
5537 
5538     case ct_LT:
5539 	result = 1;
5540 	if (buf != NULL)
5541 	    *buf = '<';
5542 	break;
5543 
5544     default:
5545 	/* Not recognized: just copy the '<' and return -1. */
5546 	result = (size_t)-1;
5547 	if (buf != NULL)
5548 	    *buf = '<';
5549 	break;
5550     }
5551 
5552     return result;
5553 }
5554 
5555     static void
5556 do_ucmd(eap)
5557     exarg_T	*eap;
5558 {
5559     char_u	*buf;
5560     char_u	*p;
5561     char_u	*q;
5562 
5563     char_u	*start;
5564     char_u	*end;
5565     size_t	len, totlen;
5566 
5567     size_t	split_len = 0;
5568     char_u	*split_buf = NULL;
5569     ucmd_T	*cmd;
5570 #ifdef FEAT_EVAL
5571     scid_T	save_current_SID = current_SID;
5572 #endif
5573 
5574     if (eap->cmdidx == CMD_USER)
5575 	cmd = USER_CMD(eap->useridx);
5576     else
5577 	cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5578 
5579     /*
5580      * Replace <> in the command by the arguments.
5581      */
5582     buf = NULL;
5583     for (;;)
5584     {
5585 	p = cmd->uc_rep;
5586 	q = buf;
5587 	totlen = 0;
5588 	while ((start = vim_strchr(p, '<')) != NULL
5589 	       && (end = vim_strchr(start + 1, '>')) != NULL)
5590 	{
5591 	    /* Include the '>' */
5592 	    ++end;
5593 
5594 	    /* Take everything up to the '<' */
5595 	    len = start - p;
5596 	    if (buf == NULL)
5597 		totlen += len;
5598 	    else
5599 	    {
5600 		mch_memmove(q, p, len);
5601 		q += len;
5602 	    }
5603 
5604 	    len = uc_check_code(start, end - start, q, cmd, eap,
5605 			     &split_buf, &split_len);
5606 	    if (len == (size_t)-1)
5607 	    {
5608 		/* no match, continue after '<' */
5609 		p = start + 1;
5610 		len = 1;
5611 	    }
5612 	    else
5613 		p = end;
5614 	    if (buf == NULL)
5615 		totlen += len;
5616 	    else
5617 		q += len;
5618 	}
5619 	if (buf != NULL)	    /* second time here, finished */
5620 	{
5621 	    STRCPY(q, p);
5622 	    break;
5623 	}
5624 
5625 	totlen += STRLEN(p);	    /* Add on the trailing characters */
5626 	buf = alloc((unsigned)(totlen + 1));
5627 	if (buf == NULL)
5628 	{
5629 	    vim_free(split_buf);
5630 	    return;
5631 	}
5632     }
5633 
5634 #ifdef FEAT_EVAL
5635     current_SID = cmd->uc_scriptID;
5636 #endif
5637     (void)do_cmdline(buf, eap->getline, eap->cookie,
5638 				   DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
5639 #ifdef FEAT_EVAL
5640     current_SID = save_current_SID;
5641 #endif
5642     vim_free(buf);
5643     vim_free(split_buf);
5644 }
5645 
5646 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
5647     static char_u *
5648 get_user_command_name(idx)
5649     int		idx;
5650 {
5651     return get_user_commands(NULL, idx - (int)CMD_SIZE);
5652 }
5653 
5654 /*
5655  * Function given to ExpandGeneric() to obtain the list of user command names.
5656  */
5657 /*ARGSUSED*/
5658     char_u *
5659 get_user_commands(xp, idx)
5660     expand_T	*xp;
5661     int		idx;
5662 {
5663     if (idx < curbuf->b_ucmds.ga_len)
5664 	return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
5665     idx -= curbuf->b_ucmds.ga_len;
5666     if (idx < ucmds.ga_len)
5667 	return USER_CMD(idx)->uc_name;
5668     return NULL;
5669 }
5670 
5671 /*
5672  * Function given to ExpandGeneric() to obtain the list of user command
5673  * attributes.
5674  */
5675 /*ARGSUSED*/
5676     char_u *
5677 get_user_cmd_flags(xp, idx)
5678     expand_T	*xp;
5679     int		idx;
5680 {
5681     static char *user_cmd_flags[] =
5682 	{"bang", "bar", "buffer", "complete", "count",
5683 	    "nargs", "range", "register"};
5684 
5685     if (idx >= sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0]))
5686 	return NULL;
5687     return (char_u *)user_cmd_flags[idx];
5688 }
5689 
5690 /*
5691  * Function given to ExpandGeneric() to obtain the list of values for -nargs.
5692  */
5693 /*ARGSUSED*/
5694     char_u *
5695 get_user_cmd_nargs(xp, idx)
5696     expand_T	*xp;
5697     int		idx;
5698 {
5699     static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
5700 
5701     if (idx >= sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0]))
5702 	return NULL;
5703     return (char_u *)user_cmd_nargs[idx];
5704 }
5705 
5706 /*
5707  * Function given to ExpandGeneric() to obtain the list of values for -complete.
5708  */
5709 /*ARGSUSED*/
5710     char_u *
5711 get_user_cmd_complete(xp, idx)
5712     expand_T	*xp;
5713     int		idx;
5714 {
5715     return (char_u *)command_complete[idx].name;
5716 }
5717 # endif /* FEAT_CMDL_COMPL */
5718 
5719 #endif	/* FEAT_USR_CMDS */
5720 
5721     static void
5722 ex_colorscheme(eap)
5723     exarg_T	*eap;
5724 {
5725     if (load_colors(eap->arg) == FAIL)
5726 	EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
5727 }
5728 
5729     static void
5730 ex_highlight(eap)
5731     exarg_T	*eap;
5732 {
5733     if (*eap->arg == NUL && eap->cmd[2] == '!')
5734 	MSG(_("Greetings, Vim user!"));
5735     do_highlight(eap->arg, eap->forceit, FALSE);
5736 }
5737 
5738 
5739 /*
5740  * Call this function if we thought we were going to exit, but we won't
5741  * (because of an error).  May need to restore the terminal mode.
5742  */
5743     void
5744 not_exiting()
5745 {
5746     exiting = FALSE;
5747     settmode(TMODE_RAW);
5748 }
5749 
5750 /*
5751  * ":quit": quit current window, quit Vim if closed the last window.
5752  */
5753     static void
5754 ex_quit(eap)
5755     exarg_T	*eap;
5756 {
5757 #ifdef FEAT_CMDWIN
5758     if (cmdwin_type != 0)
5759     {
5760 	cmdwin_result = Ctrl_C;
5761 	return;
5762     }
5763 #endif
5764 
5765 #ifdef FEAT_NETBEANS_INTG
5766     netbeansForcedQuit = eap->forceit;
5767 #endif
5768 
5769     /*
5770      * If there are more files or windows we won't exit.
5771      */
5772     if (check_more(FALSE, eap->forceit) == OK && only_one_window())
5773 	exiting = TRUE;
5774     if ((!P_HID(curbuf)
5775 		&& check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
5776 	    || check_more(TRUE, eap->forceit) == FAIL
5777 	    || (only_one_window() && check_changed_any(eap->forceit)))
5778     {
5779 	not_exiting();
5780     }
5781     else
5782     {
5783 #ifdef FEAT_WINDOWS
5784 	if (only_one_window())	    /* quit last window */
5785 #endif
5786 	    getout(0);
5787 #ifdef FEAT_WINDOWS
5788 # ifdef FEAT_GUI
5789 	need_mouse_correct = TRUE;
5790 # endif
5791 	/* close window; may free buffer */
5792 	win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
5793 #endif
5794     }
5795 }
5796 
5797 /*
5798  * ":cquit".
5799  */
5800 /*ARGSUSED*/
5801     static void
5802 ex_cquit(eap)
5803     exarg_T	*eap;
5804 {
5805     getout(1);	/* this does not always pass on the exit code to the Manx
5806 		   compiler. why? */
5807 }
5808 
5809 /*
5810  * ":qall": try to quit all windows
5811  */
5812     static void
5813 ex_quit_all(eap)
5814     exarg_T	*eap;
5815 {
5816 # ifdef FEAT_CMDWIN
5817     if (cmdwin_type != 0)
5818     {
5819 	if (eap->forceit)
5820 	    cmdwin_result = K_XF1;	/* ex_window() takes care of this */
5821 	else
5822 	    cmdwin_result = K_XF2;
5823 	return;
5824     }
5825 # endif
5826     exiting = TRUE;
5827     if (eap->forceit || !check_changed_any(FALSE))
5828 	getout(0);
5829     not_exiting();
5830 }
5831 
5832 #ifdef FEAT_WINDOWS
5833 /*
5834  * ":close": close current window, unless it is the last one
5835  */
5836     static void
5837 ex_close(eap)
5838     exarg_T	*eap;
5839 {
5840 # ifdef FEAT_CMDWIN
5841     if (cmdwin_type != 0)
5842 	cmdwin_result = K_IGNORE;
5843     else
5844 # endif
5845 	ex_win_close(eap, curwin);
5846 }
5847 
5848     static void
5849 ex_win_close(eap, win)
5850     exarg_T	*eap;
5851     win_T	*win;
5852 {
5853     int		need_hide;
5854     buf_T	*buf = win->w_buffer;
5855 
5856     need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
5857     if (need_hide && !P_HID(buf) && !eap->forceit)
5858     {
5859 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5860 	if ((p_confirm || cmdmod.confirm) && p_write)
5861 	{
5862 	    dialog_changed(buf, FALSE);
5863 	    if (buf_valid(buf) && bufIsChanged(buf))
5864 		return;
5865 	    need_hide = FALSE;
5866 	}
5867 	else
5868 #endif
5869 	{
5870 	    EMSG(_(e_nowrtmsg));
5871 	    return;
5872 	}
5873     }
5874 
5875 #ifdef FEAT_GUI
5876     need_mouse_correct = TRUE;
5877 #endif
5878     /* free buffer when not hiding it or when it's a scratch buffer */
5879     win_close(win, !need_hide && !P_HID(buf));
5880 }
5881 
5882 #ifdef FEAT_QUICKFIX
5883 /*
5884  * ":pclose": Close any preview window.
5885  */
5886     static void
5887 ex_pclose(eap)
5888     exarg_T	*eap;
5889 {
5890     win_T	*win;
5891 
5892     for (win = firstwin; win != NULL; win = win->w_next)
5893 	if (win->w_p_pvw)
5894 	{
5895 	    ex_win_close(eap, win);
5896 	    break;
5897 	}
5898 }
5899 #endif
5900 
5901 /*
5902  * ":only".
5903  */
5904     static void
5905 ex_only(eap)
5906     exarg_T	*eap;
5907 {
5908 # ifdef FEAT_GUI
5909     need_mouse_correct = TRUE;
5910 # endif
5911     close_others(TRUE, eap->forceit);
5912 }
5913 
5914 /*
5915  * ":all" and ":sall".
5916  */
5917     static void
5918 ex_all(eap)
5919     exarg_T	*eap;
5920 {
5921     if (eap->addr_count == 0)
5922 	eap->line2 = 9999;
5923     do_arg_all((int)eap->line2, eap->forceit);
5924 }
5925 #endif /* FEAT_WINDOWS */
5926 
5927     static void
5928 ex_hide(eap)
5929     exarg_T	*eap;
5930 {
5931     if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
5932 	eap->errmsg = e_invarg;
5933     else
5934     {
5935 	/* ":hide" or ":hide | cmd": hide current window */
5936 	eap->nextcmd = check_nextcmd(eap->arg);
5937 #ifdef FEAT_WINDOWS
5938 	if (!eap->skip)
5939 	{
5940 # ifdef FEAT_GUI
5941 	    need_mouse_correct = TRUE;
5942 # endif
5943 	    win_close(curwin, FALSE);	/* don't free buffer */
5944 	}
5945 #endif
5946     }
5947 }
5948 
5949 /*
5950  * ":stop" and ":suspend": Suspend Vim.
5951  */
5952     static void
5953 ex_stop(eap)
5954     exarg_T	*eap;
5955 {
5956     /*
5957      * Disallow suspending for "rvim".
5958      */
5959     if (!check_restricted()
5960 #ifdef WIN3264
5961 	/*
5962 	 * Check if external commands are allowed now.
5963 	 */
5964 	&& can_end_termcap_mode(TRUE)
5965 #endif
5966 					)
5967     {
5968 	if (!eap->forceit)
5969 	    autowrite_all();
5970 	windgoto((int)Rows - 1, 0);
5971 	out_char('\n');
5972 	out_flush();
5973 	stoptermcap();
5974 	out_flush();		/* needed for SUN to restore xterm buffer */
5975 #ifdef FEAT_TITLE
5976 	mch_restore_title(3);	/* restore window titles */
5977 #endif
5978 	ui_suspend();		/* call machine specific function */
5979 #ifdef FEAT_TITLE
5980 	maketitle();
5981 	resettitle();		/* force updating the title */
5982 #endif
5983 	starttermcap();
5984 	scroll_start();		/* scroll screen before redrawing */
5985 	redraw_later_clear();
5986 	shell_resized();	/* may have resized window */
5987     }
5988 }
5989 
5990 /*
5991  * ":exit", ":xit" and ":wq": Write file and exit Vim.
5992  */
5993     static void
5994 ex_exit(eap)
5995     exarg_T	*eap;
5996 {
5997 #ifdef FEAT_CMDWIN
5998     if (cmdwin_type != 0)
5999     {
6000 	cmdwin_result = Ctrl_C;
6001 	return;
6002     }
6003 #endif
6004 
6005     /*
6006      * if more files or windows we won't exit
6007      */
6008     if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6009 	exiting = TRUE;
6010     if (       ((eap->cmdidx == CMD_wq
6011 		    || curbufIsChanged())
6012 		&& do_write(eap) == FAIL)
6013 	    || check_more(TRUE, eap->forceit) == FAIL
6014 	    || (only_one_window() && check_changed_any(eap->forceit)))
6015     {
6016 	not_exiting();
6017     }
6018     else
6019     {
6020 #ifdef FEAT_WINDOWS
6021 	if (only_one_window())	    /* quit last window, exit Vim */
6022 #endif
6023 	    getout(0);
6024 #ifdef FEAT_WINDOWS
6025 # ifdef FEAT_GUI
6026 	need_mouse_correct = TRUE;
6027 # endif
6028 	/* quit current window, may free buffer */
6029 	win_close(curwin, !P_HID(curwin->w_buffer));
6030 #endif
6031     }
6032 }
6033 
6034 /*
6035  * ":print", ":list", ":number".
6036  */
6037     static void
6038 ex_print(eap)
6039     exarg_T	*eap;
6040 {
6041     int		save_list = 0;	    /* init for GCC */
6042 
6043     if (eap->cmdidx == CMD_list)
6044     {
6045 	save_list = curwin->w_p_list;
6046 	curwin->w_p_list = 1;
6047     }
6048 
6049     for ( ;!got_int; ui_breakcheck())
6050     {
6051 	print_line(eap->line1,
6052 		   (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound));
6053 	if (++eap->line1 > eap->line2)
6054 	    break;
6055 	out_flush();	    /* show one line at a time */
6056     }
6057     setpcmark();
6058     /* put cursor at last line */
6059     curwin->w_cursor.lnum = eap->line2;
6060     beginline(BL_SOL | BL_FIX);
6061 
6062     ex_no_reprint = TRUE;
6063 
6064     if (eap->cmdidx == CMD_list)
6065 	curwin->w_p_list = save_list;
6066 }
6067 
6068 #ifdef FEAT_BYTEOFF
6069     static void
6070 ex_goto(eap)
6071     exarg_T	*eap;
6072 {
6073     goto_byte(eap->line2);
6074 }
6075 #endif
6076 
6077 /*
6078  * ":shell".
6079  */
6080 /*ARGSUSED*/
6081     static void
6082 ex_shell(eap)
6083     exarg_T	*eap;
6084 {
6085     do_shell(NULL, 0);
6086 }
6087 
6088 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6089 	|| (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6090 	|| defined(PROTO)
6091 
6092 /*
6093  * Handle a file drop. The code is here because a drop is *nearly* like an
6094  * :args command, but not quite (we have a list of exact filenames, so we
6095  * don't want to (a) parse a command line, or (b) expand wildcards. So the
6096  * code is very similar to :args and hence needs access to a lot of the static
6097  * functions in this file.
6098  *
6099  * The list should be allocated using alloc(), as should each item in the
6100  * list. This function takes over responsibility for freeing the list.
6101  *
6102  * XXX The list is made into the arggument list. This is freed using
6103  * FreeWild(), which does a series of vim_free() calls, unless the two defines
6104  * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6105  * routine _fnexplodefree() is used. This may cause problems, but as the drop
6106  * file functionality is (currently) not in EMX this is not presently a
6107  * problem.
6108  */
6109     void
6110 handle_drop(filec, filev, split)
6111     int		filec;		/* the number of files dropped */
6112     char_u	**filev;	/* the list of files dropped */
6113     int		split;		/* force splitting the window */
6114 {
6115     exarg_T	ea;
6116     int		save_msg_scroll = msg_scroll;
6117 
6118 # ifdef FEAT_CMDWIN
6119     if (cmdwin_type != 0)
6120 	return;
6121 # endif
6122 
6123     /* Check whether the current buffer is changed. If so, we will need
6124      * to split the current window or data could be lost.
6125      * We don't need to check if the 'hidden' option is set, as in this
6126      * case the buffer won't be lost.
6127      */
6128     if (!P_HID(curbuf) && !split)
6129     {
6130 	++emsg_off;
6131 	split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6132 	--emsg_off;
6133     }
6134     if (split)
6135     {
6136 # ifdef FEAT_WINDOWS
6137 	if (win_split(0, 0) == FAIL)
6138 	    return;
6139 #  ifdef FEAT_SCROLLBIND
6140 	curwin->w_p_scb = FALSE;
6141 #  endif
6142 
6143 	/* When splitting the window, create a new alist.  Otherwise the
6144 	 * existing one is overwritten. */
6145 	alist_unlink(curwin->w_alist);
6146 	alist_new();
6147 # else
6148 	return;	    /* can't split, always fail */
6149 # endif
6150     }
6151 
6152     /*
6153      * Set up the new argument list.
6154      */
6155     alist_set(ALIST(curwin), filec, filev, FALSE);
6156 
6157     /*
6158      * Move to the first file.
6159      */
6160     /* Fake up a minimal "next" command for do_argfile() */
6161     vim_memset(&ea, 0, sizeof(ea));
6162     ea.cmd = (char_u *)"next";
6163     do_argfile(&ea, 0);
6164 
6165     /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6166      * mode that is not needed here. */
6167     need_start_insertmode = FALSE;
6168 
6169     /* Restore msg_scroll, otherwise a following command may cause scrolling
6170      * unexpectedly.  The screen will be redrawn by the caller, thus
6171      * msg_scroll being set by displaying a message is irrelevant. */
6172     msg_scroll = save_msg_scroll;
6173 }
6174 #endif
6175 
6176 /*
6177  * Clear an argument list: free all file names and reset it to zero entries.
6178  */
6179     void
6180 alist_clear(al)
6181     alist_T	*al;
6182 {
6183     while (--al->al_ga.ga_len >= 0)
6184 	vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6185     ga_clear(&al->al_ga);
6186 }
6187 
6188 /*
6189  * Init an argument list.
6190  */
6191     void
6192 alist_init(al)
6193     alist_T	*al;
6194 {
6195     ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6196 }
6197 
6198 #if defined(FEAT_WINDOWS) || defined(PROTO)
6199 
6200 /*
6201  * Remove a reference from an argument list.
6202  * Ignored when the argument list is the global one.
6203  * If the argument list is no longer used by any window, free it.
6204  */
6205     void
6206 alist_unlink(al)
6207     alist_T	*al;
6208 {
6209     if (al != &global_alist && --al->al_refcount <= 0)
6210     {
6211 	alist_clear(al);
6212 	vim_free(al);
6213     }
6214 }
6215 
6216 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6217 /*
6218  * Create a new argument list and use it for the current window.
6219  */
6220     void
6221 alist_new()
6222 {
6223     curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6224     if (curwin->w_alist == NULL)
6225     {
6226 	curwin->w_alist = &global_alist;
6227 	++global_alist.al_refcount;
6228     }
6229     else
6230     {
6231 	curwin->w_alist->al_refcount = 1;
6232 	alist_init(curwin->w_alist);
6233     }
6234 }
6235 # endif
6236 #endif
6237 
6238 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6239 /*
6240  * Expand the file names in the global argument list.
6241  */
6242     void
6243 alist_expand()
6244 {
6245     char_u	**old_arg_files;
6246     char_u	**new_arg_files;
6247     int		new_arg_file_count;
6248     char_u	*save_p_su = p_su;
6249     int		i;
6250 
6251     /* Don't use 'suffixes' here.  This should work like the shell did the
6252      * expansion.  Also, the vimrc file isn't read yet, thus the user
6253      * can't set the options. */
6254     p_su = empty_option;
6255     old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6256     if (old_arg_files != NULL)
6257     {
6258 	for (i = 0; i < GARGCOUNT; ++i)
6259 	    old_arg_files[i] = GARGLIST[i].ae_fname;
6260 	if (expand_wildcards(GARGCOUNT, old_arg_files,
6261 		    &new_arg_file_count, &new_arg_files,
6262 		    EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6263 		&& new_arg_file_count > 0)
6264 	{
6265 	    alist_set(&global_alist, new_arg_file_count, new_arg_files, TRUE);
6266 	    vim_free(old_arg_files);
6267 	}
6268     }
6269     p_su = save_p_su;
6270 }
6271 #endif
6272 
6273 /*
6274  * Set the argument list for the current window.
6275  * Takes over the allocated files[] and the allocated fnames in it.
6276  */
6277     void
6278 alist_set(al, count, files, use_curbuf)
6279     alist_T	*al;
6280     int		count;
6281     char_u	**files;
6282     int		use_curbuf;
6283 {
6284     int		i;
6285 
6286     alist_clear(al);
6287     if (ga_grow(&al->al_ga, count) == OK)
6288     {
6289 	for (i = 0; i < count; ++i)
6290 	{
6291 	    if (got_int)
6292 	    {
6293 		/* When adding many buffers this can take a long time.  Allow
6294 		 * interrupting here. */
6295 		while (i < count)
6296 		    vim_free(files[i++]);
6297 		break;
6298 	    }
6299 	    alist_add(al, files[i], use_curbuf ? 2 : 1);
6300 	    ui_breakcheck();
6301 	}
6302 	vim_free(files);
6303     }
6304     else
6305 	FreeWild(count, files);
6306 #ifdef FEAT_WINDOWS
6307     if (al == &global_alist)
6308 #endif
6309 	arg_had_last = FALSE;
6310 }
6311 
6312 /*
6313  * Add file "fname" to argument list "al".
6314  * "fname" must have been allocated and "al" must have been checked for room.
6315  */
6316     void
6317 alist_add(al, fname, set_fnum)
6318     alist_T	*al;
6319     char_u	*fname;
6320     int		set_fnum;	/* 1: set buffer number; 2: re-use curbuf */
6321 {
6322     if (fname == NULL)		/* don't add NULL file names */
6323 	return;
6324 #ifdef BACKSLASH_IN_FILENAME
6325     slash_adjust(fname);
6326 #endif
6327     AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
6328     if (set_fnum > 0)
6329 	AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
6330 	    buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
6331     ++al->al_ga.ga_len;
6332     --al->al_ga.ga_room;
6333 }
6334 
6335 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
6336 /*
6337  * Adjust slashes in file names.  Called after 'shellslash' was set.
6338  */
6339     void
6340 alist_slash_adjust()
6341 {
6342     int		i;
6343 # ifdef FEAT_WINDOWS
6344     win_T	*wp;
6345 # endif
6346 
6347     for (i = 0; i < GARGCOUNT; ++i)
6348 	if (GARGLIST[i].ae_fname != NULL)
6349 	    slash_adjust(GARGLIST[i].ae_fname);
6350 # ifdef FEAT_WINDOWS
6351     for (wp = firstwin; wp != NULL; wp = wp->w_next)
6352 	if (wp->w_alist != &global_alist)
6353 	    for (i = 0; i < WARGCOUNT(wp); ++i)
6354 		if (WARGLIST(wp)[i].ae_fname != NULL)
6355 		    slash_adjust(WARGLIST(wp)[i].ae_fname);
6356 # endif
6357 }
6358 #endif
6359 
6360 /*
6361  * ":preserve".
6362  */
6363 /*ARGSUSED*/
6364     static void
6365 ex_preserve(eap)
6366     exarg_T	*eap;
6367 {
6368     ml_preserve(curbuf, TRUE);
6369 }
6370 
6371 /*
6372  * ":recover".
6373  */
6374     static void
6375 ex_recover(eap)
6376     exarg_T	*eap;
6377 {
6378     /* Set recoverymode right away to avoid the ATTENTION prompt. */
6379     recoverymode = TRUE;
6380     if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
6381 	    && (*eap->arg == NUL
6382 			     || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
6383 	ml_recover();
6384     recoverymode = FALSE;
6385 }
6386 
6387 /*
6388  * Command modifier used in a wrong way.
6389  */
6390     static void
6391 ex_wrongmodifier(eap)
6392     exarg_T	*eap;
6393 {
6394     eap->errmsg = e_invcmd;
6395 }
6396 
6397 #ifdef FEAT_WINDOWS
6398 /*
6399  * :sview [+command] file	split window with new file, read-only
6400  * :split [[+command] file]	split window with current or new file
6401  * :vsplit [[+command] file]	split window vertically with current or new file
6402  * :new [[+command] file]	split window with no or new file
6403  * :vnew [[+command] file]	split vertically window with no or new file
6404  * :sfind [+command] file	split window with file in 'path'
6405  */
6406     void
6407 ex_splitview(eap)
6408     exarg_T	*eap;
6409 {
6410     win_T	*old_curwin;
6411 #if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
6412     char_u	*fname = NULL;
6413 #endif
6414 #ifdef FEAT_BROWSE
6415     int		browse_flag = cmdmod.browse;
6416 #endif
6417 
6418 #ifndef FEAT_VERTSPLIT
6419     if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
6420     {
6421 	ex_ni(eap);
6422 	return;
6423     }
6424 #endif
6425 
6426     old_curwin = curwin;
6427 #ifdef FEAT_GUI
6428     need_mouse_correct = TRUE;
6429 #endif
6430 
6431 #ifdef FEAT_QUICKFIX
6432     /* A ":split" in the quickfix window works like ":new".  Don't want two
6433      * quickfix windows. */
6434     if (bt_quickfix(curbuf))
6435     {
6436 	if (eap->cmdidx == CMD_split)
6437 	    eap->cmdidx = CMD_new;
6438 # ifdef FEAT_VERTSPLIT
6439 	if (eap->cmdidx == CMD_vsplit)
6440 	    eap->cmdidx = CMD_vnew;
6441 # endif
6442     }
6443 #endif
6444 
6445 #ifdef FEAT_SEARCHPATH
6446     if (eap->cmdidx == CMD_sfind)
6447     {
6448 	fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
6449 					  FNAME_MESS, TRUE, curbuf->b_ffname);
6450 	if (fname == NULL)
6451 	    goto theend;
6452 	eap->arg = fname;
6453     }
6454 # ifdef FEAT_BROWSE
6455     else
6456 # endif
6457 #endif
6458 #ifdef FEAT_BROWSE
6459     if (cmdmod.browse
6460 # ifdef FEAT_VERTSPLIT
6461 	    && eap->cmdidx != CMD_vnew
6462 #endif
6463 	    && eap->cmdidx != CMD_new)
6464     {
6465 	fname = do_browse(FALSE, (char_u *)_("Edit File in new window"),
6466 					  eap->arg, NULL, NULL, NULL, curbuf);
6467 	if (fname == NULL)
6468 	    goto theend;
6469 	eap->arg = fname;
6470     }
6471     cmdmod.browse = FALSE;	/* Don't browse again in do_ecmd(). */
6472 #endif
6473 
6474     if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
6475 				     *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
6476     {
6477 #ifdef FEAT_SCROLLBIND
6478 	/* Reset 'scrollbind' when editing another file, but keep it when
6479 	 * doing ":split" without arguments. */
6480 	if (*eap->arg != NUL
6481 #ifdef FEAT_BROWSE
6482 		|| cmdmod.browse
6483 #endif
6484 	   )
6485 	    curwin->w_p_scb = FALSE;
6486 	else
6487 	    do_check_scrollbind(FALSE);
6488 #endif
6489 	do_exedit(eap, old_curwin);
6490     }
6491 
6492 #ifdef FEAT_BROWSE
6493     cmdmod.browse = browse_flag;
6494 #endif
6495 
6496 #if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
6497 theend:
6498     vim_free(fname);
6499 #endif
6500 }
6501 #endif
6502 
6503 /*
6504  * ":mode": Set screen mode.
6505  * If no argument given, just get the screen size and redraw.
6506  */
6507     static void
6508 ex_mode(eap)
6509     exarg_T	*eap;
6510 {
6511     if (*eap->arg == NUL)
6512 	shell_resized();
6513     else
6514 	mch_screenmode(eap->arg);
6515 }
6516 
6517 #ifdef FEAT_WINDOWS
6518 /*
6519  * ":resize".
6520  * set, increment or decrement current window height
6521  */
6522     static void
6523 ex_resize(eap)
6524     exarg_T	*eap;
6525 {
6526     int		n;
6527     win_T	*wp = curwin;
6528 
6529     if (eap->addr_count > 0)
6530     {
6531 	n = eap->line2;
6532 	for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
6533 	    ;
6534     }
6535 
6536 #ifdef FEAT_GUI
6537     need_mouse_correct = TRUE;
6538 #endif
6539     n = atol((char *)eap->arg);
6540 #ifdef FEAT_VERTSPLIT
6541     if (cmdmod.split & WSP_VERT)
6542     {
6543 	if (*eap->arg == '-' || *eap->arg == '+')
6544 	    n += W_WIDTH(curwin);
6545 	else if (n == 0 && eap->arg[0] == NUL)	/* default is very wide */
6546 	    n = 9999;
6547 	win_setwidth_win((int)n, wp);
6548     }
6549     else
6550 #endif
6551     {
6552 	if (*eap->arg == '-' || *eap->arg == '+')
6553 	    n += curwin->w_height;
6554 	else if (n == 0 && eap->arg[0] == NUL)	/* default is very wide */
6555 	    n = 9999;
6556 	win_setheight_win((int)n, wp);
6557     }
6558 }
6559 #endif
6560 
6561 /*
6562  * ":find [+command] <file>" command.
6563  */
6564     static void
6565 ex_find(eap)
6566     exarg_T	*eap;
6567 {
6568 #ifdef FEAT_SEARCHPATH
6569     char_u	*fname;
6570     int		count;
6571 
6572     fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
6573 						      TRUE, curbuf->b_ffname);
6574     if (eap->addr_count > 0)
6575     {
6576 	/* Repeat finding the file "count" times.  This matters when it
6577 	 * appears several times in the path. */
6578 	count = eap->line2;
6579 	while (fname != NULL && --count > 0)
6580 	{
6581 	    vim_free(fname);
6582 	    fname = find_file_in_path(NULL, 0, FNAME_MESS,
6583 						     FALSE, curbuf->b_ffname);
6584 	}
6585     }
6586 
6587     if (fname != NULL)
6588     {
6589 	eap->arg = fname;
6590 #endif
6591 	do_exedit(eap, NULL);
6592 #ifdef FEAT_SEARCHPATH
6593 	vim_free(fname);
6594     }
6595 #endif
6596 }
6597 
6598 /*
6599  * ":edit", ":badd".
6600  */
6601     static void
6602 ex_edit(eap)
6603     exarg_T	*eap;
6604 {
6605     do_exedit(eap, NULL);
6606 }
6607 
6608 /*
6609  * ":edit <file>" command and alikes.
6610  */
6611 /*ARGSUSED*/
6612     void
6613 do_exedit(eap, old_curwin)
6614     exarg_T	*eap;
6615     win_T	*old_curwin;	    /* curwin before doing a split or NULL */
6616 {
6617     int		n;
6618 #ifdef FEAT_WINDOWS
6619     int		need_hide;
6620 #endif
6621 
6622     /*
6623      * ":vi" command ends Ex mode.
6624      */
6625     if (exmode_active && (eap->cmdidx == CMD_visual
6626 						|| eap->cmdidx == CMD_view))
6627     {
6628 	exmode_active = FALSE;
6629 	if (*eap->arg == NUL)
6630 	    return;
6631     }
6632 
6633     if ((eap->cmdidx == CMD_new
6634 #ifdef FEAT_VERTSPLIT
6635 		|| eap->cmdidx == CMD_vnew
6636 #endif
6637 		) && *eap->arg == NUL)
6638     {
6639 	/* ":new" without argument: edit an new empty buffer */
6640 	setpcmark();
6641 	(void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
6642 			       ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0));
6643     }
6644     else if ((eap->cmdidx != CMD_split
6645 #ifdef FEAT_VERTSPLIT
6646 		&& eap->cmdidx != CMD_vsplit
6647 #endif
6648 		)
6649 	    || *eap->arg != NUL
6650 #ifdef FEAT_BROWSE
6651 	    || cmdmod.browse
6652 #endif
6653 	    )
6654     {
6655 	n = readonlymode;
6656 	if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
6657 	    readonlymode = TRUE;
6658 	else if (eap->cmdidx == CMD_enew)
6659 	    readonlymode = FALSE;   /* 'readonly' doesn't make sense in an
6660 				       empty buffer */
6661 	setpcmark();
6662 	if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
6663 		    NULL, eap,
6664 		    /* ":edit" goes to first line if Vi compatible */
6665 		    (*eap->arg == NUL && eap->do_ecmd_lnum == 0
6666 				      && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
6667 					       ? ECMD_ONE : eap->do_ecmd_lnum,
6668 		    (P_HID(curbuf) ? ECMD_HIDE : 0)
6669 		    + (eap->forceit ? ECMD_FORCEIT : 0)
6670 #ifdef FEAT_LISTCMDS
6671 		    + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
6672 #endif
6673 		    ) == FAIL)
6674 	{
6675 	    /* Editing the file failed.  If the window was split, close it. */
6676 #ifdef FEAT_WINDOWS
6677 	    if (old_curwin != NULL)
6678 	    {
6679 		need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
6680 		if (!need_hide || P_HID(curbuf))
6681 		{
6682 # ifdef FEAT_GUI
6683 		    need_mouse_correct = TRUE;
6684 # endif
6685 		    win_close(curwin, !need_hide && !P_HID(curbuf));
6686 		}
6687 	    }
6688 #endif
6689 	}
6690 	else if (readonlymode && curbuf->b_nwindows == 1)
6691 	{
6692 	    /* When editing an already visited buffer, 'readonly' won't be set
6693 	     * but the previous value is kept.  With ":view" and ":sview" we
6694 	     * want the  file to be readonly, except when another window is
6695 	     * editing the same buffer. */
6696 	    curbuf->b_p_ro = TRUE;
6697 	}
6698 	readonlymode = n;
6699     }
6700     else
6701     {
6702 	if (eap->do_ecmd_cmd != NULL)
6703 	    do_cmdline_cmd(eap->do_ecmd_cmd);
6704 #ifdef FEAT_TITLE
6705 	n = curwin->w_arg_idx_invalid;
6706 #endif
6707 	check_arg_idx(curwin);
6708 #ifdef FEAT_TITLE
6709 	if (n != curwin->w_arg_idx_invalid)
6710 	    maketitle();
6711 #endif
6712     }
6713 
6714 #ifdef FEAT_WINDOWS
6715     /*
6716      * if ":split file" worked, set alternate file name in old window to new
6717      * file
6718      */
6719     if (old_curwin != NULL
6720 	    && *eap->arg != NUL
6721 	    && curwin != old_curwin
6722 	    && win_valid(old_curwin)
6723 	    && old_curwin->w_buffer != curbuf
6724 	    && !cmdmod.keepalt)
6725 	old_curwin->w_alt_fnum = curbuf->b_fnum;
6726 #endif
6727 
6728     ex_no_reprint = TRUE;
6729 }
6730 
6731 #ifndef FEAT_GUI
6732 /*
6733  * ":gui" and ":gvim" when there is no GUI.
6734  */
6735     static void
6736 ex_nogui(eap)
6737     exarg_T	*eap;
6738 {
6739     eap->errmsg = e_nogvim;
6740 }
6741 #endif
6742 
6743 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
6744     static void
6745 ex_tearoff(eap)
6746     exarg_T	*eap;
6747 {
6748     gui_make_tearoff(eap->arg);
6749 }
6750 #endif
6751 
6752 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_KDE) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
6753     static void
6754 ex_popup(eap)
6755     exarg_T	*eap;
6756 {
6757     gui_make_popup(eap->arg);
6758 }
6759 #endif
6760 
6761 /*ARGSUSED*/
6762     static void
6763 ex_swapname(eap)
6764     exarg_T	*eap;
6765 {
6766     if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
6767 	MSG(_("No swap file"));
6768     else
6769 	msg(curbuf->b_ml.ml_mfp->mf_fname);
6770 }
6771 
6772 /*
6773  * ":syncbind" forces all 'scrollbind' windows to have the same relative
6774  * offset.
6775  * (1998-11-02 16:21:01  R. Edward Ralston <[email protected]>)
6776  */
6777 /*ARGSUSED*/
6778     static void
6779 ex_syncbind(eap)
6780     exarg_T	*eap;
6781 {
6782 #ifdef FEAT_SCROLLBIND
6783     win_T	*wp;
6784     long	topline;
6785     long	y;
6786     linenr_T	old_linenr = curwin->w_cursor.lnum;
6787 
6788     setpcmark();
6789 
6790     /*
6791      * determine max topline
6792      */
6793     if (curwin->w_p_scb)
6794     {
6795 	topline = curwin->w_topline;
6796 	for (wp = firstwin; wp; wp = wp->w_next)
6797 	{
6798 	    if (wp->w_p_scb && wp->w_buffer)
6799 	    {
6800 		y = wp->w_buffer->b_ml.ml_line_count - p_so;
6801 		if (topline > y)
6802 		    topline = y;
6803 	    }
6804 	}
6805 	if (topline < 1)
6806 	    topline = 1;
6807     }
6808     else
6809     {
6810 	topline = 1;
6811     }
6812 
6813 
6814     /*
6815      * set all scrollbind windows to the same topline
6816      */
6817     wp = curwin;
6818     for (curwin = firstwin; curwin; curwin = curwin->w_next)
6819     {
6820 	if (curwin->w_p_scb)
6821 	{
6822 	    y = topline - curwin->w_topline;
6823 	    if (y > 0)
6824 		scrollup(y, TRUE);
6825 	    else
6826 		scrolldown(-y, TRUE);
6827 	    curwin->w_scbind_pos = topline;
6828 	    redraw_later(VALID);
6829 	    cursor_correct();
6830 #ifdef FEAT_WINDOWS
6831 	    curwin->w_redr_status = TRUE;
6832 #endif
6833 	}
6834     }
6835     curwin = wp;
6836     if (curwin->w_p_scb)
6837     {
6838 	did_syncbind = TRUE;
6839 	checkpcmark();
6840 	if (old_linenr != curwin->w_cursor.lnum)
6841 	{
6842 	    char_u ctrl_o[2];
6843 
6844 	    ctrl_o[0] = Ctrl_O;
6845 	    ctrl_o[1] = 0;
6846 	    ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
6847 	}
6848     }
6849 #endif
6850 }
6851 
6852 
6853     static void
6854 ex_read(eap)
6855     exarg_T	*eap;
6856 {
6857     int	    i;
6858 
6859     if (eap->usefilter)			/* :r!cmd */
6860 	do_bang(1, eap, FALSE, FALSE, TRUE);
6861     else
6862     {
6863 	if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
6864 	    return;
6865 
6866 #ifdef FEAT_BROWSE
6867 	if (cmdmod.browse)
6868 	{
6869 	    char_u *browseFile;
6870 
6871 	    browseFile = do_browse(FALSE, (char_u *)_("Append File"), eap->arg,
6872 						    NULL, NULL, NULL, curbuf);
6873 	    if (browseFile != NULL)
6874 	    {
6875 		i = readfile(browseFile, NULL,
6876 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
6877 		vim_free(browseFile);
6878 	    }
6879 	    else
6880 		i = OK;
6881 	}
6882 	else
6883 #endif
6884 	     if (*eap->arg == NUL)
6885 	{
6886 	    if (check_fname() == FAIL)	/* check for no file name */
6887 		return;
6888 	    i = readfile(curbuf->b_ffname, curbuf->b_fname,
6889 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
6890 	}
6891 	else
6892 	{
6893 	    if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
6894 		(void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
6895 	    i = readfile(eap->arg, NULL,
6896 			  eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
6897 
6898 	}
6899 	if (i == FAIL)
6900 	{
6901 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6902 	    if (!aborting())
6903 #endif
6904 		EMSG2(_(e_notopen), eap->arg);
6905 	}
6906 	else
6907 	    redraw_curbuf_later(VALID);
6908     }
6909 }
6910 
6911 /*
6912  * ":cd", ":lcd", ":chdir" and ":lchdir".
6913  */
6914     static void
6915 ex_cd(eap)
6916     exarg_T	*eap;
6917 {
6918     static char_u	*prev_dir = NULL;
6919     char_u		*new_dir;
6920     char_u		*tofree;
6921 
6922     new_dir = eap->arg;
6923 #if !defined(UNIX) && !defined(VMS)
6924     /* for non-UNIX ":cd" means: print current directory */
6925     if (*new_dir == NUL)
6926 	ex_pwd(NULL);
6927     else
6928 #endif
6929     {
6930 	/* ":cd -": Change to previous directory */
6931 	if (STRCMP(new_dir, "-") == 0)
6932 	{
6933 	    if (prev_dir == NULL)
6934 	    {
6935 		EMSG(_("E186: No previous directory"));
6936 		return;
6937 	    }
6938 	    new_dir = prev_dir;
6939 	}
6940 
6941 	/* Save current directory for next ":cd -" */
6942 	tofree = prev_dir;
6943 	if (mch_dirname(NameBuff, MAXPATHL) == OK)
6944 	    prev_dir = vim_strsave(NameBuff);
6945 	else
6946 	    prev_dir = NULL;
6947 
6948 #if defined(UNIX) || defined(VMS)
6949 	/* for UNIX ":cd" means: go to home directory */
6950 	if (*new_dir == NUL)
6951 	{
6952 	    /* use NameBuff for home directory name */
6953 # ifdef VMS
6954 	    char_u	*p;
6955 
6956 	    p = mch_getenv((char_u *)"SYS$LOGIN");
6957 	    if (p == NULL || *p == NUL)	/* empty is the same as not set */
6958 		NameBuff[0] = NUL;
6959 	    else
6960 		STRNCPY(NameBuff, p, MAXPATHL);
6961 # else
6962 	    expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
6963 # endif
6964 	    new_dir = NameBuff;
6965 	}
6966 #endif
6967 	if (new_dir == NULL || vim_chdir(new_dir))
6968 	    EMSG(_(e_failed));
6969 	else
6970 	{
6971 	    vim_free(curwin->w_localdir);
6972 	    if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
6973 	    {
6974 		/* If still in global directory, need to remember current
6975 		 * directory as global directory. */
6976 		if (globaldir == NULL && prev_dir != NULL)
6977 		    globaldir = vim_strsave(prev_dir);
6978 		/* Remember this local directory for the window. */
6979 		if (mch_dirname(NameBuff, MAXPATHL) == OK)
6980 		    curwin->w_localdir = vim_strsave(NameBuff);
6981 	    }
6982 	    else
6983 	    {
6984 		/* We are now in the global directory, no need to remember its
6985 		 * name. */
6986 		vim_free(globaldir);
6987 		globaldir = NULL;
6988 		curwin->w_localdir = NULL;
6989 	    }
6990 
6991 	    shorten_fnames(TRUE);
6992 
6993 	    /* Echo the new current directory if the command was typed. */
6994 	    if (KeyTyped)
6995 		ex_pwd(eap);
6996 	}
6997 	vim_free(tofree);
6998     }
6999 }
7000 
7001 /*
7002  * ":pwd".
7003  */
7004 /*ARGSUSED*/
7005     static void
7006 ex_pwd(eap)
7007     exarg_T	*eap;
7008 {
7009     if (mch_dirname(NameBuff, MAXPATHL) == OK)
7010     {
7011 #ifdef BACKSLASH_IN_FILENAME
7012 	slash_adjust(NameBuff);
7013 #endif
7014 	msg(NameBuff);
7015     }
7016     else
7017 	EMSG(_("E187: Unknown"));
7018 }
7019 
7020 /*
7021  * ":=".
7022  */
7023     static void
7024 ex_equal(eap)
7025     exarg_T	*eap;
7026 {
7027     smsg((char_u *)"%ld", (long)eap->line2);
7028 }
7029 
7030     static void
7031 ex_sleep(eap)
7032     exarg_T	*eap;
7033 {
7034     int	    n;
7035 
7036     if (cursor_valid())
7037     {
7038 	n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
7039 	if (n >= 0)
7040 	    windgoto((int)n, curwin->w_wcol);
7041     }
7042     do_sleep(eap->line2 * (*eap->arg == 'm' ? 1L : 1000L));
7043 }
7044 
7045 /*
7046  * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
7047  */
7048     void
7049 do_sleep(msec)
7050     long	msec;
7051 {
7052     long	done;
7053 
7054     cursor_on();
7055     out_flush();
7056     for (done = 0; !got_int && done < msec; done += 1000L)
7057     {
7058 	ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
7059 	ui_breakcheck();
7060     }
7061 }
7062 
7063     static void
7064 do_exmap(eap, isabbrev)
7065     exarg_T	*eap;
7066     int		isabbrev;
7067 {
7068     int	    mode;
7069     char_u  *cmdp;
7070 
7071     cmdp = eap->cmd;
7072     mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
7073 
7074     switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
7075 						    eap->arg, mode, isabbrev))
7076     {
7077 	case 1: EMSG(_(e_invarg));
7078 		break;
7079 	case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
7080 		break;
7081     }
7082 }
7083 
7084 /*
7085  * ":winsize" command (obsolete).
7086  */
7087     static void
7088 ex_winsize(eap)
7089     exarg_T	*eap;
7090 {
7091     int		w, h;
7092     char_u	*arg = eap->arg;
7093     char_u	*p;
7094 
7095     w = getdigits(&arg);
7096     arg = skipwhite(arg);
7097     p = arg;
7098     h = getdigits(&arg);
7099     if (*p != NUL && *arg == NUL)
7100 	set_shellsize(w, h, TRUE);
7101     else
7102 	EMSG(_("E465: :winsize requires two number arguments"));
7103 }
7104 
7105 #ifdef FEAT_WINDOWS
7106     static void
7107 ex_wincmd(eap)
7108     exarg_T	*eap;
7109 {
7110     int		xchar = NUL;
7111     char_u	*p;
7112 
7113     if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
7114     {
7115 	/* CTRL-W g and CTRL-W CTRL-G  have an extra command character */
7116 	if (eap->arg[1] == NUL)
7117 	{
7118 	    EMSG(_(e_invarg));
7119 	    return;
7120 	}
7121 	xchar = eap->arg[1];
7122 	p = eap->arg + 2;
7123     }
7124     else
7125 	p = eap->arg + 1;
7126 
7127     eap->nextcmd = check_nextcmd(p);
7128     p = skipwhite(p);
7129     if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
7130 	EMSG(_(e_invarg));
7131     else
7132     {
7133 	/* Pass flags on for ":vertical wincmd ]". */
7134 	postponed_split_flags = cmdmod.split;
7135 	do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
7136 	postponed_split_flags = 0;
7137     }
7138 }
7139 #endif
7140 
7141 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
7142 /*
7143  * ":winpos".
7144  */
7145     static void
7146 ex_winpos(eap)
7147     exarg_T	*eap;
7148 {
7149     int		x, y;
7150     char_u	*arg = eap->arg;
7151     char_u	*p;
7152 
7153     if (*arg == NUL)
7154     {
7155 # if defined(FEAT_GUI) || defined(MSWIN)
7156 #  ifdef FEAT_GUI
7157 	if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
7158 #  else
7159 	if (mch_get_winpos(&x, &y) != FAIL)
7160 #  endif
7161 	{
7162 	    sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
7163 	    msg(IObuff);
7164 	}
7165 	else
7166 # endif
7167 	    EMSG(_("E188: Obtaining window position not implemented for this platform"));
7168     }
7169     else
7170     {
7171 	x = getdigits(&arg);
7172 	arg = skipwhite(arg);
7173 	p = arg;
7174 	y = getdigits(&arg);
7175 	if (*p == NUL || *arg != NUL)
7176 	{
7177 	    EMSG(_("E466: :winpos requires two number arguments"));
7178 	    return;
7179 	}
7180 # ifdef FEAT_GUI
7181 	if (gui.in_use)
7182 	    gui_mch_set_winpos(x, y);
7183 	else if (gui.starting)
7184 	{
7185 	    /* Remember the coordinates for when the window is opened. */
7186 	    gui_win_x = x;
7187 	    gui_win_y = y;
7188 	}
7189 #  ifdef HAVE_TGETENT
7190 	else
7191 #  endif
7192 # else
7193 #  ifdef MSWIN
7194 	    mch_set_winpos(x, y);
7195 #  endif
7196 # endif
7197 # ifdef HAVE_TGETENT
7198 	if (*T_CWP)
7199 	    term_set_winpos(x, y);
7200 # endif
7201     }
7202 }
7203 #endif
7204 
7205 /*
7206  * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
7207  */
7208     static void
7209 ex_operators(eap)
7210     exarg_T	*eap;
7211 {
7212     oparg_T	oa;
7213 
7214     clear_oparg(&oa);
7215     oa.regname = eap->regname;
7216     oa.start.lnum = eap->line1;
7217     oa.end.lnum = eap->line2;
7218     oa.line_count = eap->line2 - eap->line1 + 1;
7219     oa.motion_type = MLINE;
7220 #ifdef FEAT_VIRTUALEDIT
7221     virtual_op = FALSE;
7222 #endif
7223     if (eap->cmdidx != CMD_yank)	/* position cursor for undo */
7224     {
7225 	setpcmark();
7226 	curwin->w_cursor.lnum = eap->line1;
7227 	beginline(BL_SOL | BL_FIX);
7228     }
7229 
7230     switch (eap->cmdidx)
7231     {
7232 	case CMD_delete:
7233 	    oa.op_type = OP_DELETE;
7234 	    op_delete(&oa);
7235 	    break;
7236 
7237 	case CMD_yank:
7238 	    oa.op_type = OP_YANK;
7239 	    (void)op_yank(&oa, FALSE, TRUE);
7240 	    break;
7241 
7242 	default:    /* CMD_rshift or CMD_lshift */
7243 	    if ((eap->cmdidx == CMD_rshift)
7244 #ifdef FEAT_RIGHTLEFT
7245 				    ^ curwin->w_p_rl
7246 #endif
7247 						    )
7248 		oa.op_type = OP_RSHIFT;
7249 	    else
7250 		oa.op_type = OP_LSHIFT;
7251 	    op_shift(&oa, FALSE, eap->amount);
7252 	    break;
7253     }
7254 #ifdef FEAT_VIRTUALEDIT
7255     virtual_op = MAYBE;
7256 #endif
7257 }
7258 
7259 /*
7260  * ":put".
7261  */
7262     static void
7263 ex_put(eap)
7264     exarg_T	*eap;
7265 {
7266     /* ":0put" works like ":1put!". */
7267     if (eap->line2 == 0)
7268     {
7269 	eap->line2 = 1;
7270 	eap->forceit = TRUE;
7271     }
7272     curwin->w_cursor.lnum = eap->line2;
7273     do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L, PUT_LINE);
7274 }
7275 
7276 /*
7277  * Handle ":copy" and ":move".
7278  */
7279     static void
7280 ex_copymove(eap)
7281     exarg_T	*eap;
7282 {
7283     long	n;
7284 
7285     n = get_address(&eap->arg, FALSE, FALSE);
7286     if (eap->arg == NULL)	    /* error detected */
7287     {
7288 	eap->nextcmd = NULL;
7289 	return;
7290     }
7291 
7292     /*
7293      * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
7294      */
7295     if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
7296     {
7297 	EMSG(_(e_invaddr));
7298 	return;
7299     }
7300 
7301     if (eap->cmdidx == CMD_move)
7302     {
7303 	if (do_move(eap->line1, eap->line2, n) == FAIL)
7304 	    return;
7305     }
7306     else
7307 	ex_copy(eap->line1, eap->line2, n);
7308     u_clearline();
7309     beginline(BL_SOL | BL_FIX);
7310 }
7311 
7312 /*
7313  * ":smagic" and ":snomagic".
7314  */
7315     static void
7316 ex_submagic(eap)
7317     exarg_T	*eap;
7318 {
7319     int		magic_save = p_magic;
7320 
7321     p_magic = (eap->cmdidx == CMD_smagic);
7322     do_sub(eap);
7323     p_magic = magic_save;
7324 }
7325 
7326 /*
7327  * ":join".
7328  */
7329     static void
7330 ex_join(eap)
7331     exarg_T	*eap;
7332 {
7333     curwin->w_cursor.lnum = eap->line1;
7334     if (eap->line1 == eap->line2)
7335     {
7336 	if (eap->addr_count >= 2)   /* :2,2join does nothing */
7337 	    return;
7338 	if (eap->line2 == curbuf->b_ml.ml_line_count)
7339 	{
7340 	    beep_flush();
7341 	    return;
7342 	}
7343 	++eap->line2;
7344     }
7345     do_do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
7346     beginline(BL_WHITE | BL_FIX);
7347 }
7348 
7349 /*
7350  * ":[addr]@r" or ":[addr]*r": execute register
7351  */
7352     static void
7353 ex_at(eap)
7354     exarg_T	*eap;
7355 {
7356     int		c;
7357 
7358     curwin->w_cursor.lnum = eap->line2;
7359 
7360 #ifdef USE_ON_FLY_SCROLL
7361     dont_scroll = TRUE;		/* disallow scrolling here */
7362 #endif
7363 
7364     /* get the register name.  No name means to use the previous one */
7365     c = *eap->arg;
7366     if (c == NUL || (c == '*' && *eap->cmd == '*'))
7367 	c = '@';
7368     /* put the register in mapbuf */
7369     if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL) == FAIL)
7370 	beep_flush();
7371     else
7372     {
7373 	int	save_efr = exec_from_reg;
7374 
7375 	exec_from_reg = TRUE;
7376 
7377 	/*
7378 	 * Execute from the typeahead buffer.
7379 	 * Originally this didn't check for the typeahead buffer to be empty,
7380 	 * thus could read more Ex commands from stdin.  It's not clear why,
7381 	 * it is certainly unexpected.
7382 	 */
7383 	while ((!stuff_empty() || typebuf.tb_len > 0) && vpeekc() == ':')
7384 	    (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
7385 
7386 	exec_from_reg = save_efr;
7387     }
7388 }
7389 
7390 /*
7391  * ":!".
7392  */
7393     static void
7394 ex_bang(eap)
7395     exarg_T	*eap;
7396 {
7397     do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
7398 }
7399 
7400 /*
7401  * ":undo".
7402  */
7403 /*ARGSUSED*/
7404     static void
7405 ex_undo(eap)
7406     exarg_T	*eap;
7407 {
7408     u_undo(1);
7409 }
7410 
7411 /*
7412  * ":redo".
7413  */
7414 /*ARGSUSED*/
7415     static void
7416 ex_redo(eap)
7417     exarg_T	*eap;
7418 {
7419     u_redo(1);
7420 }
7421 
7422 /*
7423  * ":redir": start/stop redirection.
7424  */
7425     static void
7426 ex_redir(eap)
7427     exarg_T	*eap;
7428 {
7429     char	*mode;
7430     char_u	*fname;
7431 
7432     if (STRICMP(eap->arg, "END") == 0)
7433 	close_redir();
7434     else
7435     {
7436 	if (*eap->arg == '>')
7437 	{
7438 	    ++eap->arg;
7439 	    if (*eap->arg == '>')
7440 	    {
7441 		++eap->arg;
7442 		mode = "a";
7443 	    }
7444 	    else
7445 		mode = "w";
7446 	    eap->arg = skipwhite(eap->arg);
7447 
7448 	    close_redir();
7449 
7450 	    /* Expand environment variables and "~/". */
7451 	    fname = expand_env_save(eap->arg);
7452 	    if (fname == NULL)
7453 		return;
7454 #ifdef FEAT_BROWSE
7455 	    if (cmdmod.browse)
7456 	    {
7457 		char_u	*browseFile;
7458 
7459 		browseFile = do_browse(TRUE, (char_u *)_("Save Redirection"),
7460 		       fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
7461 		if (browseFile == NULL)
7462 		    return;		/* operation cancelled */
7463 		vim_free(fname);
7464 		fname = browseFile;
7465 		eap->forceit = TRUE;	/* since dialog already asked */
7466 	    }
7467 #endif
7468 
7469 	    redir_fd = open_exfile(fname, eap->forceit, mode);
7470 	    vim_free(fname);
7471 	}
7472 #ifdef FEAT_EVAL
7473 	else if (*eap->arg == '@')
7474 	{
7475 	    /* redirect to a register a-z (resp. A-Z for appending) */
7476 	    close_redir();
7477 	    ++eap->arg;
7478 	    if (ASCII_ISALPHA(*eap->arg)
7479 # ifdef FEAT_CLIPBOARD
7480 		    || *eap->arg == '*'
7481 # endif
7482 		    || *eap->arg == '"')
7483 	    {
7484 		redir_reg = *eap->arg;
7485 		if (islower(redir_reg)
7486 # ifdef FEAT_CLIPBOARD
7487 			|| redir_reg == '*'
7488 # endif
7489 			|| redir_reg == '"')
7490 		{
7491 		    /* make register empty */
7492 		    write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
7493 		}
7494 	    }
7495 	    else
7496 		EMSG(_(e_invarg));
7497 	}
7498 #endif
7499 
7500 	/* TODO: redirect to a buffer */
7501 
7502 	/* TODO: redirect to an internal variable */
7503 
7504 	else
7505 	    EMSG(_(e_invarg));
7506     }
7507 }
7508 
7509 /*
7510  * ":redraw": force redraw
7511  */
7512     static void
7513 ex_redraw(eap)
7514     exarg_T	*eap;
7515 {
7516     int		r = RedrawingDisabled;
7517     int		p = p_lz;
7518 
7519     RedrawingDisabled = 0;
7520     p_lz = FALSE;
7521     update_topline();
7522     update_screen(eap->forceit ? CLEAR :
7523 #ifdef FEAT_VISUAL
7524 	    VIsual_active ? INVERTED :
7525 #endif
7526 	    0);
7527 #ifdef FEAT_TITLE
7528     if (need_maketitle)
7529 	maketitle();
7530 #endif
7531     RedrawingDisabled = r;
7532     p_lz = p;
7533 
7534     /* Reset msg_didout, so that a message that's there is overwritten. */
7535     msg_didout = FALSE;
7536     msg_col = 0;
7537 
7538     out_flush();
7539 }
7540 
7541 /*
7542  * ":redrawstatus": force redraw of status line(s)
7543  */
7544 /*ARGSUSED*/
7545     static void
7546 ex_redrawstatus(eap)
7547     exarg_T	*eap;
7548 {
7549 #if defined(FEAT_WINDOWS)
7550     int		r = RedrawingDisabled;
7551     int		p = p_lz;
7552 
7553     RedrawingDisabled = 0;
7554     p_lz = FALSE;
7555     if (eap->forceit)
7556 	status_redraw_all();
7557     else
7558 	status_redraw_curbuf();
7559     update_screen(
7560 # ifdef FEAT_VISUAL
7561 	    VIsual_active ? INVERTED :
7562 # endif
7563 	    0);
7564     RedrawingDisabled = r;
7565     p_lz = p;
7566     out_flush();
7567 #endif
7568 }
7569 
7570     static void
7571 close_redir()
7572 {
7573     if (redir_fd != NULL)
7574     {
7575 	fclose(redir_fd);
7576 	redir_fd = NULL;
7577     }
7578 #ifdef FEAT_EVAL
7579     redir_reg = 0;
7580 #endif
7581 }
7582 
7583 #if defined(FEAT_SESSION) && defined(USE_CRNL)
7584 # define MKSESSION_NL
7585 static int mksession_nl = FALSE;    /* use NL only in put_eol() */
7586 #endif
7587 
7588 /*
7589  * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
7590  */
7591     static void
7592 ex_mkrc(eap)
7593     exarg_T	*eap;
7594 {
7595     FILE	*fd;
7596     int		failed = FALSE;
7597     char_u	*fname;
7598 #ifdef FEAT_BROWSE
7599     char_u	*browseFile = NULL;
7600 #endif
7601 #ifdef FEAT_SESSION
7602     int		view_session = FALSE;
7603     int		using_vdir = FALSE;	/* using 'viewdir'? */
7604     char_u	*viewFile = NULL;
7605     unsigned	*flagp;
7606 #endif
7607 
7608     if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
7609     {
7610 #ifdef FEAT_SESSION
7611 	view_session = TRUE;
7612 #else
7613 	ex_ni(eap);
7614 	return;
7615 #endif
7616     }
7617 
7618 #ifdef FEAT_SESSION
7619     /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
7620     if (eap->cmdidx == CMD_mkview
7621 	    && (*eap->arg == NUL
7622 		|| (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
7623     {
7624 	eap->forceit = TRUE;
7625 	fname = get_view_file(*eap->arg);
7626 	if (fname == NULL)
7627 	    return;
7628 	viewFile = fname;
7629 	using_vdir = TRUE;
7630     }
7631     else
7632 #endif
7633 	if (*eap->arg != NUL)
7634 	fname = eap->arg;
7635     else if (eap->cmdidx == CMD_mkvimrc)
7636 	fname = (char_u *)VIMRC_FILE;
7637 #ifdef FEAT_SESSION
7638     else if (eap->cmdidx == CMD_mksession)
7639 	fname = (char_u *)SESSION_FILE;
7640 #endif
7641     else
7642 	fname = (char_u *)EXRC_FILE;
7643 
7644 #ifdef FEAT_BROWSE
7645     if (cmdmod.browse)
7646     {
7647 	browseFile = do_browse(TRUE,
7648 # ifdef FEAT_SESSION
7649 		eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
7650 		eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
7651 # endif
7652 		(char_u *)_("Save Setup"),
7653 		fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
7654 	if (browseFile == NULL)
7655 	    goto theend;
7656 	fname = browseFile;
7657 	eap->forceit = TRUE;	/* since dialog already asked */
7658     }
7659 #endif
7660 
7661 #if defined(FEAT_SESSION) && defined(vim_mkdir)
7662     /* When using 'viewdir' may have to create the directory. */
7663     if (using_vdir && !mch_isdir(p_vdir))
7664 	vim_mkdir(p_vdir, 0755); /* ignore errors, open_exfile() will fail */
7665 #endif
7666 
7667     fd = open_exfile(fname, eap->forceit, WRITEBIN);
7668     if (fd != NULL)
7669     {
7670 #ifdef FEAT_SESSION
7671 	if (eap->cmdidx == CMD_mkview)
7672 	    flagp = &vop_flags;
7673 	else
7674 	    flagp = &ssop_flags;
7675 #endif
7676 
7677 #ifdef MKSESSION_NL
7678 	/* "unix" in 'sessionoptions': use NL line separator */
7679 	if (view_session && (*flagp & SSOP_UNIX))
7680 	    mksession_nl = TRUE;
7681 #endif
7682 
7683 	/* Write the version command for :mkvimrc */
7684 	if (eap->cmdidx == CMD_mkvimrc)
7685 	    (void)put_line(fd, "version 6.0");
7686 
7687 #ifdef FEAT_SESSION
7688 	if (eap->cmdidx != CMD_mkview)
7689 #endif
7690 	{
7691 	    /* Write setting 'compatible' first, because it has side effects.
7692 	     * For that same reason only do it when needed. */
7693 	    if (p_cp)
7694 		(void)put_line(fd, "if !&cp | set cp | endif");
7695 	    else
7696 		(void)put_line(fd, "if &cp | set nocp | endif");
7697 	}
7698 
7699 #ifdef FEAT_SESSION
7700 	if (!view_session
7701 		|| (eap->cmdidx == CMD_mksession
7702 		    && (*flagp & SSOP_OPTIONS)))
7703 #endif
7704 	    failed |= (makemap(fd, NULL) == FAIL
7705 				   || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
7706 
7707 #ifdef FEAT_SESSION
7708 	if (!failed && view_session)
7709 	{
7710 	    if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
7711 		failed = TRUE;
7712 	    if (eap->cmdidx == CMD_mksession)
7713 	    {
7714 		char_u dirnow[MAXPATHL];	/* current directory */
7715 
7716 		/*
7717 		 * Change to session file's dir.
7718 		 */
7719 		if (mch_dirname(dirnow, MAXPATHL) == FAIL
7720 					    || mch_chdir((char *)dirnow) != 0)
7721 		    *dirnow = NUL;
7722 		if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
7723 		{
7724 		    if (vim_chdirfile(fname) == OK)
7725 			shorten_fnames(TRUE);
7726 		}
7727 		else if (*dirnow != NUL
7728 			&& (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
7729 		{
7730 		    (void)mch_chdir((char *)globaldir);
7731 		    shorten_fnames(TRUE);
7732 		}
7733 
7734 		failed |= (makeopens(fd, dirnow) == FAIL);
7735 
7736 		/* restore original dir */
7737 		if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
7738 			|| ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
7739 		{
7740 		    if (mch_chdir((char *)dirnow) != 0)
7741 			EMSG(_(e_prev_dir));
7742 		    shorten_fnames(TRUE);
7743 		}
7744 	    }
7745 	    else
7746 	    {
7747 		failed |= (put_view(fd, curwin, !using_vdir, flagp) == FAIL);
7748 	    }
7749 	    if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
7750 								      == FAIL)
7751 		failed = TRUE;
7752 	}
7753 #endif
7754 	failed |= fclose(fd);
7755 
7756 	if (failed)
7757 	    EMSG(_(e_write));
7758 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
7759 	else if (eap->cmdidx == CMD_mksession)
7760 	{
7761 	    /* successful session write - set this_session var */
7762 	    char_u	tbuf[MAXPATHL];
7763 
7764 	    if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
7765 		set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
7766 	}
7767 #endif
7768 #ifdef MKSESSION_NL
7769 	mksession_nl = FALSE;
7770 #endif
7771     }
7772 
7773 #ifdef FEAT_BROWSE
7774 theend:
7775     vim_free(browseFile);
7776 #endif
7777 #ifdef FEAT_SESSION
7778     vim_free(viewFile);
7779 #endif
7780 }
7781 
7782 /*
7783  * Open a file for writing for an Ex command, with some checks.
7784  * Return file descriptor, or NULL on failure.
7785  */
7786     FILE *
7787 open_exfile(fname, forceit, mode)
7788     char_u	*fname;
7789     int		forceit;
7790     char	*mode;	    /* "w" for create new file or "a" for append */
7791 {
7792     FILE	*fd;
7793 
7794 #ifdef UNIX
7795     /* with Unix it is possible to open a directory */
7796     if (mch_isdir(fname))
7797     {
7798 	EMSG2(_(e_isadir2), fname);
7799 	return NULL;
7800     }
7801 #endif
7802     if (!forceit && *mode != 'a' && vim_fexists(fname))
7803     {
7804 	EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
7805 	return NULL;
7806     }
7807 
7808     if ((fd = mch_fopen((char *)fname, mode)) == NULL)
7809 	EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
7810 
7811     return fd;
7812 }
7813 
7814 /*
7815  * ":mark" and ":k".
7816  */
7817     static void
7818 ex_mark(eap)
7819     exarg_T	*eap;
7820 {
7821     pos_T	pos;
7822 
7823     if (*eap->arg == NUL)		/* No argument? */
7824 	EMSG(_(e_argreq));
7825     else if (eap->arg[1] != NUL)	/* more than one character? */
7826 	EMSG(_(e_trailing));
7827     else
7828     {
7829 	pos = curwin->w_cursor;		/* save curwin->w_cursor */
7830 	curwin->w_cursor.lnum = eap->line2;
7831 	beginline(BL_WHITE | BL_FIX);
7832 	if (setmark(*eap->arg) == FAIL)	/* set mark */
7833 	    EMSG(_("E191: Argument must be a letter or forward/backward quote"));
7834 	curwin->w_cursor = pos;		/* restore curwin->w_cursor */
7835     }
7836 }
7837 
7838 /*
7839  * Update w_topline, w_leftcol and the cursor position.
7840  */
7841     void
7842 update_topline_cursor()
7843 {
7844     check_cursor();		/* put cursor on valid line */
7845     update_topline();
7846     if (!curwin->w_p_wrap)
7847 	validate_cursor();
7848     update_curswant();
7849 }
7850 
7851 #ifdef FEAT_EX_EXTRA
7852 /*
7853  * ":normal[!] {commands}": Execute normal mode commands.
7854  */
7855     static void
7856 ex_normal(eap)
7857     exarg_T	*eap;
7858 {
7859     oparg_T	oa;
7860     int		save_msg_scroll = msg_scroll;
7861     int		save_restart_edit = restart_edit;
7862     int		save_msg_didout = msg_didout;
7863     int		save_State = State;
7864     tasave_T	tabuf;
7865     int		save_insertmode = p_im;
7866     int		save_finish_op = finish_op;
7867 #ifdef FEAT_MBYTE
7868     char_u	*arg = NULL;
7869     int		l;
7870     char_u	*p;
7871 #endif
7872 
7873     if (ex_normal_busy >= p_mmd)
7874     {
7875 	EMSG(_("E192: Recursive use of :normal too deep"));
7876 	return;
7877     }
7878     ++ex_normal_busy;
7879 
7880     msg_scroll = FALSE;	    /* no msg scrolling in Normal mode */
7881     restart_edit = 0;	    /* don't go to Insert mode */
7882     p_im = FALSE;	    /* don't use 'insertmode' */
7883 
7884 #ifdef FEAT_MBYTE
7885     /*
7886      * vgetc() expects a CSI and K_SPECIAL to have been escaped.  Don't do
7887      * this for the K_SPECIAL leading byte, otherwise special keys will not
7888      * work.
7889      */
7890     if (has_mbyte)
7891     {
7892 	int	len = 0;
7893 
7894 	/* Count the number of characters to be escaped. */
7895 	for (p = eap->arg; *p != NUL; ++p)
7896 	{
7897 # ifdef FEAT_GUI
7898 	    if (*p == CSI)  /* leadbyte CSI */
7899 		len += 2;
7900 # endif
7901 	    for (l = (*mb_ptr2len_check)(p) - 1; l > 0; --l)
7902 		if (*++p == K_SPECIAL	  /* trailbyte K_SPECIAL or CSI */
7903 # ifdef FEAT_GUI
7904 			|| *p == CSI
7905 # endif
7906 			)
7907 		    len += 2;
7908 	}
7909 	if (len > 0)
7910 	{
7911 	    arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
7912 	    if (arg != NULL)
7913 	    {
7914 		len = 0;
7915 		for (p = eap->arg; *p != NUL; ++p)
7916 		{
7917 		    arg[len++] = *p;
7918 # ifdef FEAT_GUI
7919 		    if (*p == CSI)
7920 		    {
7921 			arg[len++] = KS_EXTRA;
7922 			arg[len++] = (int)KE_CSI;
7923 		    }
7924 # endif
7925 		    for (l = (*mb_ptr2len_check)(p) - 1; l > 0; --l)
7926 		    {
7927 			arg[len++] = *++p;
7928 			if (*p == K_SPECIAL)
7929 			{
7930 			    arg[len++] = KS_SPECIAL;
7931 			    arg[len++] = KE_FILLER;
7932 			}
7933 # ifdef FEAT_GUI
7934 			else if (*p == CSI)
7935 			{
7936 			    arg[len++] = KS_EXTRA;
7937 			    arg[len++] = (int)KE_CSI;
7938 			}
7939 # endif
7940 		    }
7941 		    arg[len] = NUL;
7942 		}
7943 	    }
7944 	}
7945     }
7946 #endif
7947 
7948     /*
7949      * Save the current typeahead.  This is required to allow using ":normal"
7950      * from an event handler and makes sure we don't hang when the argument
7951      * ends with half a command.
7952      */
7953     save_typeahead(&tabuf);
7954     if (tabuf.typebuf_valid)
7955     {
7956 	/*
7957 	 * Repeat the :normal command for each line in the range.  When no
7958 	 * range given, execute it just once, without positioning the cursor
7959 	 * first.
7960 	 */
7961 	do
7962 	{
7963 	    clear_oparg(&oa);
7964 	    finish_op = FALSE;
7965 	    if (eap->addr_count != 0)
7966 	    {
7967 		curwin->w_cursor.lnum = eap->line1++;
7968 		curwin->w_cursor.col = 0;
7969 	    }
7970 
7971 	    /*
7972 	     * Stuff the argument into the typeahead buffer.
7973 	     * Execute normal_cmd() until there is no typeahead left.
7974 	     */
7975 	    ins_typebuf(
7976 #ifdef FEAT_MBYTE
7977 		    arg != NULL ? arg :
7978 #endif
7979 		    eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, 0,
7980 								 TRUE, FALSE);
7981 	    while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
7982 		    && !got_int)
7983 	    {
7984 		update_topline_cursor();
7985 		normal_cmd(&oa, FALSE);	/* execute a Normal mode cmd */
7986 	    }
7987 	}
7988 	while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
7989     }
7990 
7991     /* Might not return to the main loop when in an event handler. */
7992     update_topline_cursor();
7993 
7994     /* Restore the previous typeahead. */
7995     restore_typeahead(&tabuf);
7996 
7997     --ex_normal_busy;
7998     msg_scroll = save_msg_scroll;
7999     restart_edit = save_restart_edit;
8000     p_im = save_insertmode;
8001     finish_op = save_finish_op;
8002     msg_didout |= save_msg_didout;	/* don't reset msg_didout now */
8003 
8004     /* Restore the state (needed when called from a function executed for
8005      * 'indentexpr'). */
8006     State = save_State;
8007 #ifdef FEAT_MBYTE
8008     vim_free(arg);
8009 #endif
8010 }
8011 
8012 /*
8013  * ":startinsert" and ":startreplace"
8014  */
8015     static void
8016 ex_startinsert(eap)
8017     exarg_T	*eap;
8018 {
8019     if (eap->forceit)
8020     {
8021 	coladvance((colnr_T)MAXCOL);
8022 	curwin->w_curswant = MAXCOL;
8023 	curwin->w_set_curswant = FALSE;
8024 	if (eap->cmdidx == CMD_startinsert)
8025 	    restart_edit = 'a';
8026 	else
8027 	    restart_edit = 'R';
8028     }
8029     else
8030     {
8031 	if (eap->cmdidx == CMD_startinsert)
8032 	    restart_edit = 'i';
8033 	else
8034 	    restart_edit = 'R';
8035 	curwin->w_curswant = 0;	    /* avoid MAXCOL */
8036     }
8037 }
8038 
8039 /*
8040  * ":stopinsert"
8041  */
8042 /*ARGSUSED*/
8043     static void
8044 ex_stopinsert(eap)
8045     exarg_T	*eap;
8046 {
8047     restart_edit = 0;
8048     stop_insert_mode = TRUE;
8049 }
8050 #endif
8051 
8052 #ifdef FEAT_FIND_ID
8053     static void
8054 ex_checkpath(eap)
8055     exarg_T	*eap;
8056 {
8057     find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
8058 				   eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
8059 					      (linenr_T)1, (linenr_T)MAXLNUM);
8060 }
8061 
8062 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
8063 /*
8064  * ":psearch"
8065  */
8066     static void
8067 ex_psearch(eap)
8068     exarg_T	*eap;
8069 {
8070     g_do_tagpreview = p_pvh;
8071     ex_findpat(eap);
8072     g_do_tagpreview = 0;
8073 }
8074 #endif
8075 
8076     static void
8077 ex_findpat(eap)
8078     exarg_T	*eap;
8079 {
8080     int		whole = TRUE;
8081     long	n;
8082     char_u	*p;
8083     int		action;
8084 
8085     switch (cmdnames[eap->cmdidx].cmd_name[2])
8086     {
8087 	case 'e':	/* ":psearch", ":isearch" and ":dsearch" */
8088 		if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
8089 		    action = ACTION_GOTO;
8090 		else
8091 		    action = ACTION_SHOW;
8092 		break;
8093 	case 'i':	/* ":ilist" and ":dlist" */
8094 		action = ACTION_SHOW_ALL;
8095 		break;
8096 	case 'u':	/* ":ijump" and ":djump" */
8097 		action = ACTION_GOTO;
8098 		break;
8099 	default:	/* ":isplit" and ":dsplit" */
8100 		action = ACTION_SPLIT;
8101 		break;
8102     }
8103 
8104     n = 1;
8105     if (vim_isdigit(*eap->arg))	/* get count */
8106     {
8107 	n = getdigits(&eap->arg);
8108 	eap->arg = skipwhite(eap->arg);
8109     }
8110     if (*eap->arg == '/')   /* Match regexp, not just whole words */
8111     {
8112 	whole = FALSE;
8113 	++eap->arg;
8114 	p = skip_regexp(eap->arg, '/', p_magic, NULL);
8115 	if (*p)
8116 	{
8117 	    *p++ = NUL;
8118 	    p = skipwhite(p);
8119 
8120 	    /* Check for trailing illegal characters */
8121 	    if (!ends_excmd(*p))
8122 		eap->errmsg = e_trailing;
8123 	    else
8124 		eap->nextcmd = check_nextcmd(p);
8125 	}
8126     }
8127     if (!eap->skip)
8128 	find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
8129 			    whole, !eap->forceit,
8130 			    *eap->cmd == 'd' ?	FIND_DEFINE : FIND_ANY,
8131 			    n, action, eap->line1, eap->line2);
8132 }
8133 #endif
8134 
8135 #ifdef FEAT_WINDOWS
8136 
8137 # ifdef FEAT_QUICKFIX
8138 /*
8139  * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
8140  */
8141     static void
8142 ex_ptag(eap)
8143     exarg_T	*eap;
8144 {
8145     g_do_tagpreview = p_pvh;
8146     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
8147 }
8148 
8149 /*
8150  * ":pedit"
8151  */
8152     static void
8153 ex_pedit(eap)
8154     exarg_T	*eap;
8155 {
8156     win_T	*curwin_save = curwin;
8157 
8158     g_do_tagpreview = p_pvh;
8159     prepare_tagpreview();
8160     keep_help_flag = curwin_save->w_buffer->b_help;
8161     do_exedit(eap, NULL);
8162     keep_help_flag = FALSE;
8163     if (curwin != curwin_save && win_valid(curwin_save))
8164     {
8165 	/* Return cursor to where we were */
8166 	validate_cursor();
8167 	redraw_later(VALID);
8168 	win_enter(curwin_save, TRUE);
8169     }
8170     g_do_tagpreview = 0;
8171 }
8172 # endif
8173 
8174 /*
8175  * ":stag", ":stselect" and ":stjump".
8176  */
8177     static void
8178 ex_stag(eap)
8179     exarg_T	*eap;
8180 {
8181     postponed_split = -1;
8182     postponed_split_flags = cmdmod.split;
8183     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
8184     postponed_split_flags = 0;
8185 }
8186 #endif
8187 
8188 /*
8189  * ":tag", ":tselect", ":tjump", ":tnext", etc.
8190  */
8191     static void
8192 ex_tag(eap)
8193     exarg_T	*eap;
8194 {
8195     ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
8196 }
8197 
8198     static void
8199 ex_tag_cmd(eap, name)
8200     exarg_T	*eap;
8201     char_u	*name;
8202 {
8203     int		cmd;
8204 
8205     switch (name[1])
8206     {
8207 	case 'j': cmd = DT_JUMP;	/* ":tjump" */
8208 		  break;
8209 	case 's': cmd = DT_SELECT;	/* ":tselect" */
8210 		  break;
8211 	case 'p': cmd = DT_PREV;	/* ":tprevious" */
8212 		  break;
8213 	case 'N': cmd = DT_PREV;	/* ":tNext" */
8214 		  break;
8215 	case 'n': cmd = DT_NEXT;	/* ":tnext" */
8216 		  break;
8217 	case 'o': cmd = DT_POP;		/* ":pop" */
8218 		  break;
8219 	case 'f':			/* ":tfirst" */
8220 	case 'r': cmd = DT_FIRST;	/* ":trewind" */
8221 		  break;
8222 	case 'l': cmd = DT_LAST;	/* ":tlast" */
8223 		  break;
8224 	default:			/* ":tag" */
8225 #ifdef FEAT_CSCOPE
8226 		  if (p_cst)
8227 		  {
8228 		      do_cstag(eap);
8229 		      return;
8230 		  }
8231 #endif
8232 		  cmd = DT_TAG;
8233 		  break;
8234     }
8235 
8236     do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
8237 							  eap->forceit, TRUE);
8238 }
8239 
8240 /*
8241  * Evaluate cmdline variables.
8242  *
8243  * change '%'	    to curbuf->b_ffname
8244  *	  '#'	    to curwin->w_altfile
8245  *	  '<cword>' to word under the cursor
8246  *	  '<cWORD>' to WORD under the cursor
8247  *	  '<cfile>' to path name under the cursor
8248  *	  '<sfile>' to sourced file name
8249  *	  '<afile>' to file name for autocommand
8250  *	  '<abuf>'  to buffer number for autocommand
8251  *	  '<amatch>' to matching name for autocommand
8252  *
8253  * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
8254  * "" for error without a message) and NULL is returned.
8255  * Returns an allocated string if a valid match was found.
8256  * Returns NULL if no match was found.	"usedlen" then still contains the
8257  * number of characters to skip.
8258  */
8259     char_u *
8260 eval_vars(src, usedlen, lnump, errormsg, srcstart)
8261     char_u	*src;		/* pointer into commandline */
8262     int		*usedlen;	/* characters after src that are used */
8263     linenr_T	*lnump;		/* line number for :e command, or NULL */
8264     char_u	**errormsg;	/* pointer to error message */
8265     char_u	*srcstart;	/* beginning of valid memory for src */
8266 {
8267     int		i;
8268     char_u	*s;
8269     char_u	*result;
8270     char_u	*resultbuf = NULL;
8271     int		resultlen;
8272     buf_T	*buf;
8273     int		valid = VALID_HEAD + VALID_PATH;    /* assume valid result */
8274     int		spec_idx;
8275 #ifdef FEAT_MODIFY_FNAME
8276     int		skip_mod = FALSE;
8277 #endif
8278     static char *(spec_str[]) =
8279 	{
8280 		    "%",
8281 #define SPEC_PERC   0
8282 		    "#",
8283 #define SPEC_HASH   1
8284 		    "<cword>",		/* cursor word */
8285 #define SPEC_CWORD  2
8286 		    "<cWORD>",		/* cursor WORD */
8287 #define SPEC_CCWORD 3
8288 		    "<cfile>",		/* cursor path name */
8289 #define SPEC_CFILE  4
8290 		    "<sfile>",		/* ":so" file name */
8291 #define SPEC_SFILE  5
8292 #ifdef FEAT_AUTOCMD
8293 		    "<afile>",		/* autocommand file name */
8294 # define SPEC_AFILE 6
8295 		    "<abuf>",		/* autocommand buffer number */
8296 # define SPEC_ABUF  7
8297 		    "<amatch>",		/* autocommand match name */
8298 # define SPEC_AMATCH 8
8299 #endif
8300 #ifdef FEAT_CLIENTSERVER
8301 		    "<client>"
8302 # define SPEC_CLIENT 9
8303 #endif
8304 		};
8305 #define SPEC_COUNT  (sizeof(spec_str) / sizeof(char *))
8306 
8307 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
8308     char_u	strbuf[30];
8309 #endif
8310 
8311     *errormsg = NULL;
8312 
8313     /*
8314      * Check if there is something to do.
8315      */
8316     for (spec_idx = 0; spec_idx < SPEC_COUNT; ++spec_idx)
8317     {
8318 	*usedlen = (int)STRLEN(spec_str[spec_idx]);
8319 	if (STRNCMP(src, spec_str[spec_idx], *usedlen) == 0)
8320 	    break;
8321     }
8322     if (spec_idx == SPEC_COUNT)	    /* no match */
8323     {
8324 	*usedlen = 1;
8325 	return NULL;
8326     }
8327 
8328     /*
8329      * Skip when preceded with a backslash "\%" and "\#".
8330      * Note: In "\\%" the % is also not recognized!
8331      */
8332     if (src > srcstart && src[-1] == '\\')
8333     {
8334 	*usedlen = 0;
8335 	STRCPY(src - 1, src);		/* remove backslash */
8336 	return NULL;
8337     }
8338 
8339     /*
8340      * word or WORD under cursor
8341      */
8342     if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
8343     {
8344 	resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
8345 				      (FIND_IDENT|FIND_STRING) : FIND_STRING);
8346 	if (resultlen == 0)
8347 	{
8348 	    *errormsg = (char_u *)"";
8349 	    return NULL;
8350 	}
8351     }
8352 
8353     /*
8354      * '#': Alternate file name
8355      * '%': Current file name
8356      *	    File name under the cursor
8357      *	    File name for autocommand
8358      *	and following modifiers
8359      */
8360     else
8361     {
8362 	switch (spec_idx)
8363 	{
8364 	case SPEC_PERC:		/* '%': current file */
8365 		if (curbuf->b_fname == NULL)
8366 		{
8367 		    result = (char_u *)"";
8368 		    valid = 0;	    /* Must have ":p:h" to be valid */
8369 		}
8370 		else
8371 #ifdef RISCOS
8372 		    /* Always use the full path for RISC OS if possible. */
8373 		    result = curbuf->b_ffname;
8374 		    if (result == NULL)
8375 			result = curbuf->b_fname;
8376 #else
8377 		    result = curbuf->b_fname;
8378 #endif
8379 		break;
8380 
8381 	case SPEC_HASH:		/* '#' or "#99": alternate file */
8382 		if (src[1] == '#')  /* "##": the argument list */
8383 		{
8384 		    result = arg_all();
8385 		    resultbuf = result;
8386 		    *usedlen = 2;
8387 #ifdef FEAT_MODIFY_FNAME
8388 		    skip_mod = TRUE;
8389 #endif
8390 		    break;
8391 		}
8392 		s = src + 1;
8393 		i = (int)getdigits(&s);
8394 		*usedlen = (int)(s - src); /* length of what we expand */
8395 
8396 		buf = buflist_findnr(i);
8397 		if (buf == NULL)
8398 		{
8399 		    *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
8400 		    return NULL;
8401 		}
8402 		if (lnump != NULL)
8403 		    *lnump = ECMD_LAST;
8404 		if (buf->b_fname == NULL)
8405 		{
8406 		    result = (char_u *)"";
8407 		    valid = 0;	    /* Must have ":p:h" to be valid */
8408 		}
8409 		else
8410 		    result = buf->b_fname;
8411 		break;
8412 
8413 #ifdef FEAT_SEARCHPATH
8414 	case SPEC_CFILE:	/* file name under cursor */
8415 		result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L);
8416 		if (result == NULL)
8417 		{
8418 		    *errormsg = (char_u *)"";
8419 		    return NULL;
8420 		}
8421 		resultbuf = result;	    /* remember allocated string */
8422 		break;
8423 #endif
8424 
8425 #ifdef FEAT_AUTOCMD
8426 	case SPEC_AFILE:	/* file name for autocommand */
8427 		result = autocmd_fname;
8428 		if (result == NULL)
8429 		{
8430 		    *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
8431 		    return NULL;
8432 		}
8433 		break;
8434 
8435 	case SPEC_ABUF:		/* buffer number for autocommand */
8436 		if (autocmd_bufnr <= 0)
8437 		{
8438 		    *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
8439 		    return NULL;
8440 		}
8441 		sprintf((char *)strbuf, "%d", autocmd_bufnr);
8442 		result = strbuf;
8443 		break;
8444 
8445 	case SPEC_AMATCH:	/* match name for autocommand */
8446 		result = autocmd_match;
8447 		if (result == NULL)
8448 		{
8449 		    *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
8450 		    return NULL;
8451 		}
8452 		break;
8453 
8454 #endif
8455 	case SPEC_SFILE:	/* file name for ":so" command */
8456 		result = sourcing_name;
8457 		if (result == NULL)
8458 		{
8459 		    *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
8460 		    return NULL;
8461 		}
8462 		break;
8463 #if defined(FEAT_CLIENTSERVER)
8464 	case SPEC_CLIENT:	/* Source of last submitted input */
8465 		sprintf((char *)strbuf, "0x%x", (unsigned int)clientWindow);
8466 		result = strbuf;
8467 		break;
8468 #endif
8469 	}
8470 
8471 	resultlen = (int)STRLEN(result);	/* length of new string */
8472 	if (src[*usedlen] == '<')	/* remove the file name extension */
8473 	{
8474 	    ++*usedlen;
8475 #ifdef RISCOS
8476 	    if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
8477 #else
8478 	    if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
8479 #endif
8480 		resultlen = (int)(s - result);
8481 	}
8482 #ifdef FEAT_MODIFY_FNAME
8483 	else if (!skip_mod)
8484 	{
8485 	    valid |= modify_fname(src, usedlen, &result, &resultbuf,
8486 								  &resultlen);
8487 	    if (result == NULL)
8488 	    {
8489 		*errormsg = (char_u *)"";
8490 		return NULL;
8491 	    }
8492 	}
8493 #endif
8494     }
8495 
8496     if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
8497     {
8498 	if (valid != VALID_HEAD + VALID_PATH)
8499 	    /* xgettext:no-c-format */
8500 	    *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
8501 	else
8502 	    *errormsg = (char_u *)_("E500: Evaluates to an empty string");
8503 	result = NULL;
8504     }
8505     else
8506 	result = vim_strnsave(result, resultlen);
8507     vim_free(resultbuf);
8508     return result;
8509 }
8510 
8511 /*
8512  * Concatenate all files in the argument list, separated by spaces, and return
8513  * it in one allocated string.
8514  * Spaces and backslashes in the file names are escaped with a backslash.
8515  * Returns NULL when out of memory.
8516  */
8517     static char_u *
8518 arg_all()
8519 {
8520     int		len;
8521     int		idx;
8522     char_u	*retval = NULL;
8523     char_u	*p;
8524 
8525     /*
8526      * Do this loop two times:
8527      * first time: compute the total length
8528      * second time: concatenate the names
8529      */
8530     for (;;)
8531     {
8532 	len = 0;
8533 	for (idx = 0; idx < ARGCOUNT; ++idx)
8534 	{
8535 	    p = alist_name(&ARGLIST[idx]);
8536 	    if (p != NULL)
8537 	    {
8538 		if (len > 0)
8539 		{
8540 		    /* insert a space in between names */
8541 		    if (retval != NULL)
8542 			retval[len] = ' ';
8543 		    ++len;
8544 		}
8545 		for ( ; *p != NUL; ++p)
8546 		{
8547 		    if (*p == ' ' || *p == '\\')
8548 		    {
8549 			/* insert a backslash */
8550 			if (retval != NULL)
8551 			    retval[len] = '\\';
8552 			++len;
8553 		    }
8554 		    if (retval != NULL)
8555 			retval[len] = *p;
8556 		    ++len;
8557 		}
8558 	    }
8559 	}
8560 
8561 	/* second time: break here */
8562 	if (retval != NULL)
8563 	{
8564 	    retval[len] = NUL;
8565 	    break;
8566 	}
8567 
8568 	/* allocate memory */
8569 	retval = alloc(len + 1);
8570 	if (retval == NULL)
8571 	    break;
8572     }
8573 
8574     return retval;
8575 }
8576 
8577 #if defined(FEAT_AUTOCMD) || defined(PROTO)
8578 /*
8579  * Expand the <sfile> string in "arg".
8580  *
8581  * Returns an allocated string, or NULL for any error.
8582  */
8583     char_u *
8584 expand_sfile(arg)
8585     char_u	*arg;
8586 {
8587     char_u	*errormsg;
8588     int		len;
8589     char_u	*result;
8590     char_u	*newres;
8591     char_u	*repl;
8592     int		srclen;
8593     char_u	*p;
8594 
8595     result = vim_strsave(arg);
8596     if (result == NULL)
8597 	return NULL;
8598 
8599     for (p = result; *p; )
8600     {
8601 	if (STRNCMP(p, "<sfile>", 7) != 0)
8602 	    ++p;
8603 	else
8604 	{
8605 	    /* replace "<sfile>" with the sourced file name, and do ":" stuff */
8606 	    repl = eval_vars(p, &srclen, NULL, &errormsg, result);
8607 	    if (errormsg != NULL)
8608 	    {
8609 		if (*errormsg)
8610 		    emsg(errormsg);
8611 		vim_free(result);
8612 		return NULL;
8613 	    }
8614 	    if (repl == NULL)		/* no match (cannot happen) */
8615 	    {
8616 		p += srclen;
8617 		continue;
8618 	    }
8619 	    len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
8620 	    newres = alloc(len);
8621 	    if (newres == NULL)
8622 	    {
8623 		vim_free(repl);
8624 		vim_free(result);
8625 		return NULL;
8626 	    }
8627 	    mch_memmove(newres, result, (size_t)(p - result));
8628 	    STRCPY(newres + (p - result), repl);
8629 	    len = (int)STRLEN(newres);
8630 	    STRCAT(newres, p + srclen);
8631 	    vim_free(repl);
8632 	    vim_free(result);
8633 	    result = newres;
8634 	    p = newres + len;		/* continue after the match */
8635 	}
8636     }
8637 
8638     return result;
8639 }
8640 #endif
8641 
8642 #ifdef FEAT_SESSION
8643 static int ses_winsizes __ARGS((FILE *fd, int restore_size));
8644 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
8645 static frame_T *ses_skipframe __ARGS((frame_T *fr));
8646 static int ses_do_frame __ARGS((frame_T *fr));
8647 static int ses_do_win __ARGS((win_T *wp));
8648 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
8649 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
8650 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
8651 
8652 /*
8653  * Write openfile commands for the current buffers to an .exrc file.
8654  * Return FAIL on error, OK otherwise.
8655  */
8656     static int
8657 makeopens(fd, dirnow)
8658     FILE	*fd;
8659     char_u	*dirnow;	/* Current directory name */
8660 {
8661     buf_T	*buf;
8662     int		only_save_windows = TRUE;
8663     int		nr;
8664     int		cnr = 1;
8665     int		restore_size = TRUE;
8666     win_T	*wp;
8667     char_u	*sname;
8668     win_T	*edited_win = NULL;
8669 
8670     if (ssop_flags & SSOP_BUFFERS)
8671 	only_save_windows = FALSE;		/* Save ALL buffers */
8672 
8673     /*
8674      * Begin by setting the this_session variable, and then other
8675      * sessionable variables.
8676      */
8677 #ifdef FEAT_EVAL
8678     if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
8679 	return FAIL;
8680     if (ssop_flags & SSOP_GLOBALS)
8681 	if (store_session_globals(fd) == FAIL)
8682 	    return FAIL;
8683 #endif
8684 
8685     /*
8686      * Close all windows but one.
8687      */
8688     if (put_line(fd, "silent only") == FAIL)
8689 	return FAIL;
8690 
8691     /*
8692      * Now a :cd command to the session directory or the current directory
8693      */
8694     if (ssop_flags & SSOP_SESDIR)
8695     {
8696 	if (put_line(fd, "exe \"cd \" . expand(\"<sfile>:p:h\")") == FAIL)
8697 	    return FAIL;
8698     }
8699     else if (ssop_flags & SSOP_CURDIR)
8700     {
8701 	sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
8702 	if (sname == NULL
8703 		|| fprintf(fd, "cd %s", sname) < 0 || put_eol(fd) == FAIL)
8704 	    return FAIL;
8705 	vim_free(sname);
8706     }
8707 
8708     /*
8709      * Now save the current files, current buffer first.
8710      */
8711     if (put_line(fd, "set shortmess=aoO") == FAIL)
8712 	return FAIL;
8713 
8714     /* Now put the other buffers into the buffer list */
8715     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8716     {
8717 	if (!(only_save_windows && buf->b_nwindows == 0)
8718 		&& !(buf->b_help && !(ssop_flags & SSOP_HELP))
8719 		&& buf->b_fname != NULL
8720 		&& buf->b_p_bl)
8721 	{
8722 	    if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
8723 					   : buf->b_wininfo->wi_fpos.lnum) < 0
8724 		    || ses_fname(fd, buf, &ssop_flags) == FAIL)
8725 		return FAIL;
8726 	}
8727     }
8728 
8729     /* the global argument list */
8730     if (ses_arglist(fd, "args", &global_alist.al_ga,
8731 			    !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
8732 	return FAIL;
8733 
8734     if (ssop_flags & SSOP_RESIZE)
8735     {
8736 	/* Note: after the restore we still check it worked!*/
8737 	if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
8738 		|| put_eol(fd) == FAIL)
8739 	    return FAIL;
8740     }
8741 
8742 #ifdef FEAT_GUI
8743     if (gui.in_use && (ssop_flags & SSOP_WINPOS))
8744     {
8745 	int	x, y;
8746 
8747 	if (gui_mch_get_winpos(&x, &y) == OK)
8748 	{
8749 	    /* Note: after the restore we still check it worked!*/
8750 	    if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
8751 		return FAIL;
8752 	}
8753     }
8754 #endif
8755 
8756     /*
8757      * Before creating the window layout, try loading one file.  If this is
8758      * aborted we don't end up with a number of useless windows.
8759      * This may have side effects! (e.g., compressed or network file).
8760      */
8761     for (wp = firstwin; wp != NULL; wp = wp->w_next)
8762     {
8763 	if (ses_do_win(wp)
8764 		&& wp->w_buffer->b_ffname != NULL
8765 		&& !wp->w_buffer->b_help
8766 #ifdef FEAT_QUICKFIX
8767 		&& !bt_nofile(wp->w_buffer)
8768 #endif
8769 		)
8770 	{
8771 	    if (fputs("edit ", fd) < 0
8772 		    || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
8773 		return FAIL;
8774 	    if (!wp->w_arg_idx_invalid)
8775 		edited_win = wp;
8776 	    break;
8777 	}
8778     }
8779 
8780     /*
8781      * Save current window layout.
8782      */
8783     if (put_line(fd, "set splitbelow splitright") == FAIL)
8784 	return FAIL;
8785     if (ses_win_rec(fd, topframe) == FAIL)
8786 	return FAIL;
8787     if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
8788 	return FAIL;
8789     if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
8790 	return FAIL;
8791 
8792     /*
8793      * Check if window sizes can be restored (no windows omitted).
8794      * Remember the window number of the current window after restoring.
8795      */
8796     nr = 0;
8797     for (wp = firstwin; wp != NULL; wp = W_NEXT(wp))
8798     {
8799 	if (ses_do_win(wp))
8800 	    ++nr;
8801 	else
8802 	    restore_size = FALSE;
8803 	if (curwin == wp)
8804 	    cnr = nr;
8805     }
8806 
8807     /* Go to the first window. */
8808     if (put_line(fd, "wincmd t") == FAIL)
8809 	return FAIL;
8810 
8811     /*
8812      * If more than one window, see if sizes can be restored.
8813      * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
8814      * resized when moving between windows.
8815      * Do this before restoring the view, so that the topline and the cursor
8816      * can be set.  This is done again below.
8817      */
8818     if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
8819 	return FAIL;
8820     if (nr > 1 && ses_winsizes(fd, restore_size) == FAIL)
8821 	return FAIL;
8822 
8823     /*
8824      * Restore the view of the window (options, file, cursor, etc.).
8825      */
8826     for (wp = firstwin; wp != NULL; wp = wp->w_next)
8827     {
8828 	if (!ses_do_win(wp))
8829 	    continue;
8830 	if (put_view(fd, wp, wp != edited_win, &ssop_flags) == FAIL)
8831 	    return FAIL;
8832 	if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
8833 	    return FAIL;
8834     }
8835 
8836     /*
8837      * Restore cursor to the current window if it's not the first one.
8838      */
8839     if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0 || put_eol(fd) == FAIL))
8840 	return FAIL;
8841 
8842     /*
8843      * Restore window sizes again after jumping around in windows, because the
8844      * current window has a minimum size while others may not.
8845      */
8846     if (nr > 1 && ses_winsizes(fd, restore_size) == FAIL)
8847 	return FAIL;
8848 
8849     /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
8850     if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
8851 			       p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
8852 	return FAIL;
8853 
8854     /*
8855      * Lastly, execute the x.vim file if it exists.
8856      */
8857     if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
8858 	    || put_line(fd, "if file_readable(s:sx)") == FAIL
8859 	    || put_line(fd, "  exe \"source \" . s:sx") == FAIL
8860 	    || put_line(fd, "endif") == FAIL)
8861 	return FAIL;
8862 
8863     return OK;
8864 }
8865 
8866     static int
8867 ses_winsizes(fd, restore_size)
8868     FILE	*fd;
8869     int		restore_size;
8870 {
8871     int		n = 0;
8872     win_T	*wp;
8873 
8874     if (restore_size && (ssop_flags & SSOP_WINSIZE))
8875     {
8876 	for (wp = firstwin; wp != NULL; wp = wp->w_next)
8877 	{
8878 	    if (!ses_do_win(wp))
8879 		continue;
8880 	    ++n;
8881 
8882 	    /* restore height when not full height */
8883 	    if (wp->w_height + wp->w_status_height < topframe->fr_height
8884 		    && (fprintf(fd,
8885 			  "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
8886 			    n, (long)wp->w_height, Rows / 2, Rows) < 0
8887 						  || put_eol(fd) == FAIL))
8888 		return FAIL;
8889 
8890 	    /* restore width when not full width */
8891 	    if (wp->w_width < Columns && (fprintf(fd,
8892 		   "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
8893 			    n, (long)wp->w_width, Columns / 2, Columns) < 0
8894 						  || put_eol(fd) == FAIL))
8895 		return FAIL;
8896 	}
8897     }
8898     else
8899     {
8900 	/* Just equalise window sizes */
8901 	if (put_line(fd, "wincmd =") == FAIL)
8902 	    return FAIL;
8903     }
8904     return OK;
8905 }
8906 
8907 /*
8908  * Write commands to "fd" to recursively create windows for frame "fr",
8909  * horizontally and vertically split.
8910  * After the commands the last window in the frame is the current window.
8911  * Returns FAIL when writing the commands to "fd" fails.
8912  */
8913     static int
8914 ses_win_rec(fd, fr)
8915     FILE	*fd;
8916     frame_T	*fr;
8917 {
8918     frame_T	*frc;
8919     int		count = 0;
8920 
8921     if (fr->fr_layout != FR_LEAF)
8922     {
8923 	/* Find first frame that's not skipped and then create a window for
8924 	 * each following one (first frame is already there). */
8925 	frc = ses_skipframe(fr->fr_child);
8926 	if (frc != NULL)
8927 	    while ((frc = ses_skipframe(frc->fr_next)) != NULL)
8928 	    {
8929 		/* Make window as big as possible so that we have lots of room
8930 		 * to split. */
8931 		if (put_line(fd, "wincmd _ | wincmd |") == FAIL
8932 			|| put_line(fd, fr->fr_layout == FR_COL
8933 						? "split" : "vsplit") == FAIL)
8934 		    return FAIL;
8935 		++count;
8936 	    }
8937 
8938 	/* Go back to the first window. */
8939 	if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
8940 			? "%dwincmd k" : "%dwincmd h", count) < 0
8941 						      || put_eol(fd) == FAIL))
8942 	    return FAIL;
8943 
8944 	/* Recursively create frames/windows in each window of this column or
8945 	 * row. */
8946 	frc = ses_skipframe(fr->fr_child);
8947 	while (frc != NULL)
8948 	{
8949 	    ses_win_rec(fd, frc);
8950 	    frc = ses_skipframe(frc->fr_next);
8951 	    /* Go to next window. */
8952 	    if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
8953 		return FAIL;
8954 	}
8955     }
8956     return OK;
8957 }
8958 
8959 /*
8960  * Skip frames that don't contain windows we want to save in the Session.
8961  * Returns NULL when there none.
8962  */
8963     static frame_T *
8964 ses_skipframe(fr)
8965     frame_T	*fr;
8966 {
8967     frame_T	*frc;
8968 
8969     for (frc = fr; frc != NULL; frc = frc->fr_next)
8970 	if (ses_do_frame(frc))
8971 	    break;
8972     return frc;
8973 }
8974 
8975 /*
8976  * Return TRUE if frame "fr" has a window somewhere that we want to save in
8977  * the Session.
8978  */
8979     static int
8980 ses_do_frame(fr)
8981     frame_T	*fr;
8982 {
8983     frame_T	*frc;
8984 
8985     if (fr->fr_layout == FR_LEAF)
8986 	return ses_do_win(fr->fr_win);
8987     for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
8988 	if (ses_do_frame(frc))
8989 	    return TRUE;
8990     return FALSE;
8991 }
8992 
8993 /*
8994  * Return non-zero if window "wp" is to be stored in the Session.
8995  */
8996     static int
8997 ses_do_win(wp)
8998     win_T	*wp;
8999 {
9000     if (wp->w_buffer->b_fname == NULL
9001 #ifdef FEAT_QUICKFIX
9002 	    /* When 'buftype' is "nofile" can't restore the window contents. */
9003 	    || bt_nofile(wp->w_buffer)
9004 #endif
9005        )
9006 	return (ssop_flags & SSOP_BLANK);
9007     if (wp->w_buffer->b_help)
9008 	return (ssop_flags & SSOP_HELP);
9009     return TRUE;
9010 }
9011 
9012 /*
9013  * Write commands to "fd" to restore the view of a window.
9014  * Caller must make sure 'scrolloff' is zero.
9015  */
9016     static int
9017 put_view(fd, wp, add_edit, flagp)
9018     FILE	*fd;
9019     win_T	*wp;
9020     int		add_edit;	/* add ":edit" command to view */
9021     unsigned	*flagp;		/* vop_flags or ssop_flags */
9022 {
9023     win_T	*save_curwin;
9024     int		f;
9025     int		do_cursor;
9026 
9027     /* Always restore cursor position for ":mksession".  For ":mkview" only
9028      * when 'viewoptions' contains "cursor". */
9029     do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
9030 
9031     /*
9032      * Local argument list.
9033      */
9034     if (wp->w_alist == &global_alist)
9035     {
9036 	if (put_line(fd, "argglobal") == FAIL)
9037 	    return FAIL;
9038     }
9039     else
9040     {
9041 	if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
9042 			flagp == &vop_flags
9043 			|| !(*flagp & SSOP_CURDIR)
9044 			|| wp->w_localdir != NULL, flagp) == FAIL)
9045 	    return FAIL;
9046     }
9047 
9048     /* Only when part of a session: restore the argument index. */
9049     if (wp->w_arg_idx != 0 && flagp == &ssop_flags)
9050     {
9051 	if (fprintf(fd, "%ldnext", (long)wp->w_arg_idx) < 0
9052 		|| put_eol(fd) == FAIL)
9053 	    return FAIL;
9054     }
9055 
9056     /* Edit the file.  Skip this when ":next" already did it. */
9057     if (add_edit && (wp->w_arg_idx == 0 || flagp != &ssop_flags
9058 						    || wp->w_arg_idx_invalid))
9059     {
9060 	/*
9061 	 * Load the file.
9062 	 */
9063 	if (wp->w_buffer->b_ffname != NULL
9064 #ifdef FEAT_QUICKFIX
9065 		&& !bt_nofile(wp->w_buffer)
9066 #endif
9067 		)
9068 	{
9069 	    /*
9070 	     * Editing a file in this buffer: use ":edit file".
9071 	     * This may have side effects! (e.g., compressed or network file).
9072 	     */
9073 	    if (fputs("edit ", fd) < 0
9074 		    || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
9075 		return FAIL;
9076 	}
9077 	else
9078 	{
9079 	    /* No file in this buffer, just make it empty. */
9080 	    if (put_line(fd, "enew") == FAIL)
9081 		return FAIL;
9082 #ifdef FEAT_QUICKFIX
9083 	    if (wp->w_buffer->b_ffname != NULL)
9084 	    {
9085 		/* The buffer does have a name, but it's not a file name. */
9086 		if (fputs("file ", fd) < 0
9087 			|| ses_fname(fd, wp->w_buffer, flagp) == FAIL)
9088 		    return FAIL;
9089 	    }
9090 #endif
9091 	    do_cursor = FALSE;
9092 	}
9093     }
9094 
9095     /*
9096      * Local mappings and abbreviations.
9097      */
9098     if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
9099 					 && makemap(fd, wp->w_buffer) == FAIL)
9100 	return FAIL;
9101 
9102     /*
9103      * Local options.  Need to go to the window temporarily.
9104      * Store only local values when using ":mkview" and when ":mksession" is
9105      * used and 'sessionoptions' doesn't include "options".
9106      * Some folding options are always stored when "folds" is included,
9107      * otherwise the folds would not be restored correctly.
9108      */
9109     save_curwin = curwin;
9110     curwin = wp;
9111     curbuf = curwin->w_buffer;
9112     if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
9113 	f = makeset(fd, OPT_LOCAL,
9114 			     flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
9115 #ifdef FEAT_FOLDING
9116     else if (*flagp & SSOP_FOLDS)
9117 	f = makefoldset(fd);
9118 #endif
9119     else
9120 	f = OK;
9121     curwin = save_curwin;
9122     curbuf = curwin->w_buffer;
9123     if (f == FAIL)
9124 	return FAIL;
9125 
9126 #ifdef FEAT_FOLDING
9127     /*
9128      * Save Folds when 'buftype' is empty and for help files.
9129      */
9130     if ((*flagp & SSOP_FOLDS)
9131 	    && wp->w_buffer->b_ffname != NULL
9132 	    && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help))
9133     {
9134 	if (put_folds(fd, wp) == FAIL)
9135 	    return FAIL;
9136     }
9137 #endif
9138 
9139     /*
9140      * Set the cursor after creating folds, since that moves the cursor.
9141      */
9142     if (do_cursor)
9143     {
9144 
9145 	/* Restore the cursor line in the file and relatively in the
9146 	 * window.  Don't use "G", it changes the jumplist. */
9147 	if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
9148 		    (long)wp->w_cursor.lnum,
9149 		    (long)(wp->w_cursor.lnum - wp->w_topline),
9150 		    (long)wp->w_height / 2, (long)wp->w_height) < 0
9151 		|| put_eol(fd) == FAIL
9152 		|| put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
9153 		|| put_line(fd, "exe s:l") == FAIL
9154 		|| put_line(fd, "normal! zt") == FAIL
9155 		|| fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
9156 		|| put_eol(fd) == FAIL)
9157 	    return FAIL;
9158 	/* Restore the cursor column and left offset when not wrapping. */
9159 	if (wp->w_cursor.col == 0)
9160 	{
9161 	    if (put_line(fd, "normal! 0") == FAIL)
9162 		return FAIL;
9163 	}
9164 	else
9165 	{
9166 	    if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
9167 	    {
9168 		if (fprintf(fd,
9169 			  "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
9170 			    (long)wp->w_cursor.col,
9171 			    (long)(wp->w_cursor.col - wp->w_leftcol),
9172 			    (long)wp->w_width / 2, (long)wp->w_width) < 0
9173 			|| put_eol(fd) == FAIL
9174 			|| put_line(fd, "if s:c > 0") == FAIL
9175 			|| fprintf(fd,
9176 			    "  exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
9177 			    (long)wp->w_cursor.col) < 0
9178 			|| put_eol(fd) == FAIL
9179 			|| put_line(fd, "else") == FAIL
9180 			|| fprintf(fd, "  normal! 0%dl", wp->w_cursor.col) < 0
9181 			|| put_eol(fd) == FAIL
9182 			|| put_line(fd, "endif") == FAIL)
9183 		    return FAIL;
9184 	    }
9185 	    else
9186 	    {
9187 		if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
9188 			|| put_eol(fd) == FAIL)
9189 		    return FAIL;
9190 	    }
9191 	}
9192     }
9193 
9194     /*
9195      * Local directory.
9196      */
9197     if (wp->w_localdir != NULL)
9198     {
9199 	if (fputs("lcd ", fd) < 0
9200 		|| ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
9201 		|| put_eol(fd) == FAIL)
9202 	    return FAIL;
9203     }
9204 
9205     return OK;
9206 }
9207 
9208 /*
9209  * Write an argument list to the session file.
9210  * Returns FAIL if writing fails.
9211  */
9212     static int
9213 ses_arglist(fd, cmd, gap, fullname, flagp)
9214     FILE	*fd;
9215     char	*cmd;
9216     garray_T	*gap;
9217     int		fullname;	/* TRUE: use full path name */
9218     unsigned	*flagp;
9219 {
9220     int		i;
9221     char_u	buf[MAXPATHL];
9222     char_u	*s;
9223 
9224     if (gap->ga_len == 0)
9225 	return put_line(fd, "silent! argdel *");
9226     if (fputs(cmd, fd) < 0)
9227 	return FAIL;
9228     for (i = 0; i < gap->ga_len; ++i)
9229     {
9230 	/* NULL file names are skipped (only happens when out of memory). */
9231 	s = alist_name(&((aentry_T *)gap->ga_data)[i]);
9232 	if (s != NULL)
9233 	{
9234 	    if (fullname)
9235 	    {
9236 		(void)vim_FullName(s, buf, MAXPATHL, FALSE);
9237 		s = buf;
9238 	    }
9239 	    if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
9240 		return FAIL;
9241 	}
9242     }
9243     return put_eol(fd);
9244 }
9245 
9246 /*
9247  * Write a buffer name to the session file.
9248  * Also ends the line.
9249  * Returns FAIL if writing fails.
9250  */
9251     static int
9252 ses_fname(fd, buf, flagp)
9253     FILE	*fd;
9254     buf_T	*buf;
9255     unsigned	*flagp;
9256 {
9257     char_u	*name;
9258 
9259     /* Use the short file name if the current directory is known at the time
9260      * the session file will be sourced.  Don't do this for ":mkview", we
9261      * don't know the current directory. */
9262     if (buf->b_sfname != NULL
9263 	    && flagp == &ssop_flags
9264 	    && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR)))
9265 	name = buf->b_sfname;
9266     else
9267 	name = buf->b_ffname;
9268     if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
9269 	return FAIL;
9270     return OK;
9271 }
9272 
9273 /*
9274  * Write a file name to the session file.
9275  * Takes care of the "slash" option in 'sessionoptions' and escapes special
9276  * characters.
9277  * Returns FAIL if writing fails.
9278  */
9279     static int
9280 ses_put_fname(fd, name, flagp)
9281     FILE	*fd;
9282     char_u	*name;
9283     unsigned	*flagp;
9284 {
9285     char_u	*sname;
9286     int		retval = OK;
9287     int		c;
9288 
9289     sname = home_replace_save(NULL, name);
9290     if (sname != NULL)
9291 	name = sname;
9292     while (*name != NUL)
9293     {
9294 #ifdef FEAT_MBYTE
9295 	{
9296 	    int l;
9297 
9298 	    if (has_mbyte && (l = (*mb_ptr2len_check)(name)) > 1)
9299 	    {
9300 		/* copy a multibyte char */
9301 		while (--l >= 0)
9302 		{
9303 		    if (putc(*name, fd) != *name)
9304 			retval = FAIL;
9305 		    ++name;
9306 		}
9307 		continue;
9308 	    }
9309 	}
9310 #endif
9311 	c = *name++;
9312 	if (c == '\\' && (*flagp & SSOP_SLASH))
9313 	    /* change a backslash to a forward slash */
9314 	    c = '/';
9315 	else if ((vim_strchr(escape_chars, c) != NULL
9316 #ifdef BACKSLASH_IN_FILENAME
9317 		    && c != '\\'
9318 #endif
9319 		 ) || c == '#' || c == '%')
9320 	{
9321 	    /* escape a special character with a backslash */
9322 	    if (putc('\\', fd) != '\\')
9323 		retval = FAIL;
9324 	}
9325 	if (putc(c, fd) != c)
9326 	    retval = FAIL;
9327     }
9328     vim_free(sname);
9329     return retval;
9330 }
9331 
9332 /*
9333  * ":loadview [nr]"
9334  */
9335     static void
9336 ex_loadview(eap)
9337     exarg_T	*eap;
9338 {
9339     char_u	*fname;
9340 
9341     fname = get_view_file(*eap->arg);
9342     if (fname != NULL)
9343     {
9344 	do_source(fname, FALSE, FALSE);
9345 	vim_free(fname);
9346     }
9347 }
9348 
9349 /*
9350  * Get the name of the view file for the current buffer.
9351  */
9352     static char_u *
9353 get_view_file(c)
9354     int		c;
9355 {
9356     int		len = 0;
9357     char_u	*p, *s;
9358     char_u	*retval;
9359     char_u	*sname;
9360 
9361     if (curbuf->b_ffname == NULL)
9362     {
9363 	EMSG(_(e_noname));
9364 	return NULL;
9365     }
9366     sname = home_replace_save(NULL, curbuf->b_ffname);
9367     if (sname == NULL)
9368 	return NULL;
9369 
9370     /*
9371      * We want a file name without separators, because we're not going to make
9372      * a directory.
9373      * "normal" path separator	-> "=+"
9374      * "="			-> "=="
9375      * ":" path separator	-> "=-"
9376      */
9377     for (p = sname; *p; ++p)
9378 	if (*p == '=' || vim_ispathsep(*p))
9379 	    ++len;
9380     retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
9381     if (retval != NULL)
9382     {
9383 	STRCPY(retval, p_vdir);
9384 	add_pathsep(retval);
9385 	s = retval + STRLEN(retval);
9386 	for (p = sname; *p; ++p)
9387 	{
9388 	    if (*p == '=')
9389 	    {
9390 		*s++ = '=';
9391 		*s++ = '=';
9392 	    }
9393 	    else if (vim_ispathsep(*p))
9394 	    {
9395 		*s++ = '=';
9396 #ifdef MACOS_CLASSIC /* TODO: Is it also needed for MACOS_X? (Dany) */
9397 		*s++ = '+';
9398 #else
9399 # if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
9400 	|| defined(VMS)
9401 		if (*p == ':')
9402 		    *s++ = '-';
9403 		else
9404 # endif
9405 		    *s++ = '+';
9406 #endif
9407 	    }
9408 	    else
9409 		*s++ = *p;
9410 	}
9411 	*s++ = '=';
9412 	*s++ = c;
9413 	STRCPY(s, ".vim");
9414     }
9415 
9416     vim_free(sname);
9417     return retval;
9418 }
9419 
9420 #endif /* FEAT_SESSION */
9421 
9422 /*
9423  * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
9424  * Return FAIL for a write error.
9425  */
9426     int
9427 put_eol(fd)
9428     FILE	*fd;
9429 {
9430     if (
9431 #ifdef USE_CRNL
9432 	    (
9433 # ifdef MKSESSION_NL
9434 	     !mksession_nl &&
9435 # endif
9436 	     (putc('\r', fd) < 0)) ||
9437 #endif
9438 	    (putc('\n', fd) < 0))
9439 	return FAIL;
9440     return OK;
9441 }
9442 
9443 /*
9444  * Write a line to "fd".
9445  * Return FAIL for a write error.
9446  */
9447     int
9448 put_line(fd, s)
9449     FILE	*fd;
9450     char	*s;
9451 {
9452     if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
9453 	return FAIL;
9454     return OK;
9455 }
9456 
9457 #ifdef FEAT_VIMINFO
9458 /*
9459  * ":rviminfo" and ":wviminfo".
9460  */
9461     static void
9462 ex_viminfo(eap)
9463     exarg_T	*eap;
9464 {
9465     char_u	*save_viminfo;
9466 
9467     save_viminfo = p_viminfo;
9468     if (*p_viminfo == NUL)
9469 	p_viminfo = (char_u *)"'100";
9470     if (eap->cmdidx == CMD_rviminfo)
9471     {
9472 	if (read_viminfo(eap->arg, TRUE, TRUE, eap->forceit) == FAIL)
9473 	    EMSG(_("E195: Cannot open viminfo file for reading"));
9474     }
9475     else
9476 	write_viminfo(eap->arg, eap->forceit);
9477     p_viminfo = save_viminfo;
9478 }
9479 #endif
9480 
9481 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
9482     void
9483 dialog_msg(buff, format, fname)
9484     char_u	*buff;
9485     char	*format;
9486     char_u	*fname;
9487 {
9488     int		len;
9489 
9490     if (fname == NULL)
9491 	fname = (char_u *)_("Untitled");
9492     len = (int)STRLEN(format) + (int)STRLEN(fname);
9493     if (len >= IOSIZE)
9494 	sprintf((char *)buff, format, (int)(IOSIZE - STRLEN(format)), fname);
9495     else
9496 	sprintf((char *)buff, format, (int)STRLEN(fname), fname);
9497 }
9498 #endif
9499 
9500 /*
9501  * ":behave {mswin,xterm}"
9502  */
9503     static void
9504 ex_behave(eap)
9505     exarg_T	*eap;
9506 {
9507     if (STRCMP(eap->arg, "mswin") == 0)
9508     {
9509 	set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
9510 	set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
9511 	set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
9512 	set_option_value((char_u *)"keymodel", 0L,
9513 					     (char_u *)"startsel,stopsel", 0);
9514     }
9515     else if (STRCMP(eap->arg, "xterm") == 0)
9516     {
9517 	set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
9518 	set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
9519 	set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
9520 	set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
9521     }
9522     else
9523 	EMSG2(_(e_invarg2), eap->arg);
9524 }
9525 
9526 #ifdef FEAT_AUTOCMD
9527 static int filetype_detect = FALSE;
9528 static int filetype_plugin = FALSE;
9529 static int filetype_indent = FALSE;
9530 
9531 /*
9532  * ":filetype [plugin] [indent] {on,off,detect}"
9533  * on: Load the filetype.vim file to install autocommands for file types.
9534  * off: Load the ftoff.vim file to remove all autocommands for file types.
9535  * plugin on: load filetype.vim and ftplugin.vim
9536  * plugin off: load ftplugof.vim
9537  * indent on: load filetype.vim and indent.vim
9538  * indent off: load indoff.vim
9539  */
9540     static void
9541 ex_filetype(eap)
9542     exarg_T	*eap;
9543 {
9544     char_u	*arg = eap->arg;
9545     int		plugin = FALSE;
9546     int		indent = FALSE;
9547 
9548     if (*eap->arg == NUL)
9549     {
9550 	/* Print current status. */
9551 	smsg((char_u *)"filetype detection:%s  plugin:%s  indent:%s",
9552 		filetype_detect ? "ON" : "OFF",
9553 		filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
9554 		filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
9555 	return;
9556     }
9557 
9558     /* Accept "plugin" and "indent" in any order. */
9559     for (;;)
9560     {
9561 	if (STRNCMP(arg, "plugin", 6) == 0)
9562 	{
9563 	    plugin = TRUE;
9564 	    arg = skipwhite(arg + 6);
9565 	    continue;
9566 	}
9567 	if (STRNCMP(arg, "indent", 6) == 0)
9568 	{
9569 	    indent = TRUE;
9570 	    arg = skipwhite(arg + 6);
9571 	    continue;
9572 	}
9573 	break;
9574     }
9575     if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
9576     {
9577 	if (*arg == 'o' || !filetype_detect)
9578 	{
9579 	    cmd_runtime((char_u *)FILETYPE_FILE, TRUE);
9580 	    filetype_detect = TRUE;
9581 	    if (plugin)
9582 	    {
9583 		cmd_runtime((char_u *)FTPLUGIN_FILE, TRUE);
9584 		filetype_plugin = TRUE;
9585 	    }
9586 	    if (indent)
9587 	    {
9588 		cmd_runtime((char_u *)INDENT_FILE, TRUE);
9589 		filetype_indent = TRUE;
9590 	    }
9591 	}
9592 	if (*arg == 'd')
9593 	{
9594 	    (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
9595 	    do_modelines(FALSE);
9596 	}
9597     }
9598     else if (STRCMP(arg, "off") == 0)
9599     {
9600 	if (plugin || indent)
9601 	{
9602 	    if (plugin)
9603 	    {
9604 		cmd_runtime((char_u *)FTPLUGOF_FILE, TRUE);
9605 		filetype_plugin = FALSE;
9606 	    }
9607 	    if (indent)
9608 	    {
9609 		cmd_runtime((char_u *)INDOFF_FILE, TRUE);
9610 		filetype_indent = FALSE;
9611 	    }
9612 	}
9613 	else
9614 	{
9615 	    cmd_runtime((char_u *)FTOFF_FILE, TRUE);
9616 	    filetype_detect = FALSE;
9617 	}
9618     }
9619     else
9620 	EMSG2(_(e_invarg2), arg);
9621 }
9622 
9623 /*
9624  * ":setfiletype {name}"
9625  */
9626     static void
9627 ex_setfiletype(eap)
9628     exarg_T	*eap;
9629 {
9630     if (!did_filetype)
9631 	set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
9632 }
9633 #endif
9634 
9635 /*ARGSUSED*/
9636     static void
9637 ex_digraphs(eap)
9638     exarg_T	*eap;
9639 {
9640 #ifdef FEAT_DIGRAPHS
9641     if (*eap->arg != NUL)
9642 	putdigraph(eap->arg);
9643     else
9644 	listdigraphs();
9645 #else
9646     EMSG(_("E196: No digraphs in this version"));
9647 #endif
9648 }
9649 
9650     static void
9651 ex_set(eap)
9652     exarg_T	*eap;
9653 {
9654     int		flags = 0;
9655 
9656     if (eap->cmdidx == CMD_setlocal)
9657 	flags = OPT_LOCAL;
9658     else if (eap->cmdidx == CMD_setglobal)
9659 	flags = OPT_GLOBAL;
9660 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
9661     if (cmdmod.browse && flags == 0)
9662 	ex_options(eap);
9663     else
9664 #endif
9665 	(void)do_set(eap->arg, flags);
9666 }
9667 
9668 #ifdef FEAT_SEARCH_EXTRA
9669 /*
9670  * ":nohlsearch"
9671  */
9672 /*ARGSUSED*/
9673     static void
9674 ex_nohlsearch(eap)
9675     exarg_T	*eap;
9676 {
9677     no_hlsearch = TRUE;
9678     redraw_all_later(NOT_VALID);
9679 }
9680 
9681 /*
9682  * ":match {group} {pattern}"
9683  * Sets nextcmd to the start of the next command, if any.  Also called when
9684  * skipping commands to find the next command.
9685  */
9686     static void
9687 ex_match(eap)
9688     exarg_T	*eap;
9689 {
9690     char_u	*p;
9691     char_u	*end;
9692     int		c;
9693 
9694     /* First clear any old pattern. */
9695     if (!eap->skip)
9696     {
9697 	vim_free(curwin->w_match.regprog);
9698 	curwin->w_match.regprog = NULL;
9699 	redraw_later(NOT_VALID);	/* always need a redraw */
9700     }
9701 
9702     if (ends_excmd(*eap->arg))
9703 	end = eap->arg;
9704     else if ((STRNICMP(eap->arg, "none", 4) == 0
9705 		&& (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
9706 	end = eap->arg + 4;
9707     else
9708     {
9709 	p = skiptowhite(eap->arg);
9710 	if (!eap->skip)
9711 	{
9712 	    curwin->w_match_id = syn_namen2id(eap->arg, (int)(p - eap->arg));
9713 	    if (curwin->w_match_id == 0)
9714 	    {
9715 		EMSG2(_(e_nogroup), eap->arg);
9716 		return;
9717 	    }
9718 	}
9719 	p = skipwhite(p);
9720 	if (*p == NUL)
9721 	{
9722 	    /* There must be two arguments. */
9723 	    EMSG2(_(e_invarg2), eap->arg);
9724 	    return;
9725 	}
9726 	end = skip_regexp(p + 1, *p, TRUE, NULL);
9727 	if (!eap->skip)
9728 	{
9729 	    if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
9730 	    {
9731 		eap->errmsg = e_trailing;
9732 		return;
9733 	    }
9734 
9735 	    c = *end;
9736 	    *end = NUL;
9737 	    curwin->w_match.regprog = vim_regcomp(p + 1, RE_MAGIC);
9738 	    *end = c;
9739 	    if (curwin->w_match.regprog == NULL)
9740 	    {
9741 		EMSG2(_(e_invarg2), p);
9742 		return;
9743 	    }
9744 	}
9745     }
9746     eap->nextcmd = find_nextcmd(end);
9747 }
9748 #endif
9749 
9750 #ifdef FEAT_CRYPT
9751 /*
9752  * ":X": Get crypt key
9753  */
9754 /*ARGSUSED*/
9755     static void
9756 ex_X(eap)
9757     exarg_T	*eap;
9758 {
9759     (void)get_crypt_key(TRUE, TRUE);
9760 }
9761 #endif
9762 
9763 #ifdef FEAT_FOLDING
9764     static void
9765 ex_fold(eap)
9766     exarg_T	*eap;
9767 {
9768     if (foldManualAllowed(TRUE))
9769 	foldCreate(eap->line1, eap->line2);
9770 }
9771 
9772     static void
9773 ex_foldopen(eap)
9774     exarg_T	*eap;
9775 {
9776     opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
9777 							 eap->forceit, FALSE);
9778 }
9779 
9780     static void
9781 ex_folddo(eap)
9782     exarg_T	*eap;
9783 {
9784     linenr_T	lnum;
9785 
9786     /* First set the marks for all lines closed/open. */
9787     for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
9788 	if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
9789 	    ml_setmarked(lnum);
9790 
9791     /* Execute the command on the marked lines. */
9792     global_exe(eap->arg);
9793     ml_clearmarked();	   /* clear rest of the marks */
9794 }
9795 #endif
9796