Merge branch 'vim' into feat/code-check
[vim_extended.git] / src / ex_docmd.c
bloba935a15ae727d574381b4c0958a521690e5ca722
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * ex_docmd.c: functions for executing an Ex command line.
14 #include "vim.h"
16 static int quitmore = 0;
17 static int ex_pressedreturn = FALSE;
18 #ifndef FEAT_PRINTER
19 # define ex_hardcopy ex_ni
20 #endif
22 #ifdef FEAT_USR_CMDS
23 typedef struct ucmd
25 char_u *uc_name; /* The command name */
26 long_u uc_argt; /* The argument type */
27 char_u *uc_rep; /* The command's replacement string */
28 long uc_def; /* The default value for a range/count */
29 scid_T uc_scriptID; /* SID where the command was defined */
30 int uc_compl; /* completion type */
31 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
32 char_u *uc_compl_arg; /* completion argument if any */
33 # endif
34 } ucmd_T;
36 #define UC_BUFFER 1 /* -buffer: local to current buffer */
38 static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL};
40 #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
41 #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
43 static void do_ucmd __ARGS((exarg_T *eap));
44 static void ex_command __ARGS((exarg_T *eap));
45 static void ex_delcommand __ARGS((exarg_T *eap));
46 # ifdef FEAT_CMDL_COMPL
47 static char_u *get_user_command_name __ARGS((int idx));
48 # endif
50 #else
51 # define ex_command ex_ni
52 # define ex_comclear ex_ni
53 # define ex_delcommand ex_ni
54 #endif
56 #ifdef FEAT_EVAL
57 static char_u *do_one_cmd __ARGS((char_u **, int, struct condstack *, char_u *(*fgetline)(int, void *, int), void *cookie));
58 #else
59 static char_u *do_one_cmd __ARGS((char_u **, int, char_u *(*fgetline)(int, void *, int), void *cookie));
60 static int if_level = 0; /* depth in :if */
61 #endif
62 static char_u *find_command __ARGS((exarg_T *eap, int *full));
64 static void ex_abbreviate __ARGS((exarg_T *eap));
65 static void ex_map __ARGS((exarg_T *eap));
66 static void ex_unmap __ARGS((exarg_T *eap));
67 static void ex_mapclear __ARGS((exarg_T *eap));
68 static void ex_abclear __ARGS((exarg_T *eap));
69 #ifndef FEAT_MENU
70 # define ex_emenu ex_ni
71 # define ex_menu ex_ni
72 # define ex_menutranslate ex_ni
73 #endif
74 #ifdef FEAT_AUTOCMD
75 static void ex_autocmd __ARGS((exarg_T *eap));
76 static void ex_doautocmd __ARGS((exarg_T *eap));
77 #else
78 # define ex_autocmd ex_ni
79 # define ex_doautocmd ex_ni
80 # define ex_doautoall ex_ni
81 #endif
82 #ifdef FEAT_LISTCMDS
83 static void ex_bunload __ARGS((exarg_T *eap));
84 static void ex_buffer __ARGS((exarg_T *eap));
85 static void ex_bmodified __ARGS((exarg_T *eap));
86 static void ex_bnext __ARGS((exarg_T *eap));
87 static void ex_bprevious __ARGS((exarg_T *eap));
88 static void ex_brewind __ARGS((exarg_T *eap));
89 static void ex_blast __ARGS((exarg_T *eap));
90 #else
91 # define ex_bunload ex_ni
92 # define ex_buffer ex_ni
93 # define ex_bmodified ex_ni
94 # define ex_bnext ex_ni
95 # define ex_bprevious ex_ni
96 # define ex_brewind ex_ni
97 # define ex_blast ex_ni
98 # define buflist_list ex_ni
99 # define ex_checktime ex_ni
100 #endif
101 #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS)
102 # define ex_buffer_all ex_ni
103 #endif
104 static char_u *getargcmd __ARGS((char_u **));
105 static char_u *skip_cmd_arg __ARGS((char_u *p, int rembs));
106 static int getargopt __ARGS((exarg_T *eap));
107 #ifndef FEAT_QUICKFIX
108 # define ex_make ex_ni
109 # define ex_cbuffer ex_ni
110 # define ex_cc ex_ni
111 # define ex_cnext ex_ni
112 # define ex_cfile ex_ni
113 # define qf_list ex_ni
114 # define qf_age ex_ni
115 # define ex_helpgrep ex_ni
116 # define ex_vimgrep ex_ni
117 #endif
118 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS)
119 # define ex_cclose ex_ni
120 # define ex_copen ex_ni
121 # define ex_cwindow ex_ni
122 #endif
123 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL)
124 # define ex_cexpr ex_ni
125 #endif
127 static int check_more __ARGS((int, int));
128 static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file));
129 static void get_flags __ARGS((exarg_T *eap));
130 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
131 || !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME)
132 # define HAVE_EX_SCRIPT_NI
133 static void ex_script_ni __ARGS((exarg_T *eap));
134 #endif
135 static char_u *invalid_range __ARGS((exarg_T *eap));
136 static void correct_range __ARGS((exarg_T *eap));
137 #ifdef FEAT_QUICKFIX
138 static char_u *replace_makeprg __ARGS((exarg_T *eap, char_u *p, char_u **cmdlinep));
139 #endif
140 static char_u *repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep));
141 static void ex_highlight __ARGS((exarg_T *eap));
142 static void ex_colorscheme __ARGS((exarg_T *eap));
143 static void ex_codecheck __ARGS((exarg_T *eap));
144 static void ex_quit __ARGS((exarg_T *eap));
145 static void ex_cquit __ARGS((exarg_T *eap));
146 static void ex_quit_all __ARGS((exarg_T *eap));
147 #ifdef FEAT_WINDOWS
148 static void ex_close __ARGS((exarg_T *eap));
149 static void ex_win_close __ARGS((int forceit, win_T *win, tabpage_T *tp));
150 static void ex_only __ARGS((exarg_T *eap));
151 static void ex_resize __ARGS((exarg_T *eap));
152 static void ex_stag __ARGS((exarg_T *eap));
153 static void ex_tabclose __ARGS((exarg_T *eap));
154 static void ex_tabonly __ARGS((exarg_T *eap));
155 static void ex_tabnext __ARGS((exarg_T *eap));
156 static void ex_tabmove __ARGS((exarg_T *eap));
157 static void ex_tabs __ARGS((exarg_T *eap));
158 #else
159 # define ex_close ex_ni
160 # define ex_only ex_ni
161 # define ex_all ex_ni
162 # define ex_resize ex_ni
163 # define ex_splitview ex_ni
164 # define ex_stag ex_ni
165 # define ex_tabnext ex_ni
166 # define ex_tabmove ex_ni
167 # define ex_tabs ex_ni
168 # define ex_tabclose ex_ni
169 # define ex_tabonly ex_ni
170 #endif
171 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
172 static void ex_pclose __ARGS((exarg_T *eap));
173 static void ex_ptag __ARGS((exarg_T *eap));
174 static void ex_pedit __ARGS((exarg_T *eap));
175 #else
176 # define ex_pclose ex_ni
177 # define ex_ptag ex_ni
178 # define ex_pedit ex_ni
179 #endif
180 static void ex_hide __ARGS((exarg_T *eap));
181 static void ex_stop __ARGS((exarg_T *eap));
182 static void ex_exit __ARGS((exarg_T *eap));
183 static void ex_print __ARGS((exarg_T *eap));
184 #ifdef FEAT_BYTEOFF
185 static void ex_goto __ARGS((exarg_T *eap));
186 #else
187 # define ex_goto ex_ni
188 #endif
189 static void ex_shell __ARGS((exarg_T *eap));
190 static void ex_preserve __ARGS((exarg_T *eap));
191 static void ex_recover __ARGS((exarg_T *eap));
192 #ifndef FEAT_LISTCMDS
193 # define ex_argedit ex_ni
194 # define ex_argadd ex_ni
195 # define ex_argdelete ex_ni
196 # define ex_listdo ex_ni
197 #endif
198 static void ex_mode __ARGS((exarg_T *eap));
199 static void ex_wrongmodifier __ARGS((exarg_T *eap));
200 static void ex_find __ARGS((exarg_T *eap));
201 static void ex_open __ARGS((exarg_T *eap));
202 static void ex_edit __ARGS((exarg_T *eap));
203 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
204 # define ex_drop ex_ni
205 #endif
206 #ifndef FEAT_GUI
207 # define ex_gui ex_nogui
208 static void ex_nogui __ARGS((exarg_T *eap));
209 #endif
210 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
211 static void ex_tearoff __ARGS((exarg_T *eap));
212 #else
213 # define ex_tearoff ex_ni
214 #endif
215 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
216 static void ex_popup __ARGS((exarg_T *eap));
217 #else
218 # define ex_popup ex_ni
219 #endif
220 #ifndef FEAT_GUI_MSWIN
221 # define ex_simalt ex_ni
222 #endif
223 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
224 # define gui_mch_find_dialog ex_ni
225 # define gui_mch_replace_dialog ex_ni
226 #endif
227 #if !defined(FEAT_GUI_GTK)
228 # define ex_helpfind ex_ni
229 #endif
230 #ifndef FEAT_CSCOPE
231 # define do_cscope ex_ni
232 # define do_scscope ex_ni
233 # define do_cstag ex_ni
234 #endif
235 #ifndef FEAT_SYN_HL
236 # define ex_syntax ex_ni
237 #endif
238 #ifndef FEAT_SPELL
239 # define ex_spell ex_ni
240 # define ex_mkspell ex_ni
241 # define ex_spelldump ex_ni
242 # define ex_spellinfo ex_ni
243 # define ex_spellrepall ex_ni
244 #endif
245 #ifndef FEAT_MZSCHEME
246 # define ex_mzscheme ex_script_ni
247 # define ex_mzfile ex_ni
248 #endif
249 #ifndef FEAT_PERL
250 # define ex_perl ex_script_ni
251 # define ex_perldo ex_ni
252 #endif
253 #ifndef FEAT_PYTHON
254 # define ex_python ex_script_ni
255 # define ex_pyfile ex_ni
256 #endif
257 #ifndef FEAT_TCL
258 # define ex_tcl ex_script_ni
259 # define ex_tcldo ex_ni
260 # define ex_tclfile ex_ni
261 #endif
262 #ifndef FEAT_RUBY
263 # define ex_ruby ex_script_ni
264 # define ex_rubydo ex_ni
265 # define ex_rubyfile ex_ni
266 #endif
267 #ifndef FEAT_SNIFF
268 # define ex_sniff ex_ni
269 #endif
270 #ifndef FEAT_KEYMAP
271 # define ex_loadkeymap ex_ni
272 #endif
273 static void ex_swapname __ARGS((exarg_T *eap));
274 static void ex_syncbind __ARGS((exarg_T *eap));
275 static void ex_read __ARGS((exarg_T *eap));
276 static void ex_pwd __ARGS((exarg_T *eap));
277 static void ex_equal __ARGS((exarg_T *eap));
278 static void ex_sleep __ARGS((exarg_T *eap));
279 static void do_exmap __ARGS((exarg_T *eap, int isabbrev));
280 static void ex_winsize __ARGS((exarg_T *eap));
281 #ifdef FEAT_WINDOWS
282 static void ex_wincmd __ARGS((exarg_T *eap));
283 #else
284 # define ex_wincmd ex_ni
285 #endif
286 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
287 static void ex_winpos __ARGS((exarg_T *eap));
288 #else
289 # define ex_winpos ex_ni
290 #endif
291 static void ex_operators __ARGS((exarg_T *eap));
292 static void ex_put __ARGS((exarg_T *eap));
293 static void ex_copymove __ARGS((exarg_T *eap));
294 static void ex_may_print __ARGS((exarg_T *eap));
295 static void ex_submagic __ARGS((exarg_T *eap));
296 static void ex_join __ARGS((exarg_T *eap));
297 static void ex_at __ARGS((exarg_T *eap));
298 static void ex_bang __ARGS((exarg_T *eap));
299 static void ex_undo __ARGS((exarg_T *eap));
300 static void ex_redo __ARGS((exarg_T *eap));
301 static void ex_later __ARGS((exarg_T *eap));
302 static void ex_redir __ARGS((exarg_T *eap));
303 static void ex_redraw __ARGS((exarg_T *eap));
304 static void ex_redrawstatus __ARGS((exarg_T *eap));
305 static void close_redir __ARGS((void));
306 static void ex_mkrc __ARGS((exarg_T *eap));
307 static void ex_mark __ARGS((exarg_T *eap));
308 #ifdef FEAT_USR_CMDS
309 static char_u *uc_fun_cmd __ARGS((void));
310 static char_u *find_ucmd __ARGS((exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl));
311 #endif
312 #ifdef FEAT_EX_EXTRA
313 static void ex_normal __ARGS((exarg_T *eap));
314 static void ex_startinsert __ARGS((exarg_T *eap));
315 static void ex_stopinsert __ARGS((exarg_T *eap));
316 #else
317 # define ex_normal ex_ni
318 # define ex_align ex_ni
319 # define ex_retab ex_ni
320 # define ex_startinsert ex_ni
321 # define ex_stopinsert ex_ni
322 # define ex_helptags ex_ni
323 # define ex_sort ex_ni
324 #endif
325 #ifdef FEAT_FIND_ID
326 static void ex_checkpath __ARGS((exarg_T *eap));
327 static void ex_findpat __ARGS((exarg_T *eap));
328 #else
329 # define ex_findpat ex_ni
330 # define ex_checkpath ex_ni
331 #endif
332 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
333 static void ex_psearch __ARGS((exarg_T *eap));
334 #else
335 # define ex_psearch ex_ni
336 #endif
337 static void ex_tag __ARGS((exarg_T *eap));
338 static void ex_tag_cmd __ARGS((exarg_T *eap, char_u *name));
339 #ifndef FEAT_EVAL
340 # define ex_scriptnames ex_ni
341 # define ex_finish ex_ni
342 # define ex_echo ex_ni
343 # define ex_echohl ex_ni
344 # define ex_execute ex_ni
345 # define ex_call ex_ni
346 # define ex_if ex_ni
347 # define ex_endif ex_ni
348 # define ex_else ex_ni
349 # define ex_while ex_ni
350 # define ex_for ex_ni
351 # define ex_continue ex_ni
352 # define ex_break ex_ni
353 # define ex_endwhile ex_ni
354 # define ex_endfor ex_ni
355 # define ex_throw ex_ni
356 # define ex_try ex_ni
357 # define ex_catch ex_ni
358 # define ex_finally ex_ni
359 # define ex_endtry ex_ni
360 # define ex_endfunction ex_ni
361 # define ex_let ex_ni
362 # define ex_unlet ex_ni
363 # define ex_lockvar ex_ni
364 # define ex_unlockvar ex_ni
365 # define ex_function ex_ni
366 # define ex_delfunction ex_ni
367 # define ex_return ex_ni
368 # define ex_oldfiles ex_ni
369 #endif
370 static char_u *arg_all __ARGS((void));
371 #ifdef FEAT_SESSION
372 static int makeopens __ARGS((FILE *fd, char_u *dirnow));
373 static int put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx));
374 static void ex_loadview __ARGS((exarg_T *eap));
375 static char_u *get_view_file __ARGS((int c));
376 static int did_lcd; /* whether ":lcd" was produced for a session */
377 #else
378 # define ex_loadview ex_ni
379 #endif
380 #ifndef FEAT_EVAL
381 # define ex_compiler ex_ni
382 #endif
383 #ifdef FEAT_VIMINFO
384 static void ex_viminfo __ARGS((exarg_T *eap));
385 #else
386 # define ex_viminfo ex_ni
387 #endif
388 static void ex_behave __ARGS((exarg_T *eap));
389 #ifdef FEAT_AUTOCMD
390 static void ex_filetype __ARGS((exarg_T *eap));
391 static void ex_setfiletype __ARGS((exarg_T *eap));
392 #else
393 # define ex_filetype ex_ni
394 # define ex_setfiletype ex_ni
395 #endif
396 #ifndef FEAT_DIFF
397 # define ex_diffoff ex_ni
398 # define ex_diffpatch ex_ni
399 # define ex_diffgetput ex_ni
400 # define ex_diffsplit ex_ni
401 # define ex_diffthis ex_ni
402 # define ex_diffupdate ex_ni
403 #endif
404 static void ex_digraphs __ARGS((exarg_T *eap));
405 static void ex_set __ARGS((exarg_T *eap));
406 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
407 # define ex_options ex_ni
408 #endif
409 #ifdef FEAT_SEARCH_EXTRA
410 static void ex_nohlsearch __ARGS((exarg_T *eap));
411 static void ex_match __ARGS((exarg_T *eap));
412 #else
413 # define ex_nohlsearch ex_ni
414 # define ex_match ex_ni
415 #endif
416 #ifdef FEAT_CRYPT
417 static void ex_X __ARGS((exarg_T *eap));
418 #else
419 # define ex_X ex_ni
420 #endif
421 #ifdef FEAT_FOLDING
422 static void ex_fold __ARGS((exarg_T *eap));
423 static void ex_foldopen __ARGS((exarg_T *eap));
424 static void ex_folddo __ARGS((exarg_T *eap));
425 #else
426 # define ex_fold ex_ni
427 # define ex_foldopen ex_ni
428 # define ex_folddo ex_ni
429 #endif
430 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
431 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
432 # define ex_language ex_ni
433 #endif
434 #ifndef FEAT_SIGNS
435 # define ex_sign ex_ni
436 #endif
437 #ifndef FEAT_SUN_WORKSHOP
438 # define ex_wsverb ex_ni
439 #endif
440 #ifndef FEAT_NETBEANS_INTG
441 # define ex_nbkey ex_ni
442 #endif
444 #ifndef FEAT_EVAL
445 # define ex_debug ex_ni
446 # define ex_breakadd ex_ni
447 # define ex_debuggreedy ex_ni
448 # define ex_breakdel ex_ni
449 # define ex_breaklist ex_ni
450 #endif
452 #ifndef FEAT_CMDHIST
453 # define ex_history ex_ni
454 #endif
455 #ifndef FEAT_JUMPLIST
456 # define ex_jumps ex_ni
457 # define ex_changes ex_ni
458 #endif
460 #ifndef FEAT_PROFILE
461 # define ex_profile ex_ni
462 #endif
465 * Declare cmdnames[].
467 #define DO_DECLARE_EXCMD
468 #include "ex_cmds.h"
471 * Table used to quickly search for a command, based on its first character.
473 static cmdidx_T cmdidxs[27] =
475 CMD_append,
476 CMD_buffer,
477 CMD_change,
478 CMD_delete,
479 CMD_edit,
480 CMD_file,
481 CMD_global,
482 CMD_help,
483 CMD_insert,
484 CMD_join,
485 CMD_k,
486 CMD_list,
487 CMD_move,
488 CMD_next,
489 CMD_open,
490 CMD_print,
491 CMD_quit,
492 CMD_read,
493 CMD_substitute,
494 CMD_t,
495 CMD_undo,
496 CMD_vglobal,
497 CMD_write,
498 CMD_xit,
499 CMD_yank,
500 CMD_z,
501 CMD_bang
504 static char_u dollar_command[2] = {'$', 0};
507 #ifdef FEAT_EVAL
508 /* Struct for storing a line inside a while/for loop */
509 typedef struct
511 char_u *line; /* command line */
512 linenr_T lnum; /* sourcing_lnum of the line */
513 } wcmd_T;
516 * Structure used to store info for line position in a while or for loop.
517 * This is required, because do_one_cmd() may invoke ex_function(), which
518 * reads more lines that may come from the while/for loop.
520 struct loop_cookie
522 garray_T *lines_gap; /* growarray with line info */
523 int current_line; /* last read line from growarray */
524 int repeating; /* TRUE when looping a second time */
525 /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
526 char_u *(*getline) __ARGS((int, void *, int));
527 void *cookie;
530 static char_u *get_loop_line __ARGS((int c, void *cookie, int indent));
531 static int store_loop_line __ARGS((garray_T *gap, char_u *line));
532 static void free_cmdlines __ARGS((garray_T *gap));
534 /* Struct to save a few things while debugging. Used in do_cmdline() only. */
535 struct dbg_stuff
537 int trylevel;
538 int force_abort;
539 except_T *caught_stack;
540 char_u *vv_exception;
541 char_u *vv_throwpoint;
542 int did_emsg;
543 int got_int;
544 int did_throw;
545 int need_rethrow;
546 int check_cstack;
547 except_T *current_exception;
550 static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp));
551 static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp));
553 static void
554 save_dbg_stuff(dsp)
555 struct dbg_stuff *dsp;
557 dsp->trylevel = trylevel; trylevel = 0;
558 dsp->force_abort = force_abort; force_abort = FALSE;
559 dsp->caught_stack = caught_stack; caught_stack = NULL;
560 dsp->vv_exception = v_exception(NULL);
561 dsp->vv_throwpoint = v_throwpoint(NULL);
563 /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
564 dsp->did_emsg = did_emsg; did_emsg = FALSE;
565 dsp->got_int = got_int; got_int = FALSE;
566 dsp->did_throw = did_throw; did_throw = FALSE;
567 dsp->need_rethrow = need_rethrow; need_rethrow = FALSE;
568 dsp->check_cstack = check_cstack; check_cstack = FALSE;
569 dsp->current_exception = current_exception; current_exception = NULL;
572 static void
573 restore_dbg_stuff(dsp)
574 struct dbg_stuff *dsp;
576 suppress_errthrow = FALSE;
577 trylevel = dsp->trylevel;
578 force_abort = dsp->force_abort;
579 caught_stack = dsp->caught_stack;
580 (void)v_exception(dsp->vv_exception);
581 (void)v_throwpoint(dsp->vv_throwpoint);
582 did_emsg = dsp->did_emsg;
583 got_int = dsp->got_int;
584 did_throw = dsp->did_throw;
585 need_rethrow = dsp->need_rethrow;
586 check_cstack = dsp->check_cstack;
587 current_exception = dsp->current_exception;
589 #endif
593 * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
594 * command is given.
596 void
597 do_exmode(improved)
598 int improved; /* TRUE for "improved Ex" mode */
600 int save_msg_scroll;
601 int prev_msg_row;
602 linenr_T prev_line;
603 int changedtick;
605 if (improved)
606 exmode_active = EXMODE_VIM;
607 else
608 exmode_active = EXMODE_NORMAL;
609 State = NORMAL;
611 /* When using ":global /pat/ visual" and then "Q" we return to continue
612 * the :global command. */
613 if (global_busy)
614 return;
616 save_msg_scroll = msg_scroll;
617 ++RedrawingDisabled; /* don't redisplay the window */
618 ++no_wait_return; /* don't wait for return */
619 #ifdef FEAT_GUI
620 /* Ignore scrollbar and mouse events in Ex mode */
621 ++hold_gui_events;
622 #endif
623 #ifdef FEAT_SNIFF
624 want_sniff_request = 0; /* No K_SNIFF wanted */
625 #endif
627 MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode."));
628 while (exmode_active)
630 #ifdef FEAT_EX_EXTRA
631 /* Check for a ":normal" command and no more characters left. */
632 if (ex_normal_busy > 0 && typebuf.tb_len == 0)
634 exmode_active = FALSE;
635 break;
637 #endif
638 msg_scroll = TRUE;
639 need_wait_return = FALSE;
640 ex_pressedreturn = FALSE;
641 ex_no_reprint = FALSE;
642 changedtick = curbuf->b_changedtick;
643 prev_msg_row = msg_row;
644 prev_line = curwin->w_cursor.lnum;
645 #ifdef FEAT_SNIFF
646 ProcessSniffRequests();
647 #endif
648 if (improved)
650 cmdline_row = msg_row;
651 do_cmdline(NULL, getexline, NULL, 0);
653 else
654 do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
655 lines_left = Rows - 1;
657 if ((prev_line != curwin->w_cursor.lnum
658 || changedtick != curbuf->b_changedtick) && !ex_no_reprint)
660 if (curbuf->b_ml.ml_flags & ML_EMPTY)
661 EMSG(_(e_emptybuf));
662 else
664 if (ex_pressedreturn)
666 /* go up one line, to overwrite the ":<CR>" line, so the
667 * output doesn't contain empty lines. */
668 msg_row = prev_msg_row;
669 if (prev_msg_row == Rows - 1)
670 msg_row--;
672 msg_col = 0;
673 print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE);
674 msg_clr_eos();
677 else if (ex_pressedreturn && !ex_no_reprint) /* must be at EOF */
679 if (curbuf->b_ml.ml_flags & ML_EMPTY)
680 EMSG(_(e_emptybuf));
681 else
682 EMSG(_("E501: At end-of-file"));
686 #ifdef FEAT_GUI
687 --hold_gui_events;
688 #endif
689 --RedrawingDisabled;
690 --no_wait_return;
691 update_screen(CLEAR);
692 need_wait_return = FALSE;
693 msg_scroll = save_msg_scroll;
697 * Execute a simple command line. Used for translated commands like "*".
700 do_cmdline_cmd(cmd)
701 char_u *cmd;
703 return do_cmdline(cmd, NULL, NULL,
704 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
708 * do_cmdline(): execute one Ex command line
710 * 1. Execute "cmdline" when it is not NULL.
711 * If "cmdline" is NULL, or more lines are needed, getline() is used.
712 * 2. Split up in parts separated with '|'.
714 * This function can be called recursively!
716 * flags:
717 * DOCMD_VERBOSE - The command will be included in the error message.
718 * DOCMD_NOWAIT - Don't call wait_return() and friends.
719 * DOCMD_REPEAT - Repeat execution until getline() returns NULL.
720 * DOCMD_KEYTYPED - Don't reset KeyTyped.
721 * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
722 * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
724 * return FAIL if cmdline could not be executed, OK otherwise
727 do_cmdline(cmdline, getline, cookie, flags)
728 char_u *cmdline;
729 char_u *(*getline) __ARGS((int, void *, int));
730 void *cookie; /* argument for getline() */
731 int flags;
733 char_u *next_cmdline; /* next cmd to execute */
734 char_u *cmdline_copy = NULL; /* copy of cmd line */
735 int used_getline = FALSE; /* used "getline" to obtain command */
736 static int recursive = 0; /* recursive depth */
737 int msg_didout_before_start = 0;
738 int count = 0; /* line number count */
739 int did_inc = FALSE; /* incremented RedrawingDisabled */
740 int retval = OK;
741 #ifdef FEAT_EVAL
742 struct condstack cstack; /* conditional stack */
743 garray_T lines_ga; /* keep lines for ":while"/":for" */
744 int current_line = 0; /* active line in lines_ga */
745 char_u *fname = NULL; /* function or script name */
746 linenr_T *breakpoint = NULL; /* ptr to breakpoint field in cookie */
747 int *dbg_tick = NULL; /* ptr to dbg_tick field in cookie */
748 struct dbg_stuff debug_saved; /* saved things for debug mode */
749 int initial_trylevel;
750 struct msglist **saved_msg_list = NULL;
751 struct msglist *private_msg_list;
753 /* "getline" and "cookie" passed to do_one_cmd() */
754 char_u *(*cmd_getline) __ARGS((int, void *, int));
755 void *cmd_cookie;
756 struct loop_cookie cmd_loop_cookie;
757 void *real_cookie;
758 int getline_is_func;
759 #else
760 # define cmd_getline getline
761 # define cmd_cookie cookie
762 #endif
763 static int call_depth = 0; /* recursiveness */
765 #ifdef FEAT_EVAL
766 /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
767 * location for storing error messages to be converted to an exception.
768 * This ensures that the do_errthrow() call in do_one_cmd() does not
769 * combine the messages stored by an earlier invocation of do_one_cmd()
770 * with the command name of the later one. This would happen when
771 * BufWritePost autocommands are executed after a write error. */
772 saved_msg_list = msg_list;
773 msg_list = &private_msg_list;
774 private_msg_list = NULL;
775 #endif
777 /* It's possible to create an endless loop with ":execute", catch that
778 * here. The value of 200 allows nested function calls, ":source", etc. */
779 if (call_depth == 200)
781 EMSG(_("E169: Command too recursive"));
782 #ifdef FEAT_EVAL
783 /* When converting to an exception, we do not include the command name
784 * since this is not an error of the specific command. */
785 do_errthrow((struct condstack *)NULL, (char_u *)NULL);
786 msg_list = saved_msg_list;
787 #endif
788 return FAIL;
790 ++call_depth;
792 #ifdef FEAT_EVAL
793 cstack.cs_idx = -1;
794 cstack.cs_looplevel = 0;
795 cstack.cs_trylevel = 0;
796 cstack.cs_emsg_silent_list = NULL;
797 cstack.cs_lflags = 0;
798 ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
800 real_cookie = getline_cookie(getline, cookie);
802 /* Inside a function use a higher nesting level. */
803 getline_is_func = getline_equal(getline, cookie, get_func_line);
804 if (getline_is_func && ex_nesting_level == func_level(real_cookie))
805 ++ex_nesting_level;
807 /* Get the function or script name and the address where the next breakpoint
808 * line and the debug tick for a function or script are stored. */
809 if (getline_is_func)
811 fname = func_name(real_cookie);
812 breakpoint = func_breakpoint(real_cookie);
813 dbg_tick = func_dbg_tick(real_cookie);
815 else if (getline_equal(getline, cookie, getsourceline))
817 fname = sourcing_name;
818 breakpoint = source_breakpoint(real_cookie);
819 dbg_tick = source_dbg_tick(real_cookie);
823 * Initialize "force_abort" and "suppress_errthrow" at the top level.
825 if (!recursive)
827 force_abort = FALSE;
828 suppress_errthrow = FALSE;
832 * If requested, store and reset the global values controlling the
833 * exception handling (used when debugging). Otherwise clear it to avoid
834 * a bogus compiler warning when the optimizer uses inline functions...
836 if (flags & DOCMD_EXCRESET)
837 save_dbg_stuff(&debug_saved);
838 else
839 memset(&debug_saved, 0, 1);
841 initial_trylevel = trylevel;
844 * "did_throw" will be set to TRUE when an exception is being thrown.
846 did_throw = FALSE;
847 #endif
849 * "did_emsg" will be set to TRUE when emsg() is used, in which case we
850 * cancel the whole command line, and any if/endif or loop.
851 * If force_abort is set, we cancel everything.
853 did_emsg = FALSE;
856 * KeyTyped is only set when calling vgetc(). Reset it here when not
857 * calling vgetc() (sourced command lines).
859 if (!(flags & DOCMD_KEYTYPED) && !getline_equal(getline, cookie, getexline))
860 KeyTyped = FALSE;
863 * Continue executing command lines:
864 * - when inside an ":if", ":while" or ":for"
865 * - for multiple commands on one line, separated with '|'
866 * - when repeating until there are no more lines (for ":source")
868 next_cmdline = cmdline;
871 #ifdef FEAT_EVAL
872 getline_is_func = getline_equal(getline, cookie, get_func_line);
873 #endif
875 /* stop skipping cmds for an error msg after all endif/while/for */
876 if (next_cmdline == NULL
877 #ifdef FEAT_EVAL
878 && !force_abort
879 && cstack.cs_idx < 0
880 && !(getline_is_func && func_has_abort(real_cookie))
881 #endif
883 did_emsg = FALSE;
886 * 1. If repeating a line in a loop, get a line from lines_ga.
887 * 2. If no line given: Get an allocated line with getline().
888 * 3. If a line is given: Make a copy, so we can mess with it.
891 #ifdef FEAT_EVAL
892 /* 1. If repeating, get a previous line from lines_ga. */
893 if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
895 /* Each '|' separated command is stored separately in lines_ga, to
896 * be able to jump to it. Don't use next_cmdline now. */
897 vim_free(cmdline_copy);
898 cmdline_copy = NULL;
900 /* Check if a function has returned or, unless it has an unclosed
901 * try conditional, aborted. */
902 if (getline_is_func)
904 # ifdef FEAT_PROFILE
905 if (do_profiling == PROF_YES)
906 func_line_end(real_cookie);
907 # endif
908 if (func_has_ended(real_cookie))
910 retval = FAIL;
911 break;
914 #ifdef FEAT_PROFILE
915 else if (do_profiling == PROF_YES
916 && getline_equal(getline, cookie, getsourceline))
917 script_line_end();
918 #endif
920 /* Check if a sourced file hit a ":finish" command. */
921 if (source_finished(getline, cookie))
923 retval = FAIL;
924 break;
927 /* If breakpoints have been added/deleted need to check for it. */
928 if (breakpoint != NULL && dbg_tick != NULL
929 && *dbg_tick != debug_tick)
931 *breakpoint = dbg_find_breakpoint(
932 getline_equal(getline, cookie, getsourceline),
933 fname, sourcing_lnum);
934 *dbg_tick = debug_tick;
937 next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
938 sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
940 /* Did we encounter a breakpoint? */
941 if (breakpoint != NULL && *breakpoint != 0
942 && *breakpoint <= sourcing_lnum)
944 dbg_breakpoint(fname, sourcing_lnum);
945 /* Find next breakpoint. */
946 *breakpoint = dbg_find_breakpoint(
947 getline_equal(getline, cookie, getsourceline),
948 fname, sourcing_lnum);
949 *dbg_tick = debug_tick;
951 # ifdef FEAT_PROFILE
952 if (do_profiling == PROF_YES)
954 if (getline_is_func)
955 func_line_start(real_cookie);
956 else if (getline_equal(getline, cookie, getsourceline))
957 script_line_start();
959 # endif
962 if (cstack.cs_looplevel > 0)
964 /* Inside a while/for loop we need to store the lines and use them
965 * again. Pass a different "getline" function to do_one_cmd()
966 * below, so that it stores lines in or reads them from
967 * "lines_ga". Makes it possible to define a function inside a
968 * while/for loop. */
969 cmd_getline = get_loop_line;
970 cmd_cookie = (void *)&cmd_loop_cookie;
971 cmd_loop_cookie.lines_gap = &lines_ga;
972 cmd_loop_cookie.current_line = current_line;
973 cmd_loop_cookie.getline = getline;
974 cmd_loop_cookie.cookie = cookie;
975 cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
977 else
979 cmd_getline = getline;
980 cmd_cookie = cookie;
982 #endif
984 /* 2. If no line given, get an allocated line with getline(). */
985 if (next_cmdline == NULL)
988 * Need to set msg_didout for the first line after an ":if",
989 * otherwise the ":if" will be overwritten.
991 if (count == 1 && getline_equal(getline, cookie, getexline))
992 msg_didout = TRUE;
993 if (getline == NULL || (next_cmdline = getline(':', cookie,
994 #ifdef FEAT_EVAL
995 cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
996 #else
998 #endif
999 )) == NULL)
1001 /* Don't call wait_return for aborted command line. The NULL
1002 * returned for the end of a sourced file or executed function
1003 * doesn't do this. */
1004 if (KeyTyped && !(flags & DOCMD_REPEAT))
1005 need_wait_return = FALSE;
1006 retval = FAIL;
1007 break;
1009 used_getline = TRUE;
1012 * Keep the first typed line. Clear it when more lines are typed.
1014 if (flags & DOCMD_KEEPLINE)
1016 vim_free(repeat_cmdline);
1017 if (count == 0)
1018 repeat_cmdline = vim_strsave(next_cmdline);
1019 else
1020 repeat_cmdline = NULL;
1024 /* 3. Make a copy of the command so we can mess with it. */
1025 else if (cmdline_copy == NULL)
1027 next_cmdline = vim_strsave(next_cmdline);
1028 if (next_cmdline == NULL)
1030 EMSG(_(e_outofmem));
1031 retval = FAIL;
1032 break;
1035 cmdline_copy = next_cmdline;
1037 #ifdef FEAT_EVAL
1039 * Save the current line when inside a ":while" or ":for", and when
1040 * the command looks like a ":while" or ":for", because we may need it
1041 * later. When there is a '|' and another command, it is stored
1042 * separately, because we need to be able to jump back to it from an
1043 * :endwhile/:endfor.
1045 if (current_line == lines_ga.ga_len
1046 && (cstack.cs_looplevel || has_loop_cmd(next_cmdline)))
1048 if (store_loop_line(&lines_ga, next_cmdline) == FAIL)
1050 retval = FAIL;
1051 break;
1054 did_endif = FALSE;
1055 #endif
1057 if (count++ == 0)
1060 * All output from the commands is put below each other, without
1061 * waiting for a return. Don't do this when executing commands
1062 * from a script or when being called recursive (e.g. for ":e
1063 * +command file").
1065 if (!(flags & DOCMD_NOWAIT) && !recursive)
1067 msg_didout_before_start = msg_didout;
1068 msg_didany = FALSE; /* no output yet */
1069 msg_start();
1070 msg_scroll = TRUE; /* put messages below each other */
1071 ++no_wait_return; /* dont wait for return until finished */
1072 ++RedrawingDisabled;
1073 did_inc = TRUE;
1077 if (p_verbose >= 15 && sourcing_name != NULL)
1079 ++no_wait_return;
1080 verbose_enter_scroll();
1082 smsg((char_u *)_("line %ld: %s"),
1083 (long)sourcing_lnum, cmdline_copy);
1084 if (msg_silent == 0)
1085 msg_puts((char_u *)"\n"); /* don't overwrite this */
1087 verbose_leave_scroll();
1088 --no_wait_return;
1092 * 2. Execute one '|' separated command.
1093 * do_one_cmd() will return NULL if there is no trailing '|'.
1094 * "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1096 ++recursive;
1097 next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1098 #ifdef FEAT_EVAL
1099 &cstack,
1100 #endif
1101 cmd_getline, cmd_cookie);
1102 --recursive;
1104 #ifdef FEAT_EVAL
1105 if (cmd_cookie == (void *)&cmd_loop_cookie)
1106 /* Use "current_line" from "cmd_loop_cookie", it may have been
1107 * incremented when defining a function. */
1108 current_line = cmd_loop_cookie.current_line;
1109 #endif
1111 if (next_cmdline == NULL)
1113 vim_free(cmdline_copy);
1114 cmdline_copy = NULL;
1115 #ifdef FEAT_CMDHIST
1117 * If the command was typed, remember it for the ':' register.
1118 * Do this AFTER executing the command to make :@: work.
1120 if (getline_equal(getline, cookie, getexline)
1121 && new_last_cmdline != NULL)
1123 vim_free(last_cmdline);
1124 last_cmdline = new_last_cmdline;
1125 new_last_cmdline = NULL;
1127 #endif
1129 else
1131 /* need to copy the command after the '|' to cmdline_copy, for the
1132 * next do_one_cmd() */
1133 STRMOVE(cmdline_copy, next_cmdline);
1134 next_cmdline = cmdline_copy;
1138 #ifdef FEAT_EVAL
1139 /* reset did_emsg for a function that is not aborted by an error */
1140 if (did_emsg && !force_abort
1141 && getline_equal(getline, cookie, get_func_line)
1142 && !func_has_abort(real_cookie))
1143 did_emsg = FALSE;
1145 if (cstack.cs_looplevel > 0)
1147 ++current_line;
1150 * An ":endwhile", ":endfor" and ":continue" is handled here.
1151 * If we were executing commands, jump back to the ":while" or
1152 * ":for".
1153 * If we were not executing commands, decrement cs_looplevel.
1155 if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
1157 cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
1159 /* Jump back to the matching ":while" or ":for". Be careful
1160 * not to use a cs_line[] from an entry that isn't a ":while"
1161 * or ":for": It would make "current_line" invalid and can
1162 * cause a crash. */
1163 if (!did_emsg && !got_int && !did_throw
1164 && cstack.cs_idx >= 0
1165 && (cstack.cs_flags[cstack.cs_idx]
1166 & (CSF_WHILE | CSF_FOR))
1167 && cstack.cs_line[cstack.cs_idx] >= 0
1168 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1170 current_line = cstack.cs_line[cstack.cs_idx];
1171 /* remember we jumped there */
1172 cstack.cs_lflags |= CSL_HAD_LOOP;
1173 line_breakcheck(); /* check if CTRL-C typed */
1175 /* Check for the next breakpoint at or after the ":while"
1176 * or ":for". */
1177 if (breakpoint != NULL)
1179 *breakpoint = dbg_find_breakpoint(
1180 getline_equal(getline, cookie, getsourceline),
1181 fname,
1182 ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1183 *dbg_tick = debug_tick;
1186 else
1188 /* can only get here with ":endwhile" or ":endfor" */
1189 if (cstack.cs_idx >= 0)
1190 rewind_conditionals(&cstack, cstack.cs_idx - 1,
1191 CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
1196 * For a ":while" or ":for" we need to remember the line number.
1198 else if (cstack.cs_lflags & CSL_HAD_LOOP)
1200 cstack.cs_lflags &= ~CSL_HAD_LOOP;
1201 cstack.cs_line[cstack.cs_idx] = current_line - 1;
1206 * When not inside any ":while" loop, clear remembered lines.
1208 if (cstack.cs_looplevel == 0)
1210 if (lines_ga.ga_len > 0)
1212 sourcing_lnum =
1213 ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1214 free_cmdlines(&lines_ga);
1216 current_line = 0;
1220 * A ":finally" makes did_emsg, got_int, and did_throw pending for
1221 * being restored at the ":endtry". Reset them here and set the
1222 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
1223 * This includes the case where a missing ":endif", ":endwhile" or
1224 * ":endfor" was detected by the ":finally" itself.
1226 if (cstack.cs_lflags & CSL_HAD_FINA)
1228 cstack.cs_lflags &= ~CSL_HAD_FINA;
1229 report_make_pending(cstack.cs_pending[cstack.cs_idx]
1230 & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1231 did_throw ? (void *)current_exception : NULL);
1232 did_emsg = got_int = did_throw = FALSE;
1233 cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1236 /* Update global "trylevel" for recursive calls to do_cmdline() from
1237 * within this loop. */
1238 trylevel = initial_trylevel + cstack.cs_trylevel;
1241 * If the outermost try conditional (across function calls and sourced
1242 * files) is aborted because of an error, an interrupt, or an uncaught
1243 * exception, cancel everything. If it is left normally, reset
1244 * force_abort to get the non-EH compatible abortion behavior for
1245 * the rest of the script.
1247 if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1248 force_abort = FALSE;
1250 /* Convert an interrupt to an exception if appropriate. */
1251 (void)do_intthrow(&cstack);
1252 #endif /* FEAT_EVAL */
1256 * Continue executing command lines when:
1257 * - no CTRL-C typed, no aborting error, no exception thrown or try
1258 * conditionals need to be checked for executing finally clauses or
1259 * catching an interrupt exception
1260 * - didn't get an error message or lines are not typed
1261 * - there is a command after '|', inside a :if, :while, :for or :try, or
1262 * looping for ":source" command or function call.
1264 while (!((got_int
1265 #ifdef FEAT_EVAL
1266 || (did_emsg && force_abort) || did_throw
1267 #endif
1269 #ifdef FEAT_EVAL
1270 && cstack.cs_trylevel == 0
1271 #endif
1273 && !(did_emsg && used_getline
1274 && (getline_equal(getline, cookie, getexmodeline)
1275 || getline_equal(getline, cookie, getexline)))
1276 && (next_cmdline != NULL
1277 #ifdef FEAT_EVAL
1278 || cstack.cs_idx >= 0
1279 #endif
1280 || (flags & DOCMD_REPEAT)));
1282 vim_free(cmdline_copy);
1283 #ifdef FEAT_EVAL
1284 free_cmdlines(&lines_ga);
1285 ga_clear(&lines_ga);
1287 if (cstack.cs_idx >= 0)
1290 * If a sourced file or executed function ran to its end, report the
1291 * unclosed conditional.
1293 if (!got_int && !did_throw
1294 && ((getline_equal(getline, cookie, getsourceline)
1295 && !source_finished(getline, cookie))
1296 || (getline_equal(getline, cookie, get_func_line)
1297 && !func_has_ended(real_cookie))))
1299 if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1300 EMSG(_(e_endtry));
1301 else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1302 EMSG(_(e_endwhile));
1303 else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
1304 EMSG(_(e_endfor));
1305 else
1306 EMSG(_(e_endif));
1310 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1311 * ":endtry" in a sourced file or executed function. If the try
1312 * conditional is in its finally clause, ignore anything pending.
1313 * If it is in a catch clause, finish the caught exception.
1314 * Also cleanup any "cs_forinfo" structures.
1318 int idx = cleanup_conditionals(&cstack, 0, TRUE);
1320 if (idx >= 0)
1321 --idx; /* remove try block not in its finally clause */
1322 rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
1323 &cstack.cs_looplevel);
1325 while (cstack.cs_idx >= 0);
1326 trylevel = initial_trylevel;
1329 /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
1330 * lack was reported above and the error message is to be converted to an
1331 * exception, do this now after rewinding the cstack. */
1332 do_errthrow(&cstack, getline_equal(getline, cookie, get_func_line)
1333 ? (char_u *)"endfunction" : (char_u *)NULL);
1335 if (trylevel == 0)
1338 * When an exception is being thrown out of the outermost try
1339 * conditional, discard the uncaught exception, disable the conversion
1340 * of interrupts or errors to exceptions, and ensure that no more
1341 * commands are executed.
1343 if (did_throw)
1345 void *p = NULL;
1346 char_u *saved_sourcing_name;
1347 int saved_sourcing_lnum;
1348 struct msglist *messages = NULL, *next;
1351 * If the uncaught exception is a user exception, report it as an
1352 * error. If it is an error exception, display the saved error
1353 * message now. For an interrupt exception, do nothing; the
1354 * interrupt message is given elsewhere.
1356 switch (current_exception->type)
1358 case ET_USER:
1359 vim_snprintf((char *)IObuff, IOSIZE,
1360 _("E605: Exception not caught: %s"),
1361 current_exception->value);
1362 p = vim_strsave(IObuff);
1363 break;
1364 case ET_ERROR:
1365 messages = current_exception->messages;
1366 current_exception->messages = NULL;
1367 break;
1368 case ET_INTERRUPT:
1369 break;
1370 default:
1371 p = vim_strsave((char_u *)_(e_internal));
1374 saved_sourcing_name = sourcing_name;
1375 saved_sourcing_lnum = sourcing_lnum;
1376 sourcing_name = current_exception->throw_name;
1377 sourcing_lnum = current_exception->throw_lnum;
1378 current_exception->throw_name = NULL;
1380 discard_current_exception(); /* uses IObuff if 'verbose' */
1381 suppress_errthrow = TRUE;
1382 force_abort = TRUE;
1384 if (messages != NULL)
1388 next = messages->next;
1389 emsg(messages->msg);
1390 vim_free(messages->msg);
1391 vim_free(messages);
1392 messages = next;
1394 while (messages != NULL);
1396 else if (p != NULL)
1398 emsg(p);
1399 vim_free(p);
1401 vim_free(sourcing_name);
1402 sourcing_name = saved_sourcing_name;
1403 sourcing_lnum = saved_sourcing_lnum;
1407 * On an interrupt or an aborting error not converted to an exception,
1408 * disable the conversion of errors to exceptions. (Interrupts are not
1409 * converted any more, here.) This enables also the interrupt message
1410 * when force_abort is set and did_emsg unset in case of an interrupt
1411 * from a finally clause after an error.
1413 else if (got_int || (did_emsg && force_abort))
1414 suppress_errthrow = TRUE;
1418 * The current cstack will be freed when do_cmdline() returns. An uncaught
1419 * exception will have to be rethrown in the previous cstack. If a function
1420 * has just returned or a script file was just finished and the previous
1421 * cstack belongs to the same function or, respectively, script file, it
1422 * will have to be checked for finally clauses to be executed due to the
1423 * ":return" or ":finish". This is done in do_one_cmd().
1425 if (did_throw)
1426 need_rethrow = TRUE;
1427 if ((getline_equal(getline, cookie, getsourceline)
1428 && ex_nesting_level > source_level(real_cookie))
1429 || (getline_equal(getline, cookie, get_func_line)
1430 && ex_nesting_level > func_level(real_cookie) + 1))
1432 if (!did_throw)
1433 check_cstack = TRUE;
1435 else
1437 /* When leaving a function, reduce nesting level. */
1438 if (getline_equal(getline, cookie, get_func_line))
1439 --ex_nesting_level;
1441 * Go to debug mode when returning from a function in which we are
1442 * single-stepping.
1444 if ((getline_equal(getline, cookie, getsourceline)
1445 || getline_equal(getline, cookie, get_func_line))
1446 && ex_nesting_level + 1 <= debug_break_level)
1447 do_debug(getline_equal(getline, cookie, getsourceline)
1448 ? (char_u *)_("End of sourced file")
1449 : (char_u *)_("End of function"));
1453 * Restore the exception environment (done after returning from the
1454 * debugger).
1456 if (flags & DOCMD_EXCRESET)
1457 restore_dbg_stuff(&debug_saved);
1459 msg_list = saved_msg_list;
1460 #endif /* FEAT_EVAL */
1463 * If there was too much output to fit on the command line, ask the user to
1464 * hit return before redrawing the screen. With the ":global" command we do
1465 * this only once after the command is finished.
1467 if (did_inc)
1469 --RedrawingDisabled;
1470 --no_wait_return;
1471 msg_scroll = FALSE;
1474 * When just finished an ":if"-":else" which was typed, no need to
1475 * wait for hit-return. Also for an error situation.
1477 if (retval == FAIL
1478 #ifdef FEAT_EVAL
1479 || (did_endif && KeyTyped && !did_emsg)
1480 #endif
1483 need_wait_return = FALSE;
1484 msg_didany = FALSE; /* don't wait when restarting edit */
1486 else if (need_wait_return)
1489 * The msg_start() above clears msg_didout. The wait_return we do
1490 * here should not overwrite the command that may be shown before
1491 * doing that.
1493 msg_didout |= msg_didout_before_start;
1494 wait_return(FALSE);
1498 #ifndef FEAT_EVAL
1500 * Reset if_level, in case a sourced script file contains more ":if" than
1501 * ":endif" (could be ":if x | foo | endif").
1503 if_level = 0;
1504 #endif
1506 --call_depth;
1507 return retval;
1510 #ifdef FEAT_EVAL
1512 * Obtain a line when inside a ":while" or ":for" loop.
1514 static char_u *
1515 get_loop_line(c, cookie, indent)
1516 int c;
1517 void *cookie;
1518 int indent;
1520 struct loop_cookie *cp = (struct loop_cookie *)cookie;
1521 wcmd_T *wp;
1522 char_u *line;
1524 if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1526 if (cp->repeating)
1527 return NULL; /* trying to read past ":endwhile"/":endfor" */
1529 /* First time inside the ":while"/":for": get line normally. */
1530 if (cp->getline == NULL)
1531 line = getcmdline(c, 0L, indent);
1532 else
1533 line = cp->getline(c, cp->cookie, indent);
1534 if (line != NULL && store_loop_line(cp->lines_gap, line) == OK)
1535 ++cp->current_line;
1537 return line;
1540 KeyTyped = FALSE;
1541 ++cp->current_line;
1542 wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1543 sourcing_lnum = wp->lnum;
1544 return vim_strsave(wp->line);
1548 * Store a line in "gap" so that a ":while" loop can execute it again.
1550 static int
1551 store_loop_line(gap, line)
1552 garray_T *gap;
1553 char_u *line;
1555 if (ga_grow(gap, 1) == FAIL)
1556 return FAIL;
1557 ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1558 ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1559 ++gap->ga_len;
1560 return OK;
1564 * Free the lines stored for a ":while" or ":for" loop.
1566 static void
1567 free_cmdlines(gap)
1568 garray_T *gap;
1570 while (gap->ga_len > 0)
1572 vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1573 --gap->ga_len;
1576 #endif
1579 * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals
1580 * "func". * Otherwise return TRUE when "fgetline" equals "func".
1583 getline_equal(fgetline, cookie, func)
1584 char_u *(*fgetline) __ARGS((int, void *, int));
1585 void *cookie UNUSED; /* argument for fgetline() */
1586 char_u *(*func) __ARGS((int, void *, int));
1588 #ifdef FEAT_EVAL
1589 char_u *(*gp) __ARGS((int, void *, int));
1590 struct loop_cookie *cp;
1592 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1593 * function that's originally used to obtain the lines. This may be
1594 * nested several levels. */
1595 gp = fgetline;
1596 cp = (struct loop_cookie *)cookie;
1597 while (gp == get_loop_line)
1599 gp = cp->getline;
1600 cp = cp->cookie;
1602 return gp == func;
1603 #else
1604 return fgetline == func;
1605 #endif
1608 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1610 * If "fgetline" is get_loop_line(), return the cookie used by the original
1611 * getline function. Otherwise return "cookie".
1613 void *
1614 getline_cookie(fgetline, cookie)
1615 char_u *(*fgetline) __ARGS((int, void *, int)) UNUSED;
1616 void *cookie; /* argument for fgetline() */
1618 # ifdef FEAT_EVAL
1619 char_u *(*gp) __ARGS((int, void *, int));
1620 struct loop_cookie *cp;
1622 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1623 * cookie that's originally used to obtain the lines. This may be nested
1624 * several levels. */
1625 gp = fgetline;
1626 cp = (struct loop_cookie *)cookie;
1627 while (gp == get_loop_line)
1629 gp = cp->getline;
1630 cp = cp->cookie;
1632 return cp;
1633 # else
1634 return cookie;
1635 # endif
1637 #endif
1640 * Execute one Ex command.
1642 * If 'sourcing' is TRUE, the command will be included in the error message.
1644 * 1. skip comment lines and leading space
1645 * 2. handle command modifiers
1646 * 3. parse range
1647 * 4. parse command
1648 * 5. parse arguments
1649 * 6. switch on command name
1651 * Note: "fgetline" can be NULL.
1653 * This function may be called recursively!
1655 #if (_MSC_VER == 1200)
1657 * Avoid optimisation bug in VC++ version 6.0
1659 #pragma optimize( "g", off )
1660 #endif
1661 static char_u *
1662 do_one_cmd(cmdlinep, sourcing,
1663 #ifdef FEAT_EVAL
1664 cstack,
1665 #endif
1666 fgetline, cookie)
1667 char_u **cmdlinep;
1668 int sourcing;
1669 #ifdef FEAT_EVAL
1670 struct condstack *cstack;
1671 #endif
1672 char_u *(*fgetline) __ARGS((int, void *, int));
1673 void *cookie; /* argument for fgetline() */
1675 char_u *p;
1676 linenr_T lnum;
1677 long n;
1678 char_u *errormsg = NULL; /* error message */
1679 exarg_T ea; /* Ex command arguments */
1680 long verbose_save = -1;
1681 int save_msg_scroll = msg_scroll;
1682 int save_msg_silent = -1;
1683 int did_esilent = 0;
1684 #ifdef HAVE_SANDBOX
1685 int did_sandbox = FALSE;
1686 #endif
1687 cmdmod_T save_cmdmod;
1688 int ni; /* set when Not Implemented */
1690 vim_memset(&ea, 0, sizeof(ea));
1691 ea.line1 = 1;
1692 ea.line2 = 1;
1693 #ifdef FEAT_EVAL
1694 ++ex_nesting_level;
1695 #endif
1697 /* when not editing the last file :q has to be typed twice */
1698 if (quitmore
1699 #ifdef FEAT_EVAL
1700 /* avoid that a function call in 'statusline' does this */
1701 && !getline_equal(fgetline, cookie, get_func_line)
1702 #endif
1704 --quitmore;
1707 * Reset browse, confirm, etc.. They are restored when returning, for
1708 * recursive calls.
1710 save_cmdmod = cmdmod;
1711 vim_memset(&cmdmod, 0, sizeof(cmdmod));
1713 /* "#!anything" is handled like a comment. */
1714 if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!')
1715 goto doend;
1718 * Repeat until no more command modifiers are found.
1720 ea.cmd = *cmdlinep;
1721 for (;;)
1724 * 1. skip comment lines and leading white space and colons
1726 while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1727 ++ea.cmd;
1729 /* in ex mode, an empty line works like :+ */
1730 if (*ea.cmd == NUL && exmode_active
1731 && (getline_equal(fgetline, cookie, getexmodeline)
1732 || getline_equal(fgetline, cookie, getexline))
1733 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1735 ea.cmd = (char_u *)"+";
1736 ex_pressedreturn = TRUE;
1739 /* ignore comment and empty lines */
1740 if (*ea.cmd == '"')
1741 goto doend;
1742 if (*ea.cmd == NUL)
1744 ex_pressedreturn = TRUE;
1745 goto doend;
1749 * 2. handle command modifiers.
1751 p = ea.cmd;
1752 if (VIM_ISDIGIT(*ea.cmd))
1753 p = skipwhite(skipdigits(ea.cmd));
1754 switch (*p)
1756 /* When adding an entry, also modify cmd_exists(). */
1757 case 'a': if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1758 break;
1759 #ifdef FEAT_WINDOWS
1760 cmdmod.split |= WSP_ABOVE;
1761 #endif
1762 continue;
1764 case 'b': if (checkforcmd(&ea.cmd, "belowright", 3))
1766 #ifdef FEAT_WINDOWS
1767 cmdmod.split |= WSP_BELOW;
1768 #endif
1769 continue;
1771 if (checkforcmd(&ea.cmd, "browse", 3))
1773 #ifdef FEAT_BROWSE_CMD
1774 cmdmod.browse = TRUE;
1775 #endif
1776 continue;
1778 if (!checkforcmd(&ea.cmd, "botright", 2))
1779 break;
1780 #ifdef FEAT_WINDOWS
1781 cmdmod.split |= WSP_BOT;
1782 #endif
1783 continue;
1785 case 'c': if (!checkforcmd(&ea.cmd, "confirm", 4))
1786 break;
1787 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1788 cmdmod.confirm = TRUE;
1789 #endif
1790 continue;
1792 case 'k': if (checkforcmd(&ea.cmd, "keepmarks", 3))
1794 cmdmod.keepmarks = TRUE;
1795 continue;
1797 if (checkforcmd(&ea.cmd, "keepalt", 5))
1799 cmdmod.keepalt = TRUE;
1800 continue;
1802 if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1803 break;
1804 cmdmod.keepjumps = TRUE;
1805 continue;
1807 /* ":hide" and ":hide | cmd" are not modifiers */
1808 case 'h': if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1809 || *p == NUL || ends_excmd(*p))
1810 break;
1811 ea.cmd = p;
1812 cmdmod.hide = TRUE;
1813 continue;
1815 case 'l': if (checkforcmd(&ea.cmd, "lockmarks", 3))
1817 cmdmod.lockmarks = TRUE;
1818 continue;
1821 if (!checkforcmd(&ea.cmd, "leftabove", 5))
1822 break;
1823 #ifdef FEAT_WINDOWS
1824 cmdmod.split |= WSP_ABOVE;
1825 #endif
1826 continue;
1828 case 'n': if (!checkforcmd(&ea.cmd, "noautocmd", 3))
1829 break;
1830 #ifdef FEAT_AUTOCMD
1831 if (cmdmod.save_ei == NULL)
1833 /* Set 'eventignore' to "all". Restore the
1834 * existing option value later. */
1835 cmdmod.save_ei = vim_strsave(p_ei);
1836 set_string_option_direct((char_u *)"ei", -1,
1837 (char_u *)"all", OPT_FREE, SID_NONE);
1839 #endif
1840 continue;
1842 case 'r': if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1843 break;
1844 #ifdef FEAT_WINDOWS
1845 cmdmod.split |= WSP_BELOW;
1846 #endif
1847 continue;
1849 case 's': if (checkforcmd(&ea.cmd, "sandbox", 3))
1851 #ifdef HAVE_SANDBOX
1852 if (!did_sandbox)
1853 ++sandbox;
1854 did_sandbox = TRUE;
1855 #endif
1856 continue;
1858 if (!checkforcmd(&ea.cmd, "silent", 3))
1859 break;
1860 if (save_msg_silent == -1)
1861 save_msg_silent = msg_silent;
1862 ++msg_silent;
1863 if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1]))
1865 /* ":silent!", but not "silent !cmd" */
1866 ea.cmd = skipwhite(ea.cmd + 1);
1867 ++emsg_silent;
1868 ++did_esilent;
1870 continue;
1872 case 't': if (checkforcmd(&p, "tab", 3))
1874 #ifdef FEAT_WINDOWS
1875 if (vim_isdigit(*ea.cmd))
1876 cmdmod.tab = atoi((char *)ea.cmd) + 1;
1877 else
1878 cmdmod.tab = tabpage_index(curtab) + 1;
1879 ea.cmd = p;
1880 #endif
1881 continue;
1883 if (!checkforcmd(&ea.cmd, "topleft", 2))
1884 break;
1885 #ifdef FEAT_WINDOWS
1886 cmdmod.split |= WSP_TOP;
1887 #endif
1888 continue;
1890 case 'u': if (!checkforcmd(&ea.cmd, "unsilent", 3))
1891 break;
1892 if (save_msg_silent == -1)
1893 save_msg_silent = msg_silent;
1894 msg_silent = 0;
1895 continue;
1897 case 'v': if (checkforcmd(&ea.cmd, "vertical", 4))
1899 #ifdef FEAT_VERTSPLIT
1900 cmdmod.split |= WSP_VERT;
1901 #endif
1902 continue;
1904 if (!checkforcmd(&p, "verbose", 4))
1905 break;
1906 if (verbose_save < 0)
1907 verbose_save = p_verbose;
1908 if (vim_isdigit(*ea.cmd))
1909 p_verbose = atoi((char *)ea.cmd);
1910 else
1911 p_verbose = 1;
1912 ea.cmd = p;
1913 continue;
1915 break;
1918 #ifdef FEAT_EVAL
1919 ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
1920 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
1921 #else
1922 ea.skip = (if_level > 0);
1923 #endif
1925 #ifdef FEAT_EVAL
1926 # ifdef FEAT_PROFILE
1927 /* Count this line for profiling if ea.skip is FALSE. */
1928 if (do_profiling == PROF_YES && !ea.skip)
1930 if (getline_equal(fgetline, cookie, get_func_line))
1931 func_line_exec(getline_cookie(fgetline, cookie));
1932 else if (getline_equal(fgetline, cookie, getsourceline))
1933 script_line_exec();
1935 #endif
1937 /* May go to debug mode. If this happens and the ">quit" debug command is
1938 * used, throw an interrupt exception and skip the next command. */
1939 dbg_check_breakpoint(&ea);
1940 if (!ea.skip && got_int)
1942 ea.skip = TRUE;
1943 (void)do_intthrow(cstack);
1945 #endif
1948 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
1950 * where 'addr' is:
1952 * % (entire file)
1953 * $ [+-NUM]
1954 * 'x [+-NUM] (where x denotes a currently defined mark)
1955 * . [+-NUM]
1956 * [+-NUM]..
1957 * NUM
1959 * The ea.cmd pointer is updated to point to the first character following the
1960 * range spec. If an initial address is found, but no second, the upper bound
1961 * is equal to the lower.
1964 /* repeat for all ',' or ';' separated addresses */
1965 for (;;)
1967 ea.line1 = ea.line2;
1968 ea.line2 = curwin->w_cursor.lnum; /* default is current line number */
1969 ea.cmd = skipwhite(ea.cmd);
1970 lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0);
1971 if (ea.cmd == NULL) /* error detected */
1972 goto doend;
1973 if (lnum == MAXLNUM)
1975 if (*ea.cmd == '%') /* '%' - all lines */
1977 ++ea.cmd;
1978 ea.line1 = 1;
1979 ea.line2 = curbuf->b_ml.ml_line_count;
1980 ++ea.addr_count;
1982 /* '*' - visual area */
1983 else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
1985 pos_T *fp;
1987 ++ea.cmd;
1988 if (!ea.skip)
1990 fp = getmark('<', FALSE);
1991 if (check_mark(fp) == FAIL)
1992 goto doend;
1993 ea.line1 = fp->lnum;
1994 fp = getmark('>', FALSE);
1995 if (check_mark(fp) == FAIL)
1996 goto doend;
1997 ea.line2 = fp->lnum;
1998 ++ea.addr_count;
2002 else
2003 ea.line2 = lnum;
2004 ea.addr_count++;
2006 if (*ea.cmd == ';')
2008 if (!ea.skip)
2009 curwin->w_cursor.lnum = ea.line2;
2011 else if (*ea.cmd != ',')
2012 break;
2013 ++ea.cmd;
2016 /* One address given: set start and end lines */
2017 if (ea.addr_count == 1)
2019 ea.line1 = ea.line2;
2020 /* ... but only implicit: really no address given */
2021 if (lnum == MAXLNUM)
2022 ea.addr_count = 0;
2025 /* Don't leave the cursor on an illegal line (caused by ';') */
2026 check_cursor_lnum();
2029 * 4. parse command
2033 * Skip ':' and any white space
2035 ea.cmd = skipwhite(ea.cmd);
2036 while (*ea.cmd == ':')
2037 ea.cmd = skipwhite(ea.cmd + 1);
2040 * If we got a line, but no command, then go to the line.
2041 * If we find a '|' or '\n' we set ea.nextcmd.
2043 if (*ea.cmd == NUL || *ea.cmd == '"' ||
2044 (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
2047 * strange vi behaviour:
2048 * ":3" jumps to line 3
2049 * ":3|..." prints line 3
2050 * ":|" prints current line
2052 if (ea.skip) /* skip this if inside :if */
2053 goto doend;
2054 if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2))
2056 ea.cmdidx = CMD_print;
2057 ea.argt = RANGE+COUNT+TRLBAR;
2058 if ((errormsg = invalid_range(&ea)) == NULL)
2060 correct_range(&ea);
2061 ex_print(&ea);
2064 else if (ea.addr_count != 0)
2066 if (ea.line2 > curbuf->b_ml.ml_line_count)
2068 /* With '-' in 'cpoptions' a line number past the file is an
2069 * error, otherwise put it at the end of the file. */
2070 if (vim_strchr(p_cpo, CPO_MINUS) != NULL)
2071 ea.line2 = -1;
2072 else
2073 ea.line2 = curbuf->b_ml.ml_line_count;
2076 if (ea.line2 < 0)
2077 errormsg = (char_u *)_(e_invrange);
2078 else
2080 if (ea.line2 == 0)
2081 curwin->w_cursor.lnum = 1;
2082 else
2083 curwin->w_cursor.lnum = ea.line2;
2084 beginline(BL_SOL | BL_FIX);
2087 goto doend;
2090 /* Find the command and let "p" point to after it. */
2091 p = find_command(&ea, NULL);
2093 #ifdef FEAT_USR_CMDS
2094 if (p == NULL)
2096 if (!ea.skip)
2097 errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
2098 goto doend;
2100 /* Check for wrong commands. */
2101 if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78)
2103 errormsg = uc_fun_cmd();
2104 goto doend;
2106 #endif
2107 if (ea.cmdidx == CMD_SIZE)
2109 if (!ea.skip)
2111 STRCPY(IObuff, _("E492: Not an editor command"));
2112 if (!sourcing)
2114 STRCAT(IObuff, ": ");
2115 STRNCAT(IObuff, *cmdlinep, 40);
2117 errormsg = IObuff;
2119 goto doend;
2122 ni = (
2123 #ifdef FEAT_USR_CMDS
2124 !USER_CMDIDX(ea.cmdidx) &&
2125 #endif
2126 (cmdnames[ea.cmdidx].cmd_func == ex_ni
2127 #ifdef HAVE_EX_SCRIPT_NI
2128 || cmdnames[ea.cmdidx].cmd_func == ex_script_ni
2129 #endif
2132 #ifndef FEAT_EVAL
2134 * When the expression evaluation is disabled, recognize the ":if" and
2135 * ":endif" commands and ignore everything in between it.
2137 if (ea.cmdidx == CMD_if)
2138 ++if_level;
2139 if (if_level)
2141 if (ea.cmdidx == CMD_endif)
2142 --if_level;
2143 goto doend;
2146 #endif
2148 /* forced commands */
2149 if (*p == '!' && ea.cmdidx != CMD_substitute
2150 && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic)
2152 ++p;
2153 ea.forceit = TRUE;
2155 else
2156 ea.forceit = FALSE;
2159 * 5. parse arguments
2161 #ifdef FEAT_USR_CMDS
2162 if (!USER_CMDIDX(ea.cmdidx))
2163 #endif
2164 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
2166 if (!ea.skip)
2168 #ifdef HAVE_SANDBOX
2169 if (sandbox != 0 && !(ea.argt & SBOXOK))
2171 /* Command not allowed in sandbox. */
2172 errormsg = (char_u *)_(e_sandbox);
2173 goto doend;
2175 #endif
2176 if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2178 /* Command not allowed in non-'modifiable' buffer */
2179 errormsg = (char_u *)_(e_modifiable);
2180 goto doend;
2183 if (text_locked() && !(ea.argt & CMDWIN)
2184 # ifdef FEAT_USR_CMDS
2185 && !USER_CMDIDX(ea.cmdidx)
2186 # endif
2189 /* Command not allowed when editing the command line. */
2190 #ifdef FEAT_CMDWIN
2191 if (cmdwin_type != 0)
2192 errormsg = (char_u *)_(e_cmdwin);
2193 else
2194 #endif
2195 errormsg = (char_u *)_(e_secure);
2196 goto doend;
2198 #ifdef FEAT_AUTOCMD
2199 /* Disallow editing another buffer when "curbuf_lock" is set.
2200 * Do allow ":edit" (check for argument later).
2201 * Do allow ":checktime" (it's postponed). */
2202 if (!(ea.argt & CMDWIN)
2203 && ea.cmdidx != CMD_edit
2204 && ea.cmdidx != CMD_checktime
2205 # ifdef FEAT_USR_CMDS
2206 && !USER_CMDIDX(ea.cmdidx)
2207 # endif
2208 && curbuf_locked())
2209 goto doend;
2210 #endif
2212 if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2214 /* no range allowed */
2215 errormsg = (char_u *)_(e_norange);
2216 goto doend;
2220 if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */
2222 errormsg = (char_u *)_(e_nobang);
2223 goto doend;
2227 * Don't complain about the range if it is not used
2228 * (could happen if line_count is accidentally set to 0).
2230 if (!ea.skip && !ni)
2233 * If the range is backwards, ask for confirmation and, if given, swap
2234 * ea.line1 & ea.line2 so it's forwards again.
2235 * When global command is busy, don't ask, will fail below.
2237 if (!global_busy && ea.line1 > ea.line2)
2239 if (msg_silent == 0)
2241 if (sourcing || exmode_active)
2243 errormsg = (char_u *)_("E493: Backwards range given");
2244 goto doend;
2246 if (ask_yesno((char_u *)
2247 _("Backwards range given, OK to swap"), FALSE) != 'y')
2248 goto doend;
2250 lnum = ea.line1;
2251 ea.line1 = ea.line2;
2252 ea.line2 = lnum;
2254 if ((errormsg = invalid_range(&ea)) != NULL)
2255 goto doend;
2258 if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2259 ea.line2 = 1;
2261 correct_range(&ea);
2263 #ifdef FEAT_FOLDING
2264 if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy)
2266 /* Put the first line at the start of a closed fold, put the last line
2267 * at the end of a closed fold. */
2268 (void)hasFolding(ea.line1, &ea.line1, NULL);
2269 (void)hasFolding(ea.line2, NULL, &ea.line2);
2271 #endif
2273 #ifdef FEAT_QUICKFIX
2275 * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2276 * option here, so things like % get expanded.
2278 p = replace_makeprg(&ea, p, cmdlinep);
2279 if (p == NULL)
2280 goto doend;
2281 #endif
2284 * Skip to start of argument.
2285 * Don't do this for the ":!" command, because ":!! -l" needs the space.
2287 if (ea.cmdidx == CMD_bang)
2288 ea.arg = p;
2289 else
2290 ea.arg = skipwhite(p);
2293 * Check for "++opt=val" argument.
2294 * Must be first, allow ":w ++enc=utf8 !cmd"
2296 if (ea.argt & ARGOPT)
2297 while (ea.arg[0] == '+' && ea.arg[1] == '+')
2298 if (getargopt(&ea) == FAIL && !ni)
2300 errormsg = (char_u *)_(e_invarg);
2301 goto doend;
2304 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2306 if (*ea.arg == '>') /* append */
2308 if (*++ea.arg != '>') /* typed wrong */
2310 errormsg = (char_u *)_("E494: Use w or w>>");
2311 goto doend;
2313 ea.arg = skipwhite(ea.arg + 1);
2314 ea.append = TRUE;
2316 else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
2318 ++ea.arg;
2319 ea.usefilter = TRUE;
2323 if (ea.cmdidx == CMD_read)
2325 if (ea.forceit)
2327 ea.usefilter = TRUE; /* :r! filter if ea.forceit */
2328 ea.forceit = FALSE;
2330 else if (*ea.arg == '!') /* :r !filter */
2332 ++ea.arg;
2333 ea.usefilter = TRUE;
2337 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2339 ea.amount = 1;
2340 while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */
2342 ++ea.arg;
2343 ++ea.amount;
2345 ea.arg = skipwhite(ea.arg);
2349 * Check for "+command" argument, before checking for next command.
2350 * Don't do this for ":read !cmd" and ":write !cmd".
2352 if ((ea.argt & EDITCMD) && !ea.usefilter)
2353 ea.do_ecmd_cmd = getargcmd(&ea.arg);
2356 * Check for '|' to separate commands and '"' to start comments.
2357 * Don't do this for ":read !cmd" and ":write !cmd".
2359 if ((ea.argt & TRLBAR) && !ea.usefilter)
2360 separate_nextcmd(&ea);
2363 * Check for <newline> to end a shell command.
2364 * Also do this for ":read !cmd", ":write !cmd" and ":global".
2365 * Any others?
2367 else if (ea.cmdidx == CMD_bang
2368 || ea.cmdidx == CMD_global
2369 || ea.cmdidx == CMD_vglobal
2370 || ea.usefilter)
2372 for (p = ea.arg; *p; ++p)
2374 /* Remove one backslash before a newline, so that it's possible to
2375 * pass a newline to the shell and also a newline that is preceded
2376 * with a backslash. This makes it impossible to end a shell
2377 * command in a backslash, but that doesn't appear useful.
2378 * Halving the number of backslashes is incompatible with previous
2379 * versions. */
2380 if (*p == '\\' && p[1] == '\n')
2381 STRMOVE(p, p + 1);
2382 else if (*p == '\n')
2384 ea.nextcmd = p + 1;
2385 *p = NUL;
2386 break;
2391 if ((ea.argt & DFLALL) && ea.addr_count == 0)
2393 ea.line1 = 1;
2394 ea.line2 = curbuf->b_ml.ml_line_count;
2397 /* accept numbered register only when no count allowed (:put) */
2398 if ( (ea.argt & REGSTR)
2399 && *ea.arg != NUL
2400 #ifdef FEAT_USR_CMDS
2401 && valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2402 && USER_CMDIDX(ea.cmdidx)))
2403 /* Do not allow register = for user commands */
2404 && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2405 #else
2406 && valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put)
2407 #endif
2408 && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2410 ea.regname = *ea.arg++;
2411 #ifdef FEAT_EVAL
2412 /* for '=' register: accept the rest of the line as an expression */
2413 if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2415 set_expr_line(vim_strsave(ea.arg));
2416 ea.arg += STRLEN(ea.arg);
2418 #endif
2419 ea.arg = skipwhite(ea.arg);
2423 * Check for a count. When accepting a BUFNAME, don't use "123foo" as a
2424 * count, it's a buffer name.
2426 if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2427 && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2428 || vim_iswhite(*p)))
2430 n = getdigits(&ea.arg);
2431 ea.arg = skipwhite(ea.arg);
2432 if (n <= 0 && !ni && (ea.argt & ZEROR) == 0)
2434 errormsg = (char_u *)_(e_zerocount);
2435 goto doend;
2437 if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */
2439 ea.line2 = n;
2440 if (ea.addr_count == 0)
2441 ea.addr_count = 1;
2443 else
2445 ea.line1 = ea.line2;
2446 ea.line2 += n - 1;
2447 ++ea.addr_count;
2449 * Be vi compatible: no error message for out of range.
2451 if (ea.line2 > curbuf->b_ml.ml_line_count)
2452 ea.line2 = curbuf->b_ml.ml_line_count;
2457 * Check for flags: 'l', 'p' and '#'.
2459 if (ea.argt & EXFLAGS)
2460 get_flags(&ea);
2461 /* no arguments allowed */
2462 if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2463 && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0))
2465 errormsg = (char_u *)_(e_trailing);
2466 goto doend;
2469 if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2471 errormsg = (char_u *)_(e_argreq);
2472 goto doend;
2475 #ifdef FEAT_EVAL
2477 * Skip the command when it's not going to be executed.
2478 * The commands like :if, :endif, etc. always need to be executed.
2479 * Also make an exception for commands that handle a trailing command
2480 * themselves.
2482 if (ea.skip)
2484 switch (ea.cmdidx)
2486 /* commands that need evaluation */
2487 case CMD_while:
2488 case CMD_endwhile:
2489 case CMD_for:
2490 case CMD_endfor:
2491 case CMD_if:
2492 case CMD_elseif:
2493 case CMD_else:
2494 case CMD_endif:
2495 case CMD_try:
2496 case CMD_catch:
2497 case CMD_finally:
2498 case CMD_endtry:
2499 case CMD_function:
2500 break;
2502 /* Commands that handle '|' themselves. Check: A command should
2503 * either have the TRLBAR flag, appear in this list or appear in
2504 * the list at ":help :bar". */
2505 case CMD_aboveleft:
2506 case CMD_and:
2507 case CMD_belowright:
2508 case CMD_botright:
2509 case CMD_browse:
2510 case CMD_call:
2511 case CMD_confirm:
2512 case CMD_delfunction:
2513 case CMD_djump:
2514 case CMD_dlist:
2515 case CMD_dsearch:
2516 case CMD_dsplit:
2517 case CMD_echo:
2518 case CMD_echoerr:
2519 case CMD_echomsg:
2520 case CMD_echon:
2521 case CMD_execute:
2522 case CMD_help:
2523 case CMD_hide:
2524 case CMD_ijump:
2525 case CMD_ilist:
2526 case CMD_isearch:
2527 case CMD_isplit:
2528 case CMD_keepalt:
2529 case CMD_keepjumps:
2530 case CMD_keepmarks:
2531 case CMD_leftabove:
2532 case CMD_let:
2533 case CMD_lockmarks:
2534 case CMD_match:
2535 case CMD_mzscheme:
2536 case CMD_perl:
2537 case CMD_psearch:
2538 case CMD_python:
2539 case CMD_return:
2540 case CMD_rightbelow:
2541 case CMD_ruby:
2542 case CMD_silent:
2543 case CMD_smagic:
2544 case CMD_snomagic:
2545 case CMD_substitute:
2546 case CMD_syntax:
2547 case CMD_tab:
2548 case CMD_tcl:
2549 case CMD_throw:
2550 case CMD_tilde:
2551 case CMD_topleft:
2552 case CMD_unlet:
2553 case CMD_verbose:
2554 case CMD_vertical:
2555 break;
2557 default: goto doend;
2560 #endif
2562 if (ea.argt & XFILE)
2564 if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2565 goto doend;
2568 #ifdef FEAT_LISTCMDS
2570 * Accept buffer name. Cannot be used at the same time with a buffer
2571 * number. Don't do this for a user command.
2573 if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2574 # ifdef FEAT_USR_CMDS
2575 && !USER_CMDIDX(ea.cmdidx)
2576 # endif
2580 * :bdelete, :bwipeout and :bunload take several arguments, separated
2581 * by spaces: find next space (skipping over escaped characters).
2582 * The others take one argument: ignore trailing spaces.
2584 if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2585 || ea.cmdidx == CMD_bunload)
2586 p = skiptowhite_esc(ea.arg);
2587 else
2589 p = ea.arg + STRLEN(ea.arg);
2590 while (p > ea.arg && vim_iswhite(p[-1]))
2591 --p;
2593 ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE);
2594 if (ea.line2 < 0) /* failed */
2595 goto doend;
2596 ea.addr_count = 1;
2597 ea.arg = skipwhite(p);
2599 #endif
2602 * 6. switch on command name
2604 * The "ea" structure holds the arguments that can be used.
2606 ea.cmdlinep = cmdlinep;
2607 ea.getline = fgetline;
2608 ea.cookie = cookie;
2609 #ifdef FEAT_EVAL
2610 ea.cstack = cstack;
2611 #endif
2613 #ifdef FEAT_USR_CMDS
2614 if (USER_CMDIDX(ea.cmdidx))
2617 * Execute a user-defined command.
2619 do_ucmd(&ea);
2621 else
2622 #endif
2625 * Call the function to execute the command.
2627 ea.errmsg = NULL;
2628 (cmdnames[ea.cmdidx].cmd_func)(&ea);
2629 if (ea.errmsg != NULL)
2630 errormsg = (char_u *)_(ea.errmsg);
2633 #ifdef FEAT_EVAL
2635 * If the command just executed called do_cmdline(), any throw or ":return"
2636 * or ":finish" encountered there must also check the cstack of the still
2637 * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught
2638 * exception, or reanimate a returned function or finished script file and
2639 * return or finish it again.
2641 if (need_rethrow)
2642 do_throw(cstack);
2643 else if (check_cstack)
2645 if (source_finished(fgetline, cookie))
2646 do_finish(&ea, TRUE);
2647 else if (getline_equal(fgetline, cookie, get_func_line)
2648 && current_func_returned())
2649 do_return(&ea, TRUE, FALSE, NULL);
2651 need_rethrow = check_cstack = FALSE;
2652 #endif
2654 doend:
2655 if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */
2656 curwin->w_cursor.lnum = 1;
2658 if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2660 if (sourcing)
2662 if (errormsg != IObuff)
2664 STRCPY(IObuff, errormsg);
2665 errormsg = IObuff;
2667 STRCAT(errormsg, ": ");
2668 STRNCAT(errormsg, *cmdlinep, IOSIZE - STRLEN(IObuff) - 1);
2670 emsg(errormsg);
2672 #ifdef FEAT_EVAL
2673 do_errthrow(cstack,
2674 (ea.cmdidx != CMD_SIZE
2675 # ifdef FEAT_USR_CMDS
2676 && !USER_CMDIDX(ea.cmdidx)
2677 # endif
2678 ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
2679 #endif
2681 if (verbose_save >= 0)
2682 p_verbose = verbose_save;
2683 #ifdef FEAT_AUTOCMD
2684 if (cmdmod.save_ei != NULL)
2686 /* Restore 'eventignore' to the value before ":noautocmd". */
2687 set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei,
2688 OPT_FREE, SID_NONE);
2689 free_string_option(cmdmod.save_ei);
2691 #endif
2693 cmdmod = save_cmdmod;
2695 if (save_msg_silent != -1)
2697 /* messages could be enabled for a serious error, need to check if the
2698 * counters don't become negative */
2699 if (!did_emsg)
2700 msg_silent = save_msg_silent;
2701 emsg_silent -= did_esilent;
2702 if (emsg_silent < 0)
2703 emsg_silent = 0;
2704 /* Restore msg_scroll, it's set by file I/O commands, even when no
2705 * message is actually displayed. */
2706 msg_scroll = save_msg_scroll;
2708 /* "silent reg" or "silent echo x" inside "redir" leaves msg_col
2709 * somewhere in the line. Put it back in the first column. */
2710 if (redirecting())
2711 msg_col = 0;
2714 #ifdef HAVE_SANDBOX
2715 if (did_sandbox)
2716 --sandbox;
2717 #endif
2719 if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */
2720 ea.nextcmd = NULL;
2722 #ifdef FEAT_EVAL
2723 --ex_nesting_level;
2724 #endif
2726 return ea.nextcmd;
2728 #if (_MSC_VER == 1200)
2729 #pragma optimize( "", on )
2730 #endif
2733 * Check for an Ex command with optional tail.
2734 * If there is a match advance "pp" to the argument and return TRUE.
2737 checkforcmd(pp, cmd, len)
2738 char_u **pp; /* start of command */
2739 char *cmd; /* name of command */
2740 int len; /* required length */
2742 int i;
2744 for (i = 0; cmd[i] != NUL; ++i)
2745 if (((char_u *)cmd)[i] != (*pp)[i])
2746 break;
2747 if (i >= len && !isalpha((*pp)[i]))
2749 *pp = skipwhite(*pp + i);
2750 return TRUE;
2752 return FALSE;
2756 * Find an Ex command by its name, either built-in or user.
2757 * Start of the name can be found at eap->cmd.
2758 * Returns pointer to char after the command name.
2759 * "full" is set to TRUE if the whole command name matched.
2760 * Returns NULL for an ambiguous user command.
2762 static char_u *
2763 find_command(eap, full)
2764 exarg_T *eap;
2765 int *full UNUSED;
2767 int len;
2768 char_u *p;
2769 int i;
2772 * Isolate the command and search for it in the command table.
2773 * Exceptions:
2774 * - the 'k' command can directly be followed by any character.
2775 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2776 * but :sre[wind] is another command, as are :scrip[tnames],
2777 * :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
2778 * - the "d" command can directly be followed by 'l' or 'p' flag.
2780 p = eap->cmd;
2781 if (*p == 'k')
2783 eap->cmdidx = CMD_k;
2784 ++p;
2786 else if (p[0] == 's'
2787 && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r'
2788 && p[3] != 'i' && p[4] != 'p')
2789 || p[1] == 'g'
2790 || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
2791 || p[1] == 'I'
2792 || (p[1] == 'r' && p[2] != 'e')))
2794 eap->cmdidx = CMD_substitute;
2795 ++p;
2797 else
2799 while (ASCII_ISALPHA(*p))
2800 ++p;
2801 /* check for non-alpha command */
2802 if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2803 ++p;
2804 len = (int)(p - eap->cmd);
2805 if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p'))
2807 /* Check for ":dl", ":dell", etc. to ":deletel": that's
2808 * :delete with the 'l' flag. Same for 'p'. */
2809 for (i = 0; i < len; ++i)
2810 if (eap->cmd[i] != ((char_u *)"delete")[i])
2811 break;
2812 if (i == len - 1)
2814 --len;
2815 if (p[-1] == 'l')
2816 eap->flags |= EXFLAG_LIST;
2817 else
2818 eap->flags |= EXFLAG_PRINT;
2822 if (ASCII_ISLOWER(*eap->cmd))
2823 eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)];
2824 else
2825 eap->cmdidx = cmdidxs[26];
2827 for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
2828 eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
2829 if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
2830 (size_t)len) == 0)
2832 #ifdef FEAT_EVAL
2833 if (full != NULL
2834 && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
2835 *full = TRUE;
2836 #endif
2837 break;
2840 #ifdef FEAT_USR_CMDS
2841 /* Look for a user defined command as a last resort */
2842 if (eap->cmdidx == CMD_SIZE && *eap->cmd >= 'A' && *eap->cmd <= 'Z')
2844 /* User defined commands may contain digits. */
2845 while (ASCII_ISALNUM(*p))
2846 ++p;
2847 p = find_ucmd(eap, p, full, NULL, NULL);
2849 #endif
2850 if (p == eap->cmd)
2851 eap->cmdidx = CMD_SIZE;
2854 return p;
2857 #ifdef FEAT_USR_CMDS
2859 * Search for a user command that matches "eap->cmd".
2860 * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
2861 * Return a pointer to just after the command.
2862 * Return NULL if there is no matching command.
2864 static char_u *
2865 find_ucmd(eap, p, full, xp, compl)
2866 exarg_T *eap;
2867 char_u *p; /* end of the command (possibly including count) */
2868 int *full; /* set to TRUE for a full match */
2869 expand_T *xp; /* used for completion, NULL otherwise */
2870 int *compl; /* completion flags or NULL */
2872 int len = (int)(p - eap->cmd);
2873 int j, k, matchlen = 0;
2874 ucmd_T *uc;
2875 int found = FALSE;
2876 int possible = FALSE;
2877 char_u *cp, *np; /* Point into typed cmd and test name */
2878 garray_T *gap;
2879 int amb_local = FALSE; /* Found ambiguous buffer-local command,
2880 only full match global is accepted. */
2883 * Look for buffer-local user commands first, then global ones.
2885 gap = &curbuf->b_ucmds;
2886 for (;;)
2888 for (j = 0; j < gap->ga_len; ++j)
2890 uc = USER_CMD_GA(gap, j);
2891 cp = eap->cmd;
2892 np = uc->uc_name;
2893 k = 0;
2894 while (k < len && *np != NUL && *cp++ == *np++)
2895 k++;
2896 if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
2898 /* If finding a second match, the command is ambiguous. But
2899 * not if a buffer-local command wasn't a full match and a
2900 * global command is a full match. */
2901 if (k == len && found && *np != NUL)
2903 if (gap == &ucmds)
2904 return NULL;
2905 amb_local = TRUE;
2908 if (!found || (k == len && *np == NUL))
2910 /* If we matched up to a digit, then there could
2911 * be another command including the digit that we
2912 * should use instead.
2914 if (k == len)
2915 found = TRUE;
2916 else
2917 possible = TRUE;
2919 if (gap == &ucmds)
2920 eap->cmdidx = CMD_USER;
2921 else
2922 eap->cmdidx = CMD_USER_BUF;
2923 eap->argt = (long)uc->uc_argt;
2924 eap->useridx = j;
2926 # ifdef FEAT_CMDL_COMPL
2927 if (compl != NULL)
2928 *compl = uc->uc_compl;
2929 # ifdef FEAT_EVAL
2930 if (xp != NULL)
2932 xp->xp_arg = uc->uc_compl_arg;
2933 xp->xp_scriptID = uc->uc_scriptID;
2935 # endif
2936 # endif
2937 /* Do not search for further abbreviations
2938 * if this is an exact match. */
2939 matchlen = k;
2940 if (k == len && *np == NUL)
2942 if (full != NULL)
2943 *full = TRUE;
2944 amb_local = FALSE;
2945 break;
2951 /* Stop if we found a full match or searched all. */
2952 if (j < gap->ga_len || gap == &ucmds)
2953 break;
2954 gap = &ucmds;
2957 /* Only found ambiguous matches. */
2958 if (amb_local)
2960 if (xp != NULL)
2961 xp->xp_context = EXPAND_UNSUCCESSFUL;
2962 return NULL;
2965 /* The match we found may be followed immediately by a number. Move "p"
2966 * back to point to it. */
2967 if (found || possible)
2968 return p + (matchlen - len);
2969 return p;
2971 #endif
2973 #if defined(FEAT_EVAL) || defined(PROTO)
2974 static struct cmdmod
2976 char *name;
2977 int minlen;
2978 int has_count; /* :123verbose :3tab */
2979 } cmdmods[] = {
2980 {"aboveleft", 3, FALSE},
2981 {"belowright", 3, FALSE},
2982 {"botright", 2, FALSE},
2983 {"browse", 3, FALSE},
2984 {"confirm", 4, FALSE},
2985 {"hide", 3, FALSE},
2986 {"keepalt", 5, FALSE},
2987 {"keepjumps", 5, FALSE},
2988 {"keepmarks", 3, FALSE},
2989 {"leftabove", 5, FALSE},
2990 {"lockmarks", 3, FALSE},
2991 {"noautocmd", 3, FALSE},
2992 {"rightbelow", 6, FALSE},
2993 {"sandbox", 3, FALSE},
2994 {"silent", 3, FALSE},
2995 {"tab", 3, TRUE},
2996 {"topleft", 2, FALSE},
2997 {"unsilent", 3, FALSE},
2998 {"verbose", 4, TRUE},
2999 {"vertical", 4, FALSE},
3003 * Return length of a command modifier (including optional count).
3004 * Return zero when it's not a modifier.
3007 modifier_len(cmd)
3008 char_u *cmd;
3010 int i, j;
3011 char_u *p = cmd;
3013 if (VIM_ISDIGIT(*cmd))
3014 p = skipwhite(skipdigits(cmd));
3015 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3017 for (j = 0; p[j] != NUL; ++j)
3018 if (p[j] != cmdmods[i].name[j])
3019 break;
3020 if (!isalpha(p[j]) && j >= cmdmods[i].minlen
3021 && (p == cmd || cmdmods[i].has_count))
3022 return j + (int)(p - cmd);
3024 return 0;
3028 * Return > 0 if an Ex command "name" exists.
3029 * Return 2 if there is an exact match.
3030 * Return 3 if there is an ambiguous match.
3033 cmd_exists(name)
3034 char_u *name;
3036 exarg_T ea;
3037 int full = FALSE;
3038 int i;
3039 int j;
3040 char_u *p;
3042 /* Check command modifiers. */
3043 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3045 for (j = 0; name[j] != NUL; ++j)
3046 if (name[j] != cmdmods[i].name[j])
3047 break;
3048 if (name[j] == NUL && j >= cmdmods[i].minlen)
3049 return (cmdmods[i].name[j] == NUL ? 2 : 1);
3052 /* Check built-in commands and user defined commands.
3053 * For ":2match" and ":3match" we need to skip the number. */
3054 ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3055 ea.cmdidx = (cmdidx_T)0;
3056 p = find_command(&ea, &full);
3057 if (p == NULL)
3058 return 3;
3059 if (vim_isdigit(*name) && ea.cmdidx != CMD_match)
3060 return 0;
3061 if (*skipwhite(p) != NUL)
3062 return 0; /* trailing garbage */
3063 return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
3065 #endif
3068 * This is all pretty much copied from do_one_cmd(), with all the extra stuff
3069 * we don't need/want deleted. Maybe this could be done better if we didn't
3070 * repeat all this stuff. The only problem is that they may not stay
3071 * perfectly compatible with each other, but then the command line syntax
3072 * probably won't change that much -- webb.
3074 char_u *
3075 set_one_cmd_context(xp, buff)
3076 expand_T *xp;
3077 char_u *buff; /* buffer for command string */
3079 char_u *p;
3080 char_u *cmd, *arg;
3081 int len = 0;
3082 exarg_T ea;
3083 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3084 int compl = EXPAND_NOTHING;
3085 #endif
3086 #ifdef FEAT_CMDL_COMPL
3087 int delim;
3088 #endif
3089 int forceit = FALSE;
3090 int usefilter = FALSE; /* filter instead of file name */
3092 ExpandInit(xp);
3093 xp->xp_pattern = buff;
3094 xp->xp_context = EXPAND_COMMANDS; /* Default until we get past command */
3095 ea.argt = 0;
3098 * 2. skip comment lines and leading space, colons or bars
3100 for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
3102 xp->xp_pattern = cmd;
3104 if (*cmd == NUL)
3105 return NULL;
3106 if (*cmd == '"') /* ignore comment lines */
3108 xp->xp_context = EXPAND_NOTHING;
3109 return NULL;
3113 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
3115 cmd = skip_range(cmd, &xp->xp_context);
3118 * 4. parse command
3120 xp->xp_pattern = cmd;
3121 if (*cmd == NUL)
3122 return NULL;
3123 if (*cmd == '"')
3125 xp->xp_context = EXPAND_NOTHING;
3126 return NULL;
3129 if (*cmd == '|' || *cmd == '\n')
3130 return cmd + 1; /* There's another command */
3133 * Isolate the command and search for it in the command table.
3134 * Exceptions:
3135 * - the 'k' command can directly be followed by any character, but
3136 * do accept "keepmarks", "keepalt" and "keepjumps".
3137 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3139 if (*cmd == 'k' && cmd[1] != 'e')
3141 ea.cmdidx = CMD_k;
3142 p = cmd + 1;
3144 else
3146 p = cmd;
3147 while (ASCII_ISALPHA(*p) || *p == '*') /* Allow * wild card */
3148 ++p;
3149 /* check for non-alpha command */
3150 if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3151 ++p;
3152 len = (int)(p - cmd);
3154 if (len == 0)
3156 xp->xp_context = EXPAND_UNSUCCESSFUL;
3157 return NULL;
3159 for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE;
3160 ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1))
3161 if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd, (size_t)len) == 0)
3162 break;
3164 #ifdef FEAT_USR_CMDS
3165 if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3167 while (ASCII_ISALNUM(*p) || *p == '*') /* Allow * wild card */
3168 ++p;
3169 len = (int)(p - cmd);
3171 #endif
3175 * If the cursor is touching the command, and it ends in an alpha-numeric
3176 * character, complete the command name.
3178 if (*p == NUL && ASCII_ISALNUM(p[-1]))
3179 return NULL;
3181 if (ea.cmdidx == CMD_SIZE)
3183 if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
3185 ea.cmdidx = CMD_substitute;
3186 p = cmd + 1;
3188 #ifdef FEAT_USR_CMDS
3189 else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3191 ea.cmd = cmd;
3192 p = find_ucmd(&ea, p, NULL, xp,
3193 # if defined(FEAT_CMDL_COMPL)
3194 &compl
3195 # else
3196 NULL
3197 # endif
3199 if (p == NULL)
3200 ea.cmdidx = CMD_SIZE; /* ambiguous user command */
3202 #endif
3204 if (ea.cmdidx == CMD_SIZE)
3206 /* Not still touching the command and it was an illegal one */
3207 xp->xp_context = EXPAND_UNSUCCESSFUL;
3208 return NULL;
3211 xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3213 if (*p == '!') /* forced commands */
3215 forceit = TRUE;
3216 ++p;
3220 * 5. parse arguments
3222 #ifdef FEAT_USR_CMDS
3223 if (!USER_CMDIDX(ea.cmdidx))
3224 #endif
3225 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
3227 arg = skipwhite(p);
3229 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
3231 if (*arg == '>') /* append */
3233 if (*++arg == '>')
3234 ++arg;
3235 arg = skipwhite(arg);
3237 else if (*arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
3239 ++arg;
3240 usefilter = TRUE;
3244 if (ea.cmdidx == CMD_read)
3246 usefilter = forceit; /* :r! filter if forced */
3247 if (*arg == '!') /* :r !filter */
3249 ++arg;
3250 usefilter = TRUE;
3254 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
3256 while (*arg == *cmd) /* allow any number of '>' or '<' */
3257 ++arg;
3258 arg = skipwhite(arg);
3261 /* Does command allow "+command"? */
3262 if ((ea.argt & EDITCMD) && !usefilter && *arg == '+')
3264 /* Check if we're in the +command */
3265 p = arg + 1;
3266 arg = skip_cmd_arg(arg, FALSE);
3268 /* Still touching the command after '+'? */
3269 if (*arg == NUL)
3270 return p;
3272 /* Skip space(s) after +command to get to the real argument */
3273 arg = skipwhite(arg);
3277 * Check for '|' to separate commands and '"' to start comments.
3278 * Don't do this for ":read !cmd" and ":write !cmd".
3280 if ((ea.argt & TRLBAR) && !usefilter)
3282 p = arg;
3283 /* ":redir @" is not the start of a comment */
3284 if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3285 p += 2;
3286 while (*p)
3288 if (*p == Ctrl_V)
3290 if (p[1] != NUL)
3291 ++p;
3293 else if ( (*p == '"' && !(ea.argt & NOTRLCOM))
3294 || *p == '|' || *p == '\n')
3296 if (*(p - 1) != '\\')
3298 if (*p == '|' || *p == '\n')
3299 return p + 1;
3300 return NULL; /* It's a comment */
3303 mb_ptr_adv(p);
3307 /* no arguments allowed */
3308 if (!(ea.argt & EXTRA) && *arg != NUL &&
3309 vim_strchr((char_u *)"|\"", *arg) == NULL)
3310 return NULL;
3312 /* Find start of last argument (argument just before cursor): */
3313 p = buff + STRLEN(buff);
3314 while (p != arg && *p != ' ' && *p != TAB)
3315 p--;
3316 if (*p == ' ' || *p == TAB)
3317 p++;
3318 xp->xp_pattern = p;
3320 if (ea.argt & XFILE)
3322 int c;
3323 int in_quote = FALSE;
3324 char_u *bow = NULL; /* Beginning of word */
3327 * Allow spaces within back-quotes to count as part of the argument
3328 * being expanded.
3330 xp->xp_pattern = skipwhite(arg);
3331 p = xp->xp_pattern;
3332 while (*p != NUL)
3334 #ifdef FEAT_MBYTE
3335 if (has_mbyte)
3336 c = mb_ptr2char(p);
3337 else
3338 #endif
3339 c = *p;
3340 if (c == '\\' && p[1] != NUL)
3341 ++p;
3342 else if (c == '`')
3344 if (!in_quote)
3346 xp->xp_pattern = p;
3347 bow = p + 1;
3349 in_quote = !in_quote;
3351 /* An argument can contain just about everything, except
3352 * characters that end the command and white space. */
3353 else if (c == '|' || c == '\n' || c == '"' || (vim_iswhite(c)
3354 #ifdef SPACE_IN_FILENAME
3355 && (!(ea.argt & NOSPC) || usefilter)
3356 #endif
3359 len = 0; /* avoid getting stuck when space is in 'isfname' */
3360 while (*p != NUL)
3362 #ifdef FEAT_MBYTE
3363 if (has_mbyte)
3364 c = mb_ptr2char(p);
3365 else
3366 #endif
3367 c = *p;
3368 if (c == '`' || vim_isfilec_or_wc(c))
3369 break;
3370 #ifdef FEAT_MBYTE
3371 if (has_mbyte)
3372 len = (*mb_ptr2len)(p);
3373 else
3374 #endif
3375 len = 1;
3376 mb_ptr_adv(p);
3378 if (in_quote)
3379 bow = p;
3380 else
3381 xp->xp_pattern = p;
3382 p -= len;
3384 mb_ptr_adv(p);
3388 * If we are still inside the quotes, and we passed a space, just
3389 * expand from there.
3391 if (bow != NULL && in_quote)
3392 xp->xp_pattern = bow;
3393 xp->xp_context = EXPAND_FILES;
3395 #ifndef BACKSLASH_IN_FILENAME
3396 /* For a shell command more chars need to be escaped. */
3397 if (usefilter || ea.cmdidx == CMD_bang)
3399 xp->xp_shell = TRUE;
3401 /* When still after the command name expand executables. */
3402 if (xp->xp_pattern == skipwhite(arg))
3403 xp->xp_context = EXPAND_SHELLCMD;
3405 #endif
3407 /* Check for environment variable */
3408 if (*xp->xp_pattern == '$'
3409 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3410 || *xp->xp_pattern == '%'
3411 #endif
3414 for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3415 if (!vim_isIDc(*p))
3416 break;
3417 if (*p == NUL)
3419 xp->xp_context = EXPAND_ENV_VARS;
3420 ++xp->xp_pattern;
3421 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3422 /* Avoid that the assignment uses EXPAND_FILES again. */
3423 if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
3424 compl = EXPAND_ENV_VARS;
3425 #endif
3431 * 6. switch on command name
3433 switch (ea.cmdidx)
3435 case CMD_cd:
3436 case CMD_chdir:
3437 case CMD_lcd:
3438 case CMD_lchdir:
3439 if (xp->xp_context == EXPAND_FILES)
3440 xp->xp_context = EXPAND_DIRECTORIES;
3441 break;
3442 case CMD_help:
3443 xp->xp_context = EXPAND_HELP;
3444 xp->xp_pattern = arg;
3445 break;
3447 /* Command modifiers: return the argument.
3448 * Also for commands with an argument that is a command. */
3449 case CMD_aboveleft:
3450 case CMD_argdo:
3451 case CMD_belowright:
3452 case CMD_botright:
3453 case CMD_browse:
3454 case CMD_bufdo:
3455 case CMD_confirm:
3456 case CMD_debug:
3457 case CMD_folddoclosed:
3458 case CMD_folddoopen:
3459 case CMD_hide:
3460 case CMD_keepalt:
3461 case CMD_keepjumps:
3462 case CMD_keepmarks:
3463 case CMD_leftabove:
3464 case CMD_lockmarks:
3465 case CMD_rightbelow:
3466 case CMD_sandbox:
3467 case CMD_silent:
3468 case CMD_tab:
3469 case CMD_topleft:
3470 case CMD_verbose:
3471 case CMD_vertical:
3472 case CMD_windo:
3473 return arg;
3475 #ifdef FEAT_CMDL_COMPL
3476 # ifdef FEAT_SEARCH_EXTRA
3477 case CMD_match:
3478 if (*arg == NUL || !ends_excmd(*arg))
3480 /* also complete "None" */
3481 set_context_in_echohl_cmd(xp, arg);
3482 arg = skipwhite(skiptowhite(arg));
3483 if (*arg != NUL)
3485 xp->xp_context = EXPAND_NOTHING;
3486 arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3489 return find_nextcmd(arg);
3490 # endif
3493 * All completion for the +cmdline_compl feature goes here.
3496 # ifdef FEAT_USR_CMDS
3497 case CMD_command:
3498 /* Check for attributes */
3499 while (*arg == '-')
3501 arg++; /* Skip "-" */
3502 p = skiptowhite(arg);
3503 if (*p == NUL)
3505 /* Cursor is still in the attribute */
3506 p = vim_strchr(arg, '=');
3507 if (p == NULL)
3509 /* No "=", so complete attribute names */
3510 xp->xp_context = EXPAND_USER_CMD_FLAGS;
3511 xp->xp_pattern = arg;
3512 return NULL;
3515 /* For the -complete and -nargs attributes, we complete
3516 * their arguments as well.
3518 if (STRNICMP(arg, "complete", p - arg) == 0)
3520 xp->xp_context = EXPAND_USER_COMPLETE;
3521 xp->xp_pattern = p + 1;
3522 return NULL;
3524 else if (STRNICMP(arg, "nargs", p - arg) == 0)
3526 xp->xp_context = EXPAND_USER_NARGS;
3527 xp->xp_pattern = p + 1;
3528 return NULL;
3530 return NULL;
3532 arg = skipwhite(p);
3535 /* After the attributes comes the new command name */
3536 p = skiptowhite(arg);
3537 if (*p == NUL)
3539 xp->xp_context = EXPAND_USER_COMMANDS;
3540 xp->xp_pattern = arg;
3541 break;
3544 /* And finally comes a normal command */
3545 return skipwhite(p);
3547 case CMD_delcommand:
3548 xp->xp_context = EXPAND_USER_COMMANDS;
3549 xp->xp_pattern = arg;
3550 break;
3551 # endif
3553 case CMD_global:
3554 case CMD_vglobal:
3555 delim = *arg; /* get the delimiter */
3556 if (delim)
3557 ++arg; /* skip delimiter if there is one */
3559 while (arg[0] != NUL && arg[0] != delim)
3561 if (arg[0] == '\\' && arg[1] != NUL)
3562 ++arg;
3563 ++arg;
3565 if (arg[0] != NUL)
3566 return arg + 1;
3567 break;
3568 case CMD_and:
3569 case CMD_substitute:
3570 delim = *arg;
3571 if (delim)
3573 /* skip "from" part */
3574 ++arg;
3575 arg = skip_regexp(arg, delim, p_magic, NULL);
3577 /* skip "to" part */
3578 while (arg[0] != NUL && arg[0] != delim)
3580 if (arg[0] == '\\' && arg[1] != NUL)
3581 ++arg;
3582 ++arg;
3584 if (arg[0] != NUL) /* skip delimiter */
3585 ++arg;
3586 while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
3587 ++arg;
3588 if (arg[0] != NUL)
3589 return arg;
3590 break;
3591 case CMD_isearch:
3592 case CMD_dsearch:
3593 case CMD_ilist:
3594 case CMD_dlist:
3595 case CMD_ijump:
3596 case CMD_psearch:
3597 case CMD_djump:
3598 case CMD_isplit:
3599 case CMD_dsplit:
3600 arg = skipwhite(skipdigits(arg)); /* skip count */
3601 if (*arg == '/') /* Match regexp, not just whole words */
3603 for (++arg; *arg && *arg != '/'; arg++)
3604 if (*arg == '\\' && arg[1] != NUL)
3605 arg++;
3606 if (*arg)
3608 arg = skipwhite(arg + 1);
3610 /* Check for trailing illegal characters */
3611 if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
3612 xp->xp_context = EXPAND_NOTHING;
3613 else
3614 return arg;
3617 break;
3618 #ifdef FEAT_AUTOCMD
3619 case CMD_autocmd:
3620 return set_context_in_autocmd(xp, arg, FALSE);
3622 case CMD_doautocmd:
3623 case CMD_doautoall:
3624 return set_context_in_autocmd(xp, arg, TRUE);
3625 #endif
3626 case CMD_set:
3627 set_context_in_set_cmd(xp, arg, 0);
3628 break;
3629 case CMD_setglobal:
3630 set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
3631 break;
3632 case CMD_setlocal:
3633 set_context_in_set_cmd(xp, arg, OPT_LOCAL);
3634 break;
3635 case CMD_tag:
3636 case CMD_stag:
3637 case CMD_ptag:
3638 case CMD_ltag:
3639 case CMD_tselect:
3640 case CMD_stselect:
3641 case CMD_ptselect:
3642 case CMD_tjump:
3643 case CMD_stjump:
3644 case CMD_ptjump:
3645 if (*p_wop != NUL)
3646 xp->xp_context = EXPAND_TAGS_LISTFILES;
3647 else
3648 xp->xp_context = EXPAND_TAGS;
3649 xp->xp_pattern = arg;
3650 break;
3651 case CMD_augroup:
3652 xp->xp_context = EXPAND_AUGROUP;
3653 xp->xp_pattern = arg;
3654 break;
3655 #ifdef FEAT_SYN_HL
3656 case CMD_syntax:
3657 set_context_in_syntax_cmd(xp, arg);
3658 break;
3659 #endif
3660 #ifdef FEAT_EVAL
3661 case CMD_let:
3662 case CMD_if:
3663 case CMD_elseif:
3664 case CMD_while:
3665 case CMD_for:
3666 case CMD_echo:
3667 case CMD_echon:
3668 case CMD_execute:
3669 case CMD_echomsg:
3670 case CMD_echoerr:
3671 case CMD_call:
3672 case CMD_return:
3673 set_context_for_expression(xp, arg, ea.cmdidx);
3674 break;
3676 case CMD_unlet:
3677 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3678 arg = xp->xp_pattern + 1;
3679 xp->xp_context = EXPAND_USER_VARS;
3680 xp->xp_pattern = arg;
3681 break;
3683 case CMD_function:
3684 case CMD_delfunction:
3685 xp->xp_context = EXPAND_USER_FUNC;
3686 xp->xp_pattern = arg;
3687 break;
3689 case CMD_echohl:
3690 set_context_in_echohl_cmd(xp, arg);
3691 break;
3692 #endif
3693 case CMD_highlight:
3694 set_context_in_highlight_cmd(xp, arg);
3695 break;
3696 #ifdef FEAT_CSCOPE
3697 case CMD_cscope:
3698 case CMD_lcscope:
3699 case CMD_scscope:
3700 set_context_in_cscope_cmd(xp, arg, ea.cmdidx);
3701 break;
3702 #endif
3703 #ifdef FEAT_SIGNS
3704 case CMD_sign:
3705 set_context_in_sign_cmd(xp, arg);
3706 break;
3707 #endif
3708 #ifdef FEAT_LISTCMDS
3709 case CMD_bdelete:
3710 case CMD_bwipeout:
3711 case CMD_bunload:
3712 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3713 arg = xp->xp_pattern + 1;
3714 /*FALLTHROUGH*/
3715 case CMD_buffer:
3716 case CMD_sbuffer:
3717 case CMD_checktime:
3718 xp->xp_context = EXPAND_BUFFERS;
3719 xp->xp_pattern = arg;
3720 break;
3721 #endif
3722 #ifdef FEAT_USR_CMDS
3723 case CMD_USER:
3724 case CMD_USER_BUF:
3725 if (compl != EXPAND_NOTHING)
3727 /* XFILE: file names are handled above */
3728 if (!(ea.argt & XFILE))
3730 # ifdef FEAT_MENU
3731 if (compl == EXPAND_MENUS)
3732 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3733 # endif
3734 if (compl == EXPAND_COMMANDS)
3735 return arg;
3736 if (compl == EXPAND_MAPPINGS)
3737 return set_context_in_map_cmd(xp, (char_u *)"map",
3738 arg, forceit, FALSE, FALSE, CMD_map);
3739 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3740 arg = xp->xp_pattern + 1;
3741 xp->xp_pattern = arg;
3743 xp->xp_context = compl;
3745 break;
3746 #endif
3747 case CMD_map: case CMD_noremap:
3748 case CMD_nmap: case CMD_nnoremap:
3749 case CMD_vmap: case CMD_vnoremap:
3750 case CMD_omap: case CMD_onoremap:
3751 case CMD_imap: case CMD_inoremap:
3752 case CMD_cmap: case CMD_cnoremap:
3753 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3754 FALSE, FALSE, ea.cmdidx);
3755 case CMD_unmap:
3756 case CMD_nunmap:
3757 case CMD_vunmap:
3758 case CMD_ounmap:
3759 case CMD_iunmap:
3760 case CMD_cunmap:
3761 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3762 FALSE, TRUE, ea.cmdidx);
3763 case CMD_abbreviate: case CMD_noreabbrev:
3764 case CMD_cabbrev: case CMD_cnoreabbrev:
3765 case CMD_iabbrev: case CMD_inoreabbrev:
3766 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3767 TRUE, FALSE, ea.cmdidx);
3768 case CMD_unabbreviate:
3769 case CMD_cunabbrev:
3770 case CMD_iunabbrev:
3771 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3772 TRUE, TRUE, ea.cmdidx);
3773 #ifdef FEAT_MENU
3774 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
3775 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
3776 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
3777 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
3778 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
3779 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
3780 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
3781 case CMD_tmenu: case CMD_tunmenu:
3782 case CMD_popup: case CMD_tearoff: case CMD_emenu:
3783 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3784 #endif
3786 case CMD_colorscheme:
3787 xp->xp_context = EXPAND_COLORS;
3788 xp->xp_pattern = arg;
3789 break;
3791 case CMD_compiler:
3792 xp->xp_context = EXPAND_COMPILER;
3793 xp->xp_pattern = arg;
3794 break;
3796 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
3797 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
3798 case CMD_language:
3799 if (*skiptowhite(arg) == NUL)
3801 xp->xp_context = EXPAND_LANGUAGE;
3802 xp->xp_pattern = arg;
3804 else
3805 xp->xp_context = EXPAND_NOTHING;
3806 break;
3807 #endif
3809 #endif /* FEAT_CMDL_COMPL */
3811 default:
3812 break;
3814 return NULL;
3818 * skip a range specifier of the form: addr [,addr] [;addr] ..
3820 * Backslashed delimiters after / or ? will be skipped, and commands will
3821 * not be expanded between /'s and ?'s or after "'".
3823 * Also skip white space and ":" characters.
3824 * Returns the "cmd" pointer advanced to beyond the range.
3826 char_u *
3827 skip_range(cmd, ctx)
3828 char_u *cmd;
3829 int *ctx; /* pointer to xp_context or NULL */
3831 unsigned delim;
3833 while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;", *cmd) != NULL)
3835 if (*cmd == '\'')
3837 if (*++cmd == NUL && ctx != NULL)
3838 *ctx = EXPAND_NOTHING;
3840 else if (*cmd == '/' || *cmd == '?')
3842 delim = *cmd++;
3843 while (*cmd != NUL && *cmd != delim)
3844 if (*cmd++ == '\\' && *cmd != NUL)
3845 ++cmd;
3846 if (*cmd == NUL && ctx != NULL)
3847 *ctx = EXPAND_NOTHING;
3849 if (*cmd != NUL)
3850 ++cmd;
3853 /* Skip ":" and white space. */
3854 while (*cmd == ':')
3855 cmd = skipwhite(cmd + 1);
3857 return cmd;
3861 * get a single EX address
3863 * Set ptr to the next character after the part that was interpreted.
3864 * Set ptr to NULL when an error is encountered.
3866 * Return MAXLNUM when no Ex address was found.
3868 static linenr_T
3869 get_address(ptr, skip, to_other_file)
3870 char_u **ptr;
3871 int skip; /* only skip the address, don't use it */
3872 int to_other_file; /* flag: may jump to other file */
3874 int c;
3875 int i;
3876 long n;
3877 char_u *cmd;
3878 pos_T pos;
3879 pos_T *fp;
3880 linenr_T lnum;
3882 cmd = skipwhite(*ptr);
3883 lnum = MAXLNUM;
3886 switch (*cmd)
3888 case '.': /* '.' - Cursor position */
3889 ++cmd;
3890 lnum = curwin->w_cursor.lnum;
3891 break;
3893 case '$': /* '$' - last line */
3894 ++cmd;
3895 lnum = curbuf->b_ml.ml_line_count;
3896 break;
3898 case '\'': /* ''' - mark */
3899 if (*++cmd == NUL)
3901 cmd = NULL;
3902 goto error;
3904 if (skip)
3905 ++cmd;
3906 else
3908 /* Only accept a mark in another file when it is
3909 * used by itself: ":'M". */
3910 fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
3911 ++cmd;
3912 if (fp == (pos_T *)-1)
3913 /* Jumped to another file. */
3914 lnum = curwin->w_cursor.lnum;
3915 else
3917 if (check_mark(fp) == FAIL)
3919 cmd = NULL;
3920 goto error;
3922 lnum = fp->lnum;
3925 break;
3927 case '/':
3928 case '?': /* '/' or '?' - search */
3929 c = *cmd++;
3930 if (skip) /* skip "/pat/" */
3932 cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
3933 if (*cmd == c)
3934 ++cmd;
3936 else
3938 pos = curwin->w_cursor; /* save curwin->w_cursor */
3940 * When '/' or '?' follows another address, start
3941 * from there.
3943 if (lnum != MAXLNUM)
3944 curwin->w_cursor.lnum = lnum;
3946 * Start a forward search at the end of the line.
3947 * Start a backward search at the start of the line.
3948 * This makes sure we never match in the current
3949 * line, and can match anywhere in the
3950 * next/previous line.
3952 if (c == '/')
3953 curwin->w_cursor.col = MAXCOL;
3954 else
3955 curwin->w_cursor.col = 0;
3956 searchcmdlen = 0;
3957 if (!do_search(NULL, c, cmd, 1L,
3958 SEARCH_HIS | SEARCH_MSG, NULL))
3960 curwin->w_cursor = pos;
3961 cmd = NULL;
3962 goto error;
3964 lnum = curwin->w_cursor.lnum;
3965 curwin->w_cursor = pos;
3966 /* adjust command string pointer */
3967 cmd += searchcmdlen;
3969 break;
3971 case '\\': /* "\?", "\/" or "\&", repeat search */
3972 ++cmd;
3973 if (*cmd == '&')
3974 i = RE_SUBST;
3975 else if (*cmd == '?' || *cmd == '/')
3976 i = RE_SEARCH;
3977 else
3979 EMSG(_(e_backslash));
3980 cmd = NULL;
3981 goto error;
3984 if (!skip)
3987 * When search follows another address, start from
3988 * there.
3990 if (lnum != MAXLNUM)
3991 pos.lnum = lnum;
3992 else
3993 pos.lnum = curwin->w_cursor.lnum;
3996 * Start the search just like for the above
3997 * do_search().
3999 if (*cmd != '?')
4000 pos.col = MAXCOL;
4001 else
4002 pos.col = 0;
4003 if (searchit(curwin, curbuf, &pos,
4004 *cmd == '?' ? BACKWARD : FORWARD,
4005 (char_u *)"", 1L, SEARCH_MSG,
4006 i, (linenr_T)0, NULL) != FAIL)
4007 lnum = pos.lnum;
4008 else
4010 cmd = NULL;
4011 goto error;
4014 ++cmd;
4015 break;
4017 default:
4018 if (VIM_ISDIGIT(*cmd)) /* absolute line number */
4019 lnum = getdigits(&cmd);
4022 for (;;)
4024 cmd = skipwhite(cmd);
4025 if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
4026 break;
4028 if (lnum == MAXLNUM)
4029 lnum = curwin->w_cursor.lnum; /* "+1" is same as ".+1" */
4030 if (VIM_ISDIGIT(*cmd))
4031 i = '+'; /* "number" is same as "+number" */
4032 else
4033 i = *cmd++;
4034 if (!VIM_ISDIGIT(*cmd)) /* '+' is '+1', but '+0' is not '+1' */
4035 n = 1;
4036 else
4037 n = getdigits(&cmd);
4038 if (i == '-')
4039 lnum -= n;
4040 else
4041 lnum += n;
4043 } while (*cmd == '/' || *cmd == '?');
4045 error:
4046 *ptr = cmd;
4047 return lnum;
4051 * Get flags from an Ex command argument.
4053 static void
4054 get_flags(eap)
4055 exarg_T *eap;
4057 while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL)
4059 if (*eap->arg == 'l')
4060 eap->flags |= EXFLAG_LIST;
4061 else if (*eap->arg == 'p')
4062 eap->flags |= EXFLAG_PRINT;
4063 else
4064 eap->flags |= EXFLAG_NR;
4065 eap->arg = skipwhite(eap->arg + 1);
4070 * Function called for command which is Not Implemented. NI!
4072 void
4073 ex_ni(eap)
4074 exarg_T *eap;
4076 if (!eap->skip)
4077 eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
4080 #ifdef HAVE_EX_SCRIPT_NI
4082 * Function called for script command which is Not Implemented. NI!
4083 * Skips over ":perl <<EOF" constructs.
4085 static void
4086 ex_script_ni(eap)
4087 exarg_T *eap;
4089 if (!eap->skip)
4090 ex_ni(eap);
4091 else
4092 vim_free(script_get(eap, eap->arg));
4094 #endif
4097 * Check range in Ex command for validity.
4098 * Return NULL when valid, error message when invalid.
4100 static char_u *
4101 invalid_range(eap)
4102 exarg_T *eap;
4104 if ( eap->line1 < 0
4105 || eap->line2 < 0
4106 || eap->line1 > eap->line2
4107 || ((eap->argt & RANGE)
4108 && !(eap->argt & NOTADR)
4109 && eap->line2 > curbuf->b_ml.ml_line_count
4110 #ifdef FEAT_DIFF
4111 + (eap->cmdidx == CMD_diffget)
4112 #endif
4114 return (char_u *)_(e_invrange);
4115 return NULL;
4119 * Correct the range for zero line number, if required.
4121 static void
4122 correct_range(eap)
4123 exarg_T *eap;
4125 if (!(eap->argt & ZEROR)) /* zero in range not allowed */
4127 if (eap->line1 == 0)
4128 eap->line1 = 1;
4129 if (eap->line2 == 0)
4130 eap->line2 = 1;
4134 #ifdef FEAT_QUICKFIX
4135 static char_u *skip_grep_pat __ARGS((exarg_T *eap));
4138 * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
4139 * pattern. Otherwise return eap->arg.
4141 static char_u *
4142 skip_grep_pat(eap)
4143 exarg_T *eap;
4145 char_u *p = eap->arg;
4147 if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
4148 || eap->cmdidx == CMD_vimgrepadd
4149 || eap->cmdidx == CMD_lvimgrepadd
4150 || grep_internal(eap->cmdidx)))
4152 p = skip_vimgrep_pat(p, NULL, NULL);
4153 if (p == NULL)
4154 p = eap->arg;
4156 return p;
4160 * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
4161 * in the command line, so that things like % get expanded.
4163 static char_u *
4164 replace_makeprg(eap, p, cmdlinep)
4165 exarg_T *eap;
4166 char_u *p;
4167 char_u **cmdlinep;
4169 char_u *new_cmdline;
4170 char_u *program;
4171 char_u *pos;
4172 char_u *ptr;
4173 int len;
4174 int i;
4177 * Don't do it when ":vimgrep" is used for ":grep".
4179 if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake
4180 || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4181 || eap->cmdidx == CMD_grepadd
4182 || eap->cmdidx == CMD_lgrepadd)
4183 && !grep_internal(eap->cmdidx))
4185 if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4186 || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd)
4188 if (*curbuf->b_p_gp == NUL)
4189 program = p_gp;
4190 else
4191 program = curbuf->b_p_gp;
4193 else
4195 if (*curbuf->b_p_mp == NUL)
4196 program = p_mp;
4197 else
4198 program = curbuf->b_p_mp;
4201 p = skipwhite(p);
4203 if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4205 /* replace $* by given arguments */
4206 i = 1;
4207 while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
4208 ++i;
4209 len = (int)STRLEN(p);
4210 new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
4211 if (new_cmdline == NULL)
4212 return NULL; /* out of memory */
4213 ptr = new_cmdline;
4214 while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4216 i = (int)(pos - program);
4217 STRNCPY(ptr, program, i);
4218 STRCPY(ptr += i, p);
4219 ptr += len;
4220 program = pos + 2;
4222 STRCPY(ptr, program);
4224 else
4226 new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
4227 if (new_cmdline == NULL)
4228 return NULL; /* out of memory */
4229 STRCPY(new_cmdline, program);
4230 STRCAT(new_cmdline, " ");
4231 STRCAT(new_cmdline, p);
4233 msg_make(p);
4235 /* 'eap->cmd' is not set here, because it is not used at CMD_make */
4236 vim_free(*cmdlinep);
4237 *cmdlinep = new_cmdline;
4238 p = new_cmdline;
4240 return p;
4242 #endif
4245 * Expand file name in Ex command argument.
4246 * Return FAIL for failure, OK otherwise.
4249 expand_filename(eap, cmdlinep, errormsgp)
4250 exarg_T *eap;
4251 char_u **cmdlinep;
4252 char_u **errormsgp;
4254 int has_wildcards; /* need to expand wildcards */
4255 char_u *repl;
4256 int srclen;
4257 char_u *p;
4258 int n;
4259 int escaped;
4261 #ifdef FEAT_QUICKFIX
4262 /* Skip a regexp pattern for ":vimgrep[add] pat file..." */
4263 p = skip_grep_pat(eap);
4264 #else
4265 p = eap->arg;
4266 #endif
4269 * Decide to expand wildcards *before* replacing '%', '#', etc. If
4270 * the file name contains a wildcard it should not cause expanding.
4271 * (it will be expanded anyway if there is a wildcard before replacing).
4273 has_wildcards = mch_has_wildcard(p);
4274 while (*p != NUL)
4276 #ifdef FEAT_EVAL
4277 /* Skip over `=expr`, wildcards in it are not expanded. */
4278 if (p[0] == '`' && p[1] == '=')
4280 p += 2;
4281 (void)skip_expr(&p);
4282 if (*p == '`')
4283 ++p;
4284 continue;
4286 #endif
4288 * Quick check if this cannot be the start of a special string.
4289 * Also removes backslash before '%', '#' and '<'.
4291 if (vim_strchr((char_u *)"%#<", *p) == NULL)
4293 ++p;
4294 continue;
4298 * Try to find a match at this position.
4300 repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
4301 errormsgp, &escaped);
4302 if (*errormsgp != NULL) /* error detected */
4303 return FAIL;
4304 if (repl == NULL) /* no match found */
4306 p += srclen;
4307 continue;
4310 /* Wildcards won't be expanded below, the replacement is taken
4311 * literally. But do expand "~/file", "~user/file" and "$HOME/file". */
4312 if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
4314 char_u *l = repl;
4316 repl = expand_env_save(repl);
4317 vim_free(l);
4320 /* Need to escape white space et al. with a backslash.
4321 * Don't do this for:
4322 * - replacement that already has been escaped: "##"
4323 * - shell commands (may have to use quotes instead).
4324 * - non-unix systems when there is a single argument (spaces don't
4325 * separate arguments then).
4327 if (!eap->usefilter
4328 && !escaped
4329 && eap->cmdidx != CMD_bang
4330 && eap->cmdidx != CMD_make
4331 && eap->cmdidx != CMD_lmake
4332 && eap->cmdidx != CMD_grep
4333 && eap->cmdidx != CMD_lgrep
4334 && eap->cmdidx != CMD_grepadd
4335 && eap->cmdidx != CMD_lgrepadd
4336 #ifndef UNIX
4337 && !(eap->argt & NOSPC)
4338 #endif
4341 char_u *l;
4342 #ifdef BACKSLASH_IN_FILENAME
4343 /* Don't escape a backslash here, because rem_backslash() doesn't
4344 * remove it later. */
4345 static char_u *nobslash = (char_u *)" \t\"|";
4346 # define ESCAPE_CHARS nobslash
4347 #else
4348 # define ESCAPE_CHARS escape_chars
4349 #endif
4351 for (l = repl; *l; ++l)
4352 if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
4354 l = vim_strsave_escaped(repl, ESCAPE_CHARS);
4355 if (l != NULL)
4357 vim_free(repl);
4358 repl = l;
4360 break;
4364 /* For a shell command a '!' must be escaped. */
4365 if ((eap->usefilter || eap->cmdidx == CMD_bang)
4366 && vim_strpbrk(repl, (char_u *)"!&;()<>") != NULL)
4368 char_u *l;
4370 l = vim_strsave_escaped(repl, (char_u *)"!&;()<>");
4371 if (l != NULL)
4373 vim_free(repl);
4374 repl = l;
4375 /* For a sh-like shell escape "!" another time. */
4376 if (strstr((char *)p_sh, "sh") != NULL)
4378 l = vim_strsave_escaped(repl, (char_u *)"!");
4379 if (l != NULL)
4381 vim_free(repl);
4382 repl = l;
4388 p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4389 vim_free(repl);
4390 if (p == NULL)
4391 return FAIL;
4395 * One file argument: Expand wildcards.
4396 * Don't do this with ":r !command" or ":w !command".
4398 if ((eap->argt & NOSPC) && !eap->usefilter)
4401 * May do this twice:
4402 * 1. Replace environment variables.
4403 * 2. Replace any other wildcards, remove backslashes.
4405 for (n = 1; n <= 2; ++n)
4407 if (n == 2)
4409 #ifdef UNIX
4411 * Only for Unix we check for more than one file name.
4412 * For other systems spaces are considered to be part
4413 * of the file name.
4414 * Only check here if there is no wildcard, otherwise
4415 * ExpandOne() will check for errors. This allows
4416 * ":e `ls ve*.c`" on Unix.
4418 if (!has_wildcards)
4419 for (p = eap->arg; *p; ++p)
4421 /* skip escaped characters */
4422 if (p[1] && (*p == '\\' || *p == Ctrl_V))
4423 ++p;
4424 else if (vim_iswhite(*p))
4426 *errormsgp = (char_u *)_("E172: Only one file name allowed");
4427 return FAIL;
4430 #endif
4433 * Halve the number of backslashes (this is Vi compatible).
4434 * For Unix and OS/2, when wildcards are expanded, this is
4435 * done by ExpandOne() below.
4437 #if defined(UNIX) || defined(OS2)
4438 if (!has_wildcards)
4439 #endif
4440 backslash_halve(eap->arg);
4443 if (has_wildcards)
4445 if (n == 1)
4448 * First loop: May expand environment variables. This
4449 * can be done much faster with expand_env() than with
4450 * something else (e.g., calling a shell).
4451 * After expanding environment variables, check again
4452 * if there are still wildcards present.
4454 if (vim_strchr(eap->arg, '$') != NULL
4455 || vim_strchr(eap->arg, '~') != NULL)
4457 expand_env_esc(eap->arg, NameBuff, MAXPATHL,
4458 TRUE, TRUE, NULL);
4459 has_wildcards = mch_has_wildcard(NameBuff);
4460 p = NameBuff;
4462 else
4463 p = NULL;
4465 else /* n == 2 */
4467 expand_T xpc;
4469 ExpandInit(&xpc);
4470 xpc.xp_context = EXPAND_FILES;
4471 p = ExpandOne(&xpc, eap->arg, NULL,
4472 WILD_LIST_NOTFOUND|WILD_ADD_SLASH,
4473 WILD_EXPAND_FREE);
4474 if (p == NULL)
4475 return FAIL;
4477 if (p != NULL)
4479 (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
4480 p, cmdlinep);
4481 if (n == 2) /* p came from ExpandOne() */
4482 vim_free(p);
4487 return OK;
4491 * Replace part of the command line, keeping eap->cmd, eap->arg and
4492 * eap->nextcmd correct.
4493 * "src" points to the part that is to be replaced, of length "srclen".
4494 * "repl" is the replacement string.
4495 * Returns a pointer to the character after the replaced string.
4496 * Returns NULL for failure.
4498 static char_u *
4499 repl_cmdline(eap, src, srclen, repl, cmdlinep)
4500 exarg_T *eap;
4501 char_u *src;
4502 int srclen;
4503 char_u *repl;
4504 char_u **cmdlinep;
4506 int len;
4507 int i;
4508 char_u *new_cmdline;
4511 * The new command line is build in new_cmdline[].
4512 * First allocate it.
4513 * Careful: a "+cmd" argument may have been NUL terminated.
4515 len = (int)STRLEN(repl);
4516 i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
4517 if (eap->nextcmd != NULL)
4518 i += (int)STRLEN(eap->nextcmd);/* add space for next command */
4519 if ((new_cmdline = alloc((unsigned)i)) == NULL)
4520 return NULL; /* out of memory! */
4523 * Copy the stuff before the expanded part.
4524 * Copy the expanded stuff.
4525 * Copy what came after the expanded part.
4526 * Copy the next commands, if there are any.
4528 i = (int)(src - *cmdlinep); /* length of part before match */
4529 mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
4531 mch_memmove(new_cmdline + i, repl, (size_t)len);
4532 i += len; /* remember the end of the string */
4533 STRCPY(new_cmdline + i, src + srclen);
4534 src = new_cmdline + i; /* remember where to continue */
4536 if (eap->nextcmd != NULL) /* append next command */
4538 i = (int)STRLEN(new_cmdline) + 1;
4539 STRCPY(new_cmdline + i, eap->nextcmd);
4540 eap->nextcmd = new_cmdline + i;
4542 eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4543 eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4544 if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
4545 eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4546 vim_free(*cmdlinep);
4547 *cmdlinep = new_cmdline;
4549 return src;
4553 * Check for '|' to separate commands and '"' to start comments.
4555 void
4556 separate_nextcmd(eap)
4557 exarg_T *eap;
4559 char_u *p;
4561 #ifdef FEAT_QUICKFIX
4562 p = skip_grep_pat(eap);
4563 #else
4564 p = eap->arg;
4565 #endif
4567 for ( ; *p; mb_ptr_adv(p))
4569 if (*p == Ctrl_V)
4571 if (eap->argt & (USECTRLV | XFILE))
4572 ++p; /* skip CTRL-V and next char */
4573 else
4574 /* remove CTRL-V and skip next char */
4575 STRMOVE(p, p + 1);
4576 if (*p == NUL) /* stop at NUL after CTRL-V */
4577 break;
4580 #ifdef FEAT_EVAL
4581 /* Skip over `=expr` when wildcards are expanded. */
4582 else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE))
4584 p += 2;
4585 (void)skip_expr(&p);
4587 #endif
4589 /* Check for '"': start of comment or '|': next command */
4590 /* :@" and :*" do not start a comment!
4591 * :redir @" doesn't either. */
4592 else if ((*p == '"' && !(eap->argt & NOTRLCOM)
4593 && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
4594 || p != eap->arg)
4595 && (eap->cmdidx != CMD_redir
4596 || p != eap->arg + 1 || p[-1] != '@'))
4597 || *p == '|' || *p == '\n')
4600 * We remove the '\' before the '|', unless USECTRLV is used
4601 * AND 'b' is present in 'cpoptions'.
4603 if ((vim_strchr(p_cpo, CPO_BAR) == NULL
4604 || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
4606 STRMOVE(p - 1, p); /* remove the '\' */
4607 --p;
4609 else
4611 eap->nextcmd = check_nextcmd(p);
4612 *p = NUL;
4613 break;
4618 if (!(eap->argt & NOTRLCOM)) /* remove trailing spaces */
4619 del_trailing_spaces(eap->arg);
4623 * get + command from ex argument
4625 static char_u *
4626 getargcmd(argp)
4627 char_u **argp;
4629 char_u *arg = *argp;
4630 char_u *command = NULL;
4632 if (*arg == '+') /* +[command] */
4634 ++arg;
4635 if (vim_isspace(*arg))
4636 command = dollar_command;
4637 else
4639 command = arg;
4640 arg = skip_cmd_arg(command, TRUE);
4641 if (*arg != NUL)
4642 *arg++ = NUL; /* terminate command with NUL */
4645 arg = skipwhite(arg); /* skip over spaces */
4646 *argp = arg;
4648 return command;
4652 * Find end of "+command" argument. Skip over "\ " and "\\".
4654 static char_u *
4655 skip_cmd_arg(p, rembs)
4656 char_u *p;
4657 int rembs; /* TRUE to halve the number of backslashes */
4659 while (*p && !vim_isspace(*p))
4661 if (*p == '\\' && p[1] != NUL)
4663 if (rembs)
4664 STRMOVE(p, p + 1);
4665 else
4666 ++p;
4668 mb_ptr_adv(p);
4670 return p;
4674 * Get "++opt=arg" argument.
4675 * Return FAIL or OK.
4677 static int
4678 getargopt(eap)
4679 exarg_T *eap;
4681 char_u *arg = eap->arg + 2;
4682 int *pp = NULL;
4683 #ifdef FEAT_MBYTE
4684 char_u *p;
4685 #endif
4687 /* ":edit ++[no]bin[ary] file" */
4688 if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4690 if (*arg == 'n')
4692 arg += 2;
4693 eap->force_bin = FORCE_NOBIN;
4695 else
4696 eap->force_bin = FORCE_BIN;
4697 if (!checkforcmd(&arg, "binary", 3))
4698 return FAIL;
4699 eap->arg = skipwhite(arg);
4700 return OK;
4703 /* ":read ++edit file" */
4704 if (STRNCMP(arg, "edit", 4) == 0)
4706 eap->read_edit = TRUE;
4707 eap->arg = skipwhite(arg + 4);
4708 return OK;
4711 if (STRNCMP(arg, "ff", 2) == 0)
4713 arg += 2;
4714 pp = &eap->force_ff;
4716 else if (STRNCMP(arg, "fileformat", 10) == 0)
4718 arg += 10;
4719 pp = &eap->force_ff;
4721 #ifdef FEAT_MBYTE
4722 else if (STRNCMP(arg, "enc", 3) == 0)
4724 arg += 3;
4725 pp = &eap->force_enc;
4727 else if (STRNCMP(arg, "encoding", 8) == 0)
4729 arg += 8;
4730 pp = &eap->force_enc;
4732 else if (STRNCMP(arg, "bad", 3) == 0)
4734 arg += 3;
4735 pp = &eap->bad_char;
4737 #endif
4739 if (pp == NULL || *arg != '=')
4740 return FAIL;
4742 ++arg;
4743 *pp = (int)(arg - eap->cmd);
4744 arg = skip_cmd_arg(arg, FALSE);
4745 eap->arg = skipwhite(arg);
4746 *arg = NUL;
4748 #ifdef FEAT_MBYTE
4749 if (pp == &eap->force_ff)
4751 #endif
4752 if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4753 return FAIL;
4754 #ifdef FEAT_MBYTE
4756 else if (pp == &eap->force_enc)
4758 /* Make 'fileencoding' lower case. */
4759 for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4760 *p = TOLOWER_ASC(*p);
4762 else
4764 /* Check ++bad= argument. Must be a single-byte character, "keep" or
4765 * "drop". */
4766 p = eap->cmd + eap->bad_char;
4767 if (STRICMP(p, "keep") == 0)
4768 eap->bad_char = BAD_KEEP;
4769 else if (STRICMP(p, "drop") == 0)
4770 eap->bad_char = BAD_DROP;
4771 else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
4772 eap->bad_char = *p;
4773 else
4774 return FAIL;
4776 #endif
4778 return OK;
4782 * ":abbreviate" and friends.
4784 static void
4785 ex_abbreviate(eap)
4786 exarg_T *eap;
4788 do_exmap(eap, TRUE); /* almost the same as mapping */
4792 * ":map" and friends.
4794 static void
4795 ex_map(eap)
4796 exarg_T *eap;
4799 * If we are sourcing .exrc or .vimrc in current directory we
4800 * print the mappings for security reasons.
4802 if (secure)
4804 secure = 2;
4805 msg_outtrans(eap->cmd);
4806 msg_putchar('\n');
4808 do_exmap(eap, FALSE);
4812 * ":unmap" and friends.
4814 static void
4815 ex_unmap(eap)
4816 exarg_T *eap;
4818 do_exmap(eap, FALSE);
4822 * ":mapclear" and friends.
4824 static void
4825 ex_mapclear(eap)
4826 exarg_T *eap;
4828 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4832 * ":abclear" and friends.
4834 static void
4835 ex_abclear(eap)
4836 exarg_T *eap;
4838 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4841 #ifdef FEAT_AUTOCMD
4842 static void
4843 ex_autocmd(eap)
4844 exarg_T *eap;
4847 * Disallow auto commands from .exrc and .vimrc in current
4848 * directory for security reasons.
4850 if (secure)
4852 secure = 2;
4853 eap->errmsg = e_curdir;
4855 else if (eap->cmdidx == CMD_autocmd)
4856 do_autocmd(eap->arg, eap->forceit);
4857 else
4858 do_augroup(eap->arg, eap->forceit);
4862 * ":doautocmd": Apply the automatic commands to the current buffer.
4864 static void
4865 ex_doautocmd(eap)
4866 exarg_T *eap;
4868 (void)do_doautocmd(eap->arg, TRUE);
4869 do_modelines(0);
4871 #endif
4873 #ifdef FEAT_LISTCMDS
4875 * :[N]bunload[!] [N] [bufname] unload buffer
4876 * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4877 * :[N]bwipeout[!] [N] [bufname] delete buffer really
4879 static void
4880 ex_bunload(eap)
4881 exarg_T *eap;
4883 eap->errmsg = do_bufdel(
4884 eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4885 : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4886 : DOBUF_UNLOAD, eap->arg,
4887 eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4891 * :[N]buffer [N] to buffer N
4892 * :[N]sbuffer [N] to buffer N
4894 static void
4895 ex_buffer(eap)
4896 exarg_T *eap;
4898 if (*eap->arg)
4899 eap->errmsg = e_trailing;
4900 else
4902 if (eap->addr_count == 0) /* default is current buffer */
4903 goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4904 else
4905 goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4910 * :[N]bmodified [N] to next mod. buffer
4911 * :[N]sbmodified [N] to next mod. buffer
4913 static void
4914 ex_bmodified(eap)
4915 exarg_T *eap;
4917 goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4921 * :[N]bnext [N] to next buffer
4922 * :[N]sbnext [N] split and to next buffer
4924 static void
4925 ex_bnext(eap)
4926 exarg_T *eap;
4928 goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4932 * :[N]bNext [N] to previous buffer
4933 * :[N]bprevious [N] to previous buffer
4934 * :[N]sbNext [N] split and to previous buffer
4935 * :[N]sbprevious [N] split and to previous buffer
4937 static void
4938 ex_bprevious(eap)
4939 exarg_T *eap;
4941 goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4945 * :brewind to first buffer
4946 * :bfirst to first buffer
4947 * :sbrewind split and to first buffer
4948 * :sbfirst split and to first buffer
4950 static void
4951 ex_brewind(eap)
4952 exarg_T *eap;
4954 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4958 * :blast to last buffer
4959 * :sblast split and to last buffer
4961 static void
4962 ex_blast(eap)
4963 exarg_T *eap;
4965 goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4967 #endif
4970 ends_excmd(c)
4971 int c;
4973 return (c == NUL || c == '|' || c == '"' || c == '\n');
4976 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
4977 || defined(PROTO)
4979 * Return the next command, after the first '|' or '\n'.
4980 * Return NULL if not found.
4982 char_u *
4983 find_nextcmd(p)
4984 char_u *p;
4986 while (*p != '|' && *p != '\n')
4988 if (*p == NUL)
4989 return NULL;
4990 ++p;
4992 return (p + 1);
4994 #endif
4997 * Check if *p is a separator between Ex commands.
4998 * Return NULL if it isn't, (p + 1) if it is.
5000 char_u *
5001 check_nextcmd(p)
5002 char_u *p;
5004 p = skipwhite(p);
5005 if (*p == '|' || *p == '\n')
5006 return (p + 1);
5007 else
5008 return NULL;
5012 * - if there are more files to edit
5013 * - and this is the last window
5014 * - and forceit not used
5015 * - and not repeated twice on a row
5016 * return FAIL and give error message if 'message' TRUE
5017 * return OK otherwise
5019 static int
5020 check_more(message, forceit)
5021 int message; /* when FALSE check only, no messages */
5022 int forceit;
5024 int n = ARGCOUNT - curwin->w_arg_idx - 1;
5026 if (!forceit && only_one_window()
5027 && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5029 if (message)
5031 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5032 if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5034 char_u buff[IOSIZE];
5036 if (n == 1)
5037 STRCPY(buff, _("1 more file to edit. Quit anyway?"));
5038 else
5039 vim_snprintf((char *)buff, IOSIZE,
5040 _("%d more files to edit. Quit anyway?"), n);
5041 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5042 return OK;
5043 return FAIL;
5045 #endif
5046 if (n == 1)
5047 EMSG(_("E173: 1 more file to edit"));
5048 else
5049 EMSGN(_("E173: %ld more files to edit"), n);
5050 quitmore = 2; /* next try to quit is allowed */
5052 return FAIL;
5054 return OK;
5057 #ifdef FEAT_CMDL_COMPL
5059 * Function given to ExpandGeneric() to obtain the list of command names.
5061 char_u *
5062 get_command_name(xp, idx)
5063 expand_T *xp UNUSED;
5064 int idx;
5066 if (idx >= (int)CMD_SIZE)
5067 # ifdef FEAT_USR_CMDS
5068 return get_user_command_name(idx);
5069 # else
5070 return NULL;
5071 # endif
5072 return cmdnames[idx].cmd_name;
5074 #endif
5076 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5077 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));
5078 static void uc_list __ARGS((char_u *name, size_t name_len));
5079 static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
5080 static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp));
5081 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));
5083 static int
5084 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
5085 char_u *name;
5086 size_t name_len;
5087 char_u *rep;
5088 long argt;
5089 long def;
5090 int flags;
5091 int compl;
5092 char_u *compl_arg;
5093 int force;
5095 ucmd_T *cmd = NULL;
5096 char_u *p;
5097 int i;
5098 int cmp = 1;
5099 char_u *rep_buf = NULL;
5100 garray_T *gap;
5102 replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5103 if (rep_buf == NULL)
5105 /* Can't replace termcodes - try using the string as is */
5106 rep_buf = vim_strsave(rep);
5108 /* Give up if out of memory */
5109 if (rep_buf == NULL)
5110 return FAIL;
5113 /* get address of growarray: global or in curbuf */
5114 if (flags & UC_BUFFER)
5116 gap = &curbuf->b_ucmds;
5117 if (gap->ga_itemsize == 0)
5118 ga_init2(gap, (int)sizeof(ucmd_T), 4);
5120 else
5121 gap = &ucmds;
5123 /* Search for the command in the already defined commands. */
5124 for (i = 0; i < gap->ga_len; ++i)
5126 size_t len;
5128 cmd = USER_CMD_GA(gap, i);
5129 len = STRLEN(cmd->uc_name);
5130 cmp = STRNCMP(name, cmd->uc_name, name_len);
5131 if (cmp == 0)
5133 if (name_len < len)
5134 cmp = -1;
5135 else if (name_len > len)
5136 cmp = 1;
5139 if (cmp == 0)
5141 if (!force)
5143 EMSG(_("E174: Command already exists: add ! to replace it"));
5144 goto fail;
5147 vim_free(cmd->uc_rep);
5148 cmd->uc_rep = NULL;
5149 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5150 vim_free(cmd->uc_compl_arg);
5151 cmd->uc_compl_arg = NULL;
5152 #endif
5153 break;
5156 /* Stop as soon as we pass the name to add */
5157 if (cmp < 0)
5158 break;
5161 /* Extend the array unless we're replacing an existing command */
5162 if (cmp != 0)
5164 if (ga_grow(gap, 1) != OK)
5165 goto fail;
5166 if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5167 goto fail;
5169 cmd = USER_CMD_GA(gap, i);
5170 mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5172 ++gap->ga_len;
5174 cmd->uc_name = p;
5177 cmd->uc_rep = rep_buf;
5178 cmd->uc_argt = argt;
5179 cmd->uc_def = def;
5180 cmd->uc_compl = compl;
5181 #ifdef FEAT_EVAL
5182 cmd->uc_scriptID = current_SID;
5183 # ifdef FEAT_CMDL_COMPL
5184 cmd->uc_compl_arg = compl_arg;
5185 # endif
5186 #endif
5188 return OK;
5190 fail:
5191 vim_free(rep_buf);
5192 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5193 vim_free(compl_arg);
5194 #endif
5195 return FAIL;
5199 * List of names for completion for ":command" with the EXPAND_ flag.
5200 * Must be alphabetical for completion.
5202 static struct
5204 int expand;
5205 char *name;
5206 } command_complete[] =
5208 {EXPAND_AUGROUP, "augroup"},
5209 {EXPAND_BUFFERS, "buffer"},
5210 {EXPAND_COMMANDS, "command"},
5211 #if defined(FEAT_CSCOPE)
5212 {EXPAND_CSCOPE, "cscope"},
5213 #endif
5214 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5215 {EXPAND_USER_DEFINED, "custom"},
5216 {EXPAND_USER_LIST, "customlist"},
5217 #endif
5218 {EXPAND_DIRECTORIES, "dir"},
5219 {EXPAND_ENV_VARS, "environment"},
5220 {EXPAND_EVENTS, "event"},
5221 {EXPAND_EXPRESSION, "expression"},
5222 {EXPAND_FILES, "file"},
5223 {EXPAND_FUNCTIONS, "function"},
5224 {EXPAND_HELP, "help"},
5225 {EXPAND_HIGHLIGHT, "highlight"},
5226 {EXPAND_MAPPINGS, "mapping"},
5227 {EXPAND_MENUS, "menu"},
5228 {EXPAND_SETTINGS, "option"},
5229 {EXPAND_SHELLCMD, "shellcmd"},
5230 #if defined(FEAT_SIGNS)
5231 {EXPAND_SIGN, "sign"},
5232 #endif
5233 {EXPAND_TAGS, "tag"},
5234 {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5235 {EXPAND_USER_VARS, "var"},
5236 {0, NULL}
5239 static void
5240 uc_list(name, name_len)
5241 char_u *name;
5242 size_t name_len;
5244 int i, j;
5245 int found = FALSE;
5246 ucmd_T *cmd;
5247 int len;
5248 long a;
5249 garray_T *gap;
5251 gap = &curbuf->b_ucmds;
5252 for (;;)
5254 for (i = 0; i < gap->ga_len; ++i)
5256 cmd = USER_CMD_GA(gap, i);
5257 a = (long)cmd->uc_argt;
5259 /* Skip commands which don't match the requested prefix */
5260 if (STRNCMP(name, cmd->uc_name, name_len) != 0)
5261 continue;
5263 /* Put out the title first time */
5264 if (!found)
5265 MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition"));
5266 found = TRUE;
5267 msg_putchar('\n');
5268 if (got_int)
5269 break;
5271 /* Special cases */
5272 msg_putchar(a & BANG ? '!' : ' ');
5273 msg_putchar(a & REGSTR ? '"' : ' ');
5274 msg_putchar(gap != &ucmds ? 'b' : ' ');
5275 msg_putchar(' ');
5277 msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
5278 len = (int)STRLEN(cmd->uc_name) + 4;
5280 do {
5281 msg_putchar(' ');
5282 ++len;
5283 } while (len < 16);
5285 len = 0;
5287 /* Arguments */
5288 switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
5290 case 0: IObuff[len++] = '0'; break;
5291 case (EXTRA): IObuff[len++] = '*'; break;
5292 case (EXTRA|NOSPC): IObuff[len++] = '?'; break;
5293 case (EXTRA|NEEDARG): IObuff[len++] = '+'; break;
5294 case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
5297 do {
5298 IObuff[len++] = ' ';
5299 } while (len < 5);
5301 /* Range */
5302 if (a & (RANGE|COUNT))
5304 if (a & COUNT)
5306 /* -count=N */
5307 sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
5308 len += (int)STRLEN(IObuff + len);
5310 else if (a & DFLALL)
5311 IObuff[len++] = '%';
5312 else if (cmd->uc_def >= 0)
5314 /* -range=N */
5315 sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
5316 len += (int)STRLEN(IObuff + len);
5318 else
5319 IObuff[len++] = '.';
5322 do {
5323 IObuff[len++] = ' ';
5324 } while (len < 11);
5326 /* Completion */
5327 for (j = 0; command_complete[j].expand != 0; ++j)
5328 if (command_complete[j].expand == cmd->uc_compl)
5330 STRCPY(IObuff + len, command_complete[j].name);
5331 len += (int)STRLEN(IObuff + len);
5332 break;
5335 do {
5336 IObuff[len++] = ' ';
5337 } while (len < 21);
5339 IObuff[len] = '\0';
5340 msg_outtrans(IObuff);
5342 msg_outtrans_special(cmd->uc_rep, FALSE);
5343 #ifdef FEAT_EVAL
5344 if (p_verbose > 0)
5345 last_set_msg(cmd->uc_scriptID);
5346 #endif
5347 out_flush();
5348 ui_breakcheck();
5349 if (got_int)
5350 break;
5352 if (gap == &ucmds || i < gap->ga_len)
5353 break;
5354 gap = &ucmds;
5357 if (!found)
5358 MSG(_("No user-defined commands found"));
5361 static char_u *
5362 uc_fun_cmd()
5364 static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
5365 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
5366 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
5367 0xb9, 0x7f, 0};
5368 int i;
5370 for (i = 0; fcmd[i]; ++i)
5371 IObuff[i] = fcmd[i] - 0x40;
5372 IObuff[i] = 0;
5373 return IObuff;
5376 static int
5377 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
5378 char_u *attr;
5379 size_t len;
5380 long *argt;
5381 long *def;
5382 int *flags;
5383 int *compl;
5384 char_u **compl_arg;
5386 char_u *p;
5388 if (len == 0)
5390 EMSG(_("E175: No attribute specified"));
5391 return FAIL;
5394 /* First, try the simple attributes (no arguments) */
5395 if (STRNICMP(attr, "bang", len) == 0)
5396 *argt |= BANG;
5397 else if (STRNICMP(attr, "buffer", len) == 0)
5398 *flags |= UC_BUFFER;
5399 else if (STRNICMP(attr, "register", len) == 0)
5400 *argt |= REGSTR;
5401 else if (STRNICMP(attr, "bar", len) == 0)
5402 *argt |= TRLBAR;
5403 else
5405 int i;
5406 char_u *val = NULL;
5407 size_t vallen = 0;
5408 size_t attrlen = len;
5410 /* Look for the attribute name - which is the part before any '=' */
5411 for (i = 0; i < (int)len; ++i)
5413 if (attr[i] == '=')
5415 val = &attr[i + 1];
5416 vallen = len - i - 1;
5417 attrlen = i;
5418 break;
5422 if (STRNICMP(attr, "nargs", attrlen) == 0)
5424 if (vallen == 1)
5426 if (*val == '0')
5427 /* Do nothing - this is the default */;
5428 else if (*val == '1')
5429 *argt |= (EXTRA | NOSPC | NEEDARG);
5430 else if (*val == '*')
5431 *argt |= EXTRA;
5432 else if (*val == '?')
5433 *argt |= (EXTRA | NOSPC);
5434 else if (*val == '+')
5435 *argt |= (EXTRA | NEEDARG);
5436 else
5437 goto wrong_nargs;
5439 else
5441 wrong_nargs:
5442 EMSG(_("E176: Invalid number of arguments"));
5443 return FAIL;
5446 else if (STRNICMP(attr, "range", attrlen) == 0)
5448 *argt |= RANGE;
5449 if (vallen == 1 && *val == '%')
5450 *argt |= DFLALL;
5451 else if (val != NULL)
5453 p = val;
5454 if (*def >= 0)
5456 two_count:
5457 EMSG(_("E177: Count cannot be specified twice"));
5458 return FAIL;
5461 *def = getdigits(&p);
5462 *argt |= (ZEROR | NOTADR);
5464 if (p != val + vallen || vallen == 0)
5466 invalid_count:
5467 EMSG(_("E178: Invalid default value for count"));
5468 return FAIL;
5472 else if (STRNICMP(attr, "count", attrlen) == 0)
5474 *argt |= (COUNT | ZEROR | RANGE | NOTADR);
5476 if (val != NULL)
5478 p = val;
5479 if (*def >= 0)
5480 goto two_count;
5482 *def = getdigits(&p);
5484 if (p != val + vallen)
5485 goto invalid_count;
5488 if (*def < 0)
5489 *def = 0;
5491 else if (STRNICMP(attr, "complete", attrlen) == 0)
5493 if (val == NULL)
5495 EMSG(_("E179: argument required for -complete"));
5496 return FAIL;
5499 if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
5500 == FAIL)
5501 return FAIL;
5503 else
5505 char_u ch = attr[len];
5506 attr[len] = '\0';
5507 EMSG2(_("E181: Invalid attribute: %s"), attr);
5508 attr[len] = ch;
5509 return FAIL;
5513 return OK;
5517 * ":command ..."
5519 static void
5520 ex_command(eap)
5521 exarg_T *eap;
5523 char_u *name;
5524 char_u *end;
5525 char_u *p;
5526 long argt = 0;
5527 long def = -1;
5528 int flags = 0;
5529 int compl = EXPAND_NOTHING;
5530 char_u *compl_arg = NULL;
5531 int has_attr = (eap->arg[0] == '-');
5533 p = eap->arg;
5535 /* Check for attributes */
5536 while (*p == '-')
5538 ++p;
5539 end = skiptowhite(p);
5540 if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5541 == FAIL)
5542 return;
5543 p = skipwhite(end);
5546 /* Get the name (if any) and skip to the following argument */
5547 name = p;
5548 if (ASCII_ISALPHA(*p))
5549 while (ASCII_ISALNUM(*p))
5550 ++p;
5551 if (!ends_excmd(*p) && !vim_iswhite(*p))
5553 EMSG(_("E182: Invalid command name"));
5554 return;
5556 end = p;
5558 /* If there is nothing after the name, and no attributes were specified,
5559 * we are listing commands
5561 p = skipwhite(end);
5562 if (!has_attr && ends_excmd(*p))
5564 uc_list(name, end - name);
5566 else if (!ASCII_ISUPPER(*name))
5568 EMSG(_("E183: User defined commands must start with an uppercase letter"));
5569 return;
5571 else
5572 uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5573 eap->forceit);
5577 * ":comclear"
5578 * Clear all user commands, global and for current buffer.
5580 void
5581 ex_comclear(eap)
5582 exarg_T *eap UNUSED;
5584 uc_clear(&ucmds);
5585 uc_clear(&curbuf->b_ucmds);
5589 * Clear all user commands for "gap".
5591 void
5592 uc_clear(gap)
5593 garray_T *gap;
5595 int i;
5596 ucmd_T *cmd;
5598 for (i = 0; i < gap->ga_len; ++i)
5600 cmd = USER_CMD_GA(gap, i);
5601 vim_free(cmd->uc_name);
5602 vim_free(cmd->uc_rep);
5603 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5604 vim_free(cmd->uc_compl_arg);
5605 # endif
5607 ga_clear(gap);
5610 static void
5611 ex_delcommand(eap)
5612 exarg_T *eap;
5614 int i = 0;
5615 ucmd_T *cmd = NULL;
5616 int cmp = -1;
5617 garray_T *gap;
5619 gap = &curbuf->b_ucmds;
5620 for (;;)
5622 for (i = 0; i < gap->ga_len; ++i)
5624 cmd = USER_CMD_GA(gap, i);
5625 cmp = STRCMP(eap->arg, cmd->uc_name);
5626 if (cmp <= 0)
5627 break;
5629 if (gap == &ucmds || cmp == 0)
5630 break;
5631 gap = &ucmds;
5634 if (cmp != 0)
5636 EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5637 return;
5640 vim_free(cmd->uc_name);
5641 vim_free(cmd->uc_rep);
5642 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5643 vim_free(cmd->uc_compl_arg);
5644 # endif
5646 --gap->ga_len;
5648 if (i < gap->ga_len)
5649 mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5653 * split and quote args for <f-args>
5655 static char_u *
5656 uc_split_args(arg, lenp)
5657 char_u *arg;
5658 size_t *lenp;
5660 char_u *buf;
5661 char_u *p;
5662 char_u *q;
5663 int len;
5665 /* Precalculate length */
5666 p = arg;
5667 len = 2; /* Initial and final quotes */
5669 while (*p)
5671 if (p[0] == '\\' && p[1] == '\\')
5673 len += 2;
5674 p += 2;
5676 else if (p[0] == '\\' && vim_iswhite(p[1]))
5678 len += 1;
5679 p += 2;
5681 else if (*p == '\\' || *p == '"')
5683 len += 2;
5684 p += 1;
5686 else if (vim_iswhite(*p))
5688 p = skipwhite(p);
5689 if (*p == NUL)
5690 break;
5691 len += 3; /* "," */
5693 else
5695 ++len;
5696 ++p;
5700 buf = alloc(len + 1);
5701 if (buf == NULL)
5703 *lenp = 0;
5704 return buf;
5707 p = arg;
5708 q = buf;
5709 *q++ = '"';
5710 while (*p)
5712 if (p[0] == '\\' && p[1] == '\\')
5714 *q++ = '\\';
5715 *q++ = '\\';
5716 p += 2;
5718 else if (p[0] == '\\' && vim_iswhite(p[1]))
5720 *q++ = p[1];
5721 p += 2;
5723 else if (*p == '\\' || *p == '"')
5725 *q++ = '\\';
5726 *q++ = *p++;
5728 else if (vim_iswhite(*p))
5730 p = skipwhite(p);
5731 if (*p == NUL)
5732 break;
5733 *q++ = '"';
5734 *q++ = ',';
5735 *q++ = '"';
5737 else
5739 *q++ = *p++;
5742 *q++ = '"';
5743 *q = 0;
5745 *lenp = len;
5746 return buf;
5750 * Check for a <> code in a user command.
5751 * "code" points to the '<'. "len" the length of the <> (inclusive).
5752 * "buf" is where the result is to be added.
5753 * "split_buf" points to a buffer used for splitting, caller should free it.
5754 * "split_len" is the length of what "split_buf" contains.
5755 * Returns the length of the replacement, which has been added to "buf".
5756 * Returns -1 if there was no match, and only the "<" has been copied.
5758 static size_t
5759 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5760 char_u *code;
5761 size_t len;
5762 char_u *buf;
5763 ucmd_T *cmd; /* the user command we're expanding */
5764 exarg_T *eap; /* ex arguments */
5765 char_u **split_buf;
5766 size_t *split_len;
5768 size_t result = 0;
5769 char_u *p = code + 1;
5770 size_t l = len - 2;
5771 int quote = 0;
5772 enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5773 ct_LT, ct_NONE } type = ct_NONE;
5775 if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5777 quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5778 p += 2;
5779 l -= 2;
5782 ++l;
5783 if (l <= 1)
5784 type = ct_NONE;
5785 else if (STRNICMP(p, "args>", l) == 0)
5786 type = ct_ARGS;
5787 else if (STRNICMP(p, "bang>", l) == 0)
5788 type = ct_BANG;
5789 else if (STRNICMP(p, "count>", l) == 0)
5790 type = ct_COUNT;
5791 else if (STRNICMP(p, "line1>", l) == 0)
5792 type = ct_LINE1;
5793 else if (STRNICMP(p, "line2>", l) == 0)
5794 type = ct_LINE2;
5795 else if (STRNICMP(p, "lt>", l) == 0)
5796 type = ct_LT;
5797 else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
5798 type = ct_REGISTER;
5800 switch (type)
5802 case ct_ARGS:
5803 /* Simple case first */
5804 if (*eap->arg == NUL)
5806 if (quote == 1)
5808 result = 2;
5809 if (buf != NULL)
5810 STRCPY(buf, "''");
5812 else
5813 result = 0;
5814 break;
5817 /* When specified there is a single argument don't split it.
5818 * Works for ":Cmd %" when % is "a b c". */
5819 if ((eap->argt & NOSPC) && quote == 2)
5820 quote = 1;
5822 switch (quote)
5824 case 0: /* No quoting, no splitting */
5825 result = STRLEN(eap->arg);
5826 if (buf != NULL)
5827 STRCPY(buf, eap->arg);
5828 break;
5829 case 1: /* Quote, but don't split */
5830 result = STRLEN(eap->arg) + 2;
5831 for (p = eap->arg; *p; ++p)
5833 if (*p == '\\' || *p == '"')
5834 ++result;
5837 if (buf != NULL)
5839 *buf++ = '"';
5840 for (p = eap->arg; *p; ++p)
5842 if (*p == '\\' || *p == '"')
5843 *buf++ = '\\';
5844 *buf++ = *p;
5846 *buf = '"';
5849 break;
5850 case 2: /* Quote and split (<f-args>) */
5851 /* This is hard, so only do it once, and cache the result */
5852 if (*split_buf == NULL)
5853 *split_buf = uc_split_args(eap->arg, split_len);
5855 result = *split_len;
5856 if (buf != NULL && result != 0)
5857 STRCPY(buf, *split_buf);
5859 break;
5861 break;
5863 case ct_BANG:
5864 result = eap->forceit ? 1 : 0;
5865 if (quote)
5866 result += 2;
5867 if (buf != NULL)
5869 if (quote)
5870 *buf++ = '"';
5871 if (eap->forceit)
5872 *buf++ = '!';
5873 if (quote)
5874 *buf = '"';
5876 break;
5878 case ct_LINE1:
5879 case ct_LINE2:
5880 case ct_COUNT:
5882 char num_buf[20];
5883 long num = (type == ct_LINE1) ? eap->line1 :
5884 (type == ct_LINE2) ? eap->line2 :
5885 (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5886 size_t num_len;
5888 sprintf(num_buf, "%ld", num);
5889 num_len = STRLEN(num_buf);
5890 result = num_len;
5892 if (quote)
5893 result += 2;
5895 if (buf != NULL)
5897 if (quote)
5898 *buf++ = '"';
5899 STRCPY(buf, num_buf);
5900 buf += num_len;
5901 if (quote)
5902 *buf = '"';
5905 break;
5908 case ct_REGISTER:
5909 result = eap->regname ? 1 : 0;
5910 if (quote)
5911 result += 2;
5912 if (buf != NULL)
5914 if (quote)
5915 *buf++ = '\'';
5916 if (eap->regname)
5917 *buf++ = eap->regname;
5918 if (quote)
5919 *buf = '\'';
5921 break;
5923 case ct_LT:
5924 result = 1;
5925 if (buf != NULL)
5926 *buf = '<';
5927 break;
5929 default:
5930 /* Not recognized: just copy the '<' and return -1. */
5931 result = (size_t)-1;
5932 if (buf != NULL)
5933 *buf = '<';
5934 break;
5937 return result;
5940 static void
5941 do_ucmd(eap)
5942 exarg_T *eap;
5944 char_u *buf;
5945 char_u *p;
5946 char_u *q;
5948 char_u *start;
5949 char_u *end = NULL;
5950 char_u *ksp;
5951 size_t len, totlen;
5953 size_t split_len = 0;
5954 char_u *split_buf = NULL;
5955 ucmd_T *cmd;
5956 #ifdef FEAT_EVAL
5957 scid_T save_current_SID = current_SID;
5958 #endif
5960 if (eap->cmdidx == CMD_USER)
5961 cmd = USER_CMD(eap->useridx);
5962 else
5963 cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5966 * Replace <> in the command by the arguments.
5967 * First round: "buf" is NULL, compute length, allocate "buf".
5968 * Second round: copy result into "buf".
5970 buf = NULL;
5971 for (;;)
5973 p = cmd->uc_rep; /* source */
5974 q = buf; /* destination */
5975 totlen = 0;
5977 for (;;)
5979 start = vim_strchr(p, '<');
5980 if (start != NULL)
5981 end = vim_strchr(start + 1, '>');
5982 if (buf != NULL)
5984 ksp = vim_strchr(p, K_SPECIAL);
5985 if (ksp != NULL && (start == NULL || ksp < start || end == NULL)
5986 && ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)
5987 # ifdef FEAT_GUI
5988 || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI)
5989 # endif
5992 /* K_SPECIAL han been put in the buffer as K_SPECIAL
5993 * KS_SPECIAL KE_FILLER, like for mappings, but
5994 * do_cmdline() doesn't handle that, so convert it back.
5995 * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */
5996 len = ksp - p;
5997 if (len > 0)
5999 mch_memmove(q, p, len);
6000 q += len;
6002 *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI;
6003 p = ksp + 3;
6004 continue;
6008 /* break if there no <item> is found */
6009 if (start == NULL || end == NULL)
6010 break;
6012 /* Include the '>' */
6013 ++end;
6015 /* Take everything up to the '<' */
6016 len = start - p;
6017 if (buf == NULL)
6018 totlen += len;
6019 else
6021 mch_memmove(q, p, len);
6022 q += len;
6025 len = uc_check_code(start, end - start, q, cmd, eap,
6026 &split_buf, &split_len);
6027 if (len == (size_t)-1)
6029 /* no match, continue after '<' */
6030 p = start + 1;
6031 len = 1;
6033 else
6034 p = end;
6035 if (buf == NULL)
6036 totlen += len;
6037 else
6038 q += len;
6040 if (buf != NULL) /* second time here, finished */
6042 STRCPY(q, p);
6043 break;
6046 totlen += STRLEN(p); /* Add on the trailing characters */
6047 buf = alloc((unsigned)(totlen + 1));
6048 if (buf == NULL)
6050 vim_free(split_buf);
6051 return;
6055 #ifdef FEAT_EVAL
6056 current_SID = cmd->uc_scriptID;
6057 #endif
6058 (void)do_cmdline(buf, eap->getline, eap->cookie,
6059 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6060 #ifdef FEAT_EVAL
6061 current_SID = save_current_SID;
6062 #endif
6063 vim_free(buf);
6064 vim_free(split_buf);
6067 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6068 static char_u *
6069 get_user_command_name(idx)
6070 int idx;
6072 return get_user_commands(NULL, idx - (int)CMD_SIZE);
6076 * Function given to ExpandGeneric() to obtain the list of user command names.
6078 char_u *
6079 get_user_commands(xp, idx)
6080 expand_T *xp UNUSED;
6081 int idx;
6083 if (idx < curbuf->b_ucmds.ga_len)
6084 return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
6085 idx -= curbuf->b_ucmds.ga_len;
6086 if (idx < ucmds.ga_len)
6087 return USER_CMD(idx)->uc_name;
6088 return NULL;
6092 * Function given to ExpandGeneric() to obtain the list of user command
6093 * attributes.
6095 char_u *
6096 get_user_cmd_flags(xp, idx)
6097 expand_T *xp UNUSED;
6098 int idx;
6100 static char *user_cmd_flags[] =
6101 {"bang", "bar", "buffer", "complete", "count",
6102 "nargs", "range", "register"};
6104 if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0])))
6105 return NULL;
6106 return (char_u *)user_cmd_flags[idx];
6110 * Function given to ExpandGeneric() to obtain the list of values for -nargs.
6112 char_u *
6113 get_user_cmd_nargs(xp, idx)
6114 expand_T *xp UNUSED;
6115 int idx;
6117 static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
6119 if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0])))
6120 return NULL;
6121 return (char_u *)user_cmd_nargs[idx];
6125 * Function given to ExpandGeneric() to obtain the list of values for -complete.
6127 char_u *
6128 get_user_cmd_complete(xp, idx)
6129 expand_T *xp UNUSED;
6130 int idx;
6132 return (char_u *)command_complete[idx].name;
6134 # endif /* FEAT_CMDL_COMPL */
6136 #endif /* FEAT_USR_CMDS */
6138 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
6140 * Parse a completion argument "value[vallen]".
6141 * The detected completion goes in "*complp", argument type in "*argt".
6142 * When there is an argument, for function and user defined completion, it's
6143 * copied to allocated memory and stored in "*compl_arg".
6144 * Returns FAIL if something is wrong.
6147 parse_compl_arg(value, vallen, complp, argt, compl_arg)
6148 char_u *value;
6149 int vallen;
6150 int *complp;
6151 long *argt;
6152 char_u **compl_arg;
6154 char_u *arg = NULL;
6155 size_t arglen = 0;
6156 int i;
6157 int valend = vallen;
6159 /* Look for any argument part - which is the part after any ',' */
6160 for (i = 0; i < vallen; ++i)
6162 if (value[i] == ',')
6164 arg = &value[i + 1];
6165 arglen = vallen - i - 1;
6166 valend = i;
6167 break;
6171 for (i = 0; command_complete[i].expand != 0; ++i)
6173 if ((int)STRLEN(command_complete[i].name) == valend
6174 && STRNCMP(value, command_complete[i].name, valend) == 0)
6176 *complp = command_complete[i].expand;
6177 if (command_complete[i].expand == EXPAND_BUFFERS)
6178 *argt |= BUFNAME;
6179 else if (command_complete[i].expand == EXPAND_DIRECTORIES
6180 || command_complete[i].expand == EXPAND_FILES)
6181 *argt |= XFILE;
6182 break;
6186 if (command_complete[i].expand == 0)
6188 EMSG2(_("E180: Invalid complete value: %s"), value);
6189 return FAIL;
6192 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6193 if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
6194 && arg != NULL)
6195 # else
6196 if (arg != NULL)
6197 # endif
6199 EMSG(_("E468: Completion argument only allowed for custom completion"));
6200 return FAIL;
6203 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6204 if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
6205 && arg == NULL)
6207 EMSG(_("E467: Custom completion requires a function argument"));
6208 return FAIL;
6211 if (arg != NULL)
6212 *compl_arg = vim_strnsave(arg, (int)arglen);
6213 # endif
6214 return OK;
6216 #endif
6218 static void
6219 ex_colorscheme(eap)
6220 exarg_T *eap;
6222 if (load_colors(eap->arg) == FAIL)
6223 EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
6226 static void
6227 ex_codecheck(eap)
6228 exarg_T *eap;
6230 switch (eap->cmdidx) {
6231 case CMD_ccadd:
6232 if (!cc_get_is_started())
6233 cc_init();
6234 if (cc_is_buf_ok(curbuf)) {
6235 if (*eap->arg != NUL)
6236 cc_addbuf_setcmd(curbuf, eap->arg);
6237 else
6238 EMSG(_("You have to specify a valid compile command "
6239 "in order to add this buffer to watchlist."));
6240 } else
6241 EMSG(_("The present version of CodeCheck does not support "
6242 "this language."));
6243 break;
6244 case CMD_ccrem:
6245 cc_rem_buf(curbuf);
6246 if (cc_get_bufcount() == 0)
6247 cc_exit();
6248 break;
6249 default:
6250 return;
6254 static void
6255 ex_highlight(eap)
6256 exarg_T *eap;
6258 if (*eap->arg == NUL && eap->cmd[2] == '!')
6259 MSG(_("Greetings, Vim user!"));
6260 do_highlight(eap->arg, eap->forceit, FALSE);
6265 * Call this function if we thought we were going to exit, but we won't
6266 * (because of an error). May need to restore the terminal mode.
6268 void
6269 not_exiting()
6271 exiting = FALSE;
6272 settmode(TMODE_RAW);
6276 * ":quit": quit current window, quit Vim if closed the last window.
6278 static void
6279 ex_quit(eap)
6280 exarg_T *eap;
6282 #ifdef FEAT_CMDWIN
6283 if (cmdwin_type != 0)
6285 cmdwin_result = Ctrl_C;
6286 return;
6288 #endif
6289 /* Don't quit while editing the command line. */
6290 if (text_locked())
6292 text_locked_msg();
6293 return;
6295 #ifdef FEAT_AUTOCMD
6296 if (curbuf_locked())
6297 return;
6298 #endif
6300 #ifdef FEAT_NETBEANS_INTG
6301 netbeansForcedQuit = eap->forceit;
6302 #endif
6305 * If there are more files or windows we won't exit.
6307 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6308 exiting = TRUE;
6309 if ((!P_HID(curbuf)
6310 && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
6311 || check_more(TRUE, eap->forceit) == FAIL
6312 || (only_one_window() && check_changed_any(eap->forceit)))
6314 not_exiting();
6316 else
6318 #ifdef FEAT_WINDOWS
6319 if (only_one_window()) /* quit last window */
6320 #endif
6321 getout(0);
6322 #ifdef FEAT_WINDOWS
6323 # ifdef FEAT_GUI
6324 need_mouse_correct = TRUE;
6325 # endif
6326 /* close window; may free buffer */
6327 win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
6328 #endif
6333 * ":cquit".
6335 static void
6336 ex_cquit(eap)
6337 exarg_T *eap UNUSED;
6339 getout(1); /* this does not always pass on the exit code to the Manx
6340 compiler. why? */
6344 * ":qall": try to quit all windows
6346 static void
6347 ex_quit_all(eap)
6348 exarg_T *eap;
6350 # ifdef FEAT_CMDWIN
6351 if (cmdwin_type != 0)
6353 if (eap->forceit)
6354 cmdwin_result = K_XF1; /* ex_window() takes care of this */
6355 else
6356 cmdwin_result = K_XF2;
6357 return;
6359 # endif
6361 /* Don't quit while editing the command line. */
6362 if (text_locked())
6364 text_locked_msg();
6365 return;
6367 #ifdef FEAT_AUTOCMD
6368 if (curbuf_locked())
6369 return;
6370 #endif
6372 exiting = TRUE;
6373 if (eap->forceit || !check_changed_any(FALSE))
6374 getout(0);
6375 not_exiting();
6378 #if defined(FEAT_WINDOWS) || defined(PROTO)
6380 * ":close": close current window, unless it is the last one
6382 static void
6383 ex_close(eap)
6384 exarg_T *eap;
6386 # ifdef FEAT_CMDWIN
6387 if (cmdwin_type != 0)
6388 cmdwin_result = K_IGNORE;
6389 else
6390 # endif
6391 if (!text_locked()
6392 #ifdef FEAT_AUTOCMD
6393 && !curbuf_locked()
6394 #endif
6396 ex_win_close(eap->forceit, curwin, NULL);
6399 # ifdef FEAT_QUICKFIX
6401 * ":pclose": Close any preview window.
6403 static void
6404 ex_pclose(eap)
6405 exarg_T *eap;
6407 win_T *win;
6409 for (win = firstwin; win != NULL; win = win->w_next)
6410 if (win->w_p_pvw)
6412 ex_win_close(eap->forceit, win, NULL);
6413 break;
6416 # endif
6419 * Close window "win" and take care of handling closing the last window for a
6420 * modified buffer.
6422 static void
6423 ex_win_close(forceit, win, tp)
6424 int forceit;
6425 win_T *win;
6426 tabpage_T *tp; /* NULL or the tab page "win" is in */
6428 int need_hide;
6429 buf_T *buf = win->w_buffer;
6431 need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
6432 if (need_hide && !P_HID(buf) && !forceit)
6434 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6435 if ((p_confirm || cmdmod.confirm) && p_write)
6437 dialog_changed(buf, FALSE);
6438 if (buf_valid(buf) && bufIsChanged(buf))
6439 return;
6440 need_hide = FALSE;
6442 else
6443 # endif
6445 EMSG(_(e_nowrtmsg));
6446 return;
6450 # ifdef FEAT_GUI
6451 need_mouse_correct = TRUE;
6452 # endif
6454 /* free buffer when not hiding it or when it's a scratch buffer */
6455 if (tp == NULL)
6456 win_close(win, !need_hide && !P_HID(buf));
6457 else
6458 win_close_othertab(win, !need_hide && !P_HID(buf), tp);
6462 * ":tabclose": close current tab page, unless it is the last one.
6463 * ":tabclose N": close tab page N.
6465 static void
6466 ex_tabclose(eap)
6467 exarg_T *eap;
6469 tabpage_T *tp;
6471 # ifdef FEAT_CMDWIN
6472 if (cmdwin_type != 0)
6473 cmdwin_result = K_IGNORE;
6474 else
6475 # endif
6476 if (first_tabpage->tp_next == NULL)
6477 EMSG(_("E784: Cannot close last tab page"));
6478 else
6480 if (eap->addr_count > 0)
6482 tp = find_tabpage((int)eap->line2);
6483 if (tp == NULL)
6485 beep_flush();
6486 return;
6488 if (tp != curtab)
6490 tabpage_close_other(tp, eap->forceit);
6491 return;
6494 if (!text_locked()
6495 #ifdef FEAT_AUTOCMD
6496 && !curbuf_locked()
6497 #endif
6499 tabpage_close(eap->forceit);
6504 * ":tabonly": close all tab pages except the current one
6506 static void
6507 ex_tabonly(eap)
6508 exarg_T *eap;
6510 tabpage_T *tp;
6511 int done;
6513 # ifdef FEAT_CMDWIN
6514 if (cmdwin_type != 0)
6515 cmdwin_result = K_IGNORE;
6516 else
6517 # endif
6518 if (first_tabpage->tp_next == NULL)
6519 MSG(_("Already only one tab page"));
6520 else
6522 /* Repeat this up to a 1000 times, because autocommands may mess
6523 * up the lists. */
6524 for (done = 0; done < 1000; ++done)
6526 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6527 if (tp->tp_topframe != topframe)
6529 tabpage_close_other(tp, eap->forceit);
6530 /* if we failed to close it quit */
6531 if (valid_tabpage(tp))
6532 done = 1000;
6533 /* start over, "tp" is now invalid */
6534 break;
6536 if (first_tabpage->tp_next == NULL)
6537 break;
6543 * Close the current tab page.
6545 void
6546 tabpage_close(forceit)
6547 int forceit;
6549 /* First close all the windows but the current one. If that worked then
6550 * close the last window in this tab, that will close it. */
6551 if (lastwin != firstwin)
6552 close_others(TRUE, forceit);
6553 if (lastwin == firstwin)
6554 ex_win_close(forceit, curwin, NULL);
6555 # ifdef FEAT_GUI
6556 need_mouse_correct = TRUE;
6557 # endif
6561 * Close tab page "tp", which is not the current tab page.
6562 * Note that autocommands may make "tp" invalid.
6563 * Also takes care of the tab pages line disappearing when closing the
6564 * last-but-one tab page.
6566 void
6567 tabpage_close_other(tp, forceit)
6568 tabpage_T *tp;
6569 int forceit;
6571 int done = 0;
6572 win_T *wp;
6573 int h = tabline_height();
6575 /* Limit to 1000 windows, autocommands may add a window while we close
6576 * one. OK, so I'm paranoid... */
6577 while (++done < 1000)
6579 wp = tp->tp_firstwin;
6580 ex_win_close(forceit, wp, tp);
6582 /* Autocommands may delete the tab page under our fingers and we may
6583 * fail to close a window with a modified buffer. */
6584 if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
6585 break;
6588 redraw_tabline = TRUE;
6589 if (h != tabline_height())
6590 shell_new_rows();
6594 * ":only".
6596 static void
6597 ex_only(eap)
6598 exarg_T *eap;
6600 # ifdef FEAT_GUI
6601 need_mouse_correct = TRUE;
6602 # endif
6603 close_others(TRUE, eap->forceit);
6607 * ":all" and ":sall".
6608 * Also used for ":tab drop file ..." after setting the argument list.
6610 void
6611 ex_all(eap)
6612 exarg_T *eap;
6614 if (eap->addr_count == 0)
6615 eap->line2 = 9999;
6616 do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
6618 #endif /* FEAT_WINDOWS */
6620 static void
6621 ex_hide(eap)
6622 exarg_T *eap;
6624 if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
6625 eap->errmsg = e_invarg;
6626 else
6628 /* ":hide" or ":hide | cmd": hide current window */
6629 eap->nextcmd = check_nextcmd(eap->arg);
6630 #ifdef FEAT_WINDOWS
6631 if (!eap->skip)
6633 # ifdef FEAT_GUI
6634 need_mouse_correct = TRUE;
6635 # endif
6636 win_close(curwin, FALSE); /* don't free buffer */
6638 #endif
6643 * ":stop" and ":suspend": Suspend Vim.
6645 static void
6646 ex_stop(eap)
6647 exarg_T *eap;
6650 * Disallow suspending for "rvim".
6652 if (!check_restricted()
6653 #ifdef WIN3264
6655 * Check if external commands are allowed now.
6657 && can_end_termcap_mode(TRUE)
6658 #endif
6661 if (!eap->forceit)
6662 autowrite_all();
6663 windgoto((int)Rows - 1, 0);
6664 out_char('\n');
6665 out_flush();
6666 stoptermcap();
6667 out_flush(); /* needed for SUN to restore xterm buffer */
6668 #ifdef FEAT_TITLE
6669 mch_restore_title(3); /* restore window titles */
6670 #endif
6671 ui_suspend(); /* call machine specific function */
6672 #ifdef FEAT_TITLE
6673 maketitle();
6674 resettitle(); /* force updating the title */
6675 #endif
6676 starttermcap();
6677 scroll_start(); /* scroll screen before redrawing */
6678 redraw_later_clear();
6679 shell_resized(); /* may have resized window */
6684 * ":exit", ":xit" and ":wq": Write file and exit Vim.
6686 static void
6687 ex_exit(eap)
6688 exarg_T *eap;
6690 #ifdef FEAT_CMDWIN
6691 if (cmdwin_type != 0)
6693 cmdwin_result = Ctrl_C;
6694 return;
6696 #endif
6697 /* Don't quit while editing the command line. */
6698 if (text_locked())
6700 text_locked_msg();
6701 return;
6703 #ifdef FEAT_AUTOCMD
6704 if (curbuf_locked())
6705 return;
6706 #endif
6709 * if more files or windows we won't exit
6711 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6712 exiting = TRUE;
6713 if ( ((eap->cmdidx == CMD_wq
6714 || curbufIsChanged())
6715 && do_write(eap) == FAIL)
6716 || check_more(TRUE, eap->forceit) == FAIL
6717 || (only_one_window() && check_changed_any(eap->forceit)))
6719 not_exiting();
6721 else
6723 #ifdef FEAT_WINDOWS
6724 if (only_one_window()) /* quit last window, exit Vim */
6725 #endif
6726 getout(0);
6727 #ifdef FEAT_WINDOWS
6728 # ifdef FEAT_GUI
6729 need_mouse_correct = TRUE;
6730 # endif
6731 /* quit current window, may free buffer */
6732 win_close(curwin, !P_HID(curwin->w_buffer));
6733 #endif
6738 * ":print", ":list", ":number".
6740 static void
6741 ex_print(eap)
6742 exarg_T *eap;
6744 if (curbuf->b_ml.ml_flags & ML_EMPTY)
6745 EMSG(_(e_emptybuf));
6746 else
6748 for ( ;!got_int; ui_breakcheck())
6750 print_line(eap->line1,
6751 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
6752 || (eap->flags & EXFLAG_NR)),
6753 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
6754 if (++eap->line1 > eap->line2)
6755 break;
6756 out_flush(); /* show one line at a time */
6758 setpcmark();
6759 /* put cursor at last line */
6760 curwin->w_cursor.lnum = eap->line2;
6761 beginline(BL_SOL | BL_FIX);
6764 ex_no_reprint = TRUE;
6767 #ifdef FEAT_BYTEOFF
6768 static void
6769 ex_goto(eap)
6770 exarg_T *eap;
6772 goto_byte(eap->line2);
6774 #endif
6777 * ":shell".
6779 static void
6780 ex_shell(eap)
6781 exarg_T *eap UNUSED;
6783 do_shell(NULL, 0);
6786 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6787 || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6788 || defined(FEAT_GUI_MSWIN) \
6789 || defined(FEAT_GUI_MAC) \
6790 || defined(PROTO)
6793 * Handle a file drop. The code is here because a drop is *nearly* like an
6794 * :args command, but not quite (we have a list of exact filenames, so we
6795 * don't want to (a) parse a command line, or (b) expand wildcards. So the
6796 * code is very similar to :args and hence needs access to a lot of the static
6797 * functions in this file.
6799 * The list should be allocated using alloc(), as should each item in the
6800 * list. This function takes over responsibility for freeing the list.
6802 * XXX The list is made into the argument list. This is freed using
6803 * FreeWild(), which does a series of vim_free() calls, unless the two defines
6804 * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6805 * routine _fnexplodefree() is used. This may cause problems, but as the drop
6806 * file functionality is (currently) not in EMX this is not presently a
6807 * problem.
6809 void
6810 handle_drop(filec, filev, split)
6811 int filec; /* the number of files dropped */
6812 char_u **filev; /* the list of files dropped */
6813 int split; /* force splitting the window */
6815 exarg_T ea;
6816 int save_msg_scroll = msg_scroll;
6818 /* Postpone this while editing the command line. */
6819 if (text_locked())
6820 return;
6821 #ifdef FEAT_AUTOCMD
6822 if (curbuf_locked())
6823 return;
6824 #endif
6825 /* When the screen is being updated we should not change buffers and
6826 * windows structures, it may cause freed memory to be used. */
6827 if (updating_screen)
6828 return;
6830 /* Check whether the current buffer is changed. If so, we will need
6831 * to split the current window or data could be lost.
6832 * We don't need to check if the 'hidden' option is set, as in this
6833 * case the buffer won't be lost.
6835 if (!P_HID(curbuf) && !split)
6837 ++emsg_off;
6838 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6839 --emsg_off;
6841 if (split)
6843 # ifdef FEAT_WINDOWS
6844 if (win_split(0, 0) == FAIL)
6845 return;
6846 # ifdef FEAT_SCROLLBIND
6847 curwin->w_p_scb = FALSE;
6848 # endif
6850 /* When splitting the window, create a new alist. Otherwise the
6851 * existing one is overwritten. */
6852 alist_unlink(curwin->w_alist);
6853 alist_new();
6854 # else
6855 return; /* can't split, always fail */
6856 # endif
6860 * Set up the new argument list.
6862 alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
6865 * Move to the first file.
6867 /* Fake up a minimal "next" command for do_argfile() */
6868 vim_memset(&ea, 0, sizeof(ea));
6869 ea.cmd = (char_u *)"next";
6870 do_argfile(&ea, 0);
6872 /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6873 * mode that is not needed here. */
6874 need_start_insertmode = FALSE;
6876 /* Restore msg_scroll, otherwise a following command may cause scrolling
6877 * unexpectedly. The screen will be redrawn by the caller, thus
6878 * msg_scroll being set by displaying a message is irrelevant. */
6879 msg_scroll = save_msg_scroll;
6881 #endif
6884 * Clear an argument list: free all file names and reset it to zero entries.
6886 void
6887 alist_clear(al)
6888 alist_T *al;
6890 while (--al->al_ga.ga_len >= 0)
6891 vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6892 ga_clear(&al->al_ga);
6896 * Init an argument list.
6898 void
6899 alist_init(al)
6900 alist_T *al;
6902 ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6905 #if defined(FEAT_WINDOWS) || defined(PROTO)
6908 * Remove a reference from an argument list.
6909 * Ignored when the argument list is the global one.
6910 * If the argument list is no longer used by any window, free it.
6912 void
6913 alist_unlink(al)
6914 alist_T *al;
6916 if (al != &global_alist && --al->al_refcount <= 0)
6918 alist_clear(al);
6919 vim_free(al);
6923 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6925 * Create a new argument list and use it for the current window.
6927 void
6928 alist_new()
6930 curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6931 if (curwin->w_alist == NULL)
6933 curwin->w_alist = &global_alist;
6934 ++global_alist.al_refcount;
6936 else
6938 curwin->w_alist->al_refcount = 1;
6939 alist_init(curwin->w_alist);
6942 # endif
6943 #endif
6945 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6947 * Expand the file names in the global argument list.
6948 * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
6949 * numbers to be re-used.
6951 void
6952 alist_expand(fnum_list, fnum_len)
6953 int *fnum_list;
6954 int fnum_len;
6956 char_u **old_arg_files;
6957 int old_arg_count;
6958 char_u **new_arg_files;
6959 int new_arg_file_count;
6960 char_u *save_p_su = p_su;
6961 int i;
6963 /* Don't use 'suffixes' here. This should work like the shell did the
6964 * expansion. Also, the vimrc file isn't read yet, thus the user
6965 * can't set the options. */
6966 p_su = empty_option;
6967 old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6968 if (old_arg_files != NULL)
6970 for (i = 0; i < GARGCOUNT; ++i)
6971 old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
6972 old_arg_count = GARGCOUNT;
6973 if (expand_wildcards(old_arg_count, old_arg_files,
6974 &new_arg_file_count, &new_arg_files,
6975 EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6976 && new_arg_file_count > 0)
6978 alist_set(&global_alist, new_arg_file_count, new_arg_files,
6979 TRUE, fnum_list, fnum_len);
6980 FreeWild(old_arg_count, old_arg_files);
6983 p_su = save_p_su;
6985 #endif
6988 * Set the argument list for the current window.
6989 * Takes over the allocated files[] and the allocated fnames in it.
6991 void
6992 alist_set(al, count, files, use_curbuf, fnum_list, fnum_len)
6993 alist_T *al;
6994 int count;
6995 char_u **files;
6996 int use_curbuf;
6997 int *fnum_list;
6998 int fnum_len;
7000 int i;
7002 alist_clear(al);
7003 if (ga_grow(&al->al_ga, count) == OK)
7005 for (i = 0; i < count; ++i)
7007 if (got_int)
7009 /* When adding many buffers this can take a long time. Allow
7010 * interrupting here. */
7011 while (i < count)
7012 vim_free(files[i++]);
7013 break;
7016 /* May set buffer name of a buffer previously used for the
7017 * argument list, so that it's re-used by alist_add. */
7018 if (fnum_list != NULL && i < fnum_len)
7019 buf_set_name(fnum_list[i], files[i]);
7021 alist_add(al, files[i], use_curbuf ? 2 : 1);
7022 ui_breakcheck();
7024 vim_free(files);
7026 else
7027 FreeWild(count, files);
7028 #ifdef FEAT_WINDOWS
7029 if (al == &global_alist)
7030 #endif
7031 arg_had_last = FALSE;
7035 * Add file "fname" to argument list "al".
7036 * "fname" must have been allocated and "al" must have been checked for room.
7038 void
7039 alist_add(al, fname, set_fnum)
7040 alist_T *al;
7041 char_u *fname;
7042 int set_fnum; /* 1: set buffer number; 2: re-use curbuf */
7044 if (fname == NULL) /* don't add NULL file names */
7045 return;
7046 #ifdef BACKSLASH_IN_FILENAME
7047 slash_adjust(fname);
7048 #endif
7049 AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
7050 if (set_fnum > 0)
7051 AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
7052 buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
7053 ++al->al_ga.ga_len;
7056 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7058 * Adjust slashes in file names. Called after 'shellslash' was set.
7060 void
7061 alist_slash_adjust()
7063 int i;
7064 # ifdef FEAT_WINDOWS
7065 win_T *wp;
7066 tabpage_T *tp;
7067 # endif
7069 for (i = 0; i < GARGCOUNT; ++i)
7070 if (GARGLIST[i].ae_fname != NULL)
7071 slash_adjust(GARGLIST[i].ae_fname);
7072 # ifdef FEAT_WINDOWS
7073 FOR_ALL_TAB_WINDOWS(tp, wp)
7074 if (wp->w_alist != &global_alist)
7075 for (i = 0; i < WARGCOUNT(wp); ++i)
7076 if (WARGLIST(wp)[i].ae_fname != NULL)
7077 slash_adjust(WARGLIST(wp)[i].ae_fname);
7078 # endif
7080 #endif
7083 * ":preserve".
7085 static void
7086 ex_preserve(eap)
7087 exarg_T *eap UNUSED;
7089 curbuf->b_flags |= BF_PRESERVED;
7090 ml_preserve(curbuf, TRUE);
7094 * ":recover".
7096 static void
7097 ex_recover(eap)
7098 exarg_T *eap;
7100 /* Set recoverymode right away to avoid the ATTENTION prompt. */
7101 recoverymode = TRUE;
7102 if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
7103 && (*eap->arg == NUL
7104 || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
7105 ml_recover();
7106 recoverymode = FALSE;
7110 * Command modifier used in a wrong way.
7112 static void
7113 ex_wrongmodifier(eap)
7114 exarg_T *eap;
7116 eap->errmsg = e_invcmd;
7119 #ifdef FEAT_WINDOWS
7121 * :sview [+command] file split window with new file, read-only
7122 * :split [[+command] file] split window with current or new file
7123 * :vsplit [[+command] file] split window vertically with current or new file
7124 * :new [[+command] file] split window with no or new file
7125 * :vnew [[+command] file] split vertically window with no or new file
7126 * :sfind [+command] file split window with file in 'path'
7128 * :tabedit open new Tab page with empty window
7129 * :tabedit [+command] file open new Tab page and edit "file"
7130 * :tabnew [[+command] file] just like :tabedit
7131 * :tabfind [+command] file open new Tab page and find "file"
7133 void
7134 ex_splitview(eap)
7135 exarg_T *eap;
7137 win_T *old_curwin = curwin;
7138 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7139 char_u *fname = NULL;
7140 # endif
7141 # ifdef FEAT_BROWSE
7142 int browse_flag = cmdmod.browse;
7143 # endif
7145 # ifndef FEAT_VERTSPLIT
7146 if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
7148 ex_ni(eap);
7149 return;
7151 # endif
7153 # ifdef FEAT_GUI
7154 need_mouse_correct = TRUE;
7155 # endif
7157 # ifdef FEAT_QUICKFIX
7158 /* A ":split" in the quickfix window works like ":new". Don't want two
7159 * quickfix windows. But it's OK when doing ":tab split". */
7160 if (bt_quickfix(curbuf) && cmdmod.tab == 0)
7162 if (eap->cmdidx == CMD_split)
7163 eap->cmdidx = CMD_new;
7164 # ifdef FEAT_VERTSPLIT
7165 if (eap->cmdidx == CMD_vsplit)
7166 eap->cmdidx = CMD_vnew;
7167 # endif
7169 # endif
7171 # ifdef FEAT_SEARCHPATH
7172 if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
7174 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
7175 FNAME_MESS, TRUE, curbuf->b_ffname);
7176 if (fname == NULL)
7177 goto theend;
7178 eap->arg = fname;
7180 # ifdef FEAT_BROWSE
7181 else
7182 # endif
7183 # endif
7184 # ifdef FEAT_BROWSE
7185 if (cmdmod.browse
7186 # ifdef FEAT_VERTSPLIT
7187 && eap->cmdidx != CMD_vnew
7188 # endif
7189 && eap->cmdidx != CMD_new)
7191 # ifdef FEAT_AUTOCMD
7192 if (
7193 # ifdef FEAT_GUI
7194 !gui.in_use &&
7195 # endif
7196 au_has_group((char_u *)"FileExplorer"))
7198 /* No browsing supported but we do have the file explorer:
7199 * Edit the directory. */
7200 if (*eap->arg == NUL || !mch_isdir(eap->arg))
7201 eap->arg = (char_u *)".";
7203 else
7204 # endif
7206 fname = do_browse(0, (char_u *)_("Edit File in new window"),
7207 eap->arg, NULL, NULL, NULL, curbuf);
7208 if (fname == NULL)
7209 goto theend;
7210 eap->arg = fname;
7213 cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */
7214 # endif
7217 * Either open new tab page or split the window.
7219 if (eap->cmdidx == CMD_tabedit
7220 || eap->cmdidx == CMD_tabfind
7221 || eap->cmdidx == CMD_tabnew)
7223 if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
7224 : eap->addr_count == 0 ? 0
7225 : (int)eap->line2 + 1) != FAIL)
7227 do_exedit(eap, old_curwin);
7229 /* set the alternate buffer for the window we came from */
7230 if (curwin != old_curwin
7231 && win_valid(old_curwin)
7232 && old_curwin->w_buffer != curbuf
7233 && !cmdmod.keepalt)
7234 old_curwin->w_alt_fnum = curbuf->b_fnum;
7237 else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
7238 *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
7240 # ifdef FEAT_SCROLLBIND
7241 /* Reset 'scrollbind' when editing another file, but keep it when
7242 * doing ":split" without arguments. */
7243 if (*eap->arg != NUL
7244 # ifdef FEAT_BROWSE
7245 || cmdmod.browse
7246 # endif
7248 curwin->w_p_scb = FALSE;
7249 else
7250 do_check_scrollbind(FALSE);
7251 # endif
7252 do_exedit(eap, old_curwin);
7255 # ifdef FEAT_BROWSE
7256 cmdmod.browse = browse_flag;
7257 # endif
7259 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7260 theend:
7261 vim_free(fname);
7262 # endif
7266 * Open a new tab page.
7268 void
7269 tabpage_new()
7271 exarg_T ea;
7273 vim_memset(&ea, 0, sizeof(ea));
7274 ea.cmdidx = CMD_tabnew;
7275 ea.cmd = (char_u *)"tabn";
7276 ea.arg = (char_u *)"";
7277 ex_splitview(&ea);
7281 * :tabnext command
7283 static void
7284 ex_tabnext(eap)
7285 exarg_T *eap;
7287 switch (eap->cmdidx)
7289 case CMD_tabfirst:
7290 case CMD_tabrewind:
7291 goto_tabpage(1);
7292 break;
7293 case CMD_tablast:
7294 goto_tabpage(9999);
7295 break;
7296 case CMD_tabprevious:
7297 case CMD_tabNext:
7298 goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2);
7299 break;
7300 default: /* CMD_tabnext */
7301 goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2);
7302 break;
7307 * :tabmove command
7309 static void
7310 ex_tabmove(eap)
7311 exarg_T *eap;
7313 tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2);
7317 * :tabs command: List tabs and their contents.
7319 static void
7320 ex_tabs(eap)
7321 exarg_T *eap UNUSED;
7323 tabpage_T *tp;
7324 win_T *wp;
7325 int tabcount = 1;
7327 msg_start();
7328 msg_scroll = TRUE;
7329 for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
7331 msg_putchar('\n');
7332 vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
7333 msg_outtrans_attr(IObuff, hl_attr(HLF_T));
7334 out_flush(); /* output one line at a time */
7335 ui_breakcheck();
7337 if (tp == curtab)
7338 wp = firstwin;
7339 else
7340 wp = tp->tp_firstwin;
7341 for ( ; wp != NULL && !got_int; wp = wp->w_next)
7343 msg_putchar('\n');
7344 msg_putchar(wp == curwin ? '>' : ' ');
7345 msg_putchar(' ');
7346 msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
7347 msg_putchar(' ');
7348 if (buf_spname(wp->w_buffer) != NULL)
7349 STRCPY(IObuff, buf_spname(wp->w_buffer));
7350 else
7351 home_replace(wp->w_buffer, wp->w_buffer->b_fname,
7352 IObuff, IOSIZE, TRUE);
7353 msg_outtrans(IObuff);
7354 out_flush(); /* output one line at a time */
7355 ui_breakcheck();
7360 #endif /* FEAT_WINDOWS */
7363 * ":mode": Set screen mode.
7364 * If no argument given, just get the screen size and redraw.
7366 static void
7367 ex_mode(eap)
7368 exarg_T *eap;
7370 if (*eap->arg == NUL)
7371 shell_resized();
7372 else
7373 mch_screenmode(eap->arg);
7376 #ifdef FEAT_WINDOWS
7378 * ":resize".
7379 * set, increment or decrement current window height
7381 static void
7382 ex_resize(eap)
7383 exarg_T *eap;
7385 int n;
7386 win_T *wp = curwin;
7388 if (eap->addr_count > 0)
7390 n = eap->line2;
7391 for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
7395 #ifdef FEAT_GUI
7396 need_mouse_correct = TRUE;
7397 #endif
7398 n = atol((char *)eap->arg);
7399 #ifdef FEAT_VERTSPLIT
7400 if (cmdmod.split & WSP_VERT)
7402 if (*eap->arg == '-' || *eap->arg == '+')
7403 n += W_WIDTH(curwin);
7404 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7405 n = 9999;
7406 win_setwidth_win((int)n, wp);
7408 else
7409 #endif
7411 if (*eap->arg == '-' || *eap->arg == '+')
7412 n += curwin->w_height;
7413 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7414 n = 9999;
7415 win_setheight_win((int)n, wp);
7418 #endif
7421 * ":find [+command] <file>" command.
7423 static void
7424 ex_find(eap)
7425 exarg_T *eap;
7427 #ifdef FEAT_SEARCHPATH
7428 char_u *fname;
7429 int count;
7431 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
7432 TRUE, curbuf->b_ffname);
7433 if (eap->addr_count > 0)
7435 /* Repeat finding the file "count" times. This matters when it
7436 * appears several times in the path. */
7437 count = eap->line2;
7438 while (fname != NULL && --count > 0)
7440 vim_free(fname);
7441 fname = find_file_in_path(NULL, 0, FNAME_MESS,
7442 FALSE, curbuf->b_ffname);
7446 if (fname != NULL)
7448 eap->arg = fname;
7449 #endif
7450 do_exedit(eap, NULL);
7451 #ifdef FEAT_SEARCHPATH
7452 vim_free(fname);
7454 #endif
7458 * ":open" simulation: for now just work like ":visual".
7460 static void
7461 ex_open(eap)
7462 exarg_T *eap;
7464 regmatch_T regmatch;
7465 char_u *p;
7467 curwin->w_cursor.lnum = eap->line2;
7468 beginline(BL_SOL | BL_FIX);
7469 if (*eap->arg == '/')
7471 /* ":open /pattern/": put cursor in column found with pattern */
7472 ++eap->arg;
7473 p = skip_regexp(eap->arg, '/', p_magic, NULL);
7474 *p = NUL;
7475 regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
7476 if (regmatch.regprog != NULL)
7478 regmatch.rm_ic = p_ic;
7479 p = ml_get_curline();
7480 if (vim_regexec(&regmatch, p, (colnr_T)0))
7481 curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
7482 else
7483 EMSG(_(e_nomatch));
7484 vim_free(regmatch.regprog);
7486 /* Move to the NUL, ignore any other arguments. */
7487 eap->arg += STRLEN(eap->arg);
7489 check_cursor();
7491 eap->cmdidx = CMD_visual;
7492 do_exedit(eap, NULL);
7496 * ":edit", ":badd", ":visual".
7498 static void
7499 ex_edit(eap)
7500 exarg_T *eap;
7502 do_exedit(eap, NULL);
7506 * ":edit <file>" command and alikes.
7508 void
7509 do_exedit(eap, old_curwin)
7510 exarg_T *eap;
7511 win_T *old_curwin; /* curwin before doing a split or NULL */
7513 int n;
7514 #ifdef FEAT_WINDOWS
7515 int need_hide;
7516 #endif
7517 int exmode_was = exmode_active;
7520 * ":vi" command ends Ex mode.
7522 if (exmode_active && (eap->cmdidx == CMD_visual
7523 || eap->cmdidx == CMD_view))
7525 exmode_active = FALSE;
7526 if (*eap->arg == NUL)
7528 /* Special case: ":global/pat/visual\NLvi-commands" */
7529 if (global_busy)
7531 int rd = RedrawingDisabled;
7532 int nwr = no_wait_return;
7533 int ms = msg_scroll;
7534 #ifdef FEAT_GUI
7535 int he = hold_gui_events;
7536 #endif
7538 if (eap->nextcmd != NULL)
7540 stuffReadbuff(eap->nextcmd);
7541 eap->nextcmd = NULL;
7544 if (exmode_was != EXMODE_VIM)
7545 settmode(TMODE_RAW);
7546 RedrawingDisabled = 0;
7547 no_wait_return = 0;
7548 need_wait_return = FALSE;
7549 msg_scroll = 0;
7550 #ifdef FEAT_GUI
7551 hold_gui_events = 0;
7552 #endif
7553 must_redraw = CLEAR;
7555 main_loop(FALSE, TRUE);
7557 RedrawingDisabled = rd;
7558 no_wait_return = nwr;
7559 msg_scroll = ms;
7560 #ifdef FEAT_GUI
7561 hold_gui_events = he;
7562 #endif
7564 return;
7568 if ((eap->cmdidx == CMD_new
7569 || eap->cmdidx == CMD_tabnew
7570 || eap->cmdidx == CMD_tabedit
7571 #ifdef FEAT_VERTSPLIT
7572 || eap->cmdidx == CMD_vnew
7573 #endif
7574 ) && *eap->arg == NUL)
7576 /* ":new" or ":tabnew" without argument: edit an new empty buffer */
7577 setpcmark();
7578 (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
7579 ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
7580 old_curwin == NULL ? curwin : NULL);
7582 else if ((eap->cmdidx != CMD_split
7583 #ifdef FEAT_VERTSPLIT
7584 && eap->cmdidx != CMD_vsplit
7585 #endif
7587 || *eap->arg != NUL
7588 #ifdef FEAT_BROWSE
7589 || cmdmod.browse
7590 #endif
7593 #ifdef FEAT_AUTOCMD
7594 /* Can't edit another file when "curbuf_lock" is set. Only ":edit"
7595 * can bring us here, others are stopped earlier. */
7596 if (*eap->arg != NUL && curbuf_locked())
7597 return;
7598 #endif
7599 n = readonlymode;
7600 if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
7601 readonlymode = TRUE;
7602 else if (eap->cmdidx == CMD_enew)
7603 readonlymode = FALSE; /* 'readonly' doesn't make sense in an
7604 empty buffer */
7605 setpcmark();
7606 if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
7607 NULL, eap,
7608 /* ":edit" goes to first line if Vi compatible */
7609 (*eap->arg == NUL && eap->do_ecmd_lnum == 0
7610 && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
7611 ? ECMD_ONE : eap->do_ecmd_lnum,
7612 (P_HID(curbuf) ? ECMD_HIDE : 0)
7613 + (eap->forceit ? ECMD_FORCEIT : 0)
7614 #ifdef FEAT_LISTCMDS
7615 + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
7616 #endif
7617 , old_curwin == NULL ? curwin : NULL) == FAIL)
7619 /* Editing the file failed. If the window was split, close it. */
7620 #ifdef FEAT_WINDOWS
7621 if (old_curwin != NULL)
7623 need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
7624 if (!need_hide || P_HID(curbuf))
7626 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7627 cleanup_T cs;
7629 /* Reset the error/interrupt/exception state here so that
7630 * aborting() returns FALSE when closing a window. */
7631 enter_cleanup(&cs);
7632 # endif
7633 # ifdef FEAT_GUI
7634 need_mouse_correct = TRUE;
7635 # endif
7636 win_close(curwin, !need_hide && !P_HID(curbuf));
7638 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7639 /* Restore the error/interrupt/exception state if not
7640 * discarded by a new aborting error, interrupt, or
7641 * uncaught exception. */
7642 leave_cleanup(&cs);
7643 # endif
7646 #endif
7648 else if (readonlymode && curbuf->b_nwindows == 1)
7650 /* When editing an already visited buffer, 'readonly' won't be set
7651 * but the previous value is kept. With ":view" and ":sview" we
7652 * want the file to be readonly, except when another window is
7653 * editing the same buffer. */
7654 curbuf->b_p_ro = TRUE;
7656 readonlymode = n;
7658 else
7660 if (eap->do_ecmd_cmd != NULL)
7661 do_cmdline_cmd(eap->do_ecmd_cmd);
7662 #ifdef FEAT_TITLE
7663 n = curwin->w_arg_idx_invalid;
7664 #endif
7665 check_arg_idx(curwin);
7666 #ifdef FEAT_TITLE
7667 if (n != curwin->w_arg_idx_invalid)
7668 maketitle();
7669 #endif
7672 #ifdef FEAT_WINDOWS
7674 * if ":split file" worked, set alternate file name in old window to new
7675 * file
7677 if (old_curwin != NULL
7678 && *eap->arg != NUL
7679 && curwin != old_curwin
7680 && win_valid(old_curwin)
7681 && old_curwin->w_buffer != curbuf
7682 && !cmdmod.keepalt)
7683 old_curwin->w_alt_fnum = curbuf->b_fnum;
7684 #endif
7686 ex_no_reprint = TRUE;
7689 #ifndef FEAT_GUI
7691 * ":gui" and ":gvim" when there is no GUI.
7693 static void
7694 ex_nogui(eap)
7695 exarg_T *eap;
7697 eap->errmsg = e_nogvim;
7699 #endif
7701 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
7702 static void
7703 ex_tearoff(eap)
7704 exarg_T *eap;
7706 gui_make_tearoff(eap->arg);
7708 #endif
7710 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
7711 static void
7712 ex_popup(eap)
7713 exarg_T *eap;
7715 gui_make_popup(eap->arg, eap->forceit);
7717 #endif
7719 static void
7720 ex_swapname(eap)
7721 exarg_T *eap UNUSED;
7723 if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
7724 MSG(_("No swap file"));
7725 else
7726 msg(curbuf->b_ml.ml_mfp->mf_fname);
7730 * ":syncbind" forces all 'scrollbind' windows to have the same relative
7731 * offset.
7732 * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
7734 static void
7735 ex_syncbind(eap)
7736 exarg_T *eap UNUSED;
7738 #ifdef FEAT_SCROLLBIND
7739 win_T *wp;
7740 long topline;
7741 long y;
7742 linenr_T old_linenr = curwin->w_cursor.lnum;
7744 setpcmark();
7747 * determine max topline
7749 if (curwin->w_p_scb)
7751 topline = curwin->w_topline;
7752 for (wp = firstwin; wp; wp = wp->w_next)
7754 if (wp->w_p_scb && wp->w_buffer)
7756 y = wp->w_buffer->b_ml.ml_line_count - p_so;
7757 if (topline > y)
7758 topline = y;
7761 if (topline < 1)
7762 topline = 1;
7764 else
7766 topline = 1;
7771 * set all scrollbind windows to the same topline
7773 wp = curwin;
7774 for (curwin = firstwin; curwin; curwin = curwin->w_next)
7776 if (curwin->w_p_scb)
7778 y = topline - curwin->w_topline;
7779 if (y > 0)
7780 scrollup(y, TRUE);
7781 else
7782 scrolldown(-y, TRUE);
7783 curwin->w_scbind_pos = topline;
7784 redraw_later(VALID);
7785 cursor_correct();
7786 #ifdef FEAT_WINDOWS
7787 curwin->w_redr_status = TRUE;
7788 #endif
7791 curwin = wp;
7792 if (curwin->w_p_scb)
7794 did_syncbind = TRUE;
7795 checkpcmark();
7796 if (old_linenr != curwin->w_cursor.lnum)
7798 char_u ctrl_o[2];
7800 ctrl_o[0] = Ctrl_O;
7801 ctrl_o[1] = 0;
7802 ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
7805 #endif
7809 static void
7810 ex_read(eap)
7811 exarg_T *eap;
7813 int i;
7814 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7815 linenr_T lnum;
7817 if (eap->usefilter) /* :r!cmd */
7818 do_bang(1, eap, FALSE, FALSE, TRUE);
7819 else
7821 if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
7822 return;
7824 #ifdef FEAT_BROWSE
7825 if (cmdmod.browse)
7827 char_u *browseFile;
7829 browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
7830 NULL, NULL, NULL, curbuf);
7831 if (browseFile != NULL)
7833 i = readfile(browseFile, NULL,
7834 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7835 vim_free(browseFile);
7837 else
7838 i = OK;
7840 else
7841 #endif
7842 if (*eap->arg == NUL)
7844 if (check_fname() == FAIL) /* check for no file name */
7845 return;
7846 i = readfile(curbuf->b_ffname, curbuf->b_fname,
7847 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7849 else
7851 if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
7852 (void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
7853 i = readfile(eap->arg, NULL,
7854 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7857 if (i == FAIL)
7859 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7860 if (!aborting())
7861 #endif
7862 EMSG2(_(e_notopen), eap->arg);
7864 else
7866 if (empty && exmode_active)
7868 /* Delete the empty line that remains. Historically ex does
7869 * this but vi doesn't. */
7870 if (eap->line2 == 0)
7871 lnum = curbuf->b_ml.ml_line_count;
7872 else
7873 lnum = 1;
7874 if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
7876 ml_delete(lnum, FALSE);
7877 if (curwin->w_cursor.lnum > 1
7878 && curwin->w_cursor.lnum >= lnum)
7879 --curwin->w_cursor.lnum;
7880 deleted_lines_mark(lnum, 1L);
7883 redraw_curbuf_later(VALID);
7888 static char_u *prev_dir = NULL;
7890 #if defined(EXITFREE) || defined(PROTO)
7891 void
7892 free_cd_dir()
7894 vim_free(prev_dir);
7895 prev_dir = NULL;
7897 vim_free(globaldir);
7898 globaldir = NULL;
7900 #endif
7904 * ":cd", ":lcd", ":chdir" and ":lchdir".
7906 void
7907 ex_cd(eap)
7908 exarg_T *eap;
7910 char_u *new_dir;
7911 char_u *tofree;
7913 new_dir = eap->arg;
7914 #if !defined(UNIX) && !defined(VMS)
7915 /* for non-UNIX ":cd" means: print current directory */
7916 if (*new_dir == NUL)
7917 ex_pwd(NULL);
7918 else
7919 #endif
7921 #ifdef FEAT_AUTOCMD
7922 if (allbuf_locked())
7923 return;
7924 #endif
7925 if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
7926 && !eap->forceit)
7928 EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
7929 return;
7932 /* ":cd -": Change to previous directory */
7933 if (STRCMP(new_dir, "-") == 0)
7935 if (prev_dir == NULL)
7937 EMSG(_("E186: No previous directory"));
7938 return;
7940 new_dir = prev_dir;
7943 /* Save current directory for next ":cd -" */
7944 tofree = prev_dir;
7945 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7946 prev_dir = vim_strsave(NameBuff);
7947 else
7948 prev_dir = NULL;
7950 #if defined(UNIX) || defined(VMS)
7951 /* for UNIX ":cd" means: go to home directory */
7952 if (*new_dir == NUL)
7954 /* use NameBuff for home directory name */
7955 # ifdef VMS
7956 char_u *p;
7958 p = mch_getenv((char_u *)"SYS$LOGIN");
7959 if (p == NULL || *p == NUL) /* empty is the same as not set */
7960 NameBuff[0] = NUL;
7961 else
7962 vim_strncpy(NameBuff, p, MAXPATHL - 1);
7963 # else
7964 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
7965 # endif
7966 new_dir = NameBuff;
7968 #endif
7969 if (new_dir == NULL || vim_chdir(new_dir))
7970 EMSG(_(e_failed));
7971 else
7973 vim_free(curwin->w_localdir);
7974 if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
7976 /* If still in global directory, need to remember current
7977 * directory as global directory. */
7978 if (globaldir == NULL && prev_dir != NULL)
7979 globaldir = vim_strsave(prev_dir);
7980 /* Remember this local directory for the window. */
7981 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7982 curwin->w_localdir = vim_strsave(NameBuff);
7984 else
7986 /* We are now in the global directory, no need to remember its
7987 * name. */
7988 vim_free(globaldir);
7989 globaldir = NULL;
7990 curwin->w_localdir = NULL;
7993 shorten_fnames(TRUE);
7995 /* Echo the new current directory if the command was typed. */
7996 if (KeyTyped || p_verbose >= 5)
7997 ex_pwd(eap);
7999 vim_free(tofree);
8004 * ":pwd".
8006 static void
8007 ex_pwd(eap)
8008 exarg_T *eap UNUSED;
8010 if (mch_dirname(NameBuff, MAXPATHL) == OK)
8012 #ifdef BACKSLASH_IN_FILENAME
8013 slash_adjust(NameBuff);
8014 #endif
8015 msg(NameBuff);
8017 else
8018 EMSG(_("E187: Unknown"));
8022 * ":=".
8024 static void
8025 ex_equal(eap)
8026 exarg_T *eap;
8028 smsg((char_u *)"%ld", (long)eap->line2);
8029 ex_may_print(eap);
8032 static void
8033 ex_sleep(eap)
8034 exarg_T *eap;
8036 int n;
8037 long len;
8039 if (cursor_valid())
8041 n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
8042 if (n >= 0)
8043 windgoto((int)n, curwin->w_wcol);
8046 len = eap->line2;
8047 switch (*eap->arg)
8049 case 'm': break;
8050 case NUL: len *= 1000L; break;
8051 default: EMSG2(_(e_invarg2), eap->arg); return;
8053 do_sleep(len);
8057 * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
8059 void
8060 do_sleep(msec)
8061 long msec;
8063 long done;
8065 cursor_on();
8066 out_flush();
8067 for (done = 0; !got_int && done < msec; done += 1000L)
8069 ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
8070 ui_breakcheck();
8074 static void
8075 do_exmap(eap, isabbrev)
8076 exarg_T *eap;
8077 int isabbrev;
8079 int mode;
8080 char_u *cmdp;
8082 cmdp = eap->cmd;
8083 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
8085 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
8086 eap->arg, mode, isabbrev))
8088 case 1: EMSG(_(e_invarg));
8089 break;
8090 case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
8091 break;
8096 * ":winsize" command (obsolete).
8098 static void
8099 ex_winsize(eap)
8100 exarg_T *eap;
8102 int w, h;
8103 char_u *arg = eap->arg;
8104 char_u *p;
8106 w = getdigits(&arg);
8107 arg = skipwhite(arg);
8108 p = arg;
8109 h = getdigits(&arg);
8110 if (*p != NUL && *arg == NUL)
8111 set_shellsize(w, h, TRUE);
8112 else
8113 EMSG(_("E465: :winsize requires two number arguments"));
8116 #ifdef FEAT_WINDOWS
8117 static void
8118 ex_wincmd(eap)
8119 exarg_T *eap;
8121 int xchar = NUL;
8122 char_u *p;
8124 if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
8126 /* CTRL-W g and CTRL-W CTRL-G have an extra command character */
8127 if (eap->arg[1] == NUL)
8129 EMSG(_(e_invarg));
8130 return;
8132 xchar = eap->arg[1];
8133 p = eap->arg + 2;
8135 else
8136 p = eap->arg + 1;
8138 eap->nextcmd = check_nextcmd(p);
8139 p = skipwhite(p);
8140 if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
8141 EMSG(_(e_invarg));
8142 else
8144 /* Pass flags on for ":vertical wincmd ]". */
8145 postponed_split_flags = cmdmod.split;
8146 postponed_split_tab = cmdmod.tab;
8147 do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
8148 postponed_split_flags = 0;
8149 postponed_split_tab = 0;
8152 #endif
8154 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
8156 * ":winpos".
8158 static void
8159 ex_winpos(eap)
8160 exarg_T *eap;
8162 int x, y;
8163 char_u *arg = eap->arg;
8164 char_u *p;
8166 if (*arg == NUL)
8168 # if defined(FEAT_GUI) || defined(MSWIN)
8169 # ifdef FEAT_GUI
8170 if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
8171 # else
8172 if (mch_get_winpos(&x, &y) != FAIL)
8173 # endif
8175 sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
8176 msg(IObuff);
8178 else
8179 # endif
8180 EMSG(_("E188: Obtaining window position not implemented for this platform"));
8182 else
8184 x = getdigits(&arg);
8185 arg = skipwhite(arg);
8186 p = arg;
8187 y = getdigits(&arg);
8188 if (*p == NUL || *arg != NUL)
8190 EMSG(_("E466: :winpos requires two number arguments"));
8191 return;
8193 # ifdef FEAT_GUI
8194 if (gui.in_use)
8195 gui_mch_set_winpos(x, y);
8196 else if (gui.starting)
8198 /* Remember the coordinates for when the window is opened. */
8199 gui_win_x = x;
8200 gui_win_y = y;
8202 # ifdef HAVE_TGETENT
8203 else
8204 # endif
8205 # else
8206 # ifdef MSWIN
8207 mch_set_winpos(x, y);
8208 # endif
8209 # endif
8210 # ifdef HAVE_TGETENT
8211 if (*T_CWP)
8212 term_set_winpos(x, y);
8213 # endif
8216 #endif
8219 * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
8221 static void
8222 ex_operators(eap)
8223 exarg_T *eap;
8225 oparg_T oa;
8227 clear_oparg(&oa);
8228 oa.regname = eap->regname;
8229 oa.start.lnum = eap->line1;
8230 oa.end.lnum = eap->line2;
8231 oa.line_count = eap->line2 - eap->line1 + 1;
8232 oa.motion_type = MLINE;
8233 #ifdef FEAT_VIRTUALEDIT
8234 virtual_op = FALSE;
8235 #endif
8236 if (eap->cmdidx != CMD_yank) /* position cursor for undo */
8238 setpcmark();
8239 curwin->w_cursor.lnum = eap->line1;
8240 beginline(BL_SOL | BL_FIX);
8243 switch (eap->cmdidx)
8245 case CMD_delete:
8246 oa.op_type = OP_DELETE;
8247 op_delete(&oa);
8248 break;
8250 case CMD_yank:
8251 oa.op_type = OP_YANK;
8252 (void)op_yank(&oa, FALSE, TRUE);
8253 break;
8255 default: /* CMD_rshift or CMD_lshift */
8256 if ((eap->cmdidx == CMD_rshift)
8257 #ifdef FEAT_RIGHTLEFT
8258 ^ curwin->w_p_rl
8259 #endif
8261 oa.op_type = OP_RSHIFT;
8262 else
8263 oa.op_type = OP_LSHIFT;
8264 op_shift(&oa, FALSE, eap->amount);
8265 break;
8267 #ifdef FEAT_VIRTUALEDIT
8268 virtual_op = MAYBE;
8269 #endif
8270 ex_may_print(eap);
8274 * ":put".
8276 static void
8277 ex_put(eap)
8278 exarg_T *eap;
8280 /* ":0put" works like ":1put!". */
8281 if (eap->line2 == 0)
8283 eap->line2 = 1;
8284 eap->forceit = TRUE;
8286 curwin->w_cursor.lnum = eap->line2;
8287 do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
8288 PUT_LINE|PUT_CURSLINE);
8292 * Handle ":copy" and ":move".
8294 static void
8295 ex_copymove(eap)
8296 exarg_T *eap;
8298 long n;
8300 n = get_address(&eap->arg, FALSE, FALSE);
8301 if (eap->arg == NULL) /* error detected */
8303 eap->nextcmd = NULL;
8304 return;
8306 get_flags(eap);
8309 * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
8311 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
8313 EMSG(_(e_invaddr));
8314 return;
8317 if (eap->cmdidx == CMD_move)
8319 if (do_move(eap->line1, eap->line2, n) == FAIL)
8320 return;
8322 else
8323 ex_copy(eap->line1, eap->line2, n);
8324 u_clearline();
8325 beginline(BL_SOL | BL_FIX);
8326 ex_may_print(eap);
8330 * Print the current line if flags were given to the Ex command.
8332 static void
8333 ex_may_print(eap)
8334 exarg_T *eap;
8336 if (eap->flags != 0)
8338 print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
8339 (eap->flags & EXFLAG_LIST));
8340 ex_no_reprint = TRUE;
8345 * ":smagic" and ":snomagic".
8347 static void
8348 ex_submagic(eap)
8349 exarg_T *eap;
8351 int magic_save = p_magic;
8353 p_magic = (eap->cmdidx == CMD_smagic);
8354 do_sub(eap);
8355 p_magic = magic_save;
8359 * ":join".
8361 static void
8362 ex_join(eap)
8363 exarg_T *eap;
8365 curwin->w_cursor.lnum = eap->line1;
8366 if (eap->line1 == eap->line2)
8368 if (eap->addr_count >= 2) /* :2,2join does nothing */
8369 return;
8370 if (eap->line2 == curbuf->b_ml.ml_line_count)
8372 beep_flush();
8373 return;
8375 ++eap->line2;
8377 do_do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
8378 beginline(BL_WHITE | BL_FIX);
8379 ex_may_print(eap);
8383 * ":[addr]@r" or ":[addr]*r": execute register
8385 static void
8386 ex_at(eap)
8387 exarg_T *eap;
8389 int c;
8391 curwin->w_cursor.lnum = eap->line2;
8393 #ifdef USE_ON_FLY_SCROLL
8394 dont_scroll = TRUE; /* disallow scrolling here */
8395 #endif
8397 /* get the register name. No name means to use the previous one */
8398 c = *eap->arg;
8399 if (c == NUL || (c == '*' && *eap->cmd == '*'))
8400 c = '@';
8401 /* Put the register in the typeahead buffer with the "silent" flag. */
8402 if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
8403 == FAIL)
8405 beep_flush();
8407 else
8409 int save_efr = exec_from_reg;
8411 exec_from_reg = TRUE;
8414 * Execute from the typeahead buffer.
8415 * Originally this didn't check for the typeahead buffer to be empty,
8416 * thus could read more Ex commands from stdin. It's not clear why,
8417 * it is certainly unexpected.
8419 while ((!stuff_empty() || typebuf.tb_len > 0) && vpeekc() == ':')
8420 (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
8422 exec_from_reg = save_efr;
8427 * ":!".
8429 static void
8430 ex_bang(eap)
8431 exarg_T *eap;
8433 do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
8437 * ":undo".
8439 static void
8440 ex_undo(eap)
8441 exarg_T *eap UNUSED;
8443 if (eap->addr_count == 1) /* :undo 123 */
8444 undo_time(eap->line2, FALSE, TRUE);
8445 else
8446 u_undo(1);
8450 * ":redo".
8452 static void
8453 ex_redo(eap)
8454 exarg_T *eap UNUSED;
8456 u_redo(1);
8460 * ":earlier" and ":later".
8462 static void
8463 ex_later(eap)
8464 exarg_T *eap;
8466 long count = 0;
8467 int sec = FALSE;
8468 char_u *p = eap->arg;
8470 if (*p == NUL)
8471 count = 1;
8472 else if (isdigit(*p))
8474 count = getdigits(&p);
8475 switch (*p)
8477 case 's': ++p; sec = TRUE; break;
8478 case 'm': ++p; sec = TRUE; count *= 60; break;
8479 case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
8483 if (*p != NUL)
8484 EMSG2(_(e_invarg2), eap->arg);
8485 else
8486 undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, FALSE);
8490 * ":redir": start/stop redirection.
8492 static void
8493 ex_redir(eap)
8494 exarg_T *eap;
8496 char *mode;
8497 char_u *fname;
8498 char_u *arg = eap->arg;
8500 if (STRICMP(eap->arg, "END") == 0)
8501 close_redir();
8502 else
8504 if (*arg == '>')
8506 ++arg;
8507 if (*arg == '>')
8509 ++arg;
8510 mode = "a";
8512 else
8513 mode = "w";
8514 arg = skipwhite(arg);
8516 close_redir();
8518 /* Expand environment variables and "~/". */
8519 fname = expand_env_save(arg);
8520 if (fname == NULL)
8521 return;
8522 #ifdef FEAT_BROWSE
8523 if (cmdmod.browse)
8525 char_u *browseFile;
8527 browseFile = do_browse(BROWSE_SAVE,
8528 (char_u *)_("Save Redirection"),
8529 fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
8530 if (browseFile == NULL)
8531 return; /* operation cancelled */
8532 vim_free(fname);
8533 fname = browseFile;
8534 eap->forceit = TRUE; /* since dialog already asked */
8536 #endif
8538 redir_fd = open_exfile(fname, eap->forceit, mode);
8539 vim_free(fname);
8541 #ifdef FEAT_EVAL
8542 else if (*arg == '@')
8544 /* redirect to a register a-z (resp. A-Z for appending) */
8545 close_redir();
8546 ++arg;
8547 if (ASCII_ISALPHA(*arg)
8548 # ifdef FEAT_CLIPBOARD
8549 || *arg == '*'
8550 || *arg == '+'
8551 # endif
8552 || *arg == '"')
8554 redir_reg = *arg++;
8555 if (*arg == '>' && arg[1] == '>') /* append */
8556 arg += 2;
8557 else
8559 /* Can use both "@a" and "@a>". */
8560 if (*arg == '>')
8561 arg++;
8562 /* Make register empty when not using @A-@Z and the
8563 * command is valid. */
8564 if (*arg == NUL && !isupper(redir_reg))
8565 write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
8568 if (*arg != NUL)
8570 redir_reg = 0;
8571 EMSG2(_(e_invarg2), eap->arg);
8574 else if (*arg == '=' && arg[1] == '>')
8576 int append;
8578 /* redirect to a variable */
8579 close_redir();
8580 arg += 2;
8582 if (*arg == '>')
8584 ++arg;
8585 append = TRUE;
8587 else
8588 append = FALSE;
8590 if (var_redir_start(skipwhite(arg), append) == OK)
8591 redir_vname = 1;
8593 #endif
8595 /* TODO: redirect to a buffer */
8597 else
8598 EMSG2(_(e_invarg2), eap->arg);
8601 /* Make sure redirection is not off. Can happen for cmdline completion
8602 * that indirectly invokes a command to catch its output. */
8603 if (redir_fd != NULL
8604 #ifdef FEAT_EVAL
8605 || redir_reg || redir_vname
8606 #endif
8608 redir_off = FALSE;
8612 * ":redraw": force redraw
8614 static void
8615 ex_redraw(eap)
8616 exarg_T *eap;
8618 int r = RedrawingDisabled;
8619 int p = p_lz;
8621 RedrawingDisabled = 0;
8622 p_lz = FALSE;
8623 update_topline();
8624 update_screen(eap->forceit ? CLEAR :
8625 #ifdef FEAT_VISUAL
8626 VIsual_active ? INVERTED :
8627 #endif
8629 #ifdef FEAT_TITLE
8630 if (need_maketitle)
8631 maketitle();
8632 #endif
8633 RedrawingDisabled = r;
8634 p_lz = p;
8636 /* Reset msg_didout, so that a message that's there is overwritten. */
8637 msg_didout = FALSE;
8638 msg_col = 0;
8640 out_flush();
8644 * ":redrawstatus": force redraw of status line(s)
8646 static void
8647 ex_redrawstatus(eap)
8648 exarg_T *eap UNUSED;
8650 #if defined(FEAT_WINDOWS)
8651 int r = RedrawingDisabled;
8652 int p = p_lz;
8654 RedrawingDisabled = 0;
8655 p_lz = FALSE;
8656 if (eap->forceit)
8657 status_redraw_all();
8658 else
8659 status_redraw_curbuf();
8660 update_screen(
8661 # ifdef FEAT_VISUAL
8662 VIsual_active ? INVERTED :
8663 # endif
8665 RedrawingDisabled = r;
8666 p_lz = p;
8667 out_flush();
8668 #endif
8671 static void
8672 close_redir()
8674 if (redir_fd != NULL)
8676 fclose(redir_fd);
8677 redir_fd = NULL;
8679 #ifdef FEAT_EVAL
8680 redir_reg = 0;
8681 if (redir_vname)
8683 var_redir_stop();
8684 redir_vname = 0;
8686 #endif
8689 #if defined(FEAT_SESSION) && defined(USE_CRNL)
8690 # define MKSESSION_NL
8691 static int mksession_nl = FALSE; /* use NL only in put_eol() */
8692 #endif
8695 * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
8697 static void
8698 ex_mkrc(eap)
8699 exarg_T *eap;
8701 FILE *fd;
8702 int failed = FALSE;
8703 char_u *fname;
8704 #ifdef FEAT_BROWSE
8705 char_u *browseFile = NULL;
8706 #endif
8707 #ifdef FEAT_SESSION
8708 int view_session = FALSE;
8709 int using_vdir = FALSE; /* using 'viewdir'? */
8710 char_u *viewFile = NULL;
8711 unsigned *flagp;
8712 #endif
8714 if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
8716 #ifdef FEAT_SESSION
8717 view_session = TRUE;
8718 #else
8719 ex_ni(eap);
8720 return;
8721 #endif
8724 #ifdef FEAT_SESSION
8725 /* Use the short file name until ":lcd" is used. We also don't use the
8726 * short file name when 'acd' is set, that is checked later. */
8727 did_lcd = FALSE;
8729 /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
8730 if (eap->cmdidx == CMD_mkview
8731 && (*eap->arg == NUL
8732 || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
8734 eap->forceit = TRUE;
8735 fname = get_view_file(*eap->arg);
8736 if (fname == NULL)
8737 return;
8738 viewFile = fname;
8739 using_vdir = TRUE;
8741 else
8742 #endif
8743 if (*eap->arg != NUL)
8744 fname = eap->arg;
8745 else if (eap->cmdidx == CMD_mkvimrc)
8746 fname = (char_u *)VIMRC_FILE;
8747 #ifdef FEAT_SESSION
8748 else if (eap->cmdidx == CMD_mksession)
8749 fname = (char_u *)SESSION_FILE;
8750 #endif
8751 else
8752 fname = (char_u *)EXRC_FILE;
8754 #ifdef FEAT_BROWSE
8755 if (cmdmod.browse)
8757 browseFile = do_browse(BROWSE_SAVE,
8758 # ifdef FEAT_SESSION
8759 eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
8760 eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
8761 # endif
8762 (char_u *)_("Save Setup"),
8763 fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
8764 if (browseFile == NULL)
8765 goto theend;
8766 fname = browseFile;
8767 eap->forceit = TRUE; /* since dialog already asked */
8769 #endif
8771 #if defined(FEAT_SESSION) && defined(vim_mkdir)
8772 /* When using 'viewdir' may have to create the directory. */
8773 if (using_vdir && !mch_isdir(p_vdir))
8774 vim_mkdir_emsg(p_vdir, 0755);
8775 #endif
8777 fd = open_exfile(fname, eap->forceit, WRITEBIN);
8778 if (fd != NULL)
8780 #ifdef FEAT_SESSION
8781 if (eap->cmdidx == CMD_mkview)
8782 flagp = &vop_flags;
8783 else
8784 flagp = &ssop_flags;
8785 #endif
8787 #ifdef MKSESSION_NL
8788 /* "unix" in 'sessionoptions': use NL line separator */
8789 if (view_session && (*flagp & SSOP_UNIX))
8790 mksession_nl = TRUE;
8791 #endif
8793 /* Write the version command for :mkvimrc */
8794 if (eap->cmdidx == CMD_mkvimrc)
8795 (void)put_line(fd, "version 6.0");
8797 #ifdef FEAT_SESSION
8798 if (eap->cmdidx == CMD_mksession)
8800 if (put_line(fd, "let SessionLoad = 1") == FAIL)
8801 failed = TRUE;
8804 if (eap->cmdidx != CMD_mkview)
8805 #endif
8807 /* Write setting 'compatible' first, because it has side effects.
8808 * For that same reason only do it when needed. */
8809 if (p_cp)
8810 (void)put_line(fd, "if !&cp | set cp | endif");
8811 else
8812 (void)put_line(fd, "if &cp | set nocp | endif");
8815 #ifdef FEAT_SESSION
8816 if (!view_session
8817 || (eap->cmdidx == CMD_mksession
8818 && (*flagp & SSOP_OPTIONS)))
8819 #endif
8820 failed |= (makemap(fd, NULL) == FAIL
8821 || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
8823 #ifdef FEAT_SESSION
8824 if (!failed && view_session)
8826 if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
8827 failed = TRUE;
8828 if (eap->cmdidx == CMD_mksession)
8830 char_u dirnow[MAXPATHL]; /* current directory */
8833 * Change to session file's dir.
8835 if (mch_dirname(dirnow, MAXPATHL) == FAIL
8836 || mch_chdir((char *)dirnow) != 0)
8837 *dirnow = NUL;
8838 if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
8840 if (vim_chdirfile(fname) == OK)
8841 shorten_fnames(TRUE);
8843 else if (*dirnow != NUL
8844 && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
8846 if (mch_chdir((char *)globaldir) == 0)
8847 shorten_fnames(TRUE);
8850 failed |= (makeopens(fd, dirnow) == FAIL);
8852 /* restore original dir */
8853 if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
8854 || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
8856 if (mch_chdir((char *)dirnow) != 0)
8857 EMSG(_(e_prev_dir));
8858 shorten_fnames(TRUE);
8861 else
8863 failed |= (put_view(fd, curwin, !using_vdir, flagp,
8864 -1) == FAIL);
8866 if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
8867 == FAIL)
8868 failed = TRUE;
8869 if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
8870 failed = TRUE;
8871 if (eap->cmdidx == CMD_mksession)
8873 if (put_line(fd, "unlet SessionLoad") == FAIL)
8874 failed = TRUE;
8877 #endif
8878 if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
8879 failed = TRUE;
8881 failed |= fclose(fd);
8883 if (failed)
8884 EMSG(_(e_write));
8885 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
8886 else if (eap->cmdidx == CMD_mksession)
8888 /* successful session write - set this_session var */
8889 char_u tbuf[MAXPATHL];
8891 if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
8892 set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
8894 #endif
8895 #ifdef MKSESSION_NL
8896 mksession_nl = FALSE;
8897 #endif
8900 #ifdef FEAT_BROWSE
8901 theend:
8902 vim_free(browseFile);
8903 #endif
8904 #ifdef FEAT_SESSION
8905 vim_free(viewFile);
8906 #endif
8909 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
8910 || defined(PROTO)
8912 vim_mkdir_emsg(name, prot)
8913 char_u *name;
8914 int prot UNUSED;
8916 if (vim_mkdir(name, prot) != 0)
8918 EMSG2(_("E739: Cannot create directory: %s"), name);
8919 return FAIL;
8921 return OK;
8923 #endif
8926 * Open a file for writing for an Ex command, with some checks.
8927 * Return file descriptor, or NULL on failure.
8929 FILE *
8930 open_exfile(fname, forceit, mode)
8931 char_u *fname;
8932 int forceit;
8933 char *mode; /* "w" for create new file or "a" for append */
8935 FILE *fd;
8937 #ifdef UNIX
8938 /* with Unix it is possible to open a directory */
8939 if (mch_isdir(fname))
8941 EMSG2(_(e_isadir2), fname);
8942 return NULL;
8944 #endif
8945 if (!forceit && *mode != 'a' && vim_fexists(fname))
8947 EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
8948 return NULL;
8951 if ((fd = mch_fopen((char *)fname, mode)) == NULL)
8952 EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
8954 return fd;
8958 * ":mark" and ":k".
8960 static void
8961 ex_mark(eap)
8962 exarg_T *eap;
8964 pos_T pos;
8966 if (*eap->arg == NUL) /* No argument? */
8967 EMSG(_(e_argreq));
8968 else if (eap->arg[1] != NUL) /* more than one character? */
8969 EMSG(_(e_trailing));
8970 else
8972 pos = curwin->w_cursor; /* save curwin->w_cursor */
8973 curwin->w_cursor.lnum = eap->line2;
8974 beginline(BL_WHITE | BL_FIX);
8975 if (setmark(*eap->arg) == FAIL) /* set mark */
8976 EMSG(_("E191: Argument must be a letter or forward/backward quote"));
8977 curwin->w_cursor = pos; /* restore curwin->w_cursor */
8982 * Update w_topline, w_leftcol and the cursor position.
8984 void
8985 update_topline_cursor()
8987 check_cursor(); /* put cursor on valid line */
8988 update_topline();
8989 if (!curwin->w_p_wrap)
8990 validate_cursor();
8991 update_curswant();
8994 #ifdef FEAT_EX_EXTRA
8996 * ":normal[!] {commands}": Execute normal mode commands.
8998 static void
8999 ex_normal(eap)
9000 exarg_T *eap;
9002 int save_msg_scroll = msg_scroll;
9003 int save_restart_edit = restart_edit;
9004 int save_msg_didout = msg_didout;
9005 int save_State = State;
9006 tasave_T tabuf;
9007 int save_insertmode = p_im;
9008 int save_finish_op = finish_op;
9009 int save_opcount = opcount;
9010 #ifdef FEAT_MBYTE
9011 char_u *arg = NULL;
9012 int l;
9013 char_u *p;
9014 #endif
9016 if (ex_normal_lock > 0)
9018 EMSG(_(e_secure));
9019 return;
9021 if (ex_normal_busy >= p_mmd)
9023 EMSG(_("E192: Recursive use of :normal too deep"));
9024 return;
9026 ++ex_normal_busy;
9028 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
9029 restart_edit = 0; /* don't go to Insert mode */
9030 p_im = FALSE; /* don't use 'insertmode' */
9032 #ifdef FEAT_MBYTE
9034 * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
9035 * this for the K_SPECIAL leading byte, otherwise special keys will not
9036 * work.
9038 if (has_mbyte)
9040 int len = 0;
9042 /* Count the number of characters to be escaped. */
9043 for (p = eap->arg; *p != NUL; ++p)
9045 # ifdef FEAT_GUI
9046 if (*p == CSI) /* leadbyte CSI */
9047 len += 2;
9048 # endif
9049 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9050 if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */
9051 # ifdef FEAT_GUI
9052 || *p == CSI
9053 # endif
9055 len += 2;
9057 if (len > 0)
9059 arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
9060 if (arg != NULL)
9062 len = 0;
9063 for (p = eap->arg; *p != NUL; ++p)
9065 arg[len++] = *p;
9066 # ifdef FEAT_GUI
9067 if (*p == CSI)
9069 arg[len++] = KS_EXTRA;
9070 arg[len++] = (int)KE_CSI;
9072 # endif
9073 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9075 arg[len++] = *++p;
9076 if (*p == K_SPECIAL)
9078 arg[len++] = KS_SPECIAL;
9079 arg[len++] = KE_FILLER;
9081 # ifdef FEAT_GUI
9082 else if (*p == CSI)
9084 arg[len++] = KS_EXTRA;
9085 arg[len++] = (int)KE_CSI;
9087 # endif
9089 arg[len] = NUL;
9094 #endif
9097 * Save the current typeahead. This is required to allow using ":normal"
9098 * from an event handler and makes sure we don't hang when the argument
9099 * ends with half a command.
9101 save_typeahead(&tabuf);
9102 if (tabuf.typebuf_valid)
9105 * Repeat the :normal command for each line in the range. When no
9106 * range given, execute it just once, without positioning the cursor
9107 * first.
9111 if (eap->addr_count != 0)
9113 curwin->w_cursor.lnum = eap->line1++;
9114 curwin->w_cursor.col = 0;
9117 exec_normal_cmd(
9118 #ifdef FEAT_MBYTE
9119 arg != NULL ? arg :
9120 #endif
9121 eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
9123 while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
9126 /* Might not return to the main loop when in an event handler. */
9127 update_topline_cursor();
9129 /* Restore the previous typeahead. */
9130 restore_typeahead(&tabuf);
9132 --ex_normal_busy;
9133 msg_scroll = save_msg_scroll;
9134 restart_edit = save_restart_edit;
9135 p_im = save_insertmode;
9136 finish_op = save_finish_op;
9137 opcount = save_opcount;
9138 msg_didout |= save_msg_didout; /* don't reset msg_didout now */
9140 /* Restore the state (needed when called from a function executed for
9141 * 'indentexpr'). */
9142 State = save_State;
9143 #ifdef FEAT_MBYTE
9144 vim_free(arg);
9145 #endif
9149 * ":startinsert", ":startreplace" and ":startgreplace"
9151 static void
9152 ex_startinsert(eap)
9153 exarg_T *eap;
9155 if (eap->forceit)
9157 coladvance((colnr_T)MAXCOL);
9158 curwin->w_curswant = MAXCOL;
9159 curwin->w_set_curswant = FALSE;
9162 /* Ignore the command when already in Insert mode. Inserting an
9163 * expression register that invokes a function can do this. */
9164 if (State & INSERT)
9165 return;
9167 if (eap->cmdidx == CMD_startinsert)
9168 restart_edit = 'a';
9169 else if (eap->cmdidx == CMD_startreplace)
9170 restart_edit = 'R';
9171 else
9172 restart_edit = 'V';
9174 if (!eap->forceit)
9176 if (eap->cmdidx == CMD_startinsert)
9177 restart_edit = 'i';
9178 curwin->w_curswant = 0; /* avoid MAXCOL */
9183 * ":stopinsert"
9185 static void
9186 ex_stopinsert(eap)
9187 exarg_T *eap UNUSED;
9189 restart_edit = 0;
9190 stop_insert_mode = TRUE;
9192 #endif
9194 #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO)
9196 * Execute normal mode command "cmd".
9197 * "remap" can be REMAP_NONE or REMAP_YES.
9199 void
9200 exec_normal_cmd(cmd, remap, silent)
9201 char_u *cmd;
9202 int remap;
9203 int silent;
9205 oparg_T oa;
9208 * Stuff the argument into the typeahead buffer.
9209 * Execute normal_cmd() until there is no typeahead left.
9211 clear_oparg(&oa);
9212 finish_op = FALSE;
9213 ins_typebuf(cmd, remap, 0, TRUE, silent);
9214 while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
9215 && !got_int)
9217 update_topline_cursor();
9218 normal_cmd(&oa, FALSE); /* execute a Normal mode cmd */
9221 #endif
9223 #ifdef FEAT_FIND_ID
9224 static void
9225 ex_checkpath(eap)
9226 exarg_T *eap;
9228 find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
9229 eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
9230 (linenr_T)1, (linenr_T)MAXLNUM);
9233 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
9235 * ":psearch"
9237 static void
9238 ex_psearch(eap)
9239 exarg_T *eap;
9241 g_do_tagpreview = p_pvh;
9242 ex_findpat(eap);
9243 g_do_tagpreview = 0;
9245 #endif
9247 static void
9248 ex_findpat(eap)
9249 exarg_T *eap;
9251 int whole = TRUE;
9252 long n;
9253 char_u *p;
9254 int action;
9256 switch (cmdnames[eap->cmdidx].cmd_name[2])
9258 case 'e': /* ":psearch", ":isearch" and ":dsearch" */
9259 if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
9260 action = ACTION_GOTO;
9261 else
9262 action = ACTION_SHOW;
9263 break;
9264 case 'i': /* ":ilist" and ":dlist" */
9265 action = ACTION_SHOW_ALL;
9266 break;
9267 case 'u': /* ":ijump" and ":djump" */
9268 action = ACTION_GOTO;
9269 break;
9270 default: /* ":isplit" and ":dsplit" */
9271 action = ACTION_SPLIT;
9272 break;
9275 n = 1;
9276 if (vim_isdigit(*eap->arg)) /* get count */
9278 n = getdigits(&eap->arg);
9279 eap->arg = skipwhite(eap->arg);
9281 if (*eap->arg == '/') /* Match regexp, not just whole words */
9283 whole = FALSE;
9284 ++eap->arg;
9285 p = skip_regexp(eap->arg, '/', p_magic, NULL);
9286 if (*p)
9288 *p++ = NUL;
9289 p = skipwhite(p);
9291 /* Check for trailing illegal characters */
9292 if (!ends_excmd(*p))
9293 eap->errmsg = e_trailing;
9294 else
9295 eap->nextcmd = check_nextcmd(p);
9298 if (!eap->skip)
9299 find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
9300 whole, !eap->forceit,
9301 *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY,
9302 n, action, eap->line1, eap->line2);
9304 #endif
9306 #ifdef FEAT_WINDOWS
9308 # ifdef FEAT_QUICKFIX
9310 * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
9312 static void
9313 ex_ptag(eap)
9314 exarg_T *eap;
9316 g_do_tagpreview = p_pvh;
9317 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9321 * ":pedit"
9323 static void
9324 ex_pedit(eap)
9325 exarg_T *eap;
9327 win_T *curwin_save = curwin;
9329 g_do_tagpreview = p_pvh;
9330 prepare_tagpreview(TRUE);
9331 keep_help_flag = curwin_save->w_buffer->b_help;
9332 do_exedit(eap, NULL);
9333 keep_help_flag = FALSE;
9334 if (curwin != curwin_save && win_valid(curwin_save))
9336 /* Return cursor to where we were */
9337 validate_cursor();
9338 redraw_later(VALID);
9339 win_enter(curwin_save, TRUE);
9341 g_do_tagpreview = 0;
9343 # endif
9346 * ":stag", ":stselect" and ":stjump".
9348 static void
9349 ex_stag(eap)
9350 exarg_T *eap;
9352 postponed_split = -1;
9353 postponed_split_flags = cmdmod.split;
9354 postponed_split_tab = cmdmod.tab;
9355 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9356 postponed_split_flags = 0;
9357 postponed_split_tab = 0;
9359 #endif
9362 * ":tag", ":tselect", ":tjump", ":tnext", etc.
9364 static void
9365 ex_tag(eap)
9366 exarg_T *eap;
9368 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
9371 static void
9372 ex_tag_cmd(eap, name)
9373 exarg_T *eap;
9374 char_u *name;
9376 int cmd;
9378 switch (name[1])
9380 case 'j': cmd = DT_JUMP; /* ":tjump" */
9381 break;
9382 case 's': cmd = DT_SELECT; /* ":tselect" */
9383 break;
9384 case 'p': cmd = DT_PREV; /* ":tprevious" */
9385 break;
9386 case 'N': cmd = DT_PREV; /* ":tNext" */
9387 break;
9388 case 'n': cmd = DT_NEXT; /* ":tnext" */
9389 break;
9390 case 'o': cmd = DT_POP; /* ":pop" */
9391 break;
9392 case 'f': /* ":tfirst" */
9393 case 'r': cmd = DT_FIRST; /* ":trewind" */
9394 break;
9395 case 'l': cmd = DT_LAST; /* ":tlast" */
9396 break;
9397 default: /* ":tag" */
9398 #ifdef FEAT_CSCOPE
9399 if (p_cst && *eap->arg != NUL)
9401 do_cstag(eap);
9402 return;
9404 #endif
9405 cmd = DT_TAG;
9406 break;
9409 if (name[0] == 'l')
9411 #ifndef FEAT_QUICKFIX
9412 ex_ni(eap);
9413 return;
9414 #else
9415 cmd = DT_LTAG;
9416 #endif
9419 do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
9420 eap->forceit, TRUE);
9424 * Check "str" for starting with a special cmdline variable.
9425 * If found return one of the SPEC_ values and set "*usedlen" to the length of
9426 * the variable. Otherwise return -1 and "*usedlen" is unchanged.
9429 find_cmdline_var(src, usedlen)
9430 char_u *src;
9431 int *usedlen;
9433 int len;
9434 int i;
9435 static char *(spec_str[]) = {
9436 "%",
9437 #define SPEC_PERC 0
9438 "#",
9439 #define SPEC_HASH 1
9440 "<cword>", /* cursor word */
9441 #define SPEC_CWORD 2
9442 "<cWORD>", /* cursor WORD */
9443 #define SPEC_CCWORD 3
9444 "<cfile>", /* cursor path name */
9445 #define SPEC_CFILE 4
9446 "<sfile>", /* ":so" file name */
9447 #define SPEC_SFILE 5
9448 #ifdef FEAT_AUTOCMD
9449 "<afile>", /* autocommand file name */
9450 # define SPEC_AFILE 6
9451 "<abuf>", /* autocommand buffer number */
9452 # define SPEC_ABUF 7
9453 "<amatch>", /* autocommand match name */
9454 # define SPEC_AMATCH 8
9455 #endif
9456 #ifdef FEAT_CLIENTSERVER
9457 "<client>"
9458 # define SPEC_CLIENT 9
9459 #endif
9462 for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i)
9464 len = (int)STRLEN(spec_str[i]);
9465 if (STRNCMP(src, spec_str[i], len) == 0)
9467 *usedlen = len;
9468 return i;
9471 return -1;
9475 * Evaluate cmdline variables.
9477 * change '%' to curbuf->b_ffname
9478 * '#' to curwin->w_altfile
9479 * '<cword>' to word under the cursor
9480 * '<cWORD>' to WORD under the cursor
9481 * '<cfile>' to path name under the cursor
9482 * '<sfile>' to sourced file name
9483 * '<afile>' to file name for autocommand
9484 * '<abuf>' to buffer number for autocommand
9485 * '<amatch>' to matching name for autocommand
9487 * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
9488 * "" for error without a message) and NULL is returned.
9489 * Returns an allocated string if a valid match was found.
9490 * Returns NULL if no match was found. "usedlen" then still contains the
9491 * number of characters to skip.
9493 char_u *
9494 eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped)
9495 char_u *src; /* pointer into commandline */
9496 char_u *srcstart; /* beginning of valid memory for src */
9497 int *usedlen; /* characters after src that are used */
9498 linenr_T *lnump; /* line number for :e command, or NULL */
9499 char_u **errormsg; /* pointer to error message */
9500 int *escaped; /* return value has escaped white space (can
9501 * be NULL) */
9503 int i;
9504 char_u *s;
9505 char_u *result;
9506 char_u *resultbuf = NULL;
9507 int resultlen;
9508 buf_T *buf;
9509 int valid = VALID_HEAD + VALID_PATH; /* assume valid result */
9510 int spec_idx;
9511 #ifdef FEAT_MODIFY_FNAME
9512 int skip_mod = FALSE;
9513 #endif
9515 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
9516 char_u strbuf[30];
9517 #endif
9519 *errormsg = NULL;
9520 if (escaped != NULL)
9521 *escaped = FALSE;
9524 * Check if there is something to do.
9526 spec_idx = find_cmdline_var(src, usedlen);
9527 if (spec_idx < 0) /* no match */
9529 *usedlen = 1;
9530 return NULL;
9534 * Skip when preceded with a backslash "\%" and "\#".
9535 * Note: In "\\%" the % is also not recognized!
9537 if (src > srcstart && src[-1] == '\\')
9539 *usedlen = 0;
9540 STRMOVE(src - 1, src); /* remove backslash */
9541 return NULL;
9545 * word or WORD under cursor
9547 if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
9549 resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
9550 (FIND_IDENT|FIND_STRING) : FIND_STRING);
9551 if (resultlen == 0)
9553 *errormsg = (char_u *)"";
9554 return NULL;
9559 * '#': Alternate file name
9560 * '%': Current file name
9561 * File name under the cursor
9562 * File name for autocommand
9563 * and following modifiers
9565 else
9567 switch (spec_idx)
9569 case SPEC_PERC: /* '%': current file */
9570 if (curbuf->b_fname == NULL)
9572 result = (char_u *)"";
9573 valid = 0; /* Must have ":p:h" to be valid */
9575 else
9576 #ifdef RISCOS
9577 /* Always use the full path for RISC OS if possible. */
9578 result = curbuf->b_ffname;
9579 if (result == NULL)
9580 result = curbuf->b_fname;
9581 #else
9582 result = curbuf->b_fname;
9583 #endif
9584 break;
9586 case SPEC_HASH: /* '#' or "#99": alternate file */
9587 if (src[1] == '#') /* "##": the argument list */
9589 result = arg_all();
9590 resultbuf = result;
9591 *usedlen = 2;
9592 if (escaped != NULL)
9593 *escaped = TRUE;
9594 #ifdef FEAT_MODIFY_FNAME
9595 skip_mod = TRUE;
9596 #endif
9597 break;
9599 s = src + 1;
9600 if (*s == '<') /* "#<99" uses v:oldfiles */
9601 ++s;
9602 i = (int)getdigits(&s);
9603 *usedlen = (int)(s - src); /* length of what we expand */
9605 if (src[1] == '<')
9607 if (*usedlen < 2)
9609 /* Should we give an error message for #<text? */
9610 *usedlen = 1;
9611 return NULL;
9613 #ifdef FEAT_EVAL
9614 result = list_find_str(get_vim_var_list(VV_OLDFILES),
9615 (long)i);
9616 if (result == NULL)
9618 *errormsg = (char_u *)"";
9619 return NULL;
9621 #else
9622 *errormsg = (char_u *)_("E809: #< is not available without the +eval feature");
9623 return NULL;
9624 #endif
9626 else
9628 buf = buflist_findnr(i);
9629 if (buf == NULL)
9631 *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
9632 return NULL;
9634 if (lnump != NULL)
9635 *lnump = ECMD_LAST;
9636 if (buf->b_fname == NULL)
9638 result = (char_u *)"";
9639 valid = 0; /* Must have ":p:h" to be valid */
9641 else
9642 result = buf->b_fname;
9644 break;
9646 #ifdef FEAT_SEARCHPATH
9647 case SPEC_CFILE: /* file name under cursor */
9648 result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
9649 if (result == NULL)
9651 *errormsg = (char_u *)"";
9652 return NULL;
9654 resultbuf = result; /* remember allocated string */
9655 break;
9656 #endif
9658 #ifdef FEAT_AUTOCMD
9659 case SPEC_AFILE: /* file name for autocommand */
9660 result = autocmd_fname;
9661 if (result != NULL && !autocmd_fname_full)
9663 /* Still need to turn the fname into a full path. It is
9664 * postponed to avoid a delay when <afile> is not used. */
9665 autocmd_fname_full = TRUE;
9666 result = FullName_save(autocmd_fname, FALSE);
9667 vim_free(autocmd_fname);
9668 autocmd_fname = result;
9670 if (result == NULL)
9672 *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
9673 return NULL;
9675 result = shorten_fname1(result);
9676 break;
9678 case SPEC_ABUF: /* buffer number for autocommand */
9679 if (autocmd_bufnr <= 0)
9681 *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
9682 return NULL;
9684 sprintf((char *)strbuf, "%d", autocmd_bufnr);
9685 result = strbuf;
9686 break;
9688 case SPEC_AMATCH: /* match name for autocommand */
9689 result = autocmd_match;
9690 if (result == NULL)
9692 *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
9693 return NULL;
9695 break;
9697 #endif
9698 case SPEC_SFILE: /* file name for ":so" command */
9699 result = sourcing_name;
9700 if (result == NULL)
9702 *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
9703 return NULL;
9705 break;
9706 #if defined(FEAT_CLIENTSERVER)
9707 case SPEC_CLIENT: /* Source of last submitted input */
9708 sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
9709 (long_u)clientWindow);
9710 result = strbuf;
9711 break;
9712 #endif
9715 resultlen = (int)STRLEN(result); /* length of new string */
9716 if (src[*usedlen] == '<') /* remove the file name extension */
9718 ++*usedlen;
9719 #ifdef RISCOS
9720 if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
9721 #else
9722 if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
9723 #endif
9724 resultlen = (int)(s - result);
9726 #ifdef FEAT_MODIFY_FNAME
9727 else if (!skip_mod)
9729 valid |= modify_fname(src, usedlen, &result, &resultbuf,
9730 &resultlen);
9731 if (result == NULL)
9733 *errormsg = (char_u *)"";
9734 return NULL;
9737 #endif
9740 if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
9742 if (valid != VALID_HEAD + VALID_PATH)
9743 /* xgettext:no-c-format */
9744 *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
9745 else
9746 *errormsg = (char_u *)_("E500: Evaluates to an empty string");
9747 result = NULL;
9749 else
9750 result = vim_strnsave(result, resultlen);
9751 vim_free(resultbuf);
9752 return result;
9756 * Concatenate all files in the argument list, separated by spaces, and return
9757 * it in one allocated string.
9758 * Spaces and backslashes in the file names are escaped with a backslash.
9759 * Returns NULL when out of memory.
9761 static char_u *
9762 arg_all()
9764 int len;
9765 int idx;
9766 char_u *retval = NULL;
9767 char_u *p;
9770 * Do this loop two times:
9771 * first time: compute the total length
9772 * second time: concatenate the names
9774 for (;;)
9776 len = 0;
9777 for (idx = 0; idx < ARGCOUNT; ++idx)
9779 p = alist_name(&ARGLIST[idx]);
9780 if (p != NULL)
9782 if (len > 0)
9784 /* insert a space in between names */
9785 if (retval != NULL)
9786 retval[len] = ' ';
9787 ++len;
9789 for ( ; *p != NUL; ++p)
9791 if (*p == ' ' || *p == '\\')
9793 /* insert a backslash */
9794 if (retval != NULL)
9795 retval[len] = '\\';
9796 ++len;
9798 if (retval != NULL)
9799 retval[len] = *p;
9800 ++len;
9805 /* second time: break here */
9806 if (retval != NULL)
9808 retval[len] = NUL;
9809 break;
9812 /* allocate memory */
9813 retval = alloc((unsigned)len + 1);
9814 if (retval == NULL)
9815 break;
9818 return retval;
9821 #if defined(FEAT_AUTOCMD) || defined(PROTO)
9823 * Expand the <sfile> string in "arg".
9825 * Returns an allocated string, or NULL for any error.
9827 char_u *
9828 expand_sfile(arg)
9829 char_u *arg;
9831 char_u *errormsg;
9832 int len;
9833 char_u *result;
9834 char_u *newres;
9835 char_u *repl;
9836 int srclen;
9837 char_u *p;
9839 result = vim_strsave(arg);
9840 if (result == NULL)
9841 return NULL;
9843 for (p = result; *p; )
9845 if (STRNCMP(p, "<sfile>", 7) != 0)
9846 ++p;
9847 else
9849 /* replace "<sfile>" with the sourced file name, and do ":" stuff */
9850 repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
9851 if (errormsg != NULL)
9853 if (*errormsg)
9854 emsg(errormsg);
9855 vim_free(result);
9856 return NULL;
9858 if (repl == NULL) /* no match (cannot happen) */
9860 p += srclen;
9861 continue;
9863 len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
9864 newres = alloc(len);
9865 if (newres == NULL)
9867 vim_free(repl);
9868 vim_free(result);
9869 return NULL;
9871 mch_memmove(newres, result, (size_t)(p - result));
9872 STRCPY(newres + (p - result), repl);
9873 len = (int)STRLEN(newres);
9874 STRCAT(newres, p + srclen);
9875 vim_free(repl);
9876 vim_free(result);
9877 result = newres;
9878 p = newres + len; /* continue after the match */
9882 return result;
9884 #endif
9886 #ifdef FEAT_SESSION
9887 static int ses_winsizes __ARGS((FILE *fd, int restore_size,
9888 win_T *tab_firstwin));
9889 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
9890 static frame_T *ses_skipframe __ARGS((frame_T *fr));
9891 static int ses_do_frame __ARGS((frame_T *fr));
9892 static int ses_do_win __ARGS((win_T *wp));
9893 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
9894 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
9895 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
9898 * Write openfile commands for the current buffers to an .exrc file.
9899 * Return FAIL on error, OK otherwise.
9901 static int
9902 makeopens(fd, dirnow)
9903 FILE *fd;
9904 char_u *dirnow; /* Current directory name */
9906 buf_T *buf;
9907 int only_save_windows = TRUE;
9908 int nr;
9909 int cnr = 1;
9910 int restore_size = TRUE;
9911 win_T *wp;
9912 char_u *sname;
9913 win_T *edited_win = NULL;
9914 int tabnr;
9915 win_T *tab_firstwin;
9916 frame_T *tab_topframe;
9917 int cur_arg_idx = 0;
9918 int next_arg_idx = 0;
9920 if (ssop_flags & SSOP_BUFFERS)
9921 only_save_windows = FALSE; /* Save ALL buffers */
9924 * Begin by setting the this_session variable, and then other
9925 * sessionable variables.
9927 #ifdef FEAT_EVAL
9928 if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
9929 return FAIL;
9930 if (ssop_flags & SSOP_GLOBALS)
9931 if (store_session_globals(fd) == FAIL)
9932 return FAIL;
9933 #endif
9936 * Close all windows but one.
9938 if (put_line(fd, "silent only") == FAIL)
9939 return FAIL;
9942 * Now a :cd command to the session directory or the current directory
9944 if (ssop_flags & SSOP_SESDIR)
9946 if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
9947 == FAIL)
9948 return FAIL;
9950 else if (ssop_flags & SSOP_CURDIR)
9952 sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
9953 if (sname == NULL
9954 || fputs("cd ", fd) < 0
9955 || ses_put_fname(fd, sname, &ssop_flags) == FAIL
9956 || put_eol(fd) == FAIL)
9958 vim_free(sname);
9959 return FAIL;
9961 vim_free(sname);
9965 * If there is an empty, unnamed buffer we will wipe it out later.
9966 * Remember the buffer number.
9968 if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
9969 return FAIL;
9970 if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL)
9971 return FAIL;
9972 if (put_line(fd, "endif") == FAIL)
9973 return FAIL;
9976 * Now save the current files, current buffer first.
9978 if (put_line(fd, "set shortmess=aoO") == FAIL)
9979 return FAIL;
9981 /* Now put the other buffers into the buffer list */
9982 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9984 if (!(only_save_windows && buf->b_nwindows == 0)
9985 && !(buf->b_help && !(ssop_flags & SSOP_HELP))
9986 && buf->b_fname != NULL
9987 && buf->b_p_bl)
9989 if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
9990 : buf->b_wininfo->wi_fpos.lnum) < 0
9991 || ses_fname(fd, buf, &ssop_flags) == FAIL)
9992 return FAIL;
9996 /* the global argument list */
9997 if (ses_arglist(fd, "args", &global_alist.al_ga,
9998 !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
9999 return FAIL;
10001 if (ssop_flags & SSOP_RESIZE)
10003 /* Note: after the restore we still check it worked!*/
10004 if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
10005 || put_eol(fd) == FAIL)
10006 return FAIL;
10009 #ifdef FEAT_GUI
10010 if (gui.in_use && (ssop_flags & SSOP_WINPOS))
10012 int x, y;
10014 if (gui_mch_get_winpos(&x, &y) == OK)
10016 /* Note: after the restore we still check it worked!*/
10017 if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
10018 return FAIL;
10021 #endif
10024 * May repeat putting Windows for each tab, when "tabpages" is in
10025 * 'sessionoptions'.
10026 * Don't use goto_tabpage(), it may change directory and trigger
10027 * autocommands.
10029 tab_firstwin = firstwin; /* first window in tab page "tabnr" */
10030 tab_topframe = topframe;
10031 for (tabnr = 1; ; ++tabnr)
10033 int need_tabnew = FALSE;
10035 if ((ssop_flags & SSOP_TABPAGES))
10037 tabpage_T *tp = find_tabpage(tabnr);
10039 if (tp == NULL)
10040 break; /* done all tab pages */
10041 if (tp == curtab)
10043 tab_firstwin = firstwin;
10044 tab_topframe = topframe;
10046 else
10048 tab_firstwin = tp->tp_firstwin;
10049 tab_topframe = tp->tp_topframe;
10051 if (tabnr > 1)
10052 need_tabnew = TRUE;
10056 * Before creating the window layout, try loading one file. If this
10057 * is aborted we don't end up with a number of useless windows.
10058 * This may have side effects! (e.g., compressed or network file).
10060 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10062 if (ses_do_win(wp)
10063 && wp->w_buffer->b_ffname != NULL
10064 && !wp->w_buffer->b_help
10065 #ifdef FEAT_QUICKFIX
10066 && !bt_nofile(wp->w_buffer)
10067 #endif
10070 if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
10071 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
10072 return FAIL;
10073 need_tabnew = FALSE;
10074 if (!wp->w_arg_idx_invalid)
10075 edited_win = wp;
10076 break;
10080 /* If no file got edited create an empty tab page. */
10081 if (need_tabnew && put_line(fd, "tabnew") == FAIL)
10082 return FAIL;
10085 * Save current window layout.
10087 if (put_line(fd, "set splitbelow splitright") == FAIL)
10088 return FAIL;
10089 if (ses_win_rec(fd, tab_topframe) == FAIL)
10090 return FAIL;
10091 if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
10092 return FAIL;
10093 if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
10094 return FAIL;
10097 * Check if window sizes can be restored (no windows omitted).
10098 * Remember the window number of the current window after restoring.
10100 nr = 0;
10101 for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
10103 if (ses_do_win(wp))
10104 ++nr;
10105 else
10106 restore_size = FALSE;
10107 if (curwin == wp)
10108 cnr = nr;
10111 /* Go to the first window. */
10112 if (put_line(fd, "wincmd t") == FAIL)
10113 return FAIL;
10116 * If more than one window, see if sizes can be restored.
10117 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
10118 * resized when moving between windows.
10119 * Do this before restoring the view, so that the topline and the
10120 * cursor can be set. This is done again below.
10122 if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
10123 return FAIL;
10124 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10125 return FAIL;
10128 * Restore the view of the window (options, file, cursor, etc.).
10130 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10132 if (!ses_do_win(wp))
10133 continue;
10134 if (put_view(fd, wp, wp != edited_win, &ssop_flags,
10135 cur_arg_idx) == FAIL)
10136 return FAIL;
10137 if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
10138 return FAIL;
10139 next_arg_idx = wp->w_arg_idx;
10142 /* The argument index in the first tab page is zero, need to set it in
10143 * each window. For further tab pages it's the window where we do
10144 * "tabedit". */
10145 cur_arg_idx = next_arg_idx;
10148 * Restore cursor to the current window if it's not the first one.
10150 if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
10151 || put_eol(fd) == FAIL))
10152 return FAIL;
10155 * Restore window sizes again after jumping around in windows, because
10156 * the current window has a minimum size while others may not.
10158 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10159 return FAIL;
10161 /* Don't continue in another tab page when doing only the current one
10162 * or when at the last tab page. */
10163 if (!(ssop_flags & SSOP_TABPAGES))
10164 break;
10167 if (ssop_flags & SSOP_TABPAGES)
10169 if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
10170 || put_eol(fd) == FAIL)
10171 return FAIL;
10175 * Wipe out an empty unnamed buffer we started in.
10177 if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
10178 return FAIL;
10179 if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL)
10180 return FAIL;
10181 if (put_line(fd, "endif") == FAIL)
10182 return FAIL;
10183 if (put_line(fd, "unlet! s:wipebuf") == FAIL)
10184 return FAIL;
10186 /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
10187 if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
10188 p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
10189 return FAIL;
10192 * Lastly, execute the x.vim file if it exists.
10194 if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
10195 || put_line(fd, "if file_readable(s:sx)") == FAIL
10196 || put_line(fd, " exe \"source \" . fnameescape(s:sx)") == FAIL
10197 || put_line(fd, "endif") == FAIL)
10198 return FAIL;
10200 return OK;
10203 static int
10204 ses_winsizes(fd, restore_size, tab_firstwin)
10205 FILE *fd;
10206 int restore_size;
10207 win_T *tab_firstwin;
10209 int n = 0;
10210 win_T *wp;
10212 if (restore_size && (ssop_flags & SSOP_WINSIZE))
10214 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10216 if (!ses_do_win(wp))
10217 continue;
10218 ++n;
10220 /* restore height when not full height */
10221 if (wp->w_height + wp->w_status_height < topframe->fr_height
10222 && (fprintf(fd,
10223 "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
10224 n, (long)wp->w_height, Rows / 2, Rows) < 0
10225 || put_eol(fd) == FAIL))
10226 return FAIL;
10228 /* restore width when not full width */
10229 if (wp->w_width < Columns && (fprintf(fd,
10230 "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
10231 n, (long)wp->w_width, Columns / 2, Columns) < 0
10232 || put_eol(fd) == FAIL))
10233 return FAIL;
10236 else
10238 /* Just equalise window sizes */
10239 if (put_line(fd, "wincmd =") == FAIL)
10240 return FAIL;
10242 return OK;
10246 * Write commands to "fd" to recursively create windows for frame "fr",
10247 * horizontally and vertically split.
10248 * After the commands the last window in the frame is the current window.
10249 * Returns FAIL when writing the commands to "fd" fails.
10251 static int
10252 ses_win_rec(fd, fr)
10253 FILE *fd;
10254 frame_T *fr;
10256 frame_T *frc;
10257 int count = 0;
10259 if (fr->fr_layout != FR_LEAF)
10261 /* Find first frame that's not skipped and then create a window for
10262 * each following one (first frame is already there). */
10263 frc = ses_skipframe(fr->fr_child);
10264 if (frc != NULL)
10265 while ((frc = ses_skipframe(frc->fr_next)) != NULL)
10267 /* Make window as big as possible so that we have lots of room
10268 * to split. */
10269 if (put_line(fd, "wincmd _ | wincmd |") == FAIL
10270 || put_line(fd, fr->fr_layout == FR_COL
10271 ? "split" : "vsplit") == FAIL)
10272 return FAIL;
10273 ++count;
10276 /* Go back to the first window. */
10277 if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
10278 ? "%dwincmd k" : "%dwincmd h", count) < 0
10279 || put_eol(fd) == FAIL))
10280 return FAIL;
10282 /* Recursively create frames/windows in each window of this column or
10283 * row. */
10284 frc = ses_skipframe(fr->fr_child);
10285 while (frc != NULL)
10287 ses_win_rec(fd, frc);
10288 frc = ses_skipframe(frc->fr_next);
10289 /* Go to next window. */
10290 if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
10291 return FAIL;
10294 return OK;
10298 * Skip frames that don't contain windows we want to save in the Session.
10299 * Returns NULL when there none.
10301 static frame_T *
10302 ses_skipframe(fr)
10303 frame_T *fr;
10305 frame_T *frc;
10307 for (frc = fr; frc != NULL; frc = frc->fr_next)
10308 if (ses_do_frame(frc))
10309 break;
10310 return frc;
10314 * Return TRUE if frame "fr" has a window somewhere that we want to save in
10315 * the Session.
10317 static int
10318 ses_do_frame(fr)
10319 frame_T *fr;
10321 frame_T *frc;
10323 if (fr->fr_layout == FR_LEAF)
10324 return ses_do_win(fr->fr_win);
10325 for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
10326 if (ses_do_frame(frc))
10327 return TRUE;
10328 return FALSE;
10332 * Return non-zero if window "wp" is to be stored in the Session.
10334 static int
10335 ses_do_win(wp)
10336 win_T *wp;
10338 if (wp->w_buffer->b_fname == NULL
10339 #ifdef FEAT_QUICKFIX
10340 /* When 'buftype' is "nofile" can't restore the window contents. */
10341 || bt_nofile(wp->w_buffer)
10342 #endif
10344 return (ssop_flags & SSOP_BLANK);
10345 if (wp->w_buffer->b_help)
10346 return (ssop_flags & SSOP_HELP);
10347 return TRUE;
10351 * Write commands to "fd" to restore the view of a window.
10352 * Caller must make sure 'scrolloff' is zero.
10354 static int
10355 put_view(fd, wp, add_edit, flagp, current_arg_idx)
10356 FILE *fd;
10357 win_T *wp;
10358 int add_edit; /* add ":edit" command to view */
10359 unsigned *flagp; /* vop_flags or ssop_flags */
10360 int current_arg_idx; /* current argument index of the window, use
10361 * -1 if unknown */
10363 win_T *save_curwin;
10364 int f;
10365 int do_cursor;
10366 int did_next = FALSE;
10368 /* Always restore cursor position for ":mksession". For ":mkview" only
10369 * when 'viewoptions' contains "cursor". */
10370 do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
10373 * Local argument list.
10375 if (wp->w_alist == &global_alist)
10377 if (put_line(fd, "argglobal") == FAIL)
10378 return FAIL;
10380 else
10382 if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
10383 flagp == &vop_flags
10384 || !(*flagp & SSOP_CURDIR)
10385 || wp->w_localdir != NULL, flagp) == FAIL)
10386 return FAIL;
10389 /* Only when part of a session: restore the argument index. Some
10390 * arguments may have been deleted, check if the index is valid. */
10391 if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx <= WARGCOUNT(wp)
10392 && flagp == &ssop_flags)
10394 if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
10395 || put_eol(fd) == FAIL)
10396 return FAIL;
10397 did_next = TRUE;
10400 /* Edit the file. Skip this when ":next" already did it. */
10401 if (add_edit && (!did_next || wp->w_arg_idx_invalid))
10404 * Load the file.
10406 if (wp->w_buffer->b_ffname != NULL
10407 #ifdef FEAT_QUICKFIX
10408 && !bt_nofile(wp->w_buffer)
10409 #endif
10413 * Editing a file in this buffer: use ":edit file".
10414 * This may have side effects! (e.g., compressed or network file).
10416 if (fputs("edit ", fd) < 0
10417 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10418 return FAIL;
10420 else
10422 /* No file in this buffer, just make it empty. */
10423 if (put_line(fd, "enew") == FAIL)
10424 return FAIL;
10425 #ifdef FEAT_QUICKFIX
10426 if (wp->w_buffer->b_ffname != NULL)
10428 /* The buffer does have a name, but it's not a file name. */
10429 if (fputs("file ", fd) < 0
10430 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10431 return FAIL;
10433 #endif
10434 do_cursor = FALSE;
10439 * Local mappings and abbreviations.
10441 if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10442 && makemap(fd, wp->w_buffer) == FAIL)
10443 return FAIL;
10446 * Local options. Need to go to the window temporarily.
10447 * Store only local values when using ":mkview" and when ":mksession" is
10448 * used and 'sessionoptions' doesn't include "options".
10449 * Some folding options are always stored when "folds" is included,
10450 * otherwise the folds would not be restored correctly.
10452 save_curwin = curwin;
10453 curwin = wp;
10454 curbuf = curwin->w_buffer;
10455 if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10456 f = makeset(fd, OPT_LOCAL,
10457 flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
10458 #ifdef FEAT_FOLDING
10459 else if (*flagp & SSOP_FOLDS)
10460 f = makefoldset(fd);
10461 #endif
10462 else
10463 f = OK;
10464 curwin = save_curwin;
10465 curbuf = curwin->w_buffer;
10466 if (f == FAIL)
10467 return FAIL;
10469 #ifdef FEAT_FOLDING
10471 * Save Folds when 'buftype' is empty and for help files.
10473 if ((*flagp & SSOP_FOLDS)
10474 && wp->w_buffer->b_ffname != NULL
10475 # ifdef FEAT_QUICKFIX
10476 && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help)
10477 # endif
10480 if (put_folds(fd, wp) == FAIL)
10481 return FAIL;
10483 #endif
10486 * Set the cursor after creating folds, since that moves the cursor.
10488 if (do_cursor)
10491 /* Restore the cursor line in the file and relatively in the
10492 * window. Don't use "G", it changes the jumplist. */
10493 if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
10494 (long)wp->w_cursor.lnum,
10495 (long)(wp->w_cursor.lnum - wp->w_topline),
10496 (long)wp->w_height / 2, (long)wp->w_height) < 0
10497 || put_eol(fd) == FAIL
10498 || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
10499 || put_line(fd, "exe s:l") == FAIL
10500 || put_line(fd, "normal! zt") == FAIL
10501 || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
10502 || put_eol(fd) == FAIL)
10503 return FAIL;
10504 /* Restore the cursor column and left offset when not wrapping. */
10505 if (wp->w_cursor.col == 0)
10507 if (put_line(fd, "normal! 0") == FAIL)
10508 return FAIL;
10510 else
10512 if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
10514 if (fprintf(fd,
10515 "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
10516 (long)wp->w_cursor.col,
10517 (long)(wp->w_cursor.col - wp->w_leftcol),
10518 (long)wp->w_width / 2, (long)wp->w_width) < 0
10519 || put_eol(fd) == FAIL
10520 || put_line(fd, "if s:c > 0") == FAIL
10521 || fprintf(fd,
10522 " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
10523 (long)wp->w_cursor.col) < 0
10524 || put_eol(fd) == FAIL
10525 || put_line(fd, "else") == FAIL
10526 || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0
10527 || put_eol(fd) == FAIL
10528 || put_line(fd, "endif") == FAIL)
10529 return FAIL;
10531 else
10533 if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
10534 || put_eol(fd) == FAIL)
10535 return FAIL;
10541 * Local directory.
10543 if (wp->w_localdir != NULL)
10545 if (fputs("lcd ", fd) < 0
10546 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
10547 || put_eol(fd) == FAIL)
10548 return FAIL;
10549 did_lcd = TRUE;
10552 return OK;
10556 * Write an argument list to the session file.
10557 * Returns FAIL if writing fails.
10559 static int
10560 ses_arglist(fd, cmd, gap, fullname, flagp)
10561 FILE *fd;
10562 char *cmd;
10563 garray_T *gap;
10564 int fullname; /* TRUE: use full path name */
10565 unsigned *flagp;
10567 int i;
10568 char_u buf[MAXPATHL];
10569 char_u *s;
10571 if (gap->ga_len == 0)
10572 return put_line(fd, "silent! argdel *");
10573 if (fputs(cmd, fd) < 0)
10574 return FAIL;
10575 for (i = 0; i < gap->ga_len; ++i)
10577 /* NULL file names are skipped (only happens when out of memory). */
10578 s = alist_name(&((aentry_T *)gap->ga_data)[i]);
10579 if (s != NULL)
10581 if (fullname)
10583 (void)vim_FullName(s, buf, MAXPATHL, FALSE);
10584 s = buf;
10586 if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
10587 return FAIL;
10590 return put_eol(fd);
10594 * Write a buffer name to the session file.
10595 * Also ends the line.
10596 * Returns FAIL if writing fails.
10598 static int
10599 ses_fname(fd, buf, flagp)
10600 FILE *fd;
10601 buf_T *buf;
10602 unsigned *flagp;
10604 char_u *name;
10606 /* Use the short file name if the current directory is known at the time
10607 * the session file will be sourced.
10608 * Don't do this for ":mkview", we don't know the current directory.
10609 * Don't do this after ":lcd", we don't keep track of what the current
10610 * directory is. */
10611 if (buf->b_sfname != NULL
10612 && flagp == &ssop_flags
10613 && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
10614 #ifdef FEAT_AUTOCHDIR
10615 && !p_acd
10616 #endif
10617 && !did_lcd)
10618 name = buf->b_sfname;
10619 else
10620 name = buf->b_ffname;
10621 if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
10622 return FAIL;
10623 return OK;
10627 * Write a file name to the session file.
10628 * Takes care of the "slash" option in 'sessionoptions' and escapes special
10629 * characters.
10630 * Returns FAIL if writing fails.
10632 static int
10633 ses_put_fname(fd, name, flagp)
10634 FILE *fd;
10635 char_u *name;
10636 unsigned *flagp;
10638 char_u *sname;
10639 int retval = OK;
10640 int c;
10642 sname = home_replace_save(NULL, name);
10643 if (sname != NULL)
10644 name = sname;
10645 while (*name != NUL)
10647 #ifdef FEAT_MBYTE
10649 int l;
10651 if (has_mbyte && (l = (*mb_ptr2len)(name)) > 1)
10653 /* copy a multibyte char */
10654 while (--l >= 0)
10656 if (putc(*name, fd) != *name)
10657 retval = FAIL;
10658 ++name;
10660 continue;
10663 #endif
10664 c = *name++;
10665 if (c == '\\' && (*flagp & SSOP_SLASH))
10666 /* change a backslash to a forward slash */
10667 c = '/';
10668 else if ((vim_strchr(escape_chars, c) != NULL
10669 #ifdef BACKSLASH_IN_FILENAME
10670 && c != '\\'
10671 #endif
10672 ) || c == '#' || c == '%')
10674 /* escape a special character with a backslash */
10675 if (putc('\\', fd) != '\\')
10676 retval = FAIL;
10678 if (putc(c, fd) != c)
10679 retval = FAIL;
10681 vim_free(sname);
10682 return retval;
10686 * ":loadview [nr]"
10688 static void
10689 ex_loadview(eap)
10690 exarg_T *eap;
10692 char_u *fname;
10694 fname = get_view_file(*eap->arg);
10695 if (fname != NULL)
10697 do_source(fname, FALSE, DOSO_NONE);
10698 vim_free(fname);
10703 * Get the name of the view file for the current buffer.
10705 static char_u *
10706 get_view_file(c)
10707 int c;
10709 int len = 0;
10710 char_u *p, *s;
10711 char_u *retval;
10712 char_u *sname;
10714 if (curbuf->b_ffname == NULL)
10716 EMSG(_(e_noname));
10717 return NULL;
10719 sname = home_replace_save(NULL, curbuf->b_ffname);
10720 if (sname == NULL)
10721 return NULL;
10724 * We want a file name without separators, because we're not going to make
10725 * a directory.
10726 * "normal" path separator -> "=+"
10727 * "=" -> "=="
10728 * ":" path separator -> "=-"
10730 for (p = sname; *p; ++p)
10731 if (*p == '=' || vim_ispathsep(*p))
10732 ++len;
10733 retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
10734 if (retval != NULL)
10736 STRCPY(retval, p_vdir);
10737 add_pathsep(retval);
10738 s = retval + STRLEN(retval);
10739 for (p = sname; *p; ++p)
10741 if (*p == '=')
10743 *s++ = '=';
10744 *s++ = '=';
10746 else if (vim_ispathsep(*p))
10748 *s++ = '=';
10749 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
10750 || defined(VMS)
10751 if (*p == ':')
10752 *s++ = '-';
10753 else
10754 #endif
10755 *s++ = '+';
10757 else
10758 *s++ = *p;
10760 *s++ = '=';
10761 *s++ = c;
10762 STRCPY(s, ".vim");
10765 vim_free(sname);
10766 return retval;
10769 #endif /* FEAT_SESSION */
10772 * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
10773 * Return FAIL for a write error.
10776 put_eol(fd)
10777 FILE *fd;
10779 if (
10780 #ifdef USE_CRNL
10782 # ifdef MKSESSION_NL
10783 !mksession_nl &&
10784 # endif
10785 (putc('\r', fd) < 0)) ||
10786 #endif
10787 (putc('\n', fd) < 0))
10788 return FAIL;
10789 return OK;
10793 * Write a line to "fd".
10794 * Return FAIL for a write error.
10797 put_line(fd, s)
10798 FILE *fd;
10799 char *s;
10801 if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
10802 return FAIL;
10803 return OK;
10806 #ifdef FEAT_VIMINFO
10808 * ":rviminfo" and ":wviminfo".
10810 static void
10811 ex_viminfo(eap)
10812 exarg_T *eap;
10814 char_u *save_viminfo;
10816 save_viminfo = p_viminfo;
10817 if (*p_viminfo == NUL)
10818 p_viminfo = (char_u *)"'100";
10819 if (eap->cmdidx == CMD_rviminfo)
10821 if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
10822 | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
10823 EMSG(_("E195: Cannot open viminfo file for reading"));
10825 else
10826 write_viminfo(eap->arg, eap->forceit);
10827 p_viminfo = save_viminfo;
10829 #endif
10831 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
10833 * Make a dialog message in "buff[IOSIZE]".
10834 * "format" must contain "%s".
10836 void
10837 dialog_msg(buff, format, fname)
10838 char_u *buff;
10839 char *format;
10840 char_u *fname;
10842 if (fname == NULL)
10843 fname = (char_u *)_("Untitled");
10844 vim_snprintf((char *)buff, IOSIZE, format, fname);
10846 #endif
10849 * ":behave {mswin,xterm}"
10851 static void
10852 ex_behave(eap)
10853 exarg_T *eap;
10855 if (STRCMP(eap->arg, "mswin") == 0)
10857 set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
10858 set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
10859 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
10860 set_option_value((char_u *)"keymodel", 0L,
10861 (char_u *)"startsel,stopsel", 0);
10863 else if (STRCMP(eap->arg, "xterm") == 0)
10865 set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
10866 set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
10867 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
10868 set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
10870 else
10871 EMSG2(_(e_invarg2), eap->arg);
10874 #ifdef FEAT_AUTOCMD
10875 static int filetype_detect = FALSE;
10876 static int filetype_plugin = FALSE;
10877 static int filetype_indent = FALSE;
10880 * ":filetype [plugin] [indent] {on,off,detect}"
10881 * on: Load the filetype.vim file to install autocommands for file types.
10882 * off: Load the ftoff.vim file to remove all autocommands for file types.
10883 * plugin on: load filetype.vim and ftplugin.vim
10884 * plugin off: load ftplugof.vim
10885 * indent on: load filetype.vim and indent.vim
10886 * indent off: load indoff.vim
10888 static void
10889 ex_filetype(eap)
10890 exarg_T *eap;
10892 char_u *arg = eap->arg;
10893 int plugin = FALSE;
10894 int indent = FALSE;
10896 if (*eap->arg == NUL)
10898 /* Print current status. */
10899 smsg((char_u *)"filetype detection:%s plugin:%s indent:%s",
10900 filetype_detect ? "ON" : "OFF",
10901 filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
10902 filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
10903 return;
10906 /* Accept "plugin" and "indent" in any order. */
10907 for (;;)
10909 if (STRNCMP(arg, "plugin", 6) == 0)
10911 plugin = TRUE;
10912 arg = skipwhite(arg + 6);
10913 continue;
10915 if (STRNCMP(arg, "indent", 6) == 0)
10917 indent = TRUE;
10918 arg = skipwhite(arg + 6);
10919 continue;
10921 break;
10923 if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
10925 if (*arg == 'o' || !filetype_detect)
10927 source_runtime((char_u *)FILETYPE_FILE, TRUE);
10928 filetype_detect = TRUE;
10929 if (plugin)
10931 source_runtime((char_u *)FTPLUGIN_FILE, TRUE);
10932 filetype_plugin = TRUE;
10934 if (indent)
10936 source_runtime((char_u *)INDENT_FILE, TRUE);
10937 filetype_indent = TRUE;
10940 if (*arg == 'd')
10942 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
10943 do_modelines(0);
10946 else if (STRCMP(arg, "off") == 0)
10948 if (plugin || indent)
10950 if (plugin)
10952 source_runtime((char_u *)FTPLUGOF_FILE, TRUE);
10953 filetype_plugin = FALSE;
10955 if (indent)
10957 source_runtime((char_u *)INDOFF_FILE, TRUE);
10958 filetype_indent = FALSE;
10961 else
10963 source_runtime((char_u *)FTOFF_FILE, TRUE);
10964 filetype_detect = FALSE;
10967 else
10968 EMSG2(_(e_invarg2), arg);
10972 * ":setfiletype {name}"
10974 static void
10975 ex_setfiletype(eap)
10976 exarg_T *eap;
10978 if (!did_filetype)
10979 set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
10981 #endif
10983 static void
10984 ex_digraphs(eap)
10985 exarg_T *eap UNUSED;
10987 #ifdef FEAT_DIGRAPHS
10988 if (*eap->arg != NUL)
10989 putdigraph(eap->arg);
10990 else
10991 listdigraphs();
10992 #else
10993 EMSG(_("E196: No digraphs in this version"));
10994 #endif
10997 static void
10998 ex_set(eap)
10999 exarg_T *eap;
11001 int flags = 0;
11003 if (eap->cmdidx == CMD_setlocal)
11004 flags = OPT_LOCAL;
11005 else if (eap->cmdidx == CMD_setglobal)
11006 flags = OPT_GLOBAL;
11007 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
11008 if (cmdmod.browse && flags == 0)
11009 ex_options(eap);
11010 else
11011 #endif
11012 (void)do_set(eap->arg, flags);
11015 #ifdef FEAT_SEARCH_EXTRA
11017 * ":nohlsearch"
11019 static void
11020 ex_nohlsearch(eap)
11021 exarg_T *eap UNUSED;
11023 no_hlsearch = TRUE;
11024 redraw_all_later(SOME_VALID);
11028 * ":[N]match {group} {pattern}"
11029 * Sets nextcmd to the start of the next command, if any. Also called when
11030 * skipping commands to find the next command.
11032 static void
11033 ex_match(eap)
11034 exarg_T *eap;
11036 char_u *p;
11037 char_u *g = NULL;
11038 char_u *end;
11039 int c;
11040 int id;
11042 if (eap->line2 <= 3)
11043 id = eap->line2;
11044 else
11046 EMSG(e_invcmd);
11047 return;
11050 /* First clear any old pattern. */
11051 if (!eap->skip)
11052 match_delete(curwin, id, FALSE);
11054 if (ends_excmd(*eap->arg))
11055 end = eap->arg;
11056 else if ((STRNICMP(eap->arg, "none", 4) == 0
11057 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
11058 end = eap->arg + 4;
11059 else
11061 p = skiptowhite(eap->arg);
11062 if (!eap->skip)
11063 g = vim_strnsave(eap->arg, (int)(p - eap->arg));
11064 p = skipwhite(p);
11065 if (*p == NUL)
11067 /* There must be two arguments. */
11068 EMSG2(_(e_invarg2), eap->arg);
11069 return;
11071 end = skip_regexp(p + 1, *p, TRUE, NULL);
11072 if (!eap->skip)
11074 if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
11076 eap->errmsg = e_trailing;
11077 return;
11079 if (*end != *p)
11081 EMSG2(_(e_invarg2), p);
11082 return;
11085 c = *end;
11086 *end = NUL;
11087 match_add(curwin, g, p + 1, 10, id);
11088 vim_free(g);
11089 *end = c;
11092 eap->nextcmd = find_nextcmd(end);
11094 #endif
11096 #ifdef FEAT_CRYPT
11098 * ":X": Get crypt key
11100 static void
11101 ex_X(eap)
11102 exarg_T *eap UNUSED;
11104 (void)get_crypt_key(TRUE, TRUE);
11106 #endif
11108 #ifdef FEAT_FOLDING
11109 static void
11110 ex_fold(eap)
11111 exarg_T *eap;
11113 if (foldManualAllowed(TRUE))
11114 foldCreate(eap->line1, eap->line2);
11117 static void
11118 ex_foldopen(eap)
11119 exarg_T *eap;
11121 opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
11122 eap->forceit, FALSE);
11125 static void
11126 ex_folddo(eap)
11127 exarg_T *eap;
11129 linenr_T lnum;
11131 /* First set the marks for all lines closed/open. */
11132 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
11133 if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
11134 ml_setmarked(lnum);
11136 /* Execute the command on the marked lines. */
11137 global_exe(eap->arg);
11138 ml_clearmarked(); /* clear rest of the marks */
11140 #endif