Merge branch 'vim-with-runtime' into feat/persistent-undo
[vim_extended.git] / src / ex_docmd.c
blob198427737d6da2f83e116ca570d74a78f3737d81
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 int uc_compl; /* completion type */
30 # ifdef FEAT_EVAL
31 scid_T uc_scriptID; /* SID where the command was defined */
32 # ifdef FEAT_CMDL_COMPL
33 char_u *uc_compl_arg; /* completion argument if any */
34 # endif
35 # endif
36 } ucmd_T;
38 #define UC_BUFFER 1 /* -buffer: local to current buffer */
40 static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL};
42 #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
43 #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
45 static void do_ucmd __ARGS((exarg_T *eap));
46 static void ex_command __ARGS((exarg_T *eap));
47 static void ex_delcommand __ARGS((exarg_T *eap));
48 # ifdef FEAT_CMDL_COMPL
49 static char_u *get_user_command_name __ARGS((int idx));
50 # endif
52 #else
53 # define ex_command ex_ni
54 # define ex_comclear ex_ni
55 # define ex_delcommand ex_ni
56 #endif
58 #ifdef FEAT_EVAL
59 static char_u *do_one_cmd __ARGS((char_u **, int, struct condstack *, char_u *(*fgetline)(int, void *, int), void *cookie));
60 #else
61 static char_u *do_one_cmd __ARGS((char_u **, int, char_u *(*fgetline)(int, void *, int), void *cookie));
62 static int if_level = 0; /* depth in :if */
63 #endif
64 static char_u *find_command __ARGS((exarg_T *eap, int *full));
66 static void ex_abbreviate __ARGS((exarg_T *eap));
67 static void ex_map __ARGS((exarg_T *eap));
68 static void ex_unmap __ARGS((exarg_T *eap));
69 static void ex_mapclear __ARGS((exarg_T *eap));
70 static void ex_abclear __ARGS((exarg_T *eap));
71 #ifndef FEAT_MENU
72 # define ex_emenu ex_ni
73 # define ex_menu ex_ni
74 # define ex_menutranslate ex_ni
75 #endif
76 #ifdef FEAT_AUTOCMD
77 static void ex_autocmd __ARGS((exarg_T *eap));
78 static void ex_doautocmd __ARGS((exarg_T *eap));
79 #else
80 # define ex_autocmd ex_ni
81 # define ex_doautocmd ex_ni
82 # define ex_doautoall ex_ni
83 #endif
84 #ifdef FEAT_LISTCMDS
85 static void ex_bunload __ARGS((exarg_T *eap));
86 static void ex_buffer __ARGS((exarg_T *eap));
87 static void ex_bmodified __ARGS((exarg_T *eap));
88 static void ex_bnext __ARGS((exarg_T *eap));
89 static void ex_bprevious __ARGS((exarg_T *eap));
90 static void ex_brewind __ARGS((exarg_T *eap));
91 static void ex_blast __ARGS((exarg_T *eap));
92 #else
93 # define ex_bunload ex_ni
94 # define ex_buffer ex_ni
95 # define ex_bmodified ex_ni
96 # define ex_bnext ex_ni
97 # define ex_bprevious ex_ni
98 # define ex_brewind ex_ni
99 # define ex_blast ex_ni
100 # define buflist_list ex_ni
101 # define ex_checktime ex_ni
102 #endif
103 #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS)
104 # define ex_buffer_all ex_ni
105 #endif
106 static char_u *getargcmd __ARGS((char_u **));
107 static char_u *skip_cmd_arg __ARGS((char_u *p, int rembs));
108 static int getargopt __ARGS((exarg_T *eap));
109 #ifndef FEAT_QUICKFIX
110 # define ex_make ex_ni
111 # define ex_cbuffer ex_ni
112 # define ex_cc ex_ni
113 # define ex_cnext ex_ni
114 # define ex_cfile ex_ni
115 # define qf_list ex_ni
116 # define qf_age ex_ni
117 # define ex_helpgrep ex_ni
118 # define ex_vimgrep ex_ni
119 #endif
120 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS)
121 # define ex_cclose ex_ni
122 # define ex_copen ex_ni
123 # define ex_cwindow ex_ni
124 #endif
125 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL)
126 # define ex_cexpr ex_ni
127 #endif
129 static int check_more __ARGS((int, int));
130 static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file));
131 static void get_flags __ARGS((exarg_T *eap));
132 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
133 || !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME)
134 # define HAVE_EX_SCRIPT_NI
135 static void ex_script_ni __ARGS((exarg_T *eap));
136 #endif
137 static char_u *invalid_range __ARGS((exarg_T *eap));
138 static void correct_range __ARGS((exarg_T *eap));
139 #ifdef FEAT_QUICKFIX
140 static char_u *replace_makeprg __ARGS((exarg_T *eap, char_u *p, char_u **cmdlinep));
141 #endif
142 static char_u *repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep));
143 static void ex_highlight __ARGS((exarg_T *eap));
144 static void ex_colorscheme __ARGS((exarg_T *eap));
145 static void ex_quit __ARGS((exarg_T *eap));
146 static void ex_cquit __ARGS((exarg_T *eap));
147 static void ex_quit_all __ARGS((exarg_T *eap));
148 #ifdef FEAT_WINDOWS
149 static void ex_close __ARGS((exarg_T *eap));
150 static void ex_win_close __ARGS((int forceit, win_T *win, tabpage_T *tp));
151 static void ex_only __ARGS((exarg_T *eap));
152 static void ex_resize __ARGS((exarg_T *eap));
153 static void ex_stag __ARGS((exarg_T *eap));
154 static void ex_tabclose __ARGS((exarg_T *eap));
155 static void ex_tabonly __ARGS((exarg_T *eap));
156 static void ex_tabnext __ARGS((exarg_T *eap));
157 static void ex_tabmove __ARGS((exarg_T *eap));
158 static void ex_tabs __ARGS((exarg_T *eap));
159 #else
160 # define ex_close ex_ni
161 # define ex_only ex_ni
162 # define ex_all ex_ni
163 # define ex_resize ex_ni
164 # define ex_splitview ex_ni
165 # define ex_stag ex_ni
166 # define ex_tabnext ex_ni
167 # define ex_tabmove ex_ni
168 # define ex_tabs ex_ni
169 # define ex_tabclose ex_ni
170 # define ex_tabonly ex_ni
171 #endif
172 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
173 static void ex_pclose __ARGS((exarg_T *eap));
174 static void ex_ptag __ARGS((exarg_T *eap));
175 static void ex_pedit __ARGS((exarg_T *eap));
176 #else
177 # define ex_pclose ex_ni
178 # define ex_ptag ex_ni
179 # define ex_pedit ex_ni
180 #endif
181 static void ex_hide __ARGS((exarg_T *eap));
182 static void ex_stop __ARGS((exarg_T *eap));
183 static void ex_exit __ARGS((exarg_T *eap));
184 static void ex_print __ARGS((exarg_T *eap));
185 #ifdef FEAT_BYTEOFF
186 static void ex_goto __ARGS((exarg_T *eap));
187 #else
188 # define ex_goto ex_ni
189 #endif
190 static void ex_shell __ARGS((exarg_T *eap));
191 static void ex_preserve __ARGS((exarg_T *eap));
192 static void ex_recover __ARGS((exarg_T *eap));
193 #ifndef FEAT_LISTCMDS
194 # define ex_argedit ex_ni
195 # define ex_argadd ex_ni
196 # define ex_argdelete ex_ni
197 # define ex_listdo ex_ni
198 #endif
199 static void ex_mode __ARGS((exarg_T *eap));
200 static void ex_wrongmodifier __ARGS((exarg_T *eap));
201 static void ex_find __ARGS((exarg_T *eap));
202 static void ex_open __ARGS((exarg_T *eap));
203 static void ex_edit __ARGS((exarg_T *eap));
204 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
205 # define ex_drop ex_ni
206 #endif
207 #ifndef FEAT_GUI
208 # define ex_gui ex_nogui
209 static void ex_nogui __ARGS((exarg_T *eap));
210 #endif
211 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
212 static void ex_tearoff __ARGS((exarg_T *eap));
213 #else
214 # define ex_tearoff ex_ni
215 #endif
216 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
217 static void ex_popup __ARGS((exarg_T *eap));
218 #else
219 # define ex_popup ex_ni
220 #endif
221 #ifndef FEAT_GUI_MSWIN
222 # define ex_simalt ex_ni
223 #endif
224 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
225 # define gui_mch_find_dialog ex_ni
226 # define gui_mch_replace_dialog ex_ni
227 #endif
228 #if !defined(FEAT_GUI_GTK)
229 # define ex_helpfind ex_ni
230 #endif
231 #ifndef FEAT_CSCOPE
232 # define do_cscope ex_ni
233 # define do_scscope ex_ni
234 # define do_cstag ex_ni
235 #endif
236 #ifndef FEAT_SYN_HL
237 # define ex_syntax ex_ni
238 #endif
239 #ifndef FEAT_SPELL
240 # define ex_spell ex_ni
241 # define ex_mkspell ex_ni
242 # define ex_spelldump ex_ni
243 # define ex_spellinfo ex_ni
244 # define ex_spellrepall ex_ni
245 #endif
246 #ifndef FEAT_PERSISTENT_UNDO
247 # define ex_rundo ex_ni
248 # define ex_wundo ex_ni
249 #endif
250 #ifndef FEAT_MZSCHEME
251 # define ex_mzscheme ex_script_ni
252 # define ex_mzfile ex_ni
253 #endif
254 #ifndef FEAT_PERL
255 # define ex_perl ex_script_ni
256 # define ex_perldo ex_ni
257 #endif
258 #ifndef FEAT_PYTHON
259 # define ex_python ex_script_ni
260 # define ex_pyfile ex_ni
261 #endif
262 #ifndef FEAT_TCL
263 # define ex_tcl ex_script_ni
264 # define ex_tcldo ex_ni
265 # define ex_tclfile ex_ni
266 #endif
267 #ifndef FEAT_RUBY
268 # define ex_ruby ex_script_ni
269 # define ex_rubydo ex_ni
270 # define ex_rubyfile ex_ni
271 #endif
272 #ifndef FEAT_SNIFF
273 # define ex_sniff ex_ni
274 #endif
275 #ifndef FEAT_KEYMAP
276 # define ex_loadkeymap ex_ni
277 #endif
278 static void ex_swapname __ARGS((exarg_T *eap));
279 static void ex_syncbind __ARGS((exarg_T *eap));
280 static void ex_read __ARGS((exarg_T *eap));
281 static void ex_pwd __ARGS((exarg_T *eap));
282 static void ex_equal __ARGS((exarg_T *eap));
283 static void ex_sleep __ARGS((exarg_T *eap));
284 static void do_exmap __ARGS((exarg_T *eap, int isabbrev));
285 static void ex_winsize __ARGS((exarg_T *eap));
286 #ifdef FEAT_WINDOWS
287 static void ex_wincmd __ARGS((exarg_T *eap));
288 #else
289 # define ex_wincmd ex_ni
290 #endif
291 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
292 static void ex_winpos __ARGS((exarg_T *eap));
293 #else
294 # define ex_winpos ex_ni
295 #endif
296 static void ex_operators __ARGS((exarg_T *eap));
297 static void ex_put __ARGS((exarg_T *eap));
298 static void ex_copymove __ARGS((exarg_T *eap));
299 static void ex_may_print __ARGS((exarg_T *eap));
300 static void ex_submagic __ARGS((exarg_T *eap));
301 static void ex_join __ARGS((exarg_T *eap));
302 static void ex_at __ARGS((exarg_T *eap));
303 static void ex_bang __ARGS((exarg_T *eap));
304 static void ex_undo __ARGS((exarg_T *eap));
305 #ifdef FEAT_PERSISTENT_UNDO
306 static void ex_wundo __ARGS((exarg_T *eap));
307 static void ex_rundo __ARGS((exarg_T *eap));
308 #endif
309 static void ex_redo __ARGS((exarg_T *eap));
310 static void ex_later __ARGS((exarg_T *eap));
311 static void ex_redir __ARGS((exarg_T *eap));
312 static void ex_redraw __ARGS((exarg_T *eap));
313 static void ex_redrawstatus __ARGS((exarg_T *eap));
314 static void close_redir __ARGS((void));
315 static void ex_mkrc __ARGS((exarg_T *eap));
316 static void ex_mark __ARGS((exarg_T *eap));
317 #ifdef FEAT_USR_CMDS
318 static char_u *uc_fun_cmd __ARGS((void));
319 static char_u *find_ucmd __ARGS((exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl));
320 #endif
321 #ifdef FEAT_EX_EXTRA
322 static void ex_normal __ARGS((exarg_T *eap));
323 static void ex_startinsert __ARGS((exarg_T *eap));
324 static void ex_stopinsert __ARGS((exarg_T *eap));
325 #else
326 # define ex_normal ex_ni
327 # define ex_align ex_ni
328 # define ex_retab ex_ni
329 # define ex_startinsert ex_ni
330 # define ex_stopinsert ex_ni
331 # define ex_helptags ex_ni
332 # define ex_sort ex_ni
333 #endif
334 #ifdef FEAT_FIND_ID
335 static void ex_checkpath __ARGS((exarg_T *eap));
336 static void ex_findpat __ARGS((exarg_T *eap));
337 #else
338 # define ex_findpat ex_ni
339 # define ex_checkpath ex_ni
340 #endif
341 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
342 static void ex_psearch __ARGS((exarg_T *eap));
343 #else
344 # define ex_psearch ex_ni
345 #endif
346 static void ex_tag __ARGS((exarg_T *eap));
347 static void ex_tag_cmd __ARGS((exarg_T *eap, char_u *name));
348 #ifndef FEAT_EVAL
349 # define ex_scriptnames ex_ni
350 # define ex_finish ex_ni
351 # define ex_echo ex_ni
352 # define ex_echohl ex_ni
353 # define ex_execute ex_ni
354 # define ex_call ex_ni
355 # define ex_if ex_ni
356 # define ex_endif ex_ni
357 # define ex_else ex_ni
358 # define ex_while ex_ni
359 # define ex_for ex_ni
360 # define ex_continue ex_ni
361 # define ex_break ex_ni
362 # define ex_endwhile ex_ni
363 # define ex_endfor ex_ni
364 # define ex_throw ex_ni
365 # define ex_try ex_ni
366 # define ex_catch ex_ni
367 # define ex_finally ex_ni
368 # define ex_endtry ex_ni
369 # define ex_endfunction ex_ni
370 # define ex_let ex_ni
371 # define ex_unlet ex_ni
372 # define ex_lockvar ex_ni
373 # define ex_unlockvar ex_ni
374 # define ex_function ex_ni
375 # define ex_delfunction ex_ni
376 # define ex_return ex_ni
377 # define ex_oldfiles ex_ni
378 #endif
379 static char_u *arg_all __ARGS((void));
380 #ifdef FEAT_SESSION
381 static int makeopens __ARGS((FILE *fd, char_u *dirnow));
382 static int put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx));
383 static void ex_loadview __ARGS((exarg_T *eap));
384 static char_u *get_view_file __ARGS((int c));
385 static int did_lcd; /* whether ":lcd" was produced for a session */
386 #else
387 # define ex_loadview ex_ni
388 #endif
389 #ifndef FEAT_EVAL
390 # define ex_compiler ex_ni
391 #endif
392 #ifdef FEAT_VIMINFO
393 static void ex_viminfo __ARGS((exarg_T *eap));
394 #else
395 # define ex_viminfo ex_ni
396 #endif
397 static void ex_behave __ARGS((exarg_T *eap));
398 #ifdef FEAT_AUTOCMD
399 static void ex_filetype __ARGS((exarg_T *eap));
400 static void ex_setfiletype __ARGS((exarg_T *eap));
401 #else
402 # define ex_filetype ex_ni
403 # define ex_setfiletype ex_ni
404 #endif
405 #ifndef FEAT_DIFF
406 # define ex_diffoff ex_ni
407 # define ex_diffpatch ex_ni
408 # define ex_diffgetput ex_ni
409 # define ex_diffsplit ex_ni
410 # define ex_diffthis ex_ni
411 # define ex_diffupdate ex_ni
412 #endif
413 static void ex_digraphs __ARGS((exarg_T *eap));
414 static void ex_set __ARGS((exarg_T *eap));
415 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
416 # define ex_options ex_ni
417 #endif
418 #ifdef FEAT_SEARCH_EXTRA
419 static void ex_nohlsearch __ARGS((exarg_T *eap));
420 static void ex_match __ARGS((exarg_T *eap));
421 #else
422 # define ex_nohlsearch ex_ni
423 # define ex_match ex_ni
424 #endif
425 #ifdef FEAT_CRYPT
426 static void ex_X __ARGS((exarg_T *eap));
427 #else
428 # define ex_X ex_ni
429 #endif
430 #ifdef FEAT_FOLDING
431 static void ex_fold __ARGS((exarg_T *eap));
432 static void ex_foldopen __ARGS((exarg_T *eap));
433 static void ex_folddo __ARGS((exarg_T *eap));
434 #else
435 # define ex_fold ex_ni
436 # define ex_foldopen ex_ni
437 # define ex_folddo ex_ni
438 #endif
439 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
440 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
441 # define ex_language ex_ni
442 #endif
443 #ifndef FEAT_SIGNS
444 # define ex_sign ex_ni
445 #endif
446 #ifndef FEAT_SUN_WORKSHOP
447 # define ex_wsverb ex_ni
448 #endif
449 #ifndef FEAT_NETBEANS_INTG
450 # define ex_nbkey ex_ni
451 #endif
453 #ifndef FEAT_EVAL
454 # define ex_debug ex_ni
455 # define ex_breakadd ex_ni
456 # define ex_debuggreedy ex_ni
457 # define ex_breakdel ex_ni
458 # define ex_breaklist ex_ni
459 #endif
461 #ifndef FEAT_CMDHIST
462 # define ex_history ex_ni
463 #endif
464 #ifndef FEAT_JUMPLIST
465 # define ex_jumps ex_ni
466 # define ex_changes ex_ni
467 #endif
469 #ifndef FEAT_PROFILE
470 # define ex_profile ex_ni
471 #endif
474 * Declare cmdnames[].
476 #define DO_DECLARE_EXCMD
477 #include "ex_cmds.h"
480 * Table used to quickly search for a command, based on its first character.
482 static cmdidx_T cmdidxs[27] =
484 CMD_append,
485 CMD_buffer,
486 CMD_change,
487 CMD_delete,
488 CMD_edit,
489 CMD_file,
490 CMD_global,
491 CMD_help,
492 CMD_insert,
493 CMD_join,
494 CMD_k,
495 CMD_list,
496 CMD_move,
497 CMD_next,
498 CMD_open,
499 CMD_print,
500 CMD_quit,
501 CMD_read,
502 CMD_substitute,
503 CMD_t,
504 CMD_undo,
505 CMD_vglobal,
506 CMD_write,
507 CMD_xit,
508 CMD_yank,
509 CMD_z,
510 CMD_bang
513 static char_u dollar_command[2] = {'$', 0};
516 #ifdef FEAT_EVAL
517 /* Struct for storing a line inside a while/for loop */
518 typedef struct
520 char_u *line; /* command line */
521 linenr_T lnum; /* sourcing_lnum of the line */
522 } wcmd_T;
525 * Structure used to store info for line position in a while or for loop.
526 * This is required, because do_one_cmd() may invoke ex_function(), which
527 * reads more lines that may come from the while/for loop.
529 struct loop_cookie
531 garray_T *lines_gap; /* growarray with line info */
532 int current_line; /* last read line from growarray */
533 int repeating; /* TRUE when looping a second time */
534 /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
535 char_u *(*getline) __ARGS((int, void *, int));
536 void *cookie;
539 static char_u *get_loop_line __ARGS((int c, void *cookie, int indent));
540 static int store_loop_line __ARGS((garray_T *gap, char_u *line));
541 static void free_cmdlines __ARGS((garray_T *gap));
543 /* Struct to save a few things while debugging. Used in do_cmdline() only. */
544 struct dbg_stuff
546 int trylevel;
547 int force_abort;
548 except_T *caught_stack;
549 char_u *vv_exception;
550 char_u *vv_throwpoint;
551 int did_emsg;
552 int got_int;
553 int did_throw;
554 int need_rethrow;
555 int check_cstack;
556 except_T *current_exception;
559 static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp));
560 static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp));
562 static void
563 save_dbg_stuff(dsp)
564 struct dbg_stuff *dsp;
566 dsp->trylevel = trylevel; trylevel = 0;
567 dsp->force_abort = force_abort; force_abort = FALSE;
568 dsp->caught_stack = caught_stack; caught_stack = NULL;
569 dsp->vv_exception = v_exception(NULL);
570 dsp->vv_throwpoint = v_throwpoint(NULL);
572 /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
573 dsp->did_emsg = did_emsg; did_emsg = FALSE;
574 dsp->got_int = got_int; got_int = FALSE;
575 dsp->did_throw = did_throw; did_throw = FALSE;
576 dsp->need_rethrow = need_rethrow; need_rethrow = FALSE;
577 dsp->check_cstack = check_cstack; check_cstack = FALSE;
578 dsp->current_exception = current_exception; current_exception = NULL;
581 static void
582 restore_dbg_stuff(dsp)
583 struct dbg_stuff *dsp;
585 suppress_errthrow = FALSE;
586 trylevel = dsp->trylevel;
587 force_abort = dsp->force_abort;
588 caught_stack = dsp->caught_stack;
589 (void)v_exception(dsp->vv_exception);
590 (void)v_throwpoint(dsp->vv_throwpoint);
591 did_emsg = dsp->did_emsg;
592 got_int = dsp->got_int;
593 did_throw = dsp->did_throw;
594 need_rethrow = dsp->need_rethrow;
595 check_cstack = dsp->check_cstack;
596 current_exception = dsp->current_exception;
598 #endif
602 * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
603 * command is given.
605 void
606 do_exmode(improved)
607 int improved; /* TRUE for "improved Ex" mode */
609 int save_msg_scroll;
610 int prev_msg_row;
611 linenr_T prev_line;
612 int changedtick;
614 if (improved)
615 exmode_active = EXMODE_VIM;
616 else
617 exmode_active = EXMODE_NORMAL;
618 State = NORMAL;
620 /* When using ":global /pat/ visual" and then "Q" we return to continue
621 * the :global command. */
622 if (global_busy)
623 return;
625 save_msg_scroll = msg_scroll;
626 ++RedrawingDisabled; /* don't redisplay the window */
627 ++no_wait_return; /* don't wait for return */
628 #ifdef FEAT_GUI
629 /* Ignore scrollbar and mouse events in Ex mode */
630 ++hold_gui_events;
631 #endif
632 #ifdef FEAT_SNIFF
633 want_sniff_request = 0; /* No K_SNIFF wanted */
634 #endif
636 MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode."));
637 while (exmode_active)
639 #ifdef FEAT_EX_EXTRA
640 /* Check for a ":normal" command and no more characters left. */
641 if (ex_normal_busy > 0 && typebuf.tb_len == 0)
643 exmode_active = FALSE;
644 break;
646 #endif
647 msg_scroll = TRUE;
648 need_wait_return = FALSE;
649 ex_pressedreturn = FALSE;
650 ex_no_reprint = FALSE;
651 changedtick = curbuf->b_changedtick;
652 prev_msg_row = msg_row;
653 prev_line = curwin->w_cursor.lnum;
654 #ifdef FEAT_SNIFF
655 ProcessSniffRequests();
656 #endif
657 if (improved)
659 cmdline_row = msg_row;
660 do_cmdline(NULL, getexline, NULL, 0);
662 else
663 do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
664 lines_left = Rows - 1;
666 if ((prev_line != curwin->w_cursor.lnum
667 || changedtick != curbuf->b_changedtick) && !ex_no_reprint)
669 if (curbuf->b_ml.ml_flags & ML_EMPTY)
670 EMSG(_(e_emptybuf));
671 else
673 if (ex_pressedreturn)
675 /* go up one line, to overwrite the ":<CR>" line, so the
676 * output doesn't contain empty lines. */
677 msg_row = prev_msg_row;
678 if (prev_msg_row == Rows - 1)
679 msg_row--;
681 msg_col = 0;
682 print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE);
683 msg_clr_eos();
686 else if (ex_pressedreturn && !ex_no_reprint) /* must be at EOF */
688 if (curbuf->b_ml.ml_flags & ML_EMPTY)
689 EMSG(_(e_emptybuf));
690 else
691 EMSG(_("E501: At end-of-file"));
695 #ifdef FEAT_GUI
696 --hold_gui_events;
697 #endif
698 --RedrawingDisabled;
699 --no_wait_return;
700 update_screen(CLEAR);
701 need_wait_return = FALSE;
702 msg_scroll = save_msg_scroll;
706 * Execute a simple command line. Used for translated commands like "*".
709 do_cmdline_cmd(cmd)
710 char_u *cmd;
712 return do_cmdline(cmd, NULL, NULL,
713 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
717 * do_cmdline(): execute one Ex command line
719 * 1. Execute "cmdline" when it is not NULL.
720 * If "cmdline" is NULL, or more lines are needed, getline() is used.
721 * 2. Split up in parts separated with '|'.
723 * This function can be called recursively!
725 * flags:
726 * DOCMD_VERBOSE - The command will be included in the error message.
727 * DOCMD_NOWAIT - Don't call wait_return() and friends.
728 * DOCMD_REPEAT - Repeat execution until getline() returns NULL.
729 * DOCMD_KEYTYPED - Don't reset KeyTyped.
730 * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
731 * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
733 * return FAIL if cmdline could not be executed, OK otherwise
736 do_cmdline(cmdline, getline, cookie, flags)
737 char_u *cmdline;
738 char_u *(*getline) __ARGS((int, void *, int));
739 void *cookie; /* argument for getline() */
740 int flags;
742 char_u *next_cmdline; /* next cmd to execute */
743 char_u *cmdline_copy = NULL; /* copy of cmd line */
744 int used_getline = FALSE; /* used "getline" to obtain command */
745 static int recursive = 0; /* recursive depth */
746 int msg_didout_before_start = 0;
747 int count = 0; /* line number count */
748 int did_inc = FALSE; /* incremented RedrawingDisabled */
749 int retval = OK;
750 #ifdef FEAT_EVAL
751 struct condstack cstack; /* conditional stack */
752 garray_T lines_ga; /* keep lines for ":while"/":for" */
753 int current_line = 0; /* active line in lines_ga */
754 char_u *fname = NULL; /* function or script name */
755 linenr_T *breakpoint = NULL; /* ptr to breakpoint field in cookie */
756 int *dbg_tick = NULL; /* ptr to dbg_tick field in cookie */
757 struct dbg_stuff debug_saved; /* saved things for debug mode */
758 int initial_trylevel;
759 struct msglist **saved_msg_list = NULL;
760 struct msglist *private_msg_list;
762 /* "getline" and "cookie" passed to do_one_cmd() */
763 char_u *(*cmd_getline) __ARGS((int, void *, int));
764 void *cmd_cookie;
765 struct loop_cookie cmd_loop_cookie;
766 void *real_cookie;
767 int getline_is_func;
768 #else
769 # define cmd_getline getline
770 # define cmd_cookie cookie
771 #endif
772 static int call_depth = 0; /* recursiveness */
774 #ifdef FEAT_EVAL
775 /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
776 * location for storing error messages to be converted to an exception.
777 * This ensures that the do_errthrow() call in do_one_cmd() does not
778 * combine the messages stored by an earlier invocation of do_one_cmd()
779 * with the command name of the later one. This would happen when
780 * BufWritePost autocommands are executed after a write error. */
781 saved_msg_list = msg_list;
782 msg_list = &private_msg_list;
783 private_msg_list = NULL;
784 #endif
786 /* It's possible to create an endless loop with ":execute", catch that
787 * here. The value of 200 allows nested function calls, ":source", etc. */
788 if (call_depth == 200)
790 EMSG(_("E169: Command too recursive"));
791 #ifdef FEAT_EVAL
792 /* When converting to an exception, we do not include the command name
793 * since this is not an error of the specific command. */
794 do_errthrow((struct condstack *)NULL, (char_u *)NULL);
795 msg_list = saved_msg_list;
796 #endif
797 return FAIL;
799 ++call_depth;
801 #ifdef FEAT_EVAL
802 cstack.cs_idx = -1;
803 cstack.cs_looplevel = 0;
804 cstack.cs_trylevel = 0;
805 cstack.cs_emsg_silent_list = NULL;
806 cstack.cs_lflags = 0;
807 ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
809 real_cookie = getline_cookie(getline, cookie);
811 /* Inside a function use a higher nesting level. */
812 getline_is_func = getline_equal(getline, cookie, get_func_line);
813 if (getline_is_func && ex_nesting_level == func_level(real_cookie))
814 ++ex_nesting_level;
816 /* Get the function or script name and the address where the next breakpoint
817 * line and the debug tick for a function or script are stored. */
818 if (getline_is_func)
820 fname = func_name(real_cookie);
821 breakpoint = func_breakpoint(real_cookie);
822 dbg_tick = func_dbg_tick(real_cookie);
824 else if (getline_equal(getline, cookie, getsourceline))
826 fname = sourcing_name;
827 breakpoint = source_breakpoint(real_cookie);
828 dbg_tick = source_dbg_tick(real_cookie);
832 * Initialize "force_abort" and "suppress_errthrow" at the top level.
834 if (!recursive)
836 force_abort = FALSE;
837 suppress_errthrow = FALSE;
841 * If requested, store and reset the global values controlling the
842 * exception handling (used when debugging). Otherwise clear it to avoid
843 * a bogus compiler warning when the optimizer uses inline functions...
845 if (flags & DOCMD_EXCRESET)
846 save_dbg_stuff(&debug_saved);
847 else
848 memset(&debug_saved, 0, 1);
850 initial_trylevel = trylevel;
853 * "did_throw" will be set to TRUE when an exception is being thrown.
855 did_throw = FALSE;
856 #endif
858 * "did_emsg" will be set to TRUE when emsg() is used, in which case we
859 * cancel the whole command line, and any if/endif or loop.
860 * If force_abort is set, we cancel everything.
862 did_emsg = FALSE;
865 * KeyTyped is only set when calling vgetc(). Reset it here when not
866 * calling vgetc() (sourced command lines).
868 if (!(flags & DOCMD_KEYTYPED) && !getline_equal(getline, cookie, getexline))
869 KeyTyped = FALSE;
872 * Continue executing command lines:
873 * - when inside an ":if", ":while" or ":for"
874 * - for multiple commands on one line, separated with '|'
875 * - when repeating until there are no more lines (for ":source")
877 next_cmdline = cmdline;
880 #ifdef FEAT_EVAL
881 getline_is_func = getline_equal(getline, cookie, get_func_line);
882 #endif
884 /* stop skipping cmds for an error msg after all endif/while/for */
885 if (next_cmdline == NULL
886 #ifdef FEAT_EVAL
887 && !force_abort
888 && cstack.cs_idx < 0
889 && !(getline_is_func && func_has_abort(real_cookie))
890 #endif
892 did_emsg = FALSE;
895 * 1. If repeating a line in a loop, get a line from lines_ga.
896 * 2. If no line given: Get an allocated line with getline().
897 * 3. If a line is given: Make a copy, so we can mess with it.
900 #ifdef FEAT_EVAL
901 /* 1. If repeating, get a previous line from lines_ga. */
902 if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
904 /* Each '|' separated command is stored separately in lines_ga, to
905 * be able to jump to it. Don't use next_cmdline now. */
906 vim_free(cmdline_copy);
907 cmdline_copy = NULL;
909 /* Check if a function has returned or, unless it has an unclosed
910 * try conditional, aborted. */
911 if (getline_is_func)
913 # ifdef FEAT_PROFILE
914 if (do_profiling == PROF_YES)
915 func_line_end(real_cookie);
916 # endif
917 if (func_has_ended(real_cookie))
919 retval = FAIL;
920 break;
923 #ifdef FEAT_PROFILE
924 else if (do_profiling == PROF_YES
925 && getline_equal(getline, cookie, getsourceline))
926 script_line_end();
927 #endif
929 /* Check if a sourced file hit a ":finish" command. */
930 if (source_finished(getline, cookie))
932 retval = FAIL;
933 break;
936 /* If breakpoints have been added/deleted need to check for it. */
937 if (breakpoint != NULL && dbg_tick != NULL
938 && *dbg_tick != debug_tick)
940 *breakpoint = dbg_find_breakpoint(
941 getline_equal(getline, cookie, getsourceline),
942 fname, sourcing_lnum);
943 *dbg_tick = debug_tick;
946 next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
947 sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
949 /* Did we encounter a breakpoint? */
950 if (breakpoint != NULL && *breakpoint != 0
951 && *breakpoint <= sourcing_lnum)
953 dbg_breakpoint(fname, sourcing_lnum);
954 /* Find next breakpoint. */
955 *breakpoint = dbg_find_breakpoint(
956 getline_equal(getline, cookie, getsourceline),
957 fname, sourcing_lnum);
958 *dbg_tick = debug_tick;
960 # ifdef FEAT_PROFILE
961 if (do_profiling == PROF_YES)
963 if (getline_is_func)
964 func_line_start(real_cookie);
965 else if (getline_equal(getline, cookie, getsourceline))
966 script_line_start();
968 # endif
971 if (cstack.cs_looplevel > 0)
973 /* Inside a while/for loop we need to store the lines and use them
974 * again. Pass a different "getline" function to do_one_cmd()
975 * below, so that it stores lines in or reads them from
976 * "lines_ga". Makes it possible to define a function inside a
977 * while/for loop. */
978 cmd_getline = get_loop_line;
979 cmd_cookie = (void *)&cmd_loop_cookie;
980 cmd_loop_cookie.lines_gap = &lines_ga;
981 cmd_loop_cookie.current_line = current_line;
982 cmd_loop_cookie.getline = getline;
983 cmd_loop_cookie.cookie = cookie;
984 cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
986 else
988 cmd_getline = getline;
989 cmd_cookie = cookie;
991 #endif
993 /* 2. If no line given, get an allocated line with getline(). */
994 if (next_cmdline == NULL)
997 * Need to set msg_didout for the first line after an ":if",
998 * otherwise the ":if" will be overwritten.
1000 if (count == 1 && getline_equal(getline, cookie, getexline))
1001 msg_didout = TRUE;
1002 if (getline == NULL || (next_cmdline = getline(':', cookie,
1003 #ifdef FEAT_EVAL
1004 cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
1005 #else
1007 #endif
1008 )) == NULL)
1010 /* Don't call wait_return for aborted command line. The NULL
1011 * returned for the end of a sourced file or executed function
1012 * doesn't do this. */
1013 if (KeyTyped && !(flags & DOCMD_REPEAT))
1014 need_wait_return = FALSE;
1015 retval = FAIL;
1016 break;
1018 used_getline = TRUE;
1021 * Keep the first typed line. Clear it when more lines are typed.
1023 if (flags & DOCMD_KEEPLINE)
1025 vim_free(repeat_cmdline);
1026 if (count == 0)
1027 repeat_cmdline = vim_strsave(next_cmdline);
1028 else
1029 repeat_cmdline = NULL;
1033 /* 3. Make a copy of the command so we can mess with it. */
1034 else if (cmdline_copy == NULL)
1036 next_cmdline = vim_strsave(next_cmdline);
1037 if (next_cmdline == NULL)
1039 EMSG(_(e_outofmem));
1040 retval = FAIL;
1041 break;
1044 cmdline_copy = next_cmdline;
1046 #ifdef FEAT_EVAL
1048 * Save the current line when inside a ":while" or ":for", and when
1049 * the command looks like a ":while" or ":for", because we may need it
1050 * later. When there is a '|' and another command, it is stored
1051 * separately, because we need to be able to jump back to it from an
1052 * :endwhile/:endfor.
1054 if (current_line == lines_ga.ga_len
1055 && (cstack.cs_looplevel || has_loop_cmd(next_cmdline)))
1057 if (store_loop_line(&lines_ga, next_cmdline) == FAIL)
1059 retval = FAIL;
1060 break;
1063 did_endif = FALSE;
1064 #endif
1066 if (count++ == 0)
1069 * All output from the commands is put below each other, without
1070 * waiting for a return. Don't do this when executing commands
1071 * from a script or when being called recursive (e.g. for ":e
1072 * +command file").
1074 if (!(flags & DOCMD_NOWAIT) && !recursive)
1076 msg_didout_before_start = msg_didout;
1077 msg_didany = FALSE; /* no output yet */
1078 msg_start();
1079 msg_scroll = TRUE; /* put messages below each other */
1080 ++no_wait_return; /* dont wait for return until finished */
1081 ++RedrawingDisabled;
1082 did_inc = TRUE;
1086 if (p_verbose >= 15 && sourcing_name != NULL)
1088 ++no_wait_return;
1089 verbose_enter_scroll();
1091 smsg((char_u *)_("line %ld: %s"),
1092 (long)sourcing_lnum, cmdline_copy);
1093 if (msg_silent == 0)
1094 msg_puts((char_u *)"\n"); /* don't overwrite this */
1096 verbose_leave_scroll();
1097 --no_wait_return;
1101 * 2. Execute one '|' separated command.
1102 * do_one_cmd() will return NULL if there is no trailing '|'.
1103 * "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1105 ++recursive;
1106 next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1107 #ifdef FEAT_EVAL
1108 &cstack,
1109 #endif
1110 cmd_getline, cmd_cookie);
1111 --recursive;
1113 #ifdef FEAT_EVAL
1114 if (cmd_cookie == (void *)&cmd_loop_cookie)
1115 /* Use "current_line" from "cmd_loop_cookie", it may have been
1116 * incremented when defining a function. */
1117 current_line = cmd_loop_cookie.current_line;
1118 #endif
1120 if (next_cmdline == NULL)
1122 vim_free(cmdline_copy);
1123 cmdline_copy = NULL;
1124 #ifdef FEAT_CMDHIST
1126 * If the command was typed, remember it for the ':' register.
1127 * Do this AFTER executing the command to make :@: work.
1129 if (getline_equal(getline, cookie, getexline)
1130 && new_last_cmdline != NULL)
1132 vim_free(last_cmdline);
1133 last_cmdline = new_last_cmdline;
1134 new_last_cmdline = NULL;
1136 #endif
1138 else
1140 /* need to copy the command after the '|' to cmdline_copy, for the
1141 * next do_one_cmd() */
1142 STRMOVE(cmdline_copy, next_cmdline);
1143 next_cmdline = cmdline_copy;
1147 #ifdef FEAT_EVAL
1148 /* reset did_emsg for a function that is not aborted by an error */
1149 if (did_emsg && !force_abort
1150 && getline_equal(getline, cookie, get_func_line)
1151 && !func_has_abort(real_cookie))
1152 did_emsg = FALSE;
1154 if (cstack.cs_looplevel > 0)
1156 ++current_line;
1159 * An ":endwhile", ":endfor" and ":continue" is handled here.
1160 * If we were executing commands, jump back to the ":while" or
1161 * ":for".
1162 * If we were not executing commands, decrement cs_looplevel.
1164 if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
1166 cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
1168 /* Jump back to the matching ":while" or ":for". Be careful
1169 * not to use a cs_line[] from an entry that isn't a ":while"
1170 * or ":for": It would make "current_line" invalid and can
1171 * cause a crash. */
1172 if (!did_emsg && !got_int && !did_throw
1173 && cstack.cs_idx >= 0
1174 && (cstack.cs_flags[cstack.cs_idx]
1175 & (CSF_WHILE | CSF_FOR))
1176 && cstack.cs_line[cstack.cs_idx] >= 0
1177 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1179 current_line = cstack.cs_line[cstack.cs_idx];
1180 /* remember we jumped there */
1181 cstack.cs_lflags |= CSL_HAD_LOOP;
1182 line_breakcheck(); /* check if CTRL-C typed */
1184 /* Check for the next breakpoint at or after the ":while"
1185 * or ":for". */
1186 if (breakpoint != NULL)
1188 *breakpoint = dbg_find_breakpoint(
1189 getline_equal(getline, cookie, getsourceline),
1190 fname,
1191 ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1192 *dbg_tick = debug_tick;
1195 else
1197 /* can only get here with ":endwhile" or ":endfor" */
1198 if (cstack.cs_idx >= 0)
1199 rewind_conditionals(&cstack, cstack.cs_idx - 1,
1200 CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
1205 * For a ":while" or ":for" we need to remember the line number.
1207 else if (cstack.cs_lflags & CSL_HAD_LOOP)
1209 cstack.cs_lflags &= ~CSL_HAD_LOOP;
1210 cstack.cs_line[cstack.cs_idx] = current_line - 1;
1215 * When not inside any ":while" loop, clear remembered lines.
1217 if (cstack.cs_looplevel == 0)
1219 if (lines_ga.ga_len > 0)
1221 sourcing_lnum =
1222 ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1223 free_cmdlines(&lines_ga);
1225 current_line = 0;
1229 * A ":finally" makes did_emsg, got_int, and did_throw pending for
1230 * being restored at the ":endtry". Reset them here and set the
1231 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
1232 * This includes the case where a missing ":endif", ":endwhile" or
1233 * ":endfor" was detected by the ":finally" itself.
1235 if (cstack.cs_lflags & CSL_HAD_FINA)
1237 cstack.cs_lflags &= ~CSL_HAD_FINA;
1238 report_make_pending(cstack.cs_pending[cstack.cs_idx]
1239 & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1240 did_throw ? (void *)current_exception : NULL);
1241 did_emsg = got_int = did_throw = FALSE;
1242 cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1245 /* Update global "trylevel" for recursive calls to do_cmdline() from
1246 * within this loop. */
1247 trylevel = initial_trylevel + cstack.cs_trylevel;
1250 * If the outermost try conditional (across function calls and sourced
1251 * files) is aborted because of an error, an interrupt, or an uncaught
1252 * exception, cancel everything. If it is left normally, reset
1253 * force_abort to get the non-EH compatible abortion behavior for
1254 * the rest of the script.
1256 if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1257 force_abort = FALSE;
1259 /* Convert an interrupt to an exception if appropriate. */
1260 (void)do_intthrow(&cstack);
1261 #endif /* FEAT_EVAL */
1265 * Continue executing command lines when:
1266 * - no CTRL-C typed, no aborting error, no exception thrown or try
1267 * conditionals need to be checked for executing finally clauses or
1268 * catching an interrupt exception
1269 * - didn't get an error message or lines are not typed
1270 * - there is a command after '|', inside a :if, :while, :for or :try, or
1271 * looping for ":source" command or function call.
1273 while (!((got_int
1274 #ifdef FEAT_EVAL
1275 || (did_emsg && force_abort) || did_throw
1276 #endif
1278 #ifdef FEAT_EVAL
1279 && cstack.cs_trylevel == 0
1280 #endif
1282 && !(did_emsg && used_getline
1283 && (getline_equal(getline, cookie, getexmodeline)
1284 || getline_equal(getline, cookie, getexline)))
1285 && (next_cmdline != NULL
1286 #ifdef FEAT_EVAL
1287 || cstack.cs_idx >= 0
1288 #endif
1289 || (flags & DOCMD_REPEAT)));
1291 vim_free(cmdline_copy);
1292 #ifdef FEAT_EVAL
1293 free_cmdlines(&lines_ga);
1294 ga_clear(&lines_ga);
1296 if (cstack.cs_idx >= 0)
1299 * If a sourced file or executed function ran to its end, report the
1300 * unclosed conditional.
1302 if (!got_int && !did_throw
1303 && ((getline_equal(getline, cookie, getsourceline)
1304 && !source_finished(getline, cookie))
1305 || (getline_equal(getline, cookie, get_func_line)
1306 && !func_has_ended(real_cookie))))
1308 if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1309 EMSG(_(e_endtry));
1310 else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1311 EMSG(_(e_endwhile));
1312 else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
1313 EMSG(_(e_endfor));
1314 else
1315 EMSG(_(e_endif));
1319 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1320 * ":endtry" in a sourced file or executed function. If the try
1321 * conditional is in its finally clause, ignore anything pending.
1322 * If it is in a catch clause, finish the caught exception.
1323 * Also cleanup any "cs_forinfo" structures.
1327 int idx = cleanup_conditionals(&cstack, 0, TRUE);
1329 if (idx >= 0)
1330 --idx; /* remove try block not in its finally clause */
1331 rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
1332 &cstack.cs_looplevel);
1334 while (cstack.cs_idx >= 0);
1335 trylevel = initial_trylevel;
1338 /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
1339 * lack was reported above and the error message is to be converted to an
1340 * exception, do this now after rewinding the cstack. */
1341 do_errthrow(&cstack, getline_equal(getline, cookie, get_func_line)
1342 ? (char_u *)"endfunction" : (char_u *)NULL);
1344 if (trylevel == 0)
1347 * When an exception is being thrown out of the outermost try
1348 * conditional, discard the uncaught exception, disable the conversion
1349 * of interrupts or errors to exceptions, and ensure that no more
1350 * commands are executed.
1352 if (did_throw)
1354 void *p = NULL;
1355 char_u *saved_sourcing_name;
1356 int saved_sourcing_lnum;
1357 struct msglist *messages = NULL, *next;
1360 * If the uncaught exception is a user exception, report it as an
1361 * error. If it is an error exception, display the saved error
1362 * message now. For an interrupt exception, do nothing; the
1363 * interrupt message is given elsewhere.
1365 switch (current_exception->type)
1367 case ET_USER:
1368 vim_snprintf((char *)IObuff, IOSIZE,
1369 _("E605: Exception not caught: %s"),
1370 current_exception->value);
1371 p = vim_strsave(IObuff);
1372 break;
1373 case ET_ERROR:
1374 messages = current_exception->messages;
1375 current_exception->messages = NULL;
1376 break;
1377 case ET_INTERRUPT:
1378 break;
1379 default:
1380 p = vim_strsave((char_u *)_(e_internal));
1383 saved_sourcing_name = sourcing_name;
1384 saved_sourcing_lnum = sourcing_lnum;
1385 sourcing_name = current_exception->throw_name;
1386 sourcing_lnum = current_exception->throw_lnum;
1387 current_exception->throw_name = NULL;
1389 discard_current_exception(); /* uses IObuff if 'verbose' */
1390 suppress_errthrow = TRUE;
1391 force_abort = TRUE;
1393 if (messages != NULL)
1397 next = messages->next;
1398 emsg(messages->msg);
1399 vim_free(messages->msg);
1400 vim_free(messages);
1401 messages = next;
1403 while (messages != NULL);
1405 else if (p != NULL)
1407 emsg(p);
1408 vim_free(p);
1410 vim_free(sourcing_name);
1411 sourcing_name = saved_sourcing_name;
1412 sourcing_lnum = saved_sourcing_lnum;
1416 * On an interrupt or an aborting error not converted to an exception,
1417 * disable the conversion of errors to exceptions. (Interrupts are not
1418 * converted any more, here.) This enables also the interrupt message
1419 * when force_abort is set and did_emsg unset in case of an interrupt
1420 * from a finally clause after an error.
1422 else if (got_int || (did_emsg && force_abort))
1423 suppress_errthrow = TRUE;
1427 * The current cstack will be freed when do_cmdline() returns. An uncaught
1428 * exception will have to be rethrown in the previous cstack. If a function
1429 * has just returned or a script file was just finished and the previous
1430 * cstack belongs to the same function or, respectively, script file, it
1431 * will have to be checked for finally clauses to be executed due to the
1432 * ":return" or ":finish". This is done in do_one_cmd().
1434 if (did_throw)
1435 need_rethrow = TRUE;
1436 if ((getline_equal(getline, cookie, getsourceline)
1437 && ex_nesting_level > source_level(real_cookie))
1438 || (getline_equal(getline, cookie, get_func_line)
1439 && ex_nesting_level > func_level(real_cookie) + 1))
1441 if (!did_throw)
1442 check_cstack = TRUE;
1444 else
1446 /* When leaving a function, reduce nesting level. */
1447 if (getline_equal(getline, cookie, get_func_line))
1448 --ex_nesting_level;
1450 * Go to debug mode when returning from a function in which we are
1451 * single-stepping.
1453 if ((getline_equal(getline, cookie, getsourceline)
1454 || getline_equal(getline, cookie, get_func_line))
1455 && ex_nesting_level + 1 <= debug_break_level)
1456 do_debug(getline_equal(getline, cookie, getsourceline)
1457 ? (char_u *)_("End of sourced file")
1458 : (char_u *)_("End of function"));
1462 * Restore the exception environment (done after returning from the
1463 * debugger).
1465 if (flags & DOCMD_EXCRESET)
1466 restore_dbg_stuff(&debug_saved);
1468 msg_list = saved_msg_list;
1469 #endif /* FEAT_EVAL */
1472 * If there was too much output to fit on the command line, ask the user to
1473 * hit return before redrawing the screen. With the ":global" command we do
1474 * this only once after the command is finished.
1476 if (did_inc)
1478 --RedrawingDisabled;
1479 --no_wait_return;
1480 msg_scroll = FALSE;
1483 * When just finished an ":if"-":else" which was typed, no need to
1484 * wait for hit-return. Also for an error situation.
1486 if (retval == FAIL
1487 #ifdef FEAT_EVAL
1488 || (did_endif && KeyTyped && !did_emsg)
1489 #endif
1492 need_wait_return = FALSE;
1493 msg_didany = FALSE; /* don't wait when restarting edit */
1495 else if (need_wait_return)
1498 * The msg_start() above clears msg_didout. The wait_return we do
1499 * here should not overwrite the command that may be shown before
1500 * doing that.
1502 msg_didout |= msg_didout_before_start;
1503 wait_return(FALSE);
1507 #ifndef FEAT_EVAL
1509 * Reset if_level, in case a sourced script file contains more ":if" than
1510 * ":endif" (could be ":if x | foo | endif").
1512 if_level = 0;
1513 #endif
1515 --call_depth;
1516 return retval;
1519 #ifdef FEAT_EVAL
1521 * Obtain a line when inside a ":while" or ":for" loop.
1523 static char_u *
1524 get_loop_line(c, cookie, indent)
1525 int c;
1526 void *cookie;
1527 int indent;
1529 struct loop_cookie *cp = (struct loop_cookie *)cookie;
1530 wcmd_T *wp;
1531 char_u *line;
1533 if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1535 if (cp->repeating)
1536 return NULL; /* trying to read past ":endwhile"/":endfor" */
1538 /* First time inside the ":while"/":for": get line normally. */
1539 if (cp->getline == NULL)
1540 line = getcmdline(c, 0L, indent);
1541 else
1542 line = cp->getline(c, cp->cookie, indent);
1543 if (line != NULL && store_loop_line(cp->lines_gap, line) == OK)
1544 ++cp->current_line;
1546 return line;
1549 KeyTyped = FALSE;
1550 ++cp->current_line;
1551 wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1552 sourcing_lnum = wp->lnum;
1553 return vim_strsave(wp->line);
1557 * Store a line in "gap" so that a ":while" loop can execute it again.
1559 static int
1560 store_loop_line(gap, line)
1561 garray_T *gap;
1562 char_u *line;
1564 if (ga_grow(gap, 1) == FAIL)
1565 return FAIL;
1566 ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1567 ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1568 ++gap->ga_len;
1569 return OK;
1573 * Free the lines stored for a ":while" or ":for" loop.
1575 static void
1576 free_cmdlines(gap)
1577 garray_T *gap;
1579 while (gap->ga_len > 0)
1581 vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1582 --gap->ga_len;
1585 #endif
1588 * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals
1589 * "func". * Otherwise return TRUE when "fgetline" equals "func".
1592 getline_equal(fgetline, cookie, func)
1593 char_u *(*fgetline) __ARGS((int, void *, int));
1594 void *cookie UNUSED; /* argument for fgetline() */
1595 char_u *(*func) __ARGS((int, void *, int));
1597 #ifdef FEAT_EVAL
1598 char_u *(*gp) __ARGS((int, void *, int));
1599 struct loop_cookie *cp;
1601 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1602 * function that's originally used to obtain the lines. This may be
1603 * nested several levels. */
1604 gp = fgetline;
1605 cp = (struct loop_cookie *)cookie;
1606 while (gp == get_loop_line)
1608 gp = cp->getline;
1609 cp = cp->cookie;
1611 return gp == func;
1612 #else
1613 return fgetline == func;
1614 #endif
1617 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1619 * If "fgetline" is get_loop_line(), return the cookie used by the original
1620 * getline function. Otherwise return "cookie".
1622 void *
1623 getline_cookie(fgetline, cookie)
1624 char_u *(*fgetline) __ARGS((int, void *, int)) UNUSED;
1625 void *cookie; /* argument for fgetline() */
1627 # ifdef FEAT_EVAL
1628 char_u *(*gp) __ARGS((int, void *, int));
1629 struct loop_cookie *cp;
1631 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1632 * cookie that's originally used to obtain the lines. This may be nested
1633 * several levels. */
1634 gp = fgetline;
1635 cp = (struct loop_cookie *)cookie;
1636 while (gp == get_loop_line)
1638 gp = cp->getline;
1639 cp = cp->cookie;
1641 return cp;
1642 # else
1643 return cookie;
1644 # endif
1646 #endif
1649 * Execute one Ex command.
1651 * If 'sourcing' is TRUE, the command will be included in the error message.
1653 * 1. skip comment lines and leading space
1654 * 2. handle command modifiers
1655 * 3. parse range
1656 * 4. parse command
1657 * 5. parse arguments
1658 * 6. switch on command name
1660 * Note: "fgetline" can be NULL.
1662 * This function may be called recursively!
1664 #if (_MSC_VER == 1200)
1666 * Avoid optimisation bug in VC++ version 6.0
1668 #pragma optimize( "g", off )
1669 #endif
1670 static char_u *
1671 do_one_cmd(cmdlinep, sourcing,
1672 #ifdef FEAT_EVAL
1673 cstack,
1674 #endif
1675 fgetline, cookie)
1676 char_u **cmdlinep;
1677 int sourcing;
1678 #ifdef FEAT_EVAL
1679 struct condstack *cstack;
1680 #endif
1681 char_u *(*fgetline) __ARGS((int, void *, int));
1682 void *cookie; /* argument for fgetline() */
1684 char_u *p;
1685 linenr_T lnum;
1686 long n;
1687 char_u *errormsg = NULL; /* error message */
1688 exarg_T ea; /* Ex command arguments */
1689 long verbose_save = -1;
1690 int save_msg_scroll = msg_scroll;
1691 int save_msg_silent = -1;
1692 int did_esilent = 0;
1693 #ifdef HAVE_SANDBOX
1694 int did_sandbox = FALSE;
1695 #endif
1696 cmdmod_T save_cmdmod;
1697 int ni; /* set when Not Implemented */
1699 vim_memset(&ea, 0, sizeof(ea));
1700 ea.line1 = 1;
1701 ea.line2 = 1;
1702 #ifdef FEAT_EVAL
1703 ++ex_nesting_level;
1704 #endif
1706 /* when not editing the last file :q has to be typed twice */
1707 if (quitmore
1708 #ifdef FEAT_EVAL
1709 /* avoid that a function call in 'statusline' does this */
1710 && !getline_equal(fgetline, cookie, get_func_line)
1711 #endif
1713 --quitmore;
1716 * Reset browse, confirm, etc.. They are restored when returning, for
1717 * recursive calls.
1719 save_cmdmod = cmdmod;
1720 vim_memset(&cmdmod, 0, sizeof(cmdmod));
1722 /* "#!anything" is handled like a comment. */
1723 if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!')
1724 goto doend;
1727 * Repeat until no more command modifiers are found.
1729 ea.cmd = *cmdlinep;
1730 for (;;)
1733 * 1. skip comment lines and leading white space and colons
1735 while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1736 ++ea.cmd;
1738 /* in ex mode, an empty line works like :+ */
1739 if (*ea.cmd == NUL && exmode_active
1740 && (getline_equal(fgetline, cookie, getexmodeline)
1741 || getline_equal(fgetline, cookie, getexline))
1742 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1744 ea.cmd = (char_u *)"+";
1745 ex_pressedreturn = TRUE;
1748 /* ignore comment and empty lines */
1749 if (*ea.cmd == '"')
1750 goto doend;
1751 if (*ea.cmd == NUL)
1753 ex_pressedreturn = TRUE;
1754 goto doend;
1758 * 2. handle command modifiers.
1760 p = ea.cmd;
1761 if (VIM_ISDIGIT(*ea.cmd))
1762 p = skipwhite(skipdigits(ea.cmd));
1763 switch (*p)
1765 /* When adding an entry, also modify cmd_exists(). */
1766 case 'a': if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1767 break;
1768 #ifdef FEAT_WINDOWS
1769 cmdmod.split |= WSP_ABOVE;
1770 #endif
1771 continue;
1773 case 'b': if (checkforcmd(&ea.cmd, "belowright", 3))
1775 #ifdef FEAT_WINDOWS
1776 cmdmod.split |= WSP_BELOW;
1777 #endif
1778 continue;
1780 if (checkforcmd(&ea.cmd, "browse", 3))
1782 #ifdef FEAT_BROWSE_CMD
1783 cmdmod.browse = TRUE;
1784 #endif
1785 continue;
1787 if (!checkforcmd(&ea.cmd, "botright", 2))
1788 break;
1789 #ifdef FEAT_WINDOWS
1790 cmdmod.split |= WSP_BOT;
1791 #endif
1792 continue;
1794 case 'c': if (!checkforcmd(&ea.cmd, "confirm", 4))
1795 break;
1796 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1797 cmdmod.confirm = TRUE;
1798 #endif
1799 continue;
1801 case 'k': if (checkforcmd(&ea.cmd, "keepmarks", 3))
1803 cmdmod.keepmarks = TRUE;
1804 continue;
1806 if (checkforcmd(&ea.cmd, "keepalt", 5))
1808 cmdmod.keepalt = TRUE;
1809 continue;
1811 if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1812 break;
1813 cmdmod.keepjumps = TRUE;
1814 continue;
1816 /* ":hide" and ":hide | cmd" are not modifiers */
1817 case 'h': if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1818 || *p == NUL || ends_excmd(*p))
1819 break;
1820 ea.cmd = p;
1821 cmdmod.hide = TRUE;
1822 continue;
1824 case 'l': if (checkforcmd(&ea.cmd, "lockmarks", 3))
1826 cmdmod.lockmarks = TRUE;
1827 continue;
1830 if (!checkforcmd(&ea.cmd, "leftabove", 5))
1831 break;
1832 #ifdef FEAT_WINDOWS
1833 cmdmod.split |= WSP_ABOVE;
1834 #endif
1835 continue;
1837 case 'n': if (!checkforcmd(&ea.cmd, "noautocmd", 3))
1838 break;
1839 #ifdef FEAT_AUTOCMD
1840 if (cmdmod.save_ei == NULL)
1842 /* Set 'eventignore' to "all". Restore the
1843 * existing option value later. */
1844 cmdmod.save_ei = vim_strsave(p_ei);
1845 set_string_option_direct((char_u *)"ei", -1,
1846 (char_u *)"all", OPT_FREE, SID_NONE);
1848 #endif
1849 continue;
1851 case 'r': if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1852 break;
1853 #ifdef FEAT_WINDOWS
1854 cmdmod.split |= WSP_BELOW;
1855 #endif
1856 continue;
1858 case 's': if (checkforcmd(&ea.cmd, "sandbox", 3))
1860 #ifdef HAVE_SANDBOX
1861 if (!did_sandbox)
1862 ++sandbox;
1863 did_sandbox = TRUE;
1864 #endif
1865 continue;
1867 if (!checkforcmd(&ea.cmd, "silent", 3))
1868 break;
1869 if (save_msg_silent == -1)
1870 save_msg_silent = msg_silent;
1871 ++msg_silent;
1872 if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1]))
1874 /* ":silent!", but not "silent !cmd" */
1875 ea.cmd = skipwhite(ea.cmd + 1);
1876 ++emsg_silent;
1877 ++did_esilent;
1879 continue;
1881 case 't': if (checkforcmd(&p, "tab", 3))
1883 #ifdef FEAT_WINDOWS
1884 if (vim_isdigit(*ea.cmd))
1885 cmdmod.tab = atoi((char *)ea.cmd) + 1;
1886 else
1887 cmdmod.tab = tabpage_index(curtab) + 1;
1888 ea.cmd = p;
1889 #endif
1890 continue;
1892 if (!checkforcmd(&ea.cmd, "topleft", 2))
1893 break;
1894 #ifdef FEAT_WINDOWS
1895 cmdmod.split |= WSP_TOP;
1896 #endif
1897 continue;
1899 case 'u': if (!checkforcmd(&ea.cmd, "unsilent", 3))
1900 break;
1901 if (save_msg_silent == -1)
1902 save_msg_silent = msg_silent;
1903 msg_silent = 0;
1904 continue;
1906 case 'v': if (checkforcmd(&ea.cmd, "vertical", 4))
1908 #ifdef FEAT_VERTSPLIT
1909 cmdmod.split |= WSP_VERT;
1910 #endif
1911 continue;
1913 if (!checkforcmd(&p, "verbose", 4))
1914 break;
1915 if (verbose_save < 0)
1916 verbose_save = p_verbose;
1917 if (vim_isdigit(*ea.cmd))
1918 p_verbose = atoi((char *)ea.cmd);
1919 else
1920 p_verbose = 1;
1921 ea.cmd = p;
1922 continue;
1924 break;
1927 #ifdef FEAT_EVAL
1928 ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
1929 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
1930 #else
1931 ea.skip = (if_level > 0);
1932 #endif
1934 #ifdef FEAT_EVAL
1935 # ifdef FEAT_PROFILE
1936 /* Count this line for profiling if ea.skip is FALSE. */
1937 if (do_profiling == PROF_YES && !ea.skip)
1939 if (getline_equal(fgetline, cookie, get_func_line))
1940 func_line_exec(getline_cookie(fgetline, cookie));
1941 else if (getline_equal(fgetline, cookie, getsourceline))
1942 script_line_exec();
1944 #endif
1946 /* May go to debug mode. If this happens and the ">quit" debug command is
1947 * used, throw an interrupt exception and skip the next command. */
1948 dbg_check_breakpoint(&ea);
1949 if (!ea.skip && got_int)
1951 ea.skip = TRUE;
1952 (void)do_intthrow(cstack);
1954 #endif
1957 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
1959 * where 'addr' is:
1961 * % (entire file)
1962 * $ [+-NUM]
1963 * 'x [+-NUM] (where x denotes a currently defined mark)
1964 * . [+-NUM]
1965 * [+-NUM]..
1966 * NUM
1968 * The ea.cmd pointer is updated to point to the first character following the
1969 * range spec. If an initial address is found, but no second, the upper bound
1970 * is equal to the lower.
1973 /* repeat for all ',' or ';' separated addresses */
1974 for (;;)
1976 ea.line1 = ea.line2;
1977 ea.line2 = curwin->w_cursor.lnum; /* default is current line number */
1978 ea.cmd = skipwhite(ea.cmd);
1979 lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0);
1980 if (ea.cmd == NULL) /* error detected */
1981 goto doend;
1982 if (lnum == MAXLNUM)
1984 if (*ea.cmd == '%') /* '%' - all lines */
1986 ++ea.cmd;
1987 ea.line1 = 1;
1988 ea.line2 = curbuf->b_ml.ml_line_count;
1989 ++ea.addr_count;
1991 /* '*' - visual area */
1992 else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
1994 pos_T *fp;
1996 ++ea.cmd;
1997 if (!ea.skip)
1999 fp = getmark('<', FALSE);
2000 if (check_mark(fp) == FAIL)
2001 goto doend;
2002 ea.line1 = fp->lnum;
2003 fp = getmark('>', FALSE);
2004 if (check_mark(fp) == FAIL)
2005 goto doend;
2006 ea.line2 = fp->lnum;
2007 ++ea.addr_count;
2011 else
2012 ea.line2 = lnum;
2013 ea.addr_count++;
2015 if (*ea.cmd == ';')
2017 if (!ea.skip)
2018 curwin->w_cursor.lnum = ea.line2;
2020 else if (*ea.cmd != ',')
2021 break;
2022 ++ea.cmd;
2025 /* One address given: set start and end lines */
2026 if (ea.addr_count == 1)
2028 ea.line1 = ea.line2;
2029 /* ... but only implicit: really no address given */
2030 if (lnum == MAXLNUM)
2031 ea.addr_count = 0;
2034 /* Don't leave the cursor on an illegal line (caused by ';') */
2035 check_cursor_lnum();
2038 * 4. parse command
2042 * Skip ':' and any white space
2044 ea.cmd = skipwhite(ea.cmd);
2045 while (*ea.cmd == ':')
2046 ea.cmd = skipwhite(ea.cmd + 1);
2049 * If we got a line, but no command, then go to the line.
2050 * If we find a '|' or '\n' we set ea.nextcmd.
2052 if (*ea.cmd == NUL || *ea.cmd == '"' ||
2053 (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
2056 * strange vi behaviour:
2057 * ":3" jumps to line 3
2058 * ":3|..." prints line 3
2059 * ":|" prints current line
2061 if (ea.skip) /* skip this if inside :if */
2062 goto doend;
2063 if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2))
2065 ea.cmdidx = CMD_print;
2066 ea.argt = RANGE+COUNT+TRLBAR;
2067 if ((errormsg = invalid_range(&ea)) == NULL)
2069 correct_range(&ea);
2070 ex_print(&ea);
2073 else if (ea.addr_count != 0)
2075 if (ea.line2 > curbuf->b_ml.ml_line_count)
2077 /* With '-' in 'cpoptions' a line number past the file is an
2078 * error, otherwise put it at the end of the file. */
2079 if (vim_strchr(p_cpo, CPO_MINUS) != NULL)
2080 ea.line2 = -1;
2081 else
2082 ea.line2 = curbuf->b_ml.ml_line_count;
2085 if (ea.line2 < 0)
2086 errormsg = (char_u *)_(e_invrange);
2087 else
2089 if (ea.line2 == 0)
2090 curwin->w_cursor.lnum = 1;
2091 else
2092 curwin->w_cursor.lnum = ea.line2;
2093 beginline(BL_SOL | BL_FIX);
2096 goto doend;
2099 /* Find the command and let "p" point to after it. */
2100 p = find_command(&ea, NULL);
2102 #ifdef FEAT_USR_CMDS
2103 if (p == NULL)
2105 if (!ea.skip)
2106 errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
2107 goto doend;
2109 /* Check for wrong commands. */
2110 if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78)
2112 errormsg = uc_fun_cmd();
2113 goto doend;
2115 #endif
2116 if (ea.cmdidx == CMD_SIZE)
2118 if (!ea.skip)
2120 STRCPY(IObuff, _("E492: Not an editor command"));
2121 if (!sourcing)
2123 STRCAT(IObuff, ": ");
2124 STRNCAT(IObuff, *cmdlinep, 40);
2126 errormsg = IObuff;
2128 goto doend;
2131 ni = (
2132 #ifdef FEAT_USR_CMDS
2133 !USER_CMDIDX(ea.cmdidx) &&
2134 #endif
2135 (cmdnames[ea.cmdidx].cmd_func == ex_ni
2136 #ifdef HAVE_EX_SCRIPT_NI
2137 || cmdnames[ea.cmdidx].cmd_func == ex_script_ni
2138 #endif
2141 #ifndef FEAT_EVAL
2143 * When the expression evaluation is disabled, recognize the ":if" and
2144 * ":endif" commands and ignore everything in between it.
2146 if (ea.cmdidx == CMD_if)
2147 ++if_level;
2148 if (if_level)
2150 if (ea.cmdidx == CMD_endif)
2151 --if_level;
2152 goto doend;
2155 #endif
2157 /* forced commands */
2158 if (*p == '!' && ea.cmdidx != CMD_substitute
2159 && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic)
2161 ++p;
2162 ea.forceit = TRUE;
2164 else
2165 ea.forceit = FALSE;
2168 * 5. parse arguments
2170 #ifdef FEAT_USR_CMDS
2171 if (!USER_CMDIDX(ea.cmdidx))
2172 #endif
2173 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
2175 if (!ea.skip)
2177 #ifdef HAVE_SANDBOX
2178 if (sandbox != 0 && !(ea.argt & SBOXOK))
2180 /* Command not allowed in sandbox. */
2181 errormsg = (char_u *)_(e_sandbox);
2182 goto doend;
2184 #endif
2185 if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2187 /* Command not allowed in non-'modifiable' buffer */
2188 errormsg = (char_u *)_(e_modifiable);
2189 goto doend;
2192 if (text_locked() && !(ea.argt & CMDWIN)
2193 # ifdef FEAT_USR_CMDS
2194 && !USER_CMDIDX(ea.cmdidx)
2195 # endif
2198 /* Command not allowed when editing the command line. */
2199 #ifdef FEAT_CMDWIN
2200 if (cmdwin_type != 0)
2201 errormsg = (char_u *)_(e_cmdwin);
2202 else
2203 #endif
2204 errormsg = (char_u *)_(e_secure);
2205 goto doend;
2207 #ifdef FEAT_AUTOCMD
2208 /* Disallow editing another buffer when "curbuf_lock" is set.
2209 * Do allow ":edit" (check for argument later).
2210 * Do allow ":checktime" (it's postponed). */
2211 if (!(ea.argt & CMDWIN)
2212 && ea.cmdidx != CMD_edit
2213 && ea.cmdidx != CMD_checktime
2214 # ifdef FEAT_USR_CMDS
2215 && !USER_CMDIDX(ea.cmdidx)
2216 # endif
2217 && curbuf_locked())
2218 goto doend;
2219 #endif
2221 if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2223 /* no range allowed */
2224 errormsg = (char_u *)_(e_norange);
2225 goto doend;
2229 if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */
2231 errormsg = (char_u *)_(e_nobang);
2232 goto doend;
2236 * Don't complain about the range if it is not used
2237 * (could happen if line_count is accidentally set to 0).
2239 if (!ea.skip && !ni)
2242 * If the range is backwards, ask for confirmation and, if given, swap
2243 * ea.line1 & ea.line2 so it's forwards again.
2244 * When global command is busy, don't ask, will fail below.
2246 if (!global_busy && ea.line1 > ea.line2)
2248 if (msg_silent == 0)
2250 if (sourcing || exmode_active)
2252 errormsg = (char_u *)_("E493: Backwards range given");
2253 goto doend;
2255 if (ask_yesno((char_u *)
2256 _("Backwards range given, OK to swap"), FALSE) != 'y')
2257 goto doend;
2259 lnum = ea.line1;
2260 ea.line1 = ea.line2;
2261 ea.line2 = lnum;
2263 if ((errormsg = invalid_range(&ea)) != NULL)
2264 goto doend;
2267 if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2268 ea.line2 = 1;
2270 correct_range(&ea);
2272 #ifdef FEAT_FOLDING
2273 if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy)
2275 /* Put the first line at the start of a closed fold, put the last line
2276 * at the end of a closed fold. */
2277 (void)hasFolding(ea.line1, &ea.line1, NULL);
2278 (void)hasFolding(ea.line2, NULL, &ea.line2);
2280 #endif
2282 #ifdef FEAT_QUICKFIX
2284 * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2285 * option here, so things like % get expanded.
2287 p = replace_makeprg(&ea, p, cmdlinep);
2288 if (p == NULL)
2289 goto doend;
2290 #endif
2293 * Skip to start of argument.
2294 * Don't do this for the ":!" command, because ":!! -l" needs the space.
2296 if (ea.cmdidx == CMD_bang)
2297 ea.arg = p;
2298 else
2299 ea.arg = skipwhite(p);
2302 * Check for "++opt=val" argument.
2303 * Must be first, allow ":w ++enc=utf8 !cmd"
2305 if (ea.argt & ARGOPT)
2306 while (ea.arg[0] == '+' && ea.arg[1] == '+')
2307 if (getargopt(&ea) == FAIL && !ni)
2309 errormsg = (char_u *)_(e_invarg);
2310 goto doend;
2313 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2315 if (*ea.arg == '>') /* append */
2317 if (*++ea.arg != '>') /* typed wrong */
2319 errormsg = (char_u *)_("E494: Use w or w>>");
2320 goto doend;
2322 ea.arg = skipwhite(ea.arg + 1);
2323 ea.append = TRUE;
2325 else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
2327 ++ea.arg;
2328 ea.usefilter = TRUE;
2332 if (ea.cmdidx == CMD_read)
2334 if (ea.forceit)
2336 ea.usefilter = TRUE; /* :r! filter if ea.forceit */
2337 ea.forceit = FALSE;
2339 else if (*ea.arg == '!') /* :r !filter */
2341 ++ea.arg;
2342 ea.usefilter = TRUE;
2346 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2348 ea.amount = 1;
2349 while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */
2351 ++ea.arg;
2352 ++ea.amount;
2354 ea.arg = skipwhite(ea.arg);
2358 * Check for "+command" argument, before checking for next command.
2359 * Don't do this for ":read !cmd" and ":write !cmd".
2361 if ((ea.argt & EDITCMD) && !ea.usefilter)
2362 ea.do_ecmd_cmd = getargcmd(&ea.arg);
2365 * Check for '|' to separate commands and '"' to start comments.
2366 * Don't do this for ":read !cmd" and ":write !cmd".
2368 if ((ea.argt & TRLBAR) && !ea.usefilter)
2369 separate_nextcmd(&ea);
2372 * Check for <newline> to end a shell command.
2373 * Also do this for ":read !cmd", ":write !cmd" and ":global".
2374 * Any others?
2376 else if (ea.cmdidx == CMD_bang
2377 || ea.cmdidx == CMD_global
2378 || ea.cmdidx == CMD_vglobal
2379 || ea.usefilter)
2381 for (p = ea.arg; *p; ++p)
2383 /* Remove one backslash before a newline, so that it's possible to
2384 * pass a newline to the shell and also a newline that is preceded
2385 * with a backslash. This makes it impossible to end a shell
2386 * command in a backslash, but that doesn't appear useful.
2387 * Halving the number of backslashes is incompatible with previous
2388 * versions. */
2389 if (*p == '\\' && p[1] == '\n')
2390 STRMOVE(p, p + 1);
2391 else if (*p == '\n')
2393 ea.nextcmd = p + 1;
2394 *p = NUL;
2395 break;
2400 if ((ea.argt & DFLALL) && ea.addr_count == 0)
2402 ea.line1 = 1;
2403 ea.line2 = curbuf->b_ml.ml_line_count;
2406 /* accept numbered register only when no count allowed (:put) */
2407 if ( (ea.argt & REGSTR)
2408 && *ea.arg != NUL
2409 #ifdef FEAT_USR_CMDS
2410 && valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2411 && USER_CMDIDX(ea.cmdidx)))
2412 /* Do not allow register = for user commands */
2413 && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2414 #else
2415 && valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put)
2416 #endif
2417 && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2419 ea.regname = *ea.arg++;
2420 #ifdef FEAT_EVAL
2421 /* for '=' register: accept the rest of the line as an expression */
2422 if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2424 set_expr_line(vim_strsave(ea.arg));
2425 ea.arg += STRLEN(ea.arg);
2427 #endif
2428 ea.arg = skipwhite(ea.arg);
2432 * Check for a count. When accepting a BUFNAME, don't use "123foo" as a
2433 * count, it's a buffer name.
2435 if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2436 && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2437 || vim_iswhite(*p)))
2439 n = getdigits(&ea.arg);
2440 ea.arg = skipwhite(ea.arg);
2441 if (n <= 0 && !ni && (ea.argt & ZEROR) == 0)
2443 errormsg = (char_u *)_(e_zerocount);
2444 goto doend;
2446 if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */
2448 ea.line2 = n;
2449 if (ea.addr_count == 0)
2450 ea.addr_count = 1;
2452 else
2454 ea.line1 = ea.line2;
2455 ea.line2 += n - 1;
2456 ++ea.addr_count;
2458 * Be vi compatible: no error message for out of range.
2460 if (ea.line2 > curbuf->b_ml.ml_line_count)
2461 ea.line2 = curbuf->b_ml.ml_line_count;
2466 * Check for flags: 'l', 'p' and '#'.
2468 if (ea.argt & EXFLAGS)
2469 get_flags(&ea);
2470 /* no arguments allowed */
2471 if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2472 && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0))
2474 errormsg = (char_u *)_(e_trailing);
2475 goto doend;
2478 if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2480 errormsg = (char_u *)_(e_argreq);
2481 goto doend;
2484 #ifdef FEAT_EVAL
2486 * Skip the command when it's not going to be executed.
2487 * The commands like :if, :endif, etc. always need to be executed.
2488 * Also make an exception for commands that handle a trailing command
2489 * themselves.
2491 if (ea.skip)
2493 switch (ea.cmdidx)
2495 /* commands that need evaluation */
2496 case CMD_while:
2497 case CMD_endwhile:
2498 case CMD_for:
2499 case CMD_endfor:
2500 case CMD_if:
2501 case CMD_elseif:
2502 case CMD_else:
2503 case CMD_endif:
2504 case CMD_try:
2505 case CMD_catch:
2506 case CMD_finally:
2507 case CMD_endtry:
2508 case CMD_function:
2509 break;
2511 /* Commands that handle '|' themselves. Check: A command should
2512 * either have the TRLBAR flag, appear in this list or appear in
2513 * the list at ":help :bar". */
2514 case CMD_aboveleft:
2515 case CMD_and:
2516 case CMD_belowright:
2517 case CMD_botright:
2518 case CMD_browse:
2519 case CMD_call:
2520 case CMD_confirm:
2521 case CMD_delfunction:
2522 case CMD_djump:
2523 case CMD_dlist:
2524 case CMD_dsearch:
2525 case CMD_dsplit:
2526 case CMD_echo:
2527 case CMD_echoerr:
2528 case CMD_echomsg:
2529 case CMD_echon:
2530 case CMD_execute:
2531 case CMD_help:
2532 case CMD_hide:
2533 case CMD_ijump:
2534 case CMD_ilist:
2535 case CMD_isearch:
2536 case CMD_isplit:
2537 case CMD_keepalt:
2538 case CMD_keepjumps:
2539 case CMD_keepmarks:
2540 case CMD_leftabove:
2541 case CMD_let:
2542 case CMD_lockmarks:
2543 case CMD_match:
2544 case CMD_mzscheme:
2545 case CMD_perl:
2546 case CMD_psearch:
2547 case CMD_python:
2548 case CMD_return:
2549 case CMD_rightbelow:
2550 case CMD_ruby:
2551 case CMD_silent:
2552 case CMD_smagic:
2553 case CMD_snomagic:
2554 case CMD_substitute:
2555 case CMD_syntax:
2556 case CMD_tab:
2557 case CMD_tcl:
2558 case CMD_throw:
2559 case CMD_tilde:
2560 case CMD_topleft:
2561 case CMD_unlet:
2562 case CMD_verbose:
2563 case CMD_vertical:
2564 break;
2566 default: goto doend;
2569 #endif
2571 if (ea.argt & XFILE)
2573 if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2574 goto doend;
2577 #ifdef FEAT_LISTCMDS
2579 * Accept buffer name. Cannot be used at the same time with a buffer
2580 * number. Don't do this for a user command.
2582 if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2583 # ifdef FEAT_USR_CMDS
2584 && !USER_CMDIDX(ea.cmdidx)
2585 # endif
2589 * :bdelete, :bwipeout and :bunload take several arguments, separated
2590 * by spaces: find next space (skipping over escaped characters).
2591 * The others take one argument: ignore trailing spaces.
2593 if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2594 || ea.cmdidx == CMD_bunload)
2595 p = skiptowhite_esc(ea.arg);
2596 else
2598 p = ea.arg + STRLEN(ea.arg);
2599 while (p > ea.arg && vim_iswhite(p[-1]))
2600 --p;
2602 ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE);
2603 if (ea.line2 < 0) /* failed */
2604 goto doend;
2605 ea.addr_count = 1;
2606 ea.arg = skipwhite(p);
2608 #endif
2611 * 6. switch on command name
2613 * The "ea" structure holds the arguments that can be used.
2615 ea.cmdlinep = cmdlinep;
2616 ea.getline = fgetline;
2617 ea.cookie = cookie;
2618 #ifdef FEAT_EVAL
2619 ea.cstack = cstack;
2620 #endif
2622 #ifdef FEAT_USR_CMDS
2623 if (USER_CMDIDX(ea.cmdidx))
2626 * Execute a user-defined command.
2628 do_ucmd(&ea);
2630 else
2631 #endif
2634 * Call the function to execute the command.
2636 ea.errmsg = NULL;
2637 (cmdnames[ea.cmdidx].cmd_func)(&ea);
2638 if (ea.errmsg != NULL)
2639 errormsg = (char_u *)_(ea.errmsg);
2642 #ifdef FEAT_EVAL
2644 * If the command just executed called do_cmdline(), any throw or ":return"
2645 * or ":finish" encountered there must also check the cstack of the still
2646 * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught
2647 * exception, or reanimate a returned function or finished script file and
2648 * return or finish it again.
2650 if (need_rethrow)
2651 do_throw(cstack);
2652 else if (check_cstack)
2654 if (source_finished(fgetline, cookie))
2655 do_finish(&ea, TRUE);
2656 else if (getline_equal(fgetline, cookie, get_func_line)
2657 && current_func_returned())
2658 do_return(&ea, TRUE, FALSE, NULL);
2660 need_rethrow = check_cstack = FALSE;
2661 #endif
2663 doend:
2664 if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */
2665 curwin->w_cursor.lnum = 1;
2667 if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2669 if (sourcing)
2671 if (errormsg != IObuff)
2673 STRCPY(IObuff, errormsg);
2674 errormsg = IObuff;
2676 STRCAT(errormsg, ": ");
2677 STRNCAT(errormsg, *cmdlinep, IOSIZE - STRLEN(IObuff) - 1);
2679 emsg(errormsg);
2681 #ifdef FEAT_EVAL
2682 do_errthrow(cstack,
2683 (ea.cmdidx != CMD_SIZE
2684 # ifdef FEAT_USR_CMDS
2685 && !USER_CMDIDX(ea.cmdidx)
2686 # endif
2687 ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
2688 #endif
2690 if (verbose_save >= 0)
2691 p_verbose = verbose_save;
2692 #ifdef FEAT_AUTOCMD
2693 if (cmdmod.save_ei != NULL)
2695 /* Restore 'eventignore' to the value before ":noautocmd". */
2696 set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei,
2697 OPT_FREE, SID_NONE);
2698 free_string_option(cmdmod.save_ei);
2700 #endif
2702 cmdmod = save_cmdmod;
2704 if (save_msg_silent != -1)
2706 /* messages could be enabled for a serious error, need to check if the
2707 * counters don't become negative */
2708 if (!did_emsg || msg_silent > save_msg_silent)
2709 msg_silent = save_msg_silent;
2710 emsg_silent -= did_esilent;
2711 if (emsg_silent < 0)
2712 emsg_silent = 0;
2713 /* Restore msg_scroll, it's set by file I/O commands, even when no
2714 * message is actually displayed. */
2715 msg_scroll = save_msg_scroll;
2717 /* "silent reg" or "silent echo x" inside "redir" leaves msg_col
2718 * somewhere in the line. Put it back in the first column. */
2719 if (redirecting())
2720 msg_col = 0;
2723 #ifdef HAVE_SANDBOX
2724 if (did_sandbox)
2725 --sandbox;
2726 #endif
2728 if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */
2729 ea.nextcmd = NULL;
2731 #ifdef FEAT_EVAL
2732 --ex_nesting_level;
2733 #endif
2735 return ea.nextcmd;
2737 #if (_MSC_VER == 1200)
2738 #pragma optimize( "", on )
2739 #endif
2742 * Check for an Ex command with optional tail.
2743 * If there is a match advance "pp" to the argument and return TRUE.
2746 checkforcmd(pp, cmd, len)
2747 char_u **pp; /* start of command */
2748 char *cmd; /* name of command */
2749 int len; /* required length */
2751 int i;
2753 for (i = 0; cmd[i] != NUL; ++i)
2754 if (((char_u *)cmd)[i] != (*pp)[i])
2755 break;
2756 if (i >= len && !isalpha((*pp)[i]))
2758 *pp = skipwhite(*pp + i);
2759 return TRUE;
2761 return FALSE;
2765 * Find an Ex command by its name, either built-in or user.
2766 * Start of the name can be found at eap->cmd.
2767 * Returns pointer to char after the command name.
2768 * "full" is set to TRUE if the whole command name matched.
2769 * Returns NULL for an ambiguous user command.
2771 static char_u *
2772 find_command(eap, full)
2773 exarg_T *eap;
2774 int *full UNUSED;
2776 int len;
2777 char_u *p;
2778 int i;
2781 * Isolate the command and search for it in the command table.
2782 * Exceptions:
2783 * - the 'k' command can directly be followed by any character.
2784 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2785 * but :sre[wind] is another command, as are :scrip[tnames],
2786 * :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
2787 * - the "d" command can directly be followed by 'l' or 'p' flag.
2789 p = eap->cmd;
2790 if (*p == 'k')
2792 eap->cmdidx = CMD_k;
2793 ++p;
2795 else if (p[0] == 's'
2796 && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r'
2797 && p[3] != 'i' && p[4] != 'p')
2798 || p[1] == 'g'
2799 || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
2800 || p[1] == 'I'
2801 || (p[1] == 'r' && p[2] != 'e')))
2803 eap->cmdidx = CMD_substitute;
2804 ++p;
2806 else
2808 while (ASCII_ISALPHA(*p))
2809 ++p;
2810 /* check for non-alpha command */
2811 if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2812 ++p;
2813 len = (int)(p - eap->cmd);
2814 if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p'))
2816 /* Check for ":dl", ":dell", etc. to ":deletel": that's
2817 * :delete with the 'l' flag. Same for 'p'. */
2818 for (i = 0; i < len; ++i)
2819 if (eap->cmd[i] != ((char_u *)"delete")[i])
2820 break;
2821 if (i == len - 1)
2823 --len;
2824 if (p[-1] == 'l')
2825 eap->flags |= EXFLAG_LIST;
2826 else
2827 eap->flags |= EXFLAG_PRINT;
2831 if (ASCII_ISLOWER(*eap->cmd))
2832 eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)];
2833 else
2834 eap->cmdidx = cmdidxs[26];
2836 for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
2837 eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
2838 if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
2839 (size_t)len) == 0)
2841 #ifdef FEAT_EVAL
2842 if (full != NULL
2843 && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
2844 *full = TRUE;
2845 #endif
2846 break;
2849 #ifdef FEAT_USR_CMDS
2850 /* Look for a user defined command as a last resort */
2851 if (eap->cmdidx == CMD_SIZE && *eap->cmd >= 'A' && *eap->cmd <= 'Z')
2853 /* User defined commands may contain digits. */
2854 while (ASCII_ISALNUM(*p))
2855 ++p;
2856 p = find_ucmd(eap, p, full, NULL, NULL);
2858 #endif
2859 if (p == eap->cmd)
2860 eap->cmdidx = CMD_SIZE;
2863 return p;
2866 #ifdef FEAT_USR_CMDS
2868 * Search for a user command that matches "eap->cmd".
2869 * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
2870 * Return a pointer to just after the command.
2871 * Return NULL if there is no matching command.
2873 static char_u *
2874 find_ucmd(eap, p, full, xp, compl)
2875 exarg_T *eap;
2876 char_u *p; /* end of the command (possibly including count) */
2877 int *full; /* set to TRUE for a full match */
2878 expand_T *xp; /* used for completion, NULL otherwise */
2879 int *compl; /* completion flags or NULL */
2881 int len = (int)(p - eap->cmd);
2882 int j, k, matchlen = 0;
2883 ucmd_T *uc;
2884 int found = FALSE;
2885 int possible = FALSE;
2886 char_u *cp, *np; /* Point into typed cmd and test name */
2887 garray_T *gap;
2888 int amb_local = FALSE; /* Found ambiguous buffer-local command,
2889 only full match global is accepted. */
2892 * Look for buffer-local user commands first, then global ones.
2894 gap = &curbuf->b_ucmds;
2895 for (;;)
2897 for (j = 0; j < gap->ga_len; ++j)
2899 uc = USER_CMD_GA(gap, j);
2900 cp = eap->cmd;
2901 np = uc->uc_name;
2902 k = 0;
2903 while (k < len && *np != NUL && *cp++ == *np++)
2904 k++;
2905 if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
2907 /* If finding a second match, the command is ambiguous. But
2908 * not if a buffer-local command wasn't a full match and a
2909 * global command is a full match. */
2910 if (k == len && found && *np != NUL)
2912 if (gap == &ucmds)
2913 return NULL;
2914 amb_local = TRUE;
2917 if (!found || (k == len && *np == NUL))
2919 /* If we matched up to a digit, then there could
2920 * be another command including the digit that we
2921 * should use instead.
2923 if (k == len)
2924 found = TRUE;
2925 else
2926 possible = TRUE;
2928 if (gap == &ucmds)
2929 eap->cmdidx = CMD_USER;
2930 else
2931 eap->cmdidx = CMD_USER_BUF;
2932 eap->argt = (long)uc->uc_argt;
2933 eap->useridx = j;
2935 # ifdef FEAT_CMDL_COMPL
2936 if (compl != NULL)
2937 *compl = uc->uc_compl;
2938 # ifdef FEAT_EVAL
2939 if (xp != NULL)
2941 xp->xp_arg = uc->uc_compl_arg;
2942 xp->xp_scriptID = uc->uc_scriptID;
2944 # endif
2945 # endif
2946 /* Do not search for further abbreviations
2947 * if this is an exact match. */
2948 matchlen = k;
2949 if (k == len && *np == NUL)
2951 if (full != NULL)
2952 *full = TRUE;
2953 amb_local = FALSE;
2954 break;
2960 /* Stop if we found a full match or searched all. */
2961 if (j < gap->ga_len || gap == &ucmds)
2962 break;
2963 gap = &ucmds;
2966 /* Only found ambiguous matches. */
2967 if (amb_local)
2969 if (xp != NULL)
2970 xp->xp_context = EXPAND_UNSUCCESSFUL;
2971 return NULL;
2974 /* The match we found may be followed immediately by a number. Move "p"
2975 * back to point to it. */
2976 if (found || possible)
2977 return p + (matchlen - len);
2978 return p;
2980 #endif
2982 #if defined(FEAT_EVAL) || defined(PROTO)
2983 static struct cmdmod
2985 char *name;
2986 int minlen;
2987 int has_count; /* :123verbose :3tab */
2988 } cmdmods[] = {
2989 {"aboveleft", 3, FALSE},
2990 {"belowright", 3, FALSE},
2991 {"botright", 2, FALSE},
2992 {"browse", 3, FALSE},
2993 {"confirm", 4, FALSE},
2994 {"hide", 3, FALSE},
2995 {"keepalt", 5, FALSE},
2996 {"keepjumps", 5, FALSE},
2997 {"keepmarks", 3, FALSE},
2998 {"leftabove", 5, FALSE},
2999 {"lockmarks", 3, FALSE},
3000 {"noautocmd", 3, FALSE},
3001 {"rightbelow", 6, FALSE},
3002 {"sandbox", 3, FALSE},
3003 {"silent", 3, FALSE},
3004 {"tab", 3, TRUE},
3005 {"topleft", 2, FALSE},
3006 {"unsilent", 3, FALSE},
3007 {"verbose", 4, TRUE},
3008 {"vertical", 4, FALSE},
3012 * Return length of a command modifier (including optional count).
3013 * Return zero when it's not a modifier.
3016 modifier_len(cmd)
3017 char_u *cmd;
3019 int i, j;
3020 char_u *p = cmd;
3022 if (VIM_ISDIGIT(*cmd))
3023 p = skipwhite(skipdigits(cmd));
3024 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3026 for (j = 0; p[j] != NUL; ++j)
3027 if (p[j] != cmdmods[i].name[j])
3028 break;
3029 if (!isalpha(p[j]) && j >= cmdmods[i].minlen
3030 && (p == cmd || cmdmods[i].has_count))
3031 return j + (int)(p - cmd);
3033 return 0;
3037 * Return > 0 if an Ex command "name" exists.
3038 * Return 2 if there is an exact match.
3039 * Return 3 if there is an ambiguous match.
3042 cmd_exists(name)
3043 char_u *name;
3045 exarg_T ea;
3046 int full = FALSE;
3047 int i;
3048 int j;
3049 char_u *p;
3051 /* Check command modifiers. */
3052 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3054 for (j = 0; name[j] != NUL; ++j)
3055 if (name[j] != cmdmods[i].name[j])
3056 break;
3057 if (name[j] == NUL && j >= cmdmods[i].minlen)
3058 return (cmdmods[i].name[j] == NUL ? 2 : 1);
3061 /* Check built-in commands and user defined commands.
3062 * For ":2match" and ":3match" we need to skip the number. */
3063 ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3064 ea.cmdidx = (cmdidx_T)0;
3065 p = find_command(&ea, &full);
3066 if (p == NULL)
3067 return 3;
3068 if (vim_isdigit(*name) && ea.cmdidx != CMD_match)
3069 return 0;
3070 if (*skipwhite(p) != NUL)
3071 return 0; /* trailing garbage */
3072 return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
3074 #endif
3077 * This is all pretty much copied from do_one_cmd(), with all the extra stuff
3078 * we don't need/want deleted. Maybe this could be done better if we didn't
3079 * repeat all this stuff. The only problem is that they may not stay
3080 * perfectly compatible with each other, but then the command line syntax
3081 * probably won't change that much -- webb.
3083 char_u *
3084 set_one_cmd_context(xp, buff)
3085 expand_T *xp;
3086 char_u *buff; /* buffer for command string */
3088 char_u *p;
3089 char_u *cmd, *arg;
3090 int len = 0;
3091 exarg_T ea;
3092 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3093 int compl = EXPAND_NOTHING;
3094 #endif
3095 #ifdef FEAT_CMDL_COMPL
3096 int delim;
3097 #endif
3098 int forceit = FALSE;
3099 int usefilter = FALSE; /* filter instead of file name */
3101 ExpandInit(xp);
3102 xp->xp_pattern = buff;
3103 xp->xp_context = EXPAND_COMMANDS; /* Default until we get past command */
3104 ea.argt = 0;
3107 * 2. skip comment lines and leading space, colons or bars
3109 for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
3111 xp->xp_pattern = cmd;
3113 if (*cmd == NUL)
3114 return NULL;
3115 if (*cmd == '"') /* ignore comment lines */
3117 xp->xp_context = EXPAND_NOTHING;
3118 return NULL;
3122 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
3124 cmd = skip_range(cmd, &xp->xp_context);
3127 * 4. parse command
3129 xp->xp_pattern = cmd;
3130 if (*cmd == NUL)
3131 return NULL;
3132 if (*cmd == '"')
3134 xp->xp_context = EXPAND_NOTHING;
3135 return NULL;
3138 if (*cmd == '|' || *cmd == '\n')
3139 return cmd + 1; /* There's another command */
3142 * Isolate the command and search for it in the command table.
3143 * Exceptions:
3144 * - the 'k' command can directly be followed by any character, but
3145 * do accept "keepmarks", "keepalt" and "keepjumps".
3146 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3148 if (*cmd == 'k' && cmd[1] != 'e')
3150 ea.cmdidx = CMD_k;
3151 p = cmd + 1;
3153 else
3155 p = cmd;
3156 while (ASCII_ISALPHA(*p) || *p == '*') /* Allow * wild card */
3157 ++p;
3158 /* check for non-alpha command */
3159 if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3160 ++p;
3161 len = (int)(p - cmd);
3163 if (len == 0)
3165 xp->xp_context = EXPAND_UNSUCCESSFUL;
3166 return NULL;
3168 for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE;
3169 ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1))
3170 if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd,
3171 (size_t)len) == 0)
3172 break;
3174 #ifdef FEAT_USR_CMDS
3175 if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3176 while (ASCII_ISALNUM(*p) || *p == '*') /* Allow * wild card */
3177 ++p;
3178 #endif
3182 * If the cursor is touching the command, and it ends in an alpha-numeric
3183 * character, complete the command name.
3185 if (*p == NUL && ASCII_ISALNUM(p[-1]))
3186 return NULL;
3188 if (ea.cmdidx == CMD_SIZE)
3190 if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
3192 ea.cmdidx = CMD_substitute;
3193 p = cmd + 1;
3195 #ifdef FEAT_USR_CMDS
3196 else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3198 ea.cmd = cmd;
3199 p = find_ucmd(&ea, p, NULL, xp,
3200 # if defined(FEAT_CMDL_COMPL)
3201 &compl
3202 # else
3203 NULL
3204 # endif
3206 if (p == NULL)
3207 ea.cmdidx = CMD_SIZE; /* ambiguous user command */
3209 #endif
3211 if (ea.cmdidx == CMD_SIZE)
3213 /* Not still touching the command and it was an illegal one */
3214 xp->xp_context = EXPAND_UNSUCCESSFUL;
3215 return NULL;
3218 xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3220 if (*p == '!') /* forced commands */
3222 forceit = TRUE;
3223 ++p;
3227 * 5. parse arguments
3229 #ifdef FEAT_USR_CMDS
3230 if (!USER_CMDIDX(ea.cmdidx))
3231 #endif
3232 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
3234 arg = skipwhite(p);
3236 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
3238 if (*arg == '>') /* append */
3240 if (*++arg == '>')
3241 ++arg;
3242 arg = skipwhite(arg);
3244 else if (*arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
3246 ++arg;
3247 usefilter = TRUE;
3251 if (ea.cmdidx == CMD_read)
3253 usefilter = forceit; /* :r! filter if forced */
3254 if (*arg == '!') /* :r !filter */
3256 ++arg;
3257 usefilter = TRUE;
3261 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
3263 while (*arg == *cmd) /* allow any number of '>' or '<' */
3264 ++arg;
3265 arg = skipwhite(arg);
3268 /* Does command allow "+command"? */
3269 if ((ea.argt & EDITCMD) && !usefilter && *arg == '+')
3271 /* Check if we're in the +command */
3272 p = arg + 1;
3273 arg = skip_cmd_arg(arg, FALSE);
3275 /* Still touching the command after '+'? */
3276 if (*arg == NUL)
3277 return p;
3279 /* Skip space(s) after +command to get to the real argument */
3280 arg = skipwhite(arg);
3284 * Check for '|' to separate commands and '"' to start comments.
3285 * Don't do this for ":read !cmd" and ":write !cmd".
3287 if ((ea.argt & TRLBAR) && !usefilter)
3289 p = arg;
3290 /* ":redir @" is not the start of a comment */
3291 if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3292 p += 2;
3293 while (*p)
3295 if (*p == Ctrl_V)
3297 if (p[1] != NUL)
3298 ++p;
3300 else if ( (*p == '"' && !(ea.argt & NOTRLCOM))
3301 || *p == '|' || *p == '\n')
3303 if (*(p - 1) != '\\')
3305 if (*p == '|' || *p == '\n')
3306 return p + 1;
3307 return NULL; /* It's a comment */
3310 mb_ptr_adv(p);
3314 /* no arguments allowed */
3315 if (!(ea.argt & EXTRA) && *arg != NUL &&
3316 vim_strchr((char_u *)"|\"", *arg) == NULL)
3317 return NULL;
3319 /* Find start of last argument (argument just before cursor): */
3320 p = buff + STRLEN(buff);
3321 while (p != arg && *p != ' ' && *p != TAB)
3322 p--;
3323 if (*p == ' ' || *p == TAB)
3324 p++;
3325 xp->xp_pattern = p;
3327 if (ea.argt & XFILE)
3329 int c;
3330 int in_quote = FALSE;
3331 char_u *bow = NULL; /* Beginning of word */
3334 * Allow spaces within back-quotes to count as part of the argument
3335 * being expanded.
3337 xp->xp_pattern = skipwhite(arg);
3338 p = xp->xp_pattern;
3339 while (*p != NUL)
3341 #ifdef FEAT_MBYTE
3342 if (has_mbyte)
3343 c = mb_ptr2char(p);
3344 else
3345 #endif
3346 c = *p;
3347 if (c == '\\' && p[1] != NUL)
3348 ++p;
3349 else if (c == '`')
3351 if (!in_quote)
3353 xp->xp_pattern = p;
3354 bow = p + 1;
3356 in_quote = !in_quote;
3358 /* An argument can contain just about everything, except
3359 * characters that end the command and white space. */
3360 else if (c == '|' || c == '\n' || c == '"' || (vim_iswhite(c)
3361 #ifdef SPACE_IN_FILENAME
3362 && (!(ea.argt & NOSPC) || usefilter)
3363 #endif
3366 len = 0; /* avoid getting stuck when space is in 'isfname' */
3367 while (*p != NUL)
3369 #ifdef FEAT_MBYTE
3370 if (has_mbyte)
3371 c = mb_ptr2char(p);
3372 else
3373 #endif
3374 c = *p;
3375 if (c == '`' || vim_isfilec_or_wc(c))
3376 break;
3377 #ifdef FEAT_MBYTE
3378 if (has_mbyte)
3379 len = (*mb_ptr2len)(p);
3380 else
3381 #endif
3382 len = 1;
3383 mb_ptr_adv(p);
3385 if (in_quote)
3386 bow = p;
3387 else
3388 xp->xp_pattern = p;
3389 p -= len;
3391 mb_ptr_adv(p);
3395 * If we are still inside the quotes, and we passed a space, just
3396 * expand from there.
3398 if (bow != NULL && in_quote)
3399 xp->xp_pattern = bow;
3400 xp->xp_context = EXPAND_FILES;
3402 #ifndef BACKSLASH_IN_FILENAME
3403 /* For a shell command more chars need to be escaped. */
3404 if (usefilter || ea.cmdidx == CMD_bang)
3406 xp->xp_shell = TRUE;
3408 /* When still after the command name expand executables. */
3409 if (xp->xp_pattern == skipwhite(arg))
3410 xp->xp_context = EXPAND_SHELLCMD;
3412 #endif
3414 /* Check for environment variable */
3415 if (*xp->xp_pattern == '$'
3416 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3417 || *xp->xp_pattern == '%'
3418 #endif
3421 for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3422 if (!vim_isIDc(*p))
3423 break;
3424 if (*p == NUL)
3426 xp->xp_context = EXPAND_ENV_VARS;
3427 ++xp->xp_pattern;
3428 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3429 /* Avoid that the assignment uses EXPAND_FILES again. */
3430 if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
3431 compl = EXPAND_ENV_VARS;
3432 #endif
3438 * 6. switch on command name
3440 switch (ea.cmdidx)
3442 case CMD_cd:
3443 case CMD_chdir:
3444 case CMD_lcd:
3445 case CMD_lchdir:
3446 if (xp->xp_context == EXPAND_FILES)
3447 xp->xp_context = EXPAND_DIRECTORIES;
3448 break;
3449 case CMD_help:
3450 xp->xp_context = EXPAND_HELP;
3451 xp->xp_pattern = arg;
3452 break;
3454 /* Command modifiers: return the argument.
3455 * Also for commands with an argument that is a command. */
3456 case CMD_aboveleft:
3457 case CMD_argdo:
3458 case CMD_belowright:
3459 case CMD_botright:
3460 case CMD_browse:
3461 case CMD_bufdo:
3462 case CMD_confirm:
3463 case CMD_debug:
3464 case CMD_folddoclosed:
3465 case CMD_folddoopen:
3466 case CMD_hide:
3467 case CMD_keepalt:
3468 case CMD_keepjumps:
3469 case CMD_keepmarks:
3470 case CMD_leftabove:
3471 case CMD_lockmarks:
3472 case CMD_rightbelow:
3473 case CMD_sandbox:
3474 case CMD_silent:
3475 case CMD_tab:
3476 case CMD_topleft:
3477 case CMD_verbose:
3478 case CMD_vertical:
3479 case CMD_windo:
3480 return arg;
3482 #ifdef FEAT_CMDL_COMPL
3483 # ifdef FEAT_SEARCH_EXTRA
3484 case CMD_match:
3485 if (*arg == NUL || !ends_excmd(*arg))
3487 /* also complete "None" */
3488 set_context_in_echohl_cmd(xp, arg);
3489 arg = skipwhite(skiptowhite(arg));
3490 if (*arg != NUL)
3492 xp->xp_context = EXPAND_NOTHING;
3493 arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3496 return find_nextcmd(arg);
3497 # endif
3500 * All completion for the +cmdline_compl feature goes here.
3503 # ifdef FEAT_USR_CMDS
3504 case CMD_command:
3505 /* Check for attributes */
3506 while (*arg == '-')
3508 arg++; /* Skip "-" */
3509 p = skiptowhite(arg);
3510 if (*p == NUL)
3512 /* Cursor is still in the attribute */
3513 p = vim_strchr(arg, '=');
3514 if (p == NULL)
3516 /* No "=", so complete attribute names */
3517 xp->xp_context = EXPAND_USER_CMD_FLAGS;
3518 xp->xp_pattern = arg;
3519 return NULL;
3522 /* For the -complete and -nargs attributes, we complete
3523 * their arguments as well.
3525 if (STRNICMP(arg, "complete", p - arg) == 0)
3527 xp->xp_context = EXPAND_USER_COMPLETE;
3528 xp->xp_pattern = p + 1;
3529 return NULL;
3531 else if (STRNICMP(arg, "nargs", p - arg) == 0)
3533 xp->xp_context = EXPAND_USER_NARGS;
3534 xp->xp_pattern = p + 1;
3535 return NULL;
3537 return NULL;
3539 arg = skipwhite(p);
3542 /* After the attributes comes the new command name */
3543 p = skiptowhite(arg);
3544 if (*p == NUL)
3546 xp->xp_context = EXPAND_USER_COMMANDS;
3547 xp->xp_pattern = arg;
3548 break;
3551 /* And finally comes a normal command */
3552 return skipwhite(p);
3554 case CMD_delcommand:
3555 xp->xp_context = EXPAND_USER_COMMANDS;
3556 xp->xp_pattern = arg;
3557 break;
3558 # endif
3560 case CMD_global:
3561 case CMD_vglobal:
3562 delim = *arg; /* get the delimiter */
3563 if (delim)
3564 ++arg; /* skip delimiter if there is one */
3566 while (arg[0] != NUL && arg[0] != delim)
3568 if (arg[0] == '\\' && arg[1] != NUL)
3569 ++arg;
3570 ++arg;
3572 if (arg[0] != NUL)
3573 return arg + 1;
3574 break;
3575 case CMD_and:
3576 case CMD_substitute:
3577 delim = *arg;
3578 if (delim)
3580 /* skip "from" part */
3581 ++arg;
3582 arg = skip_regexp(arg, delim, p_magic, NULL);
3584 /* skip "to" part */
3585 while (arg[0] != NUL && arg[0] != delim)
3587 if (arg[0] == '\\' && arg[1] != NUL)
3588 ++arg;
3589 ++arg;
3591 if (arg[0] != NUL) /* skip delimiter */
3592 ++arg;
3593 while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
3594 ++arg;
3595 if (arg[0] != NUL)
3596 return arg;
3597 break;
3598 case CMD_isearch:
3599 case CMD_dsearch:
3600 case CMD_ilist:
3601 case CMD_dlist:
3602 case CMD_ijump:
3603 case CMD_psearch:
3604 case CMD_djump:
3605 case CMD_isplit:
3606 case CMD_dsplit:
3607 arg = skipwhite(skipdigits(arg)); /* skip count */
3608 if (*arg == '/') /* Match regexp, not just whole words */
3610 for (++arg; *arg && *arg != '/'; arg++)
3611 if (*arg == '\\' && arg[1] != NUL)
3612 arg++;
3613 if (*arg)
3615 arg = skipwhite(arg + 1);
3617 /* Check for trailing illegal characters */
3618 if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
3619 xp->xp_context = EXPAND_NOTHING;
3620 else
3621 return arg;
3624 break;
3625 #ifdef FEAT_AUTOCMD
3626 case CMD_autocmd:
3627 return set_context_in_autocmd(xp, arg, FALSE);
3629 case CMD_doautocmd:
3630 case CMD_doautoall:
3631 return set_context_in_autocmd(xp, arg, TRUE);
3632 #endif
3633 case CMD_set:
3634 set_context_in_set_cmd(xp, arg, 0);
3635 break;
3636 case CMD_setglobal:
3637 set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
3638 break;
3639 case CMD_setlocal:
3640 set_context_in_set_cmd(xp, arg, OPT_LOCAL);
3641 break;
3642 case CMD_tag:
3643 case CMD_stag:
3644 case CMD_ptag:
3645 case CMD_ltag:
3646 case CMD_tselect:
3647 case CMD_stselect:
3648 case CMD_ptselect:
3649 case CMD_tjump:
3650 case CMD_stjump:
3651 case CMD_ptjump:
3652 if (*p_wop != NUL)
3653 xp->xp_context = EXPAND_TAGS_LISTFILES;
3654 else
3655 xp->xp_context = EXPAND_TAGS;
3656 xp->xp_pattern = arg;
3657 break;
3658 case CMD_augroup:
3659 xp->xp_context = EXPAND_AUGROUP;
3660 xp->xp_pattern = arg;
3661 break;
3662 #ifdef FEAT_SYN_HL
3663 case CMD_syntax:
3664 set_context_in_syntax_cmd(xp, arg);
3665 break;
3666 #endif
3667 #ifdef FEAT_EVAL
3668 case CMD_let:
3669 case CMD_if:
3670 case CMD_elseif:
3671 case CMD_while:
3672 case CMD_for:
3673 case CMD_echo:
3674 case CMD_echon:
3675 case CMD_execute:
3676 case CMD_echomsg:
3677 case CMD_echoerr:
3678 case CMD_call:
3679 case CMD_return:
3680 set_context_for_expression(xp, arg, ea.cmdidx);
3681 break;
3683 case CMD_unlet:
3684 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3685 arg = xp->xp_pattern + 1;
3686 xp->xp_context = EXPAND_USER_VARS;
3687 xp->xp_pattern = arg;
3688 break;
3690 case CMD_function:
3691 case CMD_delfunction:
3692 xp->xp_context = EXPAND_USER_FUNC;
3693 xp->xp_pattern = arg;
3694 break;
3696 case CMD_echohl:
3697 set_context_in_echohl_cmd(xp, arg);
3698 break;
3699 #endif
3700 case CMD_highlight:
3701 set_context_in_highlight_cmd(xp, arg);
3702 break;
3703 #ifdef FEAT_CSCOPE
3704 case CMD_cscope:
3705 case CMD_lcscope:
3706 case CMD_scscope:
3707 set_context_in_cscope_cmd(xp, arg, ea.cmdidx);
3708 break;
3709 #endif
3710 #ifdef FEAT_SIGNS
3711 case CMD_sign:
3712 set_context_in_sign_cmd(xp, arg);
3713 break;
3714 #endif
3715 #ifdef FEAT_LISTCMDS
3716 case CMD_bdelete:
3717 case CMD_bwipeout:
3718 case CMD_bunload:
3719 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3720 arg = xp->xp_pattern + 1;
3721 /*FALLTHROUGH*/
3722 case CMD_buffer:
3723 case CMD_sbuffer:
3724 case CMD_checktime:
3725 xp->xp_context = EXPAND_BUFFERS;
3726 xp->xp_pattern = arg;
3727 break;
3728 #endif
3729 #ifdef FEAT_USR_CMDS
3730 case CMD_USER:
3731 case CMD_USER_BUF:
3732 if (compl != EXPAND_NOTHING)
3734 /* XFILE: file names are handled above */
3735 if (!(ea.argt & XFILE))
3737 # ifdef FEAT_MENU
3738 if (compl == EXPAND_MENUS)
3739 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3740 # endif
3741 if (compl == EXPAND_COMMANDS)
3742 return arg;
3743 if (compl == EXPAND_MAPPINGS)
3744 return set_context_in_map_cmd(xp, (char_u *)"map",
3745 arg, forceit, FALSE, FALSE, CMD_map);
3746 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3747 arg = xp->xp_pattern + 1;
3748 xp->xp_pattern = arg;
3750 xp->xp_context = compl;
3752 break;
3753 #endif
3754 case CMD_map: case CMD_noremap:
3755 case CMD_nmap: case CMD_nnoremap:
3756 case CMD_vmap: case CMD_vnoremap:
3757 case CMD_omap: case CMD_onoremap:
3758 case CMD_imap: case CMD_inoremap:
3759 case CMD_cmap: case CMD_cnoremap:
3760 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3761 FALSE, FALSE, ea.cmdidx);
3762 case CMD_unmap:
3763 case CMD_nunmap:
3764 case CMD_vunmap:
3765 case CMD_ounmap:
3766 case CMD_iunmap:
3767 case CMD_cunmap:
3768 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3769 FALSE, TRUE, ea.cmdidx);
3770 case CMD_abbreviate: case CMD_noreabbrev:
3771 case CMD_cabbrev: case CMD_cnoreabbrev:
3772 case CMD_iabbrev: case CMD_inoreabbrev:
3773 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3774 TRUE, FALSE, ea.cmdidx);
3775 case CMD_unabbreviate:
3776 case CMD_cunabbrev:
3777 case CMD_iunabbrev:
3778 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3779 TRUE, TRUE, ea.cmdidx);
3780 #ifdef FEAT_MENU
3781 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
3782 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
3783 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
3784 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
3785 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
3786 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
3787 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
3788 case CMD_tmenu: case CMD_tunmenu:
3789 case CMD_popup: case CMD_tearoff: case CMD_emenu:
3790 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3791 #endif
3793 case CMD_colorscheme:
3794 xp->xp_context = EXPAND_COLORS;
3795 xp->xp_pattern = arg;
3796 break;
3798 case CMD_compiler:
3799 xp->xp_context = EXPAND_COMPILER;
3800 xp->xp_pattern = arg;
3801 break;
3803 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
3804 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
3805 case CMD_language:
3806 if (*skiptowhite(arg) == NUL)
3808 xp->xp_context = EXPAND_LANGUAGE;
3809 xp->xp_pattern = arg;
3811 else
3812 xp->xp_context = EXPAND_NOTHING;
3813 break;
3814 #endif
3815 #if defined(FEAT_PROFILE)
3816 case CMD_profile:
3817 set_context_in_profile_cmd(xp, arg);
3818 break;
3819 #endif
3820 case CMD_behave:
3821 xp->xp_context = EXPAND_BEHAVE;
3822 break;
3824 #endif /* FEAT_CMDL_COMPL */
3826 default:
3827 break;
3829 return NULL;
3833 * skip a range specifier of the form: addr [,addr] [;addr] ..
3835 * Backslashed delimiters after / or ? will be skipped, and commands will
3836 * not be expanded between /'s and ?'s or after "'".
3838 * Also skip white space and ":" characters.
3839 * Returns the "cmd" pointer advanced to beyond the range.
3841 char_u *
3842 skip_range(cmd, ctx)
3843 char_u *cmd;
3844 int *ctx; /* pointer to xp_context or NULL */
3846 unsigned delim;
3848 while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;", *cmd) != NULL)
3850 if (*cmd == '\'')
3852 if (*++cmd == NUL && ctx != NULL)
3853 *ctx = EXPAND_NOTHING;
3855 else if (*cmd == '/' || *cmd == '?')
3857 delim = *cmd++;
3858 while (*cmd != NUL && *cmd != delim)
3859 if (*cmd++ == '\\' && *cmd != NUL)
3860 ++cmd;
3861 if (*cmd == NUL && ctx != NULL)
3862 *ctx = EXPAND_NOTHING;
3864 if (*cmd != NUL)
3865 ++cmd;
3868 /* Skip ":" and white space. */
3869 while (*cmd == ':')
3870 cmd = skipwhite(cmd + 1);
3872 return cmd;
3876 * get a single EX address
3878 * Set ptr to the next character after the part that was interpreted.
3879 * Set ptr to NULL when an error is encountered.
3881 * Return MAXLNUM when no Ex address was found.
3883 static linenr_T
3884 get_address(ptr, skip, to_other_file)
3885 char_u **ptr;
3886 int skip; /* only skip the address, don't use it */
3887 int to_other_file; /* flag: may jump to other file */
3889 int c;
3890 int i;
3891 long n;
3892 char_u *cmd;
3893 pos_T pos;
3894 pos_T *fp;
3895 linenr_T lnum;
3897 cmd = skipwhite(*ptr);
3898 lnum = MAXLNUM;
3901 switch (*cmd)
3903 case '.': /* '.' - Cursor position */
3904 ++cmd;
3905 lnum = curwin->w_cursor.lnum;
3906 break;
3908 case '$': /* '$' - last line */
3909 ++cmd;
3910 lnum = curbuf->b_ml.ml_line_count;
3911 break;
3913 case '\'': /* ''' - mark */
3914 if (*++cmd == NUL)
3916 cmd = NULL;
3917 goto error;
3919 if (skip)
3920 ++cmd;
3921 else
3923 /* Only accept a mark in another file when it is
3924 * used by itself: ":'M". */
3925 fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
3926 ++cmd;
3927 if (fp == (pos_T *)-1)
3928 /* Jumped to another file. */
3929 lnum = curwin->w_cursor.lnum;
3930 else
3932 if (check_mark(fp) == FAIL)
3934 cmd = NULL;
3935 goto error;
3937 lnum = fp->lnum;
3940 break;
3942 case '/':
3943 case '?': /* '/' or '?' - search */
3944 c = *cmd++;
3945 if (skip) /* skip "/pat/" */
3947 cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
3948 if (*cmd == c)
3949 ++cmd;
3951 else
3953 pos = curwin->w_cursor; /* save curwin->w_cursor */
3955 * When '/' or '?' follows another address, start
3956 * from there.
3958 if (lnum != MAXLNUM)
3959 curwin->w_cursor.lnum = lnum;
3961 * Start a forward search at the end of the line.
3962 * Start a backward search at the start of the line.
3963 * This makes sure we never match in the current
3964 * line, and can match anywhere in the
3965 * next/previous line.
3967 if (c == '/')
3968 curwin->w_cursor.col = MAXCOL;
3969 else
3970 curwin->w_cursor.col = 0;
3971 searchcmdlen = 0;
3972 if (!do_search(NULL, c, cmd, 1L,
3973 SEARCH_HIS | SEARCH_MSG, NULL))
3975 curwin->w_cursor = pos;
3976 cmd = NULL;
3977 goto error;
3979 lnum = curwin->w_cursor.lnum;
3980 curwin->w_cursor = pos;
3981 /* adjust command string pointer */
3982 cmd += searchcmdlen;
3984 break;
3986 case '\\': /* "\?", "\/" or "\&", repeat search */
3987 ++cmd;
3988 if (*cmd == '&')
3989 i = RE_SUBST;
3990 else if (*cmd == '?' || *cmd == '/')
3991 i = RE_SEARCH;
3992 else
3994 EMSG(_(e_backslash));
3995 cmd = NULL;
3996 goto error;
3999 if (!skip)
4002 * When search follows another address, start from
4003 * there.
4005 if (lnum != MAXLNUM)
4006 pos.lnum = lnum;
4007 else
4008 pos.lnum = curwin->w_cursor.lnum;
4011 * Start the search just like for the above
4012 * do_search().
4014 if (*cmd != '?')
4015 pos.col = MAXCOL;
4016 else
4017 pos.col = 0;
4018 if (searchit(curwin, curbuf, &pos,
4019 *cmd == '?' ? BACKWARD : FORWARD,
4020 (char_u *)"", 1L, SEARCH_MSG,
4021 i, (linenr_T)0, NULL) != FAIL)
4022 lnum = pos.lnum;
4023 else
4025 cmd = NULL;
4026 goto error;
4029 ++cmd;
4030 break;
4032 default:
4033 if (VIM_ISDIGIT(*cmd)) /* absolute line number */
4034 lnum = getdigits(&cmd);
4037 for (;;)
4039 cmd = skipwhite(cmd);
4040 if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
4041 break;
4043 if (lnum == MAXLNUM)
4044 lnum = curwin->w_cursor.lnum; /* "+1" is same as ".+1" */
4045 if (VIM_ISDIGIT(*cmd))
4046 i = '+'; /* "number" is same as "+number" */
4047 else
4048 i = *cmd++;
4049 if (!VIM_ISDIGIT(*cmd)) /* '+' is '+1', but '+0' is not '+1' */
4050 n = 1;
4051 else
4052 n = getdigits(&cmd);
4053 if (i == '-')
4054 lnum -= n;
4055 else
4056 lnum += n;
4058 } while (*cmd == '/' || *cmd == '?');
4060 error:
4061 *ptr = cmd;
4062 return lnum;
4066 * Get flags from an Ex command argument.
4068 static void
4069 get_flags(eap)
4070 exarg_T *eap;
4072 while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL)
4074 if (*eap->arg == 'l')
4075 eap->flags |= EXFLAG_LIST;
4076 else if (*eap->arg == 'p')
4077 eap->flags |= EXFLAG_PRINT;
4078 else
4079 eap->flags |= EXFLAG_NR;
4080 eap->arg = skipwhite(eap->arg + 1);
4085 * Function called for command which is Not Implemented. NI!
4087 void
4088 ex_ni(eap)
4089 exarg_T *eap;
4091 if (!eap->skip)
4092 eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
4095 #ifdef HAVE_EX_SCRIPT_NI
4097 * Function called for script command which is Not Implemented. NI!
4098 * Skips over ":perl <<EOF" constructs.
4100 static void
4101 ex_script_ni(eap)
4102 exarg_T *eap;
4104 if (!eap->skip)
4105 ex_ni(eap);
4106 else
4107 vim_free(script_get(eap, eap->arg));
4109 #endif
4112 * Check range in Ex command for validity.
4113 * Return NULL when valid, error message when invalid.
4115 static char_u *
4116 invalid_range(eap)
4117 exarg_T *eap;
4119 if ( eap->line1 < 0
4120 || eap->line2 < 0
4121 || eap->line1 > eap->line2
4122 || ((eap->argt & RANGE)
4123 && !(eap->argt & NOTADR)
4124 && eap->line2 > curbuf->b_ml.ml_line_count
4125 #ifdef FEAT_DIFF
4126 + (eap->cmdidx == CMD_diffget)
4127 #endif
4129 return (char_u *)_(e_invrange);
4130 return NULL;
4134 * Correct the range for zero line number, if required.
4136 static void
4137 correct_range(eap)
4138 exarg_T *eap;
4140 if (!(eap->argt & ZEROR)) /* zero in range not allowed */
4142 if (eap->line1 == 0)
4143 eap->line1 = 1;
4144 if (eap->line2 == 0)
4145 eap->line2 = 1;
4149 #ifdef FEAT_QUICKFIX
4150 static char_u *skip_grep_pat __ARGS((exarg_T *eap));
4153 * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
4154 * pattern. Otherwise return eap->arg.
4156 static char_u *
4157 skip_grep_pat(eap)
4158 exarg_T *eap;
4160 char_u *p = eap->arg;
4162 if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
4163 || eap->cmdidx == CMD_vimgrepadd
4164 || eap->cmdidx == CMD_lvimgrepadd
4165 || grep_internal(eap->cmdidx)))
4167 p = skip_vimgrep_pat(p, NULL, NULL);
4168 if (p == NULL)
4169 p = eap->arg;
4171 return p;
4175 * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
4176 * in the command line, so that things like % get expanded.
4178 static char_u *
4179 replace_makeprg(eap, p, cmdlinep)
4180 exarg_T *eap;
4181 char_u *p;
4182 char_u **cmdlinep;
4184 char_u *new_cmdline;
4185 char_u *program;
4186 char_u *pos;
4187 char_u *ptr;
4188 int len;
4189 int i;
4192 * Don't do it when ":vimgrep" is used for ":grep".
4194 if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake
4195 || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4196 || eap->cmdidx == CMD_grepadd
4197 || eap->cmdidx == CMD_lgrepadd)
4198 && !grep_internal(eap->cmdidx))
4200 if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4201 || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd)
4203 if (*curbuf->b_p_gp == NUL)
4204 program = p_gp;
4205 else
4206 program = curbuf->b_p_gp;
4208 else
4210 if (*curbuf->b_p_mp == NUL)
4211 program = p_mp;
4212 else
4213 program = curbuf->b_p_mp;
4216 p = skipwhite(p);
4218 if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4220 /* replace $* by given arguments */
4221 i = 1;
4222 while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
4223 ++i;
4224 len = (int)STRLEN(p);
4225 new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
4226 if (new_cmdline == NULL)
4227 return NULL; /* out of memory */
4228 ptr = new_cmdline;
4229 while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4231 i = (int)(pos - program);
4232 STRNCPY(ptr, program, i);
4233 STRCPY(ptr += i, p);
4234 ptr += len;
4235 program = pos + 2;
4237 STRCPY(ptr, program);
4239 else
4241 new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
4242 if (new_cmdline == NULL)
4243 return NULL; /* out of memory */
4244 STRCPY(new_cmdline, program);
4245 STRCAT(new_cmdline, " ");
4246 STRCAT(new_cmdline, p);
4248 msg_make(p);
4250 /* 'eap->cmd' is not set here, because it is not used at CMD_make */
4251 vim_free(*cmdlinep);
4252 *cmdlinep = new_cmdline;
4253 p = new_cmdline;
4255 return p;
4257 #endif
4260 * Expand file name in Ex command argument.
4261 * Return FAIL for failure, OK otherwise.
4264 expand_filename(eap, cmdlinep, errormsgp)
4265 exarg_T *eap;
4266 char_u **cmdlinep;
4267 char_u **errormsgp;
4269 int has_wildcards; /* need to expand wildcards */
4270 char_u *repl;
4271 int srclen;
4272 char_u *p;
4273 int n;
4274 int escaped;
4276 #ifdef FEAT_QUICKFIX
4277 /* Skip a regexp pattern for ":vimgrep[add] pat file..." */
4278 p = skip_grep_pat(eap);
4279 #else
4280 p = eap->arg;
4281 #endif
4284 * Decide to expand wildcards *before* replacing '%', '#', etc. If
4285 * the file name contains a wildcard it should not cause expanding.
4286 * (it will be expanded anyway if there is a wildcard before replacing).
4288 has_wildcards = mch_has_wildcard(p);
4289 while (*p != NUL)
4291 #ifdef FEAT_EVAL
4292 /* Skip over `=expr`, wildcards in it are not expanded. */
4293 if (p[0] == '`' && p[1] == '=')
4295 p += 2;
4296 (void)skip_expr(&p);
4297 if (*p == '`')
4298 ++p;
4299 continue;
4301 #endif
4303 * Quick check if this cannot be the start of a special string.
4304 * Also removes backslash before '%', '#' and '<'.
4306 if (vim_strchr((char_u *)"%#<", *p) == NULL)
4308 ++p;
4309 continue;
4313 * Try to find a match at this position.
4315 repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
4316 errormsgp, &escaped);
4317 if (*errormsgp != NULL) /* error detected */
4318 return FAIL;
4319 if (repl == NULL) /* no match found */
4321 p += srclen;
4322 continue;
4325 /* Wildcards won't be expanded below, the replacement is taken
4326 * literally. But do expand "~/file", "~user/file" and "$HOME/file". */
4327 if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
4329 char_u *l = repl;
4331 repl = expand_env_save(repl);
4332 vim_free(l);
4335 /* Need to escape white space et al. with a backslash.
4336 * Don't do this for:
4337 * - replacement that already has been escaped: "##"
4338 * - shell commands (may have to use quotes instead).
4339 * - non-unix systems when there is a single argument (spaces don't
4340 * separate arguments then).
4342 if (!eap->usefilter
4343 && !escaped
4344 && eap->cmdidx != CMD_bang
4345 && eap->cmdidx != CMD_make
4346 && eap->cmdidx != CMD_lmake
4347 && eap->cmdidx != CMD_grep
4348 && eap->cmdidx != CMD_lgrep
4349 && eap->cmdidx != CMD_grepadd
4350 && eap->cmdidx != CMD_lgrepadd
4351 #ifndef UNIX
4352 && !(eap->argt & NOSPC)
4353 #endif
4356 char_u *l;
4357 #ifdef BACKSLASH_IN_FILENAME
4358 /* Don't escape a backslash here, because rem_backslash() doesn't
4359 * remove it later. */
4360 static char_u *nobslash = (char_u *)" \t\"|";
4361 # define ESCAPE_CHARS nobslash
4362 #else
4363 # define ESCAPE_CHARS escape_chars
4364 #endif
4366 for (l = repl; *l; ++l)
4367 if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
4369 l = vim_strsave_escaped(repl, ESCAPE_CHARS);
4370 if (l != NULL)
4372 vim_free(repl);
4373 repl = l;
4375 break;
4379 /* For a shell command a '!' must be escaped. */
4380 if ((eap->usefilter || eap->cmdidx == CMD_bang)
4381 && vim_strpbrk(repl, (char_u *)"!&;()<>") != NULL)
4383 char_u *l;
4385 l = vim_strsave_escaped(repl, (char_u *)"!&;()<>");
4386 if (l != NULL)
4388 vim_free(repl);
4389 repl = l;
4390 /* For a sh-like shell escape "!" another time. */
4391 if (strstr((char *)p_sh, "sh") != NULL)
4393 l = vim_strsave_escaped(repl, (char_u *)"!");
4394 if (l != NULL)
4396 vim_free(repl);
4397 repl = l;
4403 p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4404 vim_free(repl);
4405 if (p == NULL)
4406 return FAIL;
4410 * One file argument: Expand wildcards.
4411 * Don't do this with ":r !command" or ":w !command".
4413 if ((eap->argt & NOSPC) && !eap->usefilter)
4416 * May do this twice:
4417 * 1. Replace environment variables.
4418 * 2. Replace any other wildcards, remove backslashes.
4420 for (n = 1; n <= 2; ++n)
4422 if (n == 2)
4424 #ifdef UNIX
4426 * Only for Unix we check for more than one file name.
4427 * For other systems spaces are considered to be part
4428 * of the file name.
4429 * Only check here if there is no wildcard, otherwise
4430 * ExpandOne() will check for errors. This allows
4431 * ":e `ls ve*.c`" on Unix.
4433 if (!has_wildcards)
4434 for (p = eap->arg; *p; ++p)
4436 /* skip escaped characters */
4437 if (p[1] && (*p == '\\' || *p == Ctrl_V))
4438 ++p;
4439 else if (vim_iswhite(*p))
4441 *errormsgp = (char_u *)_("E172: Only one file name allowed");
4442 return FAIL;
4445 #endif
4448 * Halve the number of backslashes (this is Vi compatible).
4449 * For Unix and OS/2, when wildcards are expanded, this is
4450 * done by ExpandOne() below.
4452 #if defined(UNIX) || defined(OS2)
4453 if (!has_wildcards)
4454 #endif
4455 backslash_halve(eap->arg);
4458 if (has_wildcards)
4460 if (n == 1)
4463 * First loop: May expand environment variables. This
4464 * can be done much faster with expand_env() than with
4465 * something else (e.g., calling a shell).
4466 * After expanding environment variables, check again
4467 * if there are still wildcards present.
4469 if (vim_strchr(eap->arg, '$') != NULL
4470 || vim_strchr(eap->arg, '~') != NULL)
4472 expand_env_esc(eap->arg, NameBuff, MAXPATHL,
4473 TRUE, TRUE, NULL);
4474 has_wildcards = mch_has_wildcard(NameBuff);
4475 p = NameBuff;
4477 else
4478 p = NULL;
4480 else /* n == 2 */
4482 expand_T xpc;
4484 ExpandInit(&xpc);
4485 xpc.xp_context = EXPAND_FILES;
4486 p = ExpandOne(&xpc, eap->arg, NULL,
4487 WILD_LIST_NOTFOUND|WILD_ADD_SLASH,
4488 WILD_EXPAND_FREE);
4489 if (p == NULL)
4490 return FAIL;
4492 if (p != NULL)
4494 (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
4495 p, cmdlinep);
4496 if (n == 2) /* p came from ExpandOne() */
4497 vim_free(p);
4502 return OK;
4506 * Replace part of the command line, keeping eap->cmd, eap->arg and
4507 * eap->nextcmd correct.
4508 * "src" points to the part that is to be replaced, of length "srclen".
4509 * "repl" is the replacement string.
4510 * Returns a pointer to the character after the replaced string.
4511 * Returns NULL for failure.
4513 static char_u *
4514 repl_cmdline(eap, src, srclen, repl, cmdlinep)
4515 exarg_T *eap;
4516 char_u *src;
4517 int srclen;
4518 char_u *repl;
4519 char_u **cmdlinep;
4521 int len;
4522 int i;
4523 char_u *new_cmdline;
4526 * The new command line is build in new_cmdline[].
4527 * First allocate it.
4528 * Careful: a "+cmd" argument may have been NUL terminated.
4530 len = (int)STRLEN(repl);
4531 i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
4532 if (eap->nextcmd != NULL)
4533 i += (int)STRLEN(eap->nextcmd);/* add space for next command */
4534 if ((new_cmdline = alloc((unsigned)i)) == NULL)
4535 return NULL; /* out of memory! */
4538 * Copy the stuff before the expanded part.
4539 * Copy the expanded stuff.
4540 * Copy what came after the expanded part.
4541 * Copy the next commands, if there are any.
4543 i = (int)(src - *cmdlinep); /* length of part before match */
4544 mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
4546 mch_memmove(new_cmdline + i, repl, (size_t)len);
4547 i += len; /* remember the end of the string */
4548 STRCPY(new_cmdline + i, src + srclen);
4549 src = new_cmdline + i; /* remember where to continue */
4551 if (eap->nextcmd != NULL) /* append next command */
4553 i = (int)STRLEN(new_cmdline) + 1;
4554 STRCPY(new_cmdline + i, eap->nextcmd);
4555 eap->nextcmd = new_cmdline + i;
4557 eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4558 eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4559 if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
4560 eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4561 vim_free(*cmdlinep);
4562 *cmdlinep = new_cmdline;
4564 return src;
4568 * Check for '|' to separate commands and '"' to start comments.
4570 void
4571 separate_nextcmd(eap)
4572 exarg_T *eap;
4574 char_u *p;
4576 #ifdef FEAT_QUICKFIX
4577 p = skip_grep_pat(eap);
4578 #else
4579 p = eap->arg;
4580 #endif
4582 for ( ; *p; mb_ptr_adv(p))
4584 if (*p == Ctrl_V)
4586 if (eap->argt & (USECTRLV | XFILE))
4587 ++p; /* skip CTRL-V and next char */
4588 else
4589 /* remove CTRL-V and skip next char */
4590 STRMOVE(p, p + 1);
4591 if (*p == NUL) /* stop at NUL after CTRL-V */
4592 break;
4595 #ifdef FEAT_EVAL
4596 /* Skip over `=expr` when wildcards are expanded. */
4597 else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE))
4599 p += 2;
4600 (void)skip_expr(&p);
4602 #endif
4604 /* Check for '"': start of comment or '|': next command */
4605 /* :@" and :*" do not start a comment!
4606 * :redir @" doesn't either. */
4607 else if ((*p == '"' && !(eap->argt & NOTRLCOM)
4608 && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
4609 || p != eap->arg)
4610 && (eap->cmdidx != CMD_redir
4611 || p != eap->arg + 1 || p[-1] != '@'))
4612 || *p == '|' || *p == '\n')
4615 * We remove the '\' before the '|', unless USECTRLV is used
4616 * AND 'b' is present in 'cpoptions'.
4618 if ((vim_strchr(p_cpo, CPO_BAR) == NULL
4619 || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
4621 STRMOVE(p - 1, p); /* remove the '\' */
4622 --p;
4624 else
4626 eap->nextcmd = check_nextcmd(p);
4627 *p = NUL;
4628 break;
4633 if (!(eap->argt & NOTRLCOM)) /* remove trailing spaces */
4634 del_trailing_spaces(eap->arg);
4638 * get + command from ex argument
4640 static char_u *
4641 getargcmd(argp)
4642 char_u **argp;
4644 char_u *arg = *argp;
4645 char_u *command = NULL;
4647 if (*arg == '+') /* +[command] */
4649 ++arg;
4650 if (vim_isspace(*arg))
4651 command = dollar_command;
4652 else
4654 command = arg;
4655 arg = skip_cmd_arg(command, TRUE);
4656 if (*arg != NUL)
4657 *arg++ = NUL; /* terminate command with NUL */
4660 arg = skipwhite(arg); /* skip over spaces */
4661 *argp = arg;
4663 return command;
4667 * Find end of "+command" argument. Skip over "\ " and "\\".
4669 static char_u *
4670 skip_cmd_arg(p, rembs)
4671 char_u *p;
4672 int rembs; /* TRUE to halve the number of backslashes */
4674 while (*p && !vim_isspace(*p))
4676 if (*p == '\\' && p[1] != NUL)
4678 if (rembs)
4679 STRMOVE(p, p + 1);
4680 else
4681 ++p;
4683 mb_ptr_adv(p);
4685 return p;
4689 * Get "++opt=arg" argument.
4690 * Return FAIL or OK.
4692 static int
4693 getargopt(eap)
4694 exarg_T *eap;
4696 char_u *arg = eap->arg + 2;
4697 int *pp = NULL;
4698 #ifdef FEAT_MBYTE
4699 char_u *p;
4700 #endif
4702 /* ":edit ++[no]bin[ary] file" */
4703 if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4705 if (*arg == 'n')
4707 arg += 2;
4708 eap->force_bin = FORCE_NOBIN;
4710 else
4711 eap->force_bin = FORCE_BIN;
4712 if (!checkforcmd(&arg, "binary", 3))
4713 return FAIL;
4714 eap->arg = skipwhite(arg);
4715 return OK;
4718 /* ":read ++edit file" */
4719 if (STRNCMP(arg, "edit", 4) == 0)
4721 eap->read_edit = TRUE;
4722 eap->arg = skipwhite(arg + 4);
4723 return OK;
4726 if (STRNCMP(arg, "ff", 2) == 0)
4728 arg += 2;
4729 pp = &eap->force_ff;
4731 else if (STRNCMP(arg, "fileformat", 10) == 0)
4733 arg += 10;
4734 pp = &eap->force_ff;
4736 #ifdef FEAT_MBYTE
4737 else if (STRNCMP(arg, "enc", 3) == 0)
4739 arg += 3;
4740 pp = &eap->force_enc;
4742 else if (STRNCMP(arg, "encoding", 8) == 0)
4744 arg += 8;
4745 pp = &eap->force_enc;
4747 else if (STRNCMP(arg, "bad", 3) == 0)
4749 arg += 3;
4750 pp = &eap->bad_char_idx;
4752 #endif
4754 if (pp == NULL || *arg != '=')
4755 return FAIL;
4757 ++arg;
4758 *pp = (int)(arg - eap->cmd);
4759 arg = skip_cmd_arg(arg, FALSE);
4760 eap->arg = skipwhite(arg);
4761 *arg = NUL;
4763 #ifdef FEAT_MBYTE
4764 if (pp == &eap->force_ff)
4766 #endif
4767 if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4768 return FAIL;
4769 #ifdef FEAT_MBYTE
4771 else if (pp == &eap->force_enc)
4773 /* Make 'fileencoding' lower case. */
4774 for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4775 *p = TOLOWER_ASC(*p);
4777 else
4779 /* Check ++bad= argument. Must be a single-byte character, "keep" or
4780 * "drop". */
4781 p = eap->cmd + eap->bad_char_idx;
4782 if (STRICMP(p, "keep") == 0)
4783 eap->bad_char = BAD_KEEP;
4784 else if (STRICMP(p, "drop") == 0)
4785 eap->bad_char = BAD_DROP;
4786 else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
4787 eap->bad_char = *p;
4788 else
4789 return FAIL;
4791 #endif
4793 return OK;
4797 * ":abbreviate" and friends.
4799 static void
4800 ex_abbreviate(eap)
4801 exarg_T *eap;
4803 do_exmap(eap, TRUE); /* almost the same as mapping */
4807 * ":map" and friends.
4809 static void
4810 ex_map(eap)
4811 exarg_T *eap;
4814 * If we are sourcing .exrc or .vimrc in current directory we
4815 * print the mappings for security reasons.
4817 if (secure)
4819 secure = 2;
4820 msg_outtrans(eap->cmd);
4821 msg_putchar('\n');
4823 do_exmap(eap, FALSE);
4827 * ":unmap" and friends.
4829 static void
4830 ex_unmap(eap)
4831 exarg_T *eap;
4833 do_exmap(eap, FALSE);
4837 * ":mapclear" and friends.
4839 static void
4840 ex_mapclear(eap)
4841 exarg_T *eap;
4843 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4847 * ":abclear" and friends.
4849 static void
4850 ex_abclear(eap)
4851 exarg_T *eap;
4853 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4856 #ifdef FEAT_AUTOCMD
4857 static void
4858 ex_autocmd(eap)
4859 exarg_T *eap;
4862 * Disallow auto commands from .exrc and .vimrc in current
4863 * directory for security reasons.
4865 if (secure)
4867 secure = 2;
4868 eap->errmsg = e_curdir;
4870 else if (eap->cmdidx == CMD_autocmd)
4871 do_autocmd(eap->arg, eap->forceit);
4872 else
4873 do_augroup(eap->arg, eap->forceit);
4877 * ":doautocmd": Apply the automatic commands to the current buffer.
4879 static void
4880 ex_doautocmd(eap)
4881 exarg_T *eap;
4883 (void)do_doautocmd(eap->arg, TRUE);
4884 do_modelines(0);
4886 #endif
4888 #ifdef FEAT_LISTCMDS
4890 * :[N]bunload[!] [N] [bufname] unload buffer
4891 * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4892 * :[N]bwipeout[!] [N] [bufname] delete buffer really
4894 static void
4895 ex_bunload(eap)
4896 exarg_T *eap;
4898 eap->errmsg = do_bufdel(
4899 eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4900 : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4901 : DOBUF_UNLOAD, eap->arg,
4902 eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4906 * :[N]buffer [N] to buffer N
4907 * :[N]sbuffer [N] to buffer N
4909 static void
4910 ex_buffer(eap)
4911 exarg_T *eap;
4913 if (*eap->arg)
4914 eap->errmsg = e_trailing;
4915 else
4917 if (eap->addr_count == 0) /* default is current buffer */
4918 goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4919 else
4920 goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4925 * :[N]bmodified [N] to next mod. buffer
4926 * :[N]sbmodified [N] to next mod. buffer
4928 static void
4929 ex_bmodified(eap)
4930 exarg_T *eap;
4932 goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4936 * :[N]bnext [N] to next buffer
4937 * :[N]sbnext [N] split and to next buffer
4939 static void
4940 ex_bnext(eap)
4941 exarg_T *eap;
4943 goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4947 * :[N]bNext [N] to previous buffer
4948 * :[N]bprevious [N] to previous buffer
4949 * :[N]sbNext [N] split and to previous buffer
4950 * :[N]sbprevious [N] split and to previous buffer
4952 static void
4953 ex_bprevious(eap)
4954 exarg_T *eap;
4956 goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4960 * :brewind to first buffer
4961 * :bfirst to first buffer
4962 * :sbrewind split and to first buffer
4963 * :sbfirst split and to first buffer
4965 static void
4966 ex_brewind(eap)
4967 exarg_T *eap;
4969 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4973 * :blast to last buffer
4974 * :sblast split and to last buffer
4976 static void
4977 ex_blast(eap)
4978 exarg_T *eap;
4980 goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4982 #endif
4985 ends_excmd(c)
4986 int c;
4988 return (c == NUL || c == '|' || c == '"' || c == '\n');
4991 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
4992 || defined(PROTO)
4994 * Return the next command, after the first '|' or '\n'.
4995 * Return NULL if not found.
4997 char_u *
4998 find_nextcmd(p)
4999 char_u *p;
5001 while (*p != '|' && *p != '\n')
5003 if (*p == NUL)
5004 return NULL;
5005 ++p;
5007 return (p + 1);
5009 #endif
5012 * Check if *p is a separator between Ex commands.
5013 * Return NULL if it isn't, (p + 1) if it is.
5015 char_u *
5016 check_nextcmd(p)
5017 char_u *p;
5019 p = skipwhite(p);
5020 if (*p == '|' || *p == '\n')
5021 return (p + 1);
5022 else
5023 return NULL;
5027 * - if there are more files to edit
5028 * - and this is the last window
5029 * - and forceit not used
5030 * - and not repeated twice on a row
5031 * return FAIL and give error message if 'message' TRUE
5032 * return OK otherwise
5034 static int
5035 check_more(message, forceit)
5036 int message; /* when FALSE check only, no messages */
5037 int forceit;
5039 int n = ARGCOUNT - curwin->w_arg_idx - 1;
5041 if (!forceit && only_one_window()
5042 && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5044 if (message)
5046 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5047 if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5049 char_u buff[IOSIZE];
5051 if (n == 1)
5052 STRCPY(buff, _("1 more file to edit. Quit anyway?"));
5053 else
5054 vim_snprintf((char *)buff, IOSIZE,
5055 _("%d more files to edit. Quit anyway?"), n);
5056 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5057 return OK;
5058 return FAIL;
5060 #endif
5061 if (n == 1)
5062 EMSG(_("E173: 1 more file to edit"));
5063 else
5064 EMSGN(_("E173: %ld more files to edit"), n);
5065 quitmore = 2; /* next try to quit is allowed */
5067 return FAIL;
5069 return OK;
5072 #ifdef FEAT_CMDL_COMPL
5074 * Function given to ExpandGeneric() to obtain the list of command names.
5076 char_u *
5077 get_command_name(xp, idx)
5078 expand_T *xp UNUSED;
5079 int idx;
5081 if (idx >= (int)CMD_SIZE)
5082 # ifdef FEAT_USR_CMDS
5083 return get_user_command_name(idx);
5084 # else
5085 return NULL;
5086 # endif
5087 return cmdnames[idx].cmd_name;
5089 #endif
5091 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5092 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));
5093 static void uc_list __ARGS((char_u *name, size_t name_len));
5094 static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
5095 static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp));
5096 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));
5098 static int
5099 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
5100 char_u *name;
5101 size_t name_len;
5102 char_u *rep;
5103 long argt;
5104 long def;
5105 int flags;
5106 int compl;
5107 char_u *compl_arg;
5108 int force;
5110 ucmd_T *cmd = NULL;
5111 char_u *p;
5112 int i;
5113 int cmp = 1;
5114 char_u *rep_buf = NULL;
5115 garray_T *gap;
5117 replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5118 if (rep_buf == NULL)
5120 /* Can't replace termcodes - try using the string as is */
5121 rep_buf = vim_strsave(rep);
5123 /* Give up if out of memory */
5124 if (rep_buf == NULL)
5125 return FAIL;
5128 /* get address of growarray: global or in curbuf */
5129 if (flags & UC_BUFFER)
5131 gap = &curbuf->b_ucmds;
5132 if (gap->ga_itemsize == 0)
5133 ga_init2(gap, (int)sizeof(ucmd_T), 4);
5135 else
5136 gap = &ucmds;
5138 /* Search for the command in the already defined commands. */
5139 for (i = 0; i < gap->ga_len; ++i)
5141 size_t len;
5143 cmd = USER_CMD_GA(gap, i);
5144 len = STRLEN(cmd->uc_name);
5145 cmp = STRNCMP(name, cmd->uc_name, name_len);
5146 if (cmp == 0)
5148 if (name_len < len)
5149 cmp = -1;
5150 else if (name_len > len)
5151 cmp = 1;
5154 if (cmp == 0)
5156 if (!force)
5158 EMSG(_("E174: Command already exists: add ! to replace it"));
5159 goto fail;
5162 vim_free(cmd->uc_rep);
5163 cmd->uc_rep = NULL;
5164 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5165 vim_free(cmd->uc_compl_arg);
5166 cmd->uc_compl_arg = NULL;
5167 #endif
5168 break;
5171 /* Stop as soon as we pass the name to add */
5172 if (cmp < 0)
5173 break;
5176 /* Extend the array unless we're replacing an existing command */
5177 if (cmp != 0)
5179 if (ga_grow(gap, 1) != OK)
5180 goto fail;
5181 if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5182 goto fail;
5184 cmd = USER_CMD_GA(gap, i);
5185 mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5187 ++gap->ga_len;
5189 cmd->uc_name = p;
5192 cmd->uc_rep = rep_buf;
5193 cmd->uc_argt = argt;
5194 cmd->uc_def = def;
5195 cmd->uc_compl = compl;
5196 #ifdef FEAT_EVAL
5197 cmd->uc_scriptID = current_SID;
5198 # ifdef FEAT_CMDL_COMPL
5199 cmd->uc_compl_arg = compl_arg;
5200 # endif
5201 #endif
5203 return OK;
5205 fail:
5206 vim_free(rep_buf);
5207 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5208 vim_free(compl_arg);
5209 #endif
5210 return FAIL;
5214 * List of names for completion for ":command" with the EXPAND_ flag.
5215 * Must be alphabetical for completion.
5217 static struct
5219 int expand;
5220 char *name;
5221 } command_complete[] =
5223 {EXPAND_AUGROUP, "augroup"},
5224 {EXPAND_BUFFERS, "buffer"},
5225 {EXPAND_COMMANDS, "command"},
5226 #if defined(FEAT_CSCOPE)
5227 {EXPAND_CSCOPE, "cscope"},
5228 #endif
5229 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5230 {EXPAND_USER_DEFINED, "custom"},
5231 {EXPAND_USER_LIST, "customlist"},
5232 #endif
5233 {EXPAND_DIRECTORIES, "dir"},
5234 {EXPAND_ENV_VARS, "environment"},
5235 {EXPAND_EVENTS, "event"},
5236 {EXPAND_EXPRESSION, "expression"},
5237 {EXPAND_FILES, "file"},
5238 {EXPAND_FUNCTIONS, "function"},
5239 {EXPAND_HELP, "help"},
5240 {EXPAND_HIGHLIGHT, "highlight"},
5241 {EXPAND_MAPPINGS, "mapping"},
5242 {EXPAND_MENUS, "menu"},
5243 {EXPAND_SETTINGS, "option"},
5244 {EXPAND_SHELLCMD, "shellcmd"},
5245 #if defined(FEAT_SIGNS)
5246 {EXPAND_SIGN, "sign"},
5247 #endif
5248 {EXPAND_TAGS, "tag"},
5249 {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5250 {EXPAND_USER_VARS, "var"},
5251 {0, NULL}
5254 static void
5255 uc_list(name, name_len)
5256 char_u *name;
5257 size_t name_len;
5259 int i, j;
5260 int found = FALSE;
5261 ucmd_T *cmd;
5262 int len;
5263 long a;
5264 garray_T *gap;
5266 gap = &curbuf->b_ucmds;
5267 for (;;)
5269 for (i = 0; i < gap->ga_len; ++i)
5271 cmd = USER_CMD_GA(gap, i);
5272 a = (long)cmd->uc_argt;
5274 /* Skip commands which don't match the requested prefix */
5275 if (STRNCMP(name, cmd->uc_name, name_len) != 0)
5276 continue;
5278 /* Put out the title first time */
5279 if (!found)
5280 MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition"));
5281 found = TRUE;
5282 msg_putchar('\n');
5283 if (got_int)
5284 break;
5286 /* Special cases */
5287 msg_putchar(a & BANG ? '!' : ' ');
5288 msg_putchar(a & REGSTR ? '"' : ' ');
5289 msg_putchar(gap != &ucmds ? 'b' : ' ');
5290 msg_putchar(' ');
5292 msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
5293 len = (int)STRLEN(cmd->uc_name) + 4;
5295 do {
5296 msg_putchar(' ');
5297 ++len;
5298 } while (len < 16);
5300 len = 0;
5302 /* Arguments */
5303 switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
5305 case 0: IObuff[len++] = '0'; break;
5306 case (EXTRA): IObuff[len++] = '*'; break;
5307 case (EXTRA|NOSPC): IObuff[len++] = '?'; break;
5308 case (EXTRA|NEEDARG): IObuff[len++] = '+'; break;
5309 case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
5312 do {
5313 IObuff[len++] = ' ';
5314 } while (len < 5);
5316 /* Range */
5317 if (a & (RANGE|COUNT))
5319 if (a & COUNT)
5321 /* -count=N */
5322 sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
5323 len += (int)STRLEN(IObuff + len);
5325 else if (a & DFLALL)
5326 IObuff[len++] = '%';
5327 else if (cmd->uc_def >= 0)
5329 /* -range=N */
5330 sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
5331 len += (int)STRLEN(IObuff + len);
5333 else
5334 IObuff[len++] = '.';
5337 do {
5338 IObuff[len++] = ' ';
5339 } while (len < 11);
5341 /* Completion */
5342 for (j = 0; command_complete[j].expand != 0; ++j)
5343 if (command_complete[j].expand == cmd->uc_compl)
5345 STRCPY(IObuff + len, command_complete[j].name);
5346 len += (int)STRLEN(IObuff + len);
5347 break;
5350 do {
5351 IObuff[len++] = ' ';
5352 } while (len < 21);
5354 IObuff[len] = '\0';
5355 msg_outtrans(IObuff);
5357 msg_outtrans_special(cmd->uc_rep, FALSE);
5358 #ifdef FEAT_EVAL
5359 if (p_verbose > 0)
5360 last_set_msg(cmd->uc_scriptID);
5361 #endif
5362 out_flush();
5363 ui_breakcheck();
5364 if (got_int)
5365 break;
5367 if (gap == &ucmds || i < gap->ga_len)
5368 break;
5369 gap = &ucmds;
5372 if (!found)
5373 MSG(_("No user-defined commands found"));
5376 static char_u *
5377 uc_fun_cmd()
5379 static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
5380 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
5381 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
5382 0xb9, 0x7f, 0};
5383 int i;
5385 for (i = 0; fcmd[i]; ++i)
5386 IObuff[i] = fcmd[i] - 0x40;
5387 IObuff[i] = 0;
5388 return IObuff;
5391 static int
5392 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
5393 char_u *attr;
5394 size_t len;
5395 long *argt;
5396 long *def;
5397 int *flags;
5398 int *compl;
5399 char_u **compl_arg;
5401 char_u *p;
5403 if (len == 0)
5405 EMSG(_("E175: No attribute specified"));
5406 return FAIL;
5409 /* First, try the simple attributes (no arguments) */
5410 if (STRNICMP(attr, "bang", len) == 0)
5411 *argt |= BANG;
5412 else if (STRNICMP(attr, "buffer", len) == 0)
5413 *flags |= UC_BUFFER;
5414 else if (STRNICMP(attr, "register", len) == 0)
5415 *argt |= REGSTR;
5416 else if (STRNICMP(attr, "bar", len) == 0)
5417 *argt |= TRLBAR;
5418 else
5420 int i;
5421 char_u *val = NULL;
5422 size_t vallen = 0;
5423 size_t attrlen = len;
5425 /* Look for the attribute name - which is the part before any '=' */
5426 for (i = 0; i < (int)len; ++i)
5428 if (attr[i] == '=')
5430 val = &attr[i + 1];
5431 vallen = len - i - 1;
5432 attrlen = i;
5433 break;
5437 if (STRNICMP(attr, "nargs", attrlen) == 0)
5439 if (vallen == 1)
5441 if (*val == '0')
5442 /* Do nothing - this is the default */;
5443 else if (*val == '1')
5444 *argt |= (EXTRA | NOSPC | NEEDARG);
5445 else if (*val == '*')
5446 *argt |= EXTRA;
5447 else if (*val == '?')
5448 *argt |= (EXTRA | NOSPC);
5449 else if (*val == '+')
5450 *argt |= (EXTRA | NEEDARG);
5451 else
5452 goto wrong_nargs;
5454 else
5456 wrong_nargs:
5457 EMSG(_("E176: Invalid number of arguments"));
5458 return FAIL;
5461 else if (STRNICMP(attr, "range", attrlen) == 0)
5463 *argt |= RANGE;
5464 if (vallen == 1 && *val == '%')
5465 *argt |= DFLALL;
5466 else if (val != NULL)
5468 p = val;
5469 if (*def >= 0)
5471 two_count:
5472 EMSG(_("E177: Count cannot be specified twice"));
5473 return FAIL;
5476 *def = getdigits(&p);
5477 *argt |= (ZEROR | NOTADR);
5479 if (p != val + vallen || vallen == 0)
5481 invalid_count:
5482 EMSG(_("E178: Invalid default value for count"));
5483 return FAIL;
5487 else if (STRNICMP(attr, "count", attrlen) == 0)
5489 *argt |= (COUNT | ZEROR | RANGE | NOTADR);
5491 if (val != NULL)
5493 p = val;
5494 if (*def >= 0)
5495 goto two_count;
5497 *def = getdigits(&p);
5499 if (p != val + vallen)
5500 goto invalid_count;
5503 if (*def < 0)
5504 *def = 0;
5506 else if (STRNICMP(attr, "complete", attrlen) == 0)
5508 if (val == NULL)
5510 EMSG(_("E179: argument required for -complete"));
5511 return FAIL;
5514 if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
5515 == FAIL)
5516 return FAIL;
5518 else
5520 char_u ch = attr[len];
5521 attr[len] = '\0';
5522 EMSG2(_("E181: Invalid attribute: %s"), attr);
5523 attr[len] = ch;
5524 return FAIL;
5528 return OK;
5532 * ":command ..."
5534 static void
5535 ex_command(eap)
5536 exarg_T *eap;
5538 char_u *name;
5539 char_u *end;
5540 char_u *p;
5541 long argt = 0;
5542 long def = -1;
5543 int flags = 0;
5544 int compl = EXPAND_NOTHING;
5545 char_u *compl_arg = NULL;
5546 int has_attr = (eap->arg[0] == '-');
5548 p = eap->arg;
5550 /* Check for attributes */
5551 while (*p == '-')
5553 ++p;
5554 end = skiptowhite(p);
5555 if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5556 == FAIL)
5557 return;
5558 p = skipwhite(end);
5561 /* Get the name (if any) and skip to the following argument */
5562 name = p;
5563 if (ASCII_ISALPHA(*p))
5564 while (ASCII_ISALNUM(*p))
5565 ++p;
5566 if (!ends_excmd(*p) && !vim_iswhite(*p))
5568 EMSG(_("E182: Invalid command name"));
5569 return;
5571 end = p;
5573 /* If there is nothing after the name, and no attributes were specified,
5574 * we are listing commands
5576 p = skipwhite(end);
5577 if (!has_attr && ends_excmd(*p))
5579 uc_list(name, end - name);
5581 else if (!ASCII_ISUPPER(*name))
5583 EMSG(_("E183: User defined commands must start with an uppercase letter"));
5584 return;
5586 else
5587 uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5588 eap->forceit);
5592 * ":comclear"
5593 * Clear all user commands, global and for current buffer.
5595 void
5596 ex_comclear(eap)
5597 exarg_T *eap UNUSED;
5599 uc_clear(&ucmds);
5600 uc_clear(&curbuf->b_ucmds);
5604 * Clear all user commands for "gap".
5606 void
5607 uc_clear(gap)
5608 garray_T *gap;
5610 int i;
5611 ucmd_T *cmd;
5613 for (i = 0; i < gap->ga_len; ++i)
5615 cmd = USER_CMD_GA(gap, i);
5616 vim_free(cmd->uc_name);
5617 vim_free(cmd->uc_rep);
5618 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5619 vim_free(cmd->uc_compl_arg);
5620 # endif
5622 ga_clear(gap);
5625 static void
5626 ex_delcommand(eap)
5627 exarg_T *eap;
5629 int i = 0;
5630 ucmd_T *cmd = NULL;
5631 int cmp = -1;
5632 garray_T *gap;
5634 gap = &curbuf->b_ucmds;
5635 for (;;)
5637 for (i = 0; i < gap->ga_len; ++i)
5639 cmd = USER_CMD_GA(gap, i);
5640 cmp = STRCMP(eap->arg, cmd->uc_name);
5641 if (cmp <= 0)
5642 break;
5644 if (gap == &ucmds || cmp == 0)
5645 break;
5646 gap = &ucmds;
5649 if (cmp != 0)
5651 EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5652 return;
5655 vim_free(cmd->uc_name);
5656 vim_free(cmd->uc_rep);
5657 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5658 vim_free(cmd->uc_compl_arg);
5659 # endif
5661 --gap->ga_len;
5663 if (i < gap->ga_len)
5664 mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5668 * split and quote args for <f-args>
5670 static char_u *
5671 uc_split_args(arg, lenp)
5672 char_u *arg;
5673 size_t *lenp;
5675 char_u *buf;
5676 char_u *p;
5677 char_u *q;
5678 int len;
5680 /* Precalculate length */
5681 p = arg;
5682 len = 2; /* Initial and final quotes */
5684 while (*p)
5686 if (p[0] == '\\' && p[1] == '\\')
5688 len += 2;
5689 p += 2;
5691 else if (p[0] == '\\' && vim_iswhite(p[1]))
5693 len += 1;
5694 p += 2;
5696 else if (*p == '\\' || *p == '"')
5698 len += 2;
5699 p += 1;
5701 else if (vim_iswhite(*p))
5703 p = skipwhite(p);
5704 if (*p == NUL)
5705 break;
5706 len += 3; /* "," */
5708 else
5710 ++len;
5711 ++p;
5715 buf = alloc(len + 1);
5716 if (buf == NULL)
5718 *lenp = 0;
5719 return buf;
5722 p = arg;
5723 q = buf;
5724 *q++ = '"';
5725 while (*p)
5727 if (p[0] == '\\' && p[1] == '\\')
5729 *q++ = '\\';
5730 *q++ = '\\';
5731 p += 2;
5733 else if (p[0] == '\\' && vim_iswhite(p[1]))
5735 *q++ = p[1];
5736 p += 2;
5738 else if (*p == '\\' || *p == '"')
5740 *q++ = '\\';
5741 *q++ = *p++;
5743 else if (vim_iswhite(*p))
5745 p = skipwhite(p);
5746 if (*p == NUL)
5747 break;
5748 *q++ = '"';
5749 *q++ = ',';
5750 *q++ = '"';
5752 else
5754 *q++ = *p++;
5757 *q++ = '"';
5758 *q = 0;
5760 *lenp = len;
5761 return buf;
5765 * Check for a <> code in a user command.
5766 * "code" points to the '<'. "len" the length of the <> (inclusive).
5767 * "buf" is where the result is to be added.
5768 * "split_buf" points to a buffer used for splitting, caller should free it.
5769 * "split_len" is the length of what "split_buf" contains.
5770 * Returns the length of the replacement, which has been added to "buf".
5771 * Returns -1 if there was no match, and only the "<" has been copied.
5773 static size_t
5774 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5775 char_u *code;
5776 size_t len;
5777 char_u *buf;
5778 ucmd_T *cmd; /* the user command we're expanding */
5779 exarg_T *eap; /* ex arguments */
5780 char_u **split_buf;
5781 size_t *split_len;
5783 size_t result = 0;
5784 char_u *p = code + 1;
5785 size_t l = len - 2;
5786 int quote = 0;
5787 enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5788 ct_LT, ct_NONE } type = ct_NONE;
5790 if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5792 quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5793 p += 2;
5794 l -= 2;
5797 ++l;
5798 if (l <= 1)
5799 type = ct_NONE;
5800 else if (STRNICMP(p, "args>", l) == 0)
5801 type = ct_ARGS;
5802 else if (STRNICMP(p, "bang>", l) == 0)
5803 type = ct_BANG;
5804 else if (STRNICMP(p, "count>", l) == 0)
5805 type = ct_COUNT;
5806 else if (STRNICMP(p, "line1>", l) == 0)
5807 type = ct_LINE1;
5808 else if (STRNICMP(p, "line2>", l) == 0)
5809 type = ct_LINE2;
5810 else if (STRNICMP(p, "lt>", l) == 0)
5811 type = ct_LT;
5812 else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
5813 type = ct_REGISTER;
5815 switch (type)
5817 case ct_ARGS:
5818 /* Simple case first */
5819 if (*eap->arg == NUL)
5821 if (quote == 1)
5823 result = 2;
5824 if (buf != NULL)
5825 STRCPY(buf, "''");
5827 else
5828 result = 0;
5829 break;
5832 /* When specified there is a single argument don't split it.
5833 * Works for ":Cmd %" when % is "a b c". */
5834 if ((eap->argt & NOSPC) && quote == 2)
5835 quote = 1;
5837 switch (quote)
5839 case 0: /* No quoting, no splitting */
5840 result = STRLEN(eap->arg);
5841 if (buf != NULL)
5842 STRCPY(buf, eap->arg);
5843 break;
5844 case 1: /* Quote, but don't split */
5845 result = STRLEN(eap->arg) + 2;
5846 for (p = eap->arg; *p; ++p)
5848 if (*p == '\\' || *p == '"')
5849 ++result;
5852 if (buf != NULL)
5854 *buf++ = '"';
5855 for (p = eap->arg; *p; ++p)
5857 if (*p == '\\' || *p == '"')
5858 *buf++ = '\\';
5859 *buf++ = *p;
5861 *buf = '"';
5864 break;
5865 case 2: /* Quote and split (<f-args>) */
5866 /* This is hard, so only do it once, and cache the result */
5867 if (*split_buf == NULL)
5868 *split_buf = uc_split_args(eap->arg, split_len);
5870 result = *split_len;
5871 if (buf != NULL && result != 0)
5872 STRCPY(buf, *split_buf);
5874 break;
5876 break;
5878 case ct_BANG:
5879 result = eap->forceit ? 1 : 0;
5880 if (quote)
5881 result += 2;
5882 if (buf != NULL)
5884 if (quote)
5885 *buf++ = '"';
5886 if (eap->forceit)
5887 *buf++ = '!';
5888 if (quote)
5889 *buf = '"';
5891 break;
5893 case ct_LINE1:
5894 case ct_LINE2:
5895 case ct_COUNT:
5897 char num_buf[20];
5898 long num = (type == ct_LINE1) ? eap->line1 :
5899 (type == ct_LINE2) ? eap->line2 :
5900 (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5901 size_t num_len;
5903 sprintf(num_buf, "%ld", num);
5904 num_len = STRLEN(num_buf);
5905 result = num_len;
5907 if (quote)
5908 result += 2;
5910 if (buf != NULL)
5912 if (quote)
5913 *buf++ = '"';
5914 STRCPY(buf, num_buf);
5915 buf += num_len;
5916 if (quote)
5917 *buf = '"';
5920 break;
5923 case ct_REGISTER:
5924 result = eap->regname ? 1 : 0;
5925 if (quote)
5926 result += 2;
5927 if (buf != NULL)
5929 if (quote)
5930 *buf++ = '\'';
5931 if (eap->regname)
5932 *buf++ = eap->regname;
5933 if (quote)
5934 *buf = '\'';
5936 break;
5938 case ct_LT:
5939 result = 1;
5940 if (buf != NULL)
5941 *buf = '<';
5942 break;
5944 default:
5945 /* Not recognized: just copy the '<' and return -1. */
5946 result = (size_t)-1;
5947 if (buf != NULL)
5948 *buf = '<';
5949 break;
5952 return result;
5955 static void
5956 do_ucmd(eap)
5957 exarg_T *eap;
5959 char_u *buf;
5960 char_u *p;
5961 char_u *q;
5963 char_u *start;
5964 char_u *end = NULL;
5965 char_u *ksp;
5966 size_t len, totlen;
5968 size_t split_len = 0;
5969 char_u *split_buf = NULL;
5970 ucmd_T *cmd;
5971 #ifdef FEAT_EVAL
5972 scid_T save_current_SID = current_SID;
5973 #endif
5975 if (eap->cmdidx == CMD_USER)
5976 cmd = USER_CMD(eap->useridx);
5977 else
5978 cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5981 * Replace <> in the command by the arguments.
5982 * First round: "buf" is NULL, compute length, allocate "buf".
5983 * Second round: copy result into "buf".
5985 buf = NULL;
5986 for (;;)
5988 p = cmd->uc_rep; /* source */
5989 q = buf; /* destination */
5990 totlen = 0;
5992 for (;;)
5994 start = vim_strchr(p, '<');
5995 if (start != NULL)
5996 end = vim_strchr(start + 1, '>');
5997 if (buf != NULL)
5999 ksp = vim_strchr(p, K_SPECIAL);
6000 if (ksp != NULL && (start == NULL || ksp < start || end == NULL)
6001 && ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)
6002 # ifdef FEAT_GUI
6003 || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI)
6004 # endif
6007 /* K_SPECIAL han been put in the buffer as K_SPECIAL
6008 * KS_SPECIAL KE_FILLER, like for mappings, but
6009 * do_cmdline() doesn't handle that, so convert it back.
6010 * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */
6011 len = ksp - p;
6012 if (len > 0)
6014 mch_memmove(q, p, len);
6015 q += len;
6017 *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI;
6018 p = ksp + 3;
6019 continue;
6023 /* break if there no <item> is found */
6024 if (start == NULL || end == NULL)
6025 break;
6027 /* Include the '>' */
6028 ++end;
6030 /* Take everything up to the '<' */
6031 len = start - p;
6032 if (buf == NULL)
6033 totlen += len;
6034 else
6036 mch_memmove(q, p, len);
6037 q += len;
6040 len = uc_check_code(start, end - start, q, cmd, eap,
6041 &split_buf, &split_len);
6042 if (len == (size_t)-1)
6044 /* no match, continue after '<' */
6045 p = start + 1;
6046 len = 1;
6048 else
6049 p = end;
6050 if (buf == NULL)
6051 totlen += len;
6052 else
6053 q += len;
6055 if (buf != NULL) /* second time here, finished */
6057 STRCPY(q, p);
6058 break;
6061 totlen += STRLEN(p); /* Add on the trailing characters */
6062 buf = alloc((unsigned)(totlen + 1));
6063 if (buf == NULL)
6065 vim_free(split_buf);
6066 return;
6070 #ifdef FEAT_EVAL
6071 current_SID = cmd->uc_scriptID;
6072 #endif
6073 (void)do_cmdline(buf, eap->getline, eap->cookie,
6074 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6075 #ifdef FEAT_EVAL
6076 current_SID = save_current_SID;
6077 #endif
6078 vim_free(buf);
6079 vim_free(split_buf);
6082 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6083 static char_u *
6084 get_user_command_name(idx)
6085 int idx;
6087 return get_user_commands(NULL, idx - (int)CMD_SIZE);
6091 * Function given to ExpandGeneric() to obtain the list of user command names.
6093 char_u *
6094 get_user_commands(xp, idx)
6095 expand_T *xp UNUSED;
6096 int idx;
6098 if (idx < curbuf->b_ucmds.ga_len)
6099 return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
6100 idx -= curbuf->b_ucmds.ga_len;
6101 if (idx < ucmds.ga_len)
6102 return USER_CMD(idx)->uc_name;
6103 return NULL;
6107 * Function given to ExpandGeneric() to obtain the list of user command
6108 * attributes.
6110 char_u *
6111 get_user_cmd_flags(xp, idx)
6112 expand_T *xp UNUSED;
6113 int idx;
6115 static char *user_cmd_flags[] =
6116 {"bang", "bar", "buffer", "complete", "count",
6117 "nargs", "range", "register"};
6119 if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0])))
6120 return NULL;
6121 return (char_u *)user_cmd_flags[idx];
6125 * Function given to ExpandGeneric() to obtain the list of values for -nargs.
6127 char_u *
6128 get_user_cmd_nargs(xp, idx)
6129 expand_T *xp UNUSED;
6130 int idx;
6132 static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
6134 if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0])))
6135 return NULL;
6136 return (char_u *)user_cmd_nargs[idx];
6140 * Function given to ExpandGeneric() to obtain the list of values for -complete.
6142 char_u *
6143 get_user_cmd_complete(xp, idx)
6144 expand_T *xp UNUSED;
6145 int idx;
6147 return (char_u *)command_complete[idx].name;
6149 # endif /* FEAT_CMDL_COMPL */
6151 #endif /* FEAT_USR_CMDS */
6153 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
6155 * Parse a completion argument "value[vallen]".
6156 * The detected completion goes in "*complp", argument type in "*argt".
6157 * When there is an argument, for function and user defined completion, it's
6158 * copied to allocated memory and stored in "*compl_arg".
6159 * Returns FAIL if something is wrong.
6162 parse_compl_arg(value, vallen, complp, argt, compl_arg)
6163 char_u *value;
6164 int vallen;
6165 int *complp;
6166 long *argt;
6167 char_u **compl_arg;
6169 char_u *arg = NULL;
6170 size_t arglen = 0;
6171 int i;
6172 int valend = vallen;
6174 /* Look for any argument part - which is the part after any ',' */
6175 for (i = 0; i < vallen; ++i)
6177 if (value[i] == ',')
6179 arg = &value[i + 1];
6180 arglen = vallen - i - 1;
6181 valend = i;
6182 break;
6186 for (i = 0; command_complete[i].expand != 0; ++i)
6188 if ((int)STRLEN(command_complete[i].name) == valend
6189 && STRNCMP(value, command_complete[i].name, valend) == 0)
6191 *complp = command_complete[i].expand;
6192 if (command_complete[i].expand == EXPAND_BUFFERS)
6193 *argt |= BUFNAME;
6194 else if (command_complete[i].expand == EXPAND_DIRECTORIES
6195 || command_complete[i].expand == EXPAND_FILES)
6196 *argt |= XFILE;
6197 break;
6201 if (command_complete[i].expand == 0)
6203 EMSG2(_("E180: Invalid complete value: %s"), value);
6204 return FAIL;
6207 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6208 if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
6209 && arg != NULL)
6210 # else
6211 if (arg != NULL)
6212 # endif
6214 EMSG(_("E468: Completion argument only allowed for custom completion"));
6215 return FAIL;
6218 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6219 if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
6220 && arg == NULL)
6222 EMSG(_("E467: Custom completion requires a function argument"));
6223 return FAIL;
6226 if (arg != NULL)
6227 *compl_arg = vim_strnsave(arg, (int)arglen);
6228 # endif
6229 return OK;
6231 #endif
6233 static void
6234 ex_colorscheme(eap)
6235 exarg_T *eap;
6237 if (*eap->arg == NUL)
6239 #ifdef FEAT_EVAL
6240 char_u *expr = vim_strsave((char_u *)"g:colors_name");
6241 char_u *p = NULL;
6243 if (expr != NULL)
6245 ++emsg_off;
6246 p = eval_to_string(expr, NULL, FALSE);
6247 --emsg_off;
6248 vim_free(expr);
6250 if (p != NULL)
6252 MSG(p);
6253 vim_free(p);
6255 else
6256 MSG("default");
6257 #else
6258 MSG(_("unknown"));
6259 #endif
6261 else if (load_colors(eap->arg) == FAIL)
6262 EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
6265 static void
6266 ex_highlight(eap)
6267 exarg_T *eap;
6269 if (*eap->arg == NUL && eap->cmd[2] == '!')
6270 MSG(_("Greetings, Vim user!"));
6271 do_highlight(eap->arg, eap->forceit, FALSE);
6276 * Call this function if we thought we were going to exit, but we won't
6277 * (because of an error). May need to restore the terminal mode.
6279 void
6280 not_exiting()
6282 exiting = FALSE;
6283 settmode(TMODE_RAW);
6287 * ":quit": quit current window, quit Vim if closed the last window.
6289 static void
6290 ex_quit(eap)
6291 exarg_T *eap;
6293 #ifdef FEAT_CMDWIN
6294 if (cmdwin_type != 0)
6296 cmdwin_result = Ctrl_C;
6297 return;
6299 #endif
6300 /* Don't quit while editing the command line. */
6301 if (text_locked())
6303 text_locked_msg();
6304 return;
6306 #ifdef FEAT_AUTOCMD
6307 if (curbuf_locked())
6308 return;
6309 #endif
6311 #ifdef FEAT_NETBEANS_INTG
6312 netbeansForcedQuit = eap->forceit;
6313 #endif
6316 * If there are more files or windows we won't exit.
6318 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6319 exiting = TRUE;
6320 if ((!P_HID(curbuf)
6321 && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
6322 || check_more(TRUE, eap->forceit) == FAIL
6323 || (only_one_window() && check_changed_any(eap->forceit)))
6325 not_exiting();
6327 else
6329 #ifdef FEAT_WINDOWS
6330 if (only_one_window()) /* quit last window */
6331 #endif
6332 getout(0);
6333 #ifdef FEAT_WINDOWS
6334 # ifdef FEAT_GUI
6335 need_mouse_correct = TRUE;
6336 # endif
6337 /* close window; may free buffer */
6338 win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
6339 #endif
6344 * ":cquit".
6346 static void
6347 ex_cquit(eap)
6348 exarg_T *eap UNUSED;
6350 getout(1); /* this does not always pass on the exit code to the Manx
6351 compiler. why? */
6355 * ":qall": try to quit all windows
6357 static void
6358 ex_quit_all(eap)
6359 exarg_T *eap;
6361 # ifdef FEAT_CMDWIN
6362 if (cmdwin_type != 0)
6364 if (eap->forceit)
6365 cmdwin_result = K_XF1; /* ex_window() takes care of this */
6366 else
6367 cmdwin_result = K_XF2;
6368 return;
6370 # endif
6372 /* Don't quit while editing the command line. */
6373 if (text_locked())
6375 text_locked_msg();
6376 return;
6378 #ifdef FEAT_AUTOCMD
6379 if (curbuf_locked())
6380 return;
6381 #endif
6383 exiting = TRUE;
6384 if (eap->forceit || !check_changed_any(FALSE))
6385 getout(0);
6386 not_exiting();
6389 #if defined(FEAT_WINDOWS) || defined(PROTO)
6391 * ":close": close current window, unless it is the last one
6393 static void
6394 ex_close(eap)
6395 exarg_T *eap;
6397 # ifdef FEAT_CMDWIN
6398 if (cmdwin_type != 0)
6399 cmdwin_result = K_IGNORE;
6400 else
6401 # endif
6402 if (!text_locked()
6403 #ifdef FEAT_AUTOCMD
6404 && !curbuf_locked()
6405 #endif
6407 ex_win_close(eap->forceit, curwin, NULL);
6410 # ifdef FEAT_QUICKFIX
6412 * ":pclose": Close any preview window.
6414 static void
6415 ex_pclose(eap)
6416 exarg_T *eap;
6418 win_T *win;
6420 for (win = firstwin; win != NULL; win = win->w_next)
6421 if (win->w_p_pvw)
6423 ex_win_close(eap->forceit, win, NULL);
6424 break;
6427 # endif
6430 * Close window "win" and take care of handling closing the last window for a
6431 * modified buffer.
6433 static void
6434 ex_win_close(forceit, win, tp)
6435 int forceit;
6436 win_T *win;
6437 tabpage_T *tp; /* NULL or the tab page "win" is in */
6439 int need_hide;
6440 buf_T *buf = win->w_buffer;
6442 need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
6443 if (need_hide && !P_HID(buf) && !forceit)
6445 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6446 if ((p_confirm || cmdmod.confirm) && p_write)
6448 dialog_changed(buf, FALSE);
6449 if (buf_valid(buf) && bufIsChanged(buf))
6450 return;
6451 need_hide = FALSE;
6453 else
6454 # endif
6456 EMSG(_(e_nowrtmsg));
6457 return;
6461 # ifdef FEAT_GUI
6462 need_mouse_correct = TRUE;
6463 # endif
6465 /* free buffer when not hiding it or when it's a scratch buffer */
6466 if (tp == NULL)
6467 win_close(win, !need_hide && !P_HID(buf));
6468 else
6469 win_close_othertab(win, !need_hide && !P_HID(buf), tp);
6473 * ":tabclose": close current tab page, unless it is the last one.
6474 * ":tabclose N": close tab page N.
6476 static void
6477 ex_tabclose(eap)
6478 exarg_T *eap;
6480 tabpage_T *tp;
6482 # ifdef FEAT_CMDWIN
6483 if (cmdwin_type != 0)
6484 cmdwin_result = K_IGNORE;
6485 else
6486 # endif
6487 if (first_tabpage->tp_next == NULL)
6488 EMSG(_("E784: Cannot close last tab page"));
6489 else
6491 if (eap->addr_count > 0)
6493 tp = find_tabpage((int)eap->line2);
6494 if (tp == NULL)
6496 beep_flush();
6497 return;
6499 if (tp != curtab)
6501 tabpage_close_other(tp, eap->forceit);
6502 return;
6505 if (!text_locked()
6506 #ifdef FEAT_AUTOCMD
6507 && !curbuf_locked()
6508 #endif
6510 tabpage_close(eap->forceit);
6515 * ":tabonly": close all tab pages except the current one
6517 static void
6518 ex_tabonly(eap)
6519 exarg_T *eap;
6521 tabpage_T *tp;
6522 int done;
6524 # ifdef FEAT_CMDWIN
6525 if (cmdwin_type != 0)
6526 cmdwin_result = K_IGNORE;
6527 else
6528 # endif
6529 if (first_tabpage->tp_next == NULL)
6530 MSG(_("Already only one tab page"));
6531 else
6533 /* Repeat this up to a 1000 times, because autocommands may mess
6534 * up the lists. */
6535 for (done = 0; done < 1000; ++done)
6537 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6538 if (tp->tp_topframe != topframe)
6540 tabpage_close_other(tp, eap->forceit);
6541 /* if we failed to close it quit */
6542 if (valid_tabpage(tp))
6543 done = 1000;
6544 /* start over, "tp" is now invalid */
6545 break;
6547 if (first_tabpage->tp_next == NULL)
6548 break;
6554 * Close the current tab page.
6556 void
6557 tabpage_close(forceit)
6558 int forceit;
6560 /* First close all the windows but the current one. If that worked then
6561 * close the last window in this tab, that will close it. */
6562 if (lastwin != firstwin)
6563 close_others(TRUE, forceit);
6564 if (lastwin == firstwin)
6565 ex_win_close(forceit, curwin, NULL);
6566 # ifdef FEAT_GUI
6567 need_mouse_correct = TRUE;
6568 # endif
6572 * Close tab page "tp", which is not the current tab page.
6573 * Note that autocommands may make "tp" invalid.
6574 * Also takes care of the tab pages line disappearing when closing the
6575 * last-but-one tab page.
6577 void
6578 tabpage_close_other(tp, forceit)
6579 tabpage_T *tp;
6580 int forceit;
6582 int done = 0;
6583 win_T *wp;
6584 int h = tabline_height();
6586 /* Limit to 1000 windows, autocommands may add a window while we close
6587 * one. OK, so I'm paranoid... */
6588 while (++done < 1000)
6590 wp = tp->tp_firstwin;
6591 ex_win_close(forceit, wp, tp);
6593 /* Autocommands may delete the tab page under our fingers and we may
6594 * fail to close a window with a modified buffer. */
6595 if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
6596 break;
6599 redraw_tabline = TRUE;
6600 if (h != tabline_height())
6601 shell_new_rows();
6605 * ":only".
6607 static void
6608 ex_only(eap)
6609 exarg_T *eap;
6611 # ifdef FEAT_GUI
6612 need_mouse_correct = TRUE;
6613 # endif
6614 close_others(TRUE, eap->forceit);
6618 * ":all" and ":sall".
6619 * Also used for ":tab drop file ..." after setting the argument list.
6621 void
6622 ex_all(eap)
6623 exarg_T *eap;
6625 if (eap->addr_count == 0)
6626 eap->line2 = 9999;
6627 do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
6629 #endif /* FEAT_WINDOWS */
6631 static void
6632 ex_hide(eap)
6633 exarg_T *eap;
6635 if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
6636 eap->errmsg = e_invarg;
6637 else
6639 /* ":hide" or ":hide | cmd": hide current window */
6640 eap->nextcmd = check_nextcmd(eap->arg);
6641 #ifdef FEAT_WINDOWS
6642 if (!eap->skip)
6644 # ifdef FEAT_GUI
6645 need_mouse_correct = TRUE;
6646 # endif
6647 win_close(curwin, FALSE); /* don't free buffer */
6649 #endif
6654 * ":stop" and ":suspend": Suspend Vim.
6656 static void
6657 ex_stop(eap)
6658 exarg_T *eap;
6661 * Disallow suspending for "rvim".
6663 if (!check_restricted()
6664 #ifdef WIN3264
6666 * Check if external commands are allowed now.
6668 && can_end_termcap_mode(TRUE)
6669 #endif
6672 if (!eap->forceit)
6673 autowrite_all();
6674 windgoto((int)Rows - 1, 0);
6675 out_char('\n');
6676 out_flush();
6677 stoptermcap();
6678 out_flush(); /* needed for SUN to restore xterm buffer */
6679 #ifdef FEAT_TITLE
6680 mch_restore_title(3); /* restore window titles */
6681 #endif
6682 ui_suspend(); /* call machine specific function */
6683 #ifdef FEAT_TITLE
6684 maketitle();
6685 resettitle(); /* force updating the title */
6686 #endif
6687 starttermcap();
6688 scroll_start(); /* scroll screen before redrawing */
6689 redraw_later_clear();
6690 shell_resized(); /* may have resized window */
6695 * ":exit", ":xit" and ":wq": Write file and exit Vim.
6697 static void
6698 ex_exit(eap)
6699 exarg_T *eap;
6701 #ifdef FEAT_CMDWIN
6702 if (cmdwin_type != 0)
6704 cmdwin_result = Ctrl_C;
6705 return;
6707 #endif
6708 /* Don't quit while editing the command line. */
6709 if (text_locked())
6711 text_locked_msg();
6712 return;
6714 #ifdef FEAT_AUTOCMD
6715 if (curbuf_locked())
6716 return;
6717 #endif
6720 * if more files or windows we won't exit
6722 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6723 exiting = TRUE;
6724 if ( ((eap->cmdidx == CMD_wq
6725 || curbufIsChanged())
6726 && do_write(eap) == FAIL)
6727 || check_more(TRUE, eap->forceit) == FAIL
6728 || (only_one_window() && check_changed_any(eap->forceit)))
6730 not_exiting();
6732 else
6734 #ifdef FEAT_WINDOWS
6735 if (only_one_window()) /* quit last window, exit Vim */
6736 #endif
6737 getout(0);
6738 #ifdef FEAT_WINDOWS
6739 # ifdef FEAT_GUI
6740 need_mouse_correct = TRUE;
6741 # endif
6742 /* quit current window, may free buffer */
6743 win_close(curwin, !P_HID(curwin->w_buffer));
6744 #endif
6749 * ":print", ":list", ":number".
6751 static void
6752 ex_print(eap)
6753 exarg_T *eap;
6755 if (curbuf->b_ml.ml_flags & ML_EMPTY)
6756 EMSG(_(e_emptybuf));
6757 else
6759 for ( ;!got_int; ui_breakcheck())
6761 print_line(eap->line1,
6762 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
6763 || (eap->flags & EXFLAG_NR)),
6764 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
6765 if (++eap->line1 > eap->line2)
6766 break;
6767 out_flush(); /* show one line at a time */
6769 setpcmark();
6770 /* put cursor at last line */
6771 curwin->w_cursor.lnum = eap->line2;
6772 beginline(BL_SOL | BL_FIX);
6775 ex_no_reprint = TRUE;
6778 #ifdef FEAT_BYTEOFF
6779 static void
6780 ex_goto(eap)
6781 exarg_T *eap;
6783 goto_byte(eap->line2);
6785 #endif
6788 * ":shell".
6790 static void
6791 ex_shell(eap)
6792 exarg_T *eap UNUSED;
6794 do_shell(NULL, 0);
6797 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6798 || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6799 || defined(FEAT_GUI_MSWIN) \
6800 || defined(FEAT_GUI_MAC) \
6801 || defined(PROTO)
6804 * Handle a file drop. The code is here because a drop is *nearly* like an
6805 * :args command, but not quite (we have a list of exact filenames, so we
6806 * don't want to (a) parse a command line, or (b) expand wildcards. So the
6807 * code is very similar to :args and hence needs access to a lot of the static
6808 * functions in this file.
6810 * The list should be allocated using alloc(), as should each item in the
6811 * list. This function takes over responsibility for freeing the list.
6813 * XXX The list is made into the argument list. This is freed using
6814 * FreeWild(), which does a series of vim_free() calls, unless the two defines
6815 * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6816 * routine _fnexplodefree() is used. This may cause problems, but as the drop
6817 * file functionality is (currently) not in EMX this is not presently a
6818 * problem.
6820 void
6821 handle_drop(filec, filev, split)
6822 int filec; /* the number of files dropped */
6823 char_u **filev; /* the list of files dropped */
6824 int split; /* force splitting the window */
6826 exarg_T ea;
6827 int save_msg_scroll = msg_scroll;
6829 /* Postpone this while editing the command line. */
6830 if (text_locked())
6831 return;
6832 #ifdef FEAT_AUTOCMD
6833 if (curbuf_locked())
6834 return;
6835 #endif
6836 /* When the screen is being updated we should not change buffers and
6837 * windows structures, it may cause freed memory to be used. */
6838 if (updating_screen)
6839 return;
6841 /* Check whether the current buffer is changed. If so, we will need
6842 * to split the current window or data could be lost.
6843 * We don't need to check if the 'hidden' option is set, as in this
6844 * case the buffer won't be lost.
6846 if (!P_HID(curbuf) && !split)
6848 ++emsg_off;
6849 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6850 --emsg_off;
6852 if (split)
6854 # ifdef FEAT_WINDOWS
6855 if (win_split(0, 0) == FAIL)
6856 return;
6857 # ifdef FEAT_SCROLLBIND
6858 curwin->w_p_scb = FALSE;
6859 # endif
6861 /* When splitting the window, create a new alist. Otherwise the
6862 * existing one is overwritten. */
6863 alist_unlink(curwin->w_alist);
6864 alist_new();
6865 # else
6866 return; /* can't split, always fail */
6867 # endif
6871 * Set up the new argument list.
6873 alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
6876 * Move to the first file.
6878 /* Fake up a minimal "next" command for do_argfile() */
6879 vim_memset(&ea, 0, sizeof(ea));
6880 ea.cmd = (char_u *)"next";
6881 do_argfile(&ea, 0);
6883 /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6884 * mode that is not needed here. */
6885 need_start_insertmode = FALSE;
6887 /* Restore msg_scroll, otherwise a following command may cause scrolling
6888 * unexpectedly. The screen will be redrawn by the caller, thus
6889 * msg_scroll being set by displaying a message is irrelevant. */
6890 msg_scroll = save_msg_scroll;
6892 #endif
6895 * Clear an argument list: free all file names and reset it to zero entries.
6897 void
6898 alist_clear(al)
6899 alist_T *al;
6901 while (--al->al_ga.ga_len >= 0)
6902 vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6903 ga_clear(&al->al_ga);
6907 * Init an argument list.
6909 void
6910 alist_init(al)
6911 alist_T *al;
6913 ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6916 #if defined(FEAT_WINDOWS) || defined(PROTO)
6919 * Remove a reference from an argument list.
6920 * Ignored when the argument list is the global one.
6921 * If the argument list is no longer used by any window, free it.
6923 void
6924 alist_unlink(al)
6925 alist_T *al;
6927 if (al != &global_alist && --al->al_refcount <= 0)
6929 alist_clear(al);
6930 vim_free(al);
6934 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6936 * Create a new argument list and use it for the current window.
6938 void
6939 alist_new()
6941 curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6942 if (curwin->w_alist == NULL)
6944 curwin->w_alist = &global_alist;
6945 ++global_alist.al_refcount;
6947 else
6949 curwin->w_alist->al_refcount = 1;
6950 alist_init(curwin->w_alist);
6953 # endif
6954 #endif
6956 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6958 * Expand the file names in the global argument list.
6959 * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
6960 * numbers to be re-used.
6962 void
6963 alist_expand(fnum_list, fnum_len)
6964 int *fnum_list;
6965 int fnum_len;
6967 char_u **old_arg_files;
6968 int old_arg_count;
6969 char_u **new_arg_files;
6970 int new_arg_file_count;
6971 char_u *save_p_su = p_su;
6972 int i;
6974 /* Don't use 'suffixes' here. This should work like the shell did the
6975 * expansion. Also, the vimrc file isn't read yet, thus the user
6976 * can't set the options. */
6977 p_su = empty_option;
6978 old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6979 if (old_arg_files != NULL)
6981 for (i = 0; i < GARGCOUNT; ++i)
6982 old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
6983 old_arg_count = GARGCOUNT;
6984 if (expand_wildcards(old_arg_count, old_arg_files,
6985 &new_arg_file_count, &new_arg_files,
6986 EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6987 && new_arg_file_count > 0)
6989 alist_set(&global_alist, new_arg_file_count, new_arg_files,
6990 TRUE, fnum_list, fnum_len);
6991 FreeWild(old_arg_count, old_arg_files);
6994 p_su = save_p_su;
6996 #endif
6999 * Set the argument list for the current window.
7000 * Takes over the allocated files[] and the allocated fnames in it.
7002 void
7003 alist_set(al, count, files, use_curbuf, fnum_list, fnum_len)
7004 alist_T *al;
7005 int count;
7006 char_u **files;
7007 int use_curbuf;
7008 int *fnum_list;
7009 int fnum_len;
7011 int i;
7013 alist_clear(al);
7014 if (ga_grow(&al->al_ga, count) == OK)
7016 for (i = 0; i < count; ++i)
7018 if (got_int)
7020 /* When adding many buffers this can take a long time. Allow
7021 * interrupting here. */
7022 while (i < count)
7023 vim_free(files[i++]);
7024 break;
7027 /* May set buffer name of a buffer previously used for the
7028 * argument list, so that it's re-used by alist_add. */
7029 if (fnum_list != NULL && i < fnum_len)
7030 buf_set_name(fnum_list[i], files[i]);
7032 alist_add(al, files[i], use_curbuf ? 2 : 1);
7033 ui_breakcheck();
7035 vim_free(files);
7037 else
7038 FreeWild(count, files);
7039 #ifdef FEAT_WINDOWS
7040 if (al == &global_alist)
7041 #endif
7042 arg_had_last = FALSE;
7046 * Add file "fname" to argument list "al".
7047 * "fname" must have been allocated and "al" must have been checked for room.
7049 void
7050 alist_add(al, fname, set_fnum)
7051 alist_T *al;
7052 char_u *fname;
7053 int set_fnum; /* 1: set buffer number; 2: re-use curbuf */
7055 if (fname == NULL) /* don't add NULL file names */
7056 return;
7057 #ifdef BACKSLASH_IN_FILENAME
7058 slash_adjust(fname);
7059 #endif
7060 AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
7061 if (set_fnum > 0)
7062 AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
7063 buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
7064 ++al->al_ga.ga_len;
7067 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7069 * Adjust slashes in file names. Called after 'shellslash' was set.
7071 void
7072 alist_slash_adjust()
7074 int i;
7075 # ifdef FEAT_WINDOWS
7076 win_T *wp;
7077 tabpage_T *tp;
7078 # endif
7080 for (i = 0; i < GARGCOUNT; ++i)
7081 if (GARGLIST[i].ae_fname != NULL)
7082 slash_adjust(GARGLIST[i].ae_fname);
7083 # ifdef FEAT_WINDOWS
7084 FOR_ALL_TAB_WINDOWS(tp, wp)
7085 if (wp->w_alist != &global_alist)
7086 for (i = 0; i < WARGCOUNT(wp); ++i)
7087 if (WARGLIST(wp)[i].ae_fname != NULL)
7088 slash_adjust(WARGLIST(wp)[i].ae_fname);
7089 # endif
7091 #endif
7094 * ":preserve".
7096 static void
7097 ex_preserve(eap)
7098 exarg_T *eap UNUSED;
7100 curbuf->b_flags |= BF_PRESERVED;
7101 ml_preserve(curbuf, TRUE);
7105 * ":recover".
7107 static void
7108 ex_recover(eap)
7109 exarg_T *eap;
7111 /* Set recoverymode right away to avoid the ATTENTION prompt. */
7112 recoverymode = TRUE;
7113 if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
7114 && (*eap->arg == NUL
7115 || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
7116 ml_recover();
7117 recoverymode = FALSE;
7121 * Command modifier used in a wrong way.
7123 static void
7124 ex_wrongmodifier(eap)
7125 exarg_T *eap;
7127 eap->errmsg = e_invcmd;
7130 #ifdef FEAT_WINDOWS
7132 * :sview [+command] file split window with new file, read-only
7133 * :split [[+command] file] split window with current or new file
7134 * :vsplit [[+command] file] split window vertically with current or new file
7135 * :new [[+command] file] split window with no or new file
7136 * :vnew [[+command] file] split vertically window with no or new file
7137 * :sfind [+command] file split window with file in 'path'
7139 * :tabedit open new Tab page with empty window
7140 * :tabedit [+command] file open new Tab page and edit "file"
7141 * :tabnew [[+command] file] just like :tabedit
7142 * :tabfind [+command] file open new Tab page and find "file"
7144 void
7145 ex_splitview(eap)
7146 exarg_T *eap;
7148 win_T *old_curwin = curwin;
7149 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7150 char_u *fname = NULL;
7151 # endif
7152 # ifdef FEAT_BROWSE
7153 int browse_flag = cmdmod.browse;
7154 # endif
7156 # ifndef FEAT_VERTSPLIT
7157 if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
7159 ex_ni(eap);
7160 return;
7162 # endif
7164 # ifdef FEAT_GUI
7165 need_mouse_correct = TRUE;
7166 # endif
7168 # ifdef FEAT_QUICKFIX
7169 /* A ":split" in the quickfix window works like ":new". Don't want two
7170 * quickfix windows. But it's OK when doing ":tab split". */
7171 if (bt_quickfix(curbuf) && cmdmod.tab == 0)
7173 if (eap->cmdidx == CMD_split)
7174 eap->cmdidx = CMD_new;
7175 # ifdef FEAT_VERTSPLIT
7176 if (eap->cmdidx == CMD_vsplit)
7177 eap->cmdidx = CMD_vnew;
7178 # endif
7180 # endif
7182 # ifdef FEAT_SEARCHPATH
7183 if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
7185 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
7186 FNAME_MESS, TRUE, curbuf->b_ffname);
7187 if (fname == NULL)
7188 goto theend;
7189 eap->arg = fname;
7191 # ifdef FEAT_BROWSE
7192 else
7193 # endif
7194 # endif
7195 # ifdef FEAT_BROWSE
7196 if (cmdmod.browse
7197 # ifdef FEAT_VERTSPLIT
7198 && eap->cmdidx != CMD_vnew
7199 # endif
7200 && eap->cmdidx != CMD_new)
7202 # ifdef FEAT_AUTOCMD
7203 if (
7204 # ifdef FEAT_GUI
7205 !gui.in_use &&
7206 # endif
7207 au_has_group((char_u *)"FileExplorer"))
7209 /* No browsing supported but we do have the file explorer:
7210 * Edit the directory. */
7211 if (*eap->arg == NUL || !mch_isdir(eap->arg))
7212 eap->arg = (char_u *)".";
7214 else
7215 # endif
7217 fname = do_browse(0, (char_u *)_("Edit File in new window"),
7218 eap->arg, NULL, NULL, NULL, curbuf);
7219 if (fname == NULL)
7220 goto theend;
7221 eap->arg = fname;
7224 cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */
7225 # endif
7228 * Either open new tab page or split the window.
7230 if (eap->cmdidx == CMD_tabedit
7231 || eap->cmdidx == CMD_tabfind
7232 || eap->cmdidx == CMD_tabnew)
7234 if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
7235 : eap->addr_count == 0 ? 0
7236 : (int)eap->line2 + 1) != FAIL)
7238 do_exedit(eap, old_curwin);
7240 /* set the alternate buffer for the window we came from */
7241 if (curwin != old_curwin
7242 && win_valid(old_curwin)
7243 && old_curwin->w_buffer != curbuf
7244 && !cmdmod.keepalt)
7245 old_curwin->w_alt_fnum = curbuf->b_fnum;
7248 else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
7249 *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
7251 # ifdef FEAT_SCROLLBIND
7252 /* Reset 'scrollbind' when editing another file, but keep it when
7253 * doing ":split" without arguments. */
7254 if (*eap->arg != NUL
7255 # ifdef FEAT_BROWSE
7256 || cmdmod.browse
7257 # endif
7259 curwin->w_p_scb = FALSE;
7260 else
7261 do_check_scrollbind(FALSE);
7262 # endif
7263 do_exedit(eap, old_curwin);
7266 # ifdef FEAT_BROWSE
7267 cmdmod.browse = browse_flag;
7268 # endif
7270 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7271 theend:
7272 vim_free(fname);
7273 # endif
7277 * Open a new tab page.
7279 void
7280 tabpage_new()
7282 exarg_T ea;
7284 vim_memset(&ea, 0, sizeof(ea));
7285 ea.cmdidx = CMD_tabnew;
7286 ea.cmd = (char_u *)"tabn";
7287 ea.arg = (char_u *)"";
7288 ex_splitview(&ea);
7292 * :tabnext command
7294 static void
7295 ex_tabnext(eap)
7296 exarg_T *eap;
7298 switch (eap->cmdidx)
7300 case CMD_tabfirst:
7301 case CMD_tabrewind:
7302 goto_tabpage(1);
7303 break;
7304 case CMD_tablast:
7305 goto_tabpage(9999);
7306 break;
7307 case CMD_tabprevious:
7308 case CMD_tabNext:
7309 goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2);
7310 break;
7311 default: /* CMD_tabnext */
7312 goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2);
7313 break;
7318 * :tabmove command
7320 static void
7321 ex_tabmove(eap)
7322 exarg_T *eap;
7324 tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2);
7328 * :tabs command: List tabs and their contents.
7330 static void
7331 ex_tabs(eap)
7332 exarg_T *eap UNUSED;
7334 tabpage_T *tp;
7335 win_T *wp;
7336 int tabcount = 1;
7338 msg_start();
7339 msg_scroll = TRUE;
7340 for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
7342 msg_putchar('\n');
7343 vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
7344 msg_outtrans_attr(IObuff, hl_attr(HLF_T));
7345 out_flush(); /* output one line at a time */
7346 ui_breakcheck();
7348 if (tp == curtab)
7349 wp = firstwin;
7350 else
7351 wp = tp->tp_firstwin;
7352 for ( ; wp != NULL && !got_int; wp = wp->w_next)
7354 msg_putchar('\n');
7355 msg_putchar(wp == curwin ? '>' : ' ');
7356 msg_putchar(' ');
7357 msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
7358 msg_putchar(' ');
7359 if (buf_spname(wp->w_buffer) != NULL)
7360 STRCPY(IObuff, buf_spname(wp->w_buffer));
7361 else
7362 home_replace(wp->w_buffer, wp->w_buffer->b_fname,
7363 IObuff, IOSIZE, TRUE);
7364 msg_outtrans(IObuff);
7365 out_flush(); /* output one line at a time */
7366 ui_breakcheck();
7371 #endif /* FEAT_WINDOWS */
7374 * ":mode": Set screen mode.
7375 * If no argument given, just get the screen size and redraw.
7377 static void
7378 ex_mode(eap)
7379 exarg_T *eap;
7381 if (*eap->arg == NUL)
7382 shell_resized();
7383 else
7384 mch_screenmode(eap->arg);
7387 #ifdef FEAT_WINDOWS
7389 * ":resize".
7390 * set, increment or decrement current window height
7392 static void
7393 ex_resize(eap)
7394 exarg_T *eap;
7396 int n;
7397 win_T *wp = curwin;
7399 if (eap->addr_count > 0)
7401 n = eap->line2;
7402 for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
7406 #ifdef FEAT_GUI
7407 need_mouse_correct = TRUE;
7408 #endif
7409 n = atol((char *)eap->arg);
7410 #ifdef FEAT_VERTSPLIT
7411 if (cmdmod.split & WSP_VERT)
7413 if (*eap->arg == '-' || *eap->arg == '+')
7414 n += W_WIDTH(curwin);
7415 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7416 n = 9999;
7417 win_setwidth_win((int)n, wp);
7419 else
7420 #endif
7422 if (*eap->arg == '-' || *eap->arg == '+')
7423 n += curwin->w_height;
7424 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7425 n = 9999;
7426 win_setheight_win((int)n, wp);
7429 #endif
7432 * ":find [+command] <file>" command.
7434 static void
7435 ex_find(eap)
7436 exarg_T *eap;
7438 #ifdef FEAT_SEARCHPATH
7439 char_u *fname;
7440 int count;
7442 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
7443 TRUE, curbuf->b_ffname);
7444 if (eap->addr_count > 0)
7446 /* Repeat finding the file "count" times. This matters when it
7447 * appears several times in the path. */
7448 count = eap->line2;
7449 while (fname != NULL && --count > 0)
7451 vim_free(fname);
7452 fname = find_file_in_path(NULL, 0, FNAME_MESS,
7453 FALSE, curbuf->b_ffname);
7457 if (fname != NULL)
7459 eap->arg = fname;
7460 #endif
7461 do_exedit(eap, NULL);
7462 #ifdef FEAT_SEARCHPATH
7463 vim_free(fname);
7465 #endif
7469 * ":open" simulation: for now just work like ":visual".
7471 static void
7472 ex_open(eap)
7473 exarg_T *eap;
7475 regmatch_T regmatch;
7476 char_u *p;
7478 curwin->w_cursor.lnum = eap->line2;
7479 beginline(BL_SOL | BL_FIX);
7480 if (*eap->arg == '/')
7482 /* ":open /pattern/": put cursor in column found with pattern */
7483 ++eap->arg;
7484 p = skip_regexp(eap->arg, '/', p_magic, NULL);
7485 *p = NUL;
7486 regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
7487 if (regmatch.regprog != NULL)
7489 regmatch.rm_ic = p_ic;
7490 p = ml_get_curline();
7491 if (vim_regexec(&regmatch, p, (colnr_T)0))
7492 curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
7493 else
7494 EMSG(_(e_nomatch));
7495 vim_free(regmatch.regprog);
7497 /* Move to the NUL, ignore any other arguments. */
7498 eap->arg += STRLEN(eap->arg);
7500 check_cursor();
7502 eap->cmdidx = CMD_visual;
7503 do_exedit(eap, NULL);
7507 * ":edit", ":badd", ":visual".
7509 static void
7510 ex_edit(eap)
7511 exarg_T *eap;
7513 do_exedit(eap, NULL);
7517 * ":edit <file>" command and alikes.
7519 void
7520 do_exedit(eap, old_curwin)
7521 exarg_T *eap;
7522 win_T *old_curwin; /* curwin before doing a split or NULL */
7524 int n;
7525 #ifdef FEAT_WINDOWS
7526 int need_hide;
7527 #endif
7528 int exmode_was = exmode_active;
7531 * ":vi" command ends Ex mode.
7533 if (exmode_active && (eap->cmdidx == CMD_visual
7534 || eap->cmdidx == CMD_view))
7536 exmode_active = FALSE;
7537 if (*eap->arg == NUL)
7539 /* Special case: ":global/pat/visual\NLvi-commands" */
7540 if (global_busy)
7542 int rd = RedrawingDisabled;
7543 int nwr = no_wait_return;
7544 int ms = msg_scroll;
7545 #ifdef FEAT_GUI
7546 int he = hold_gui_events;
7547 #endif
7549 if (eap->nextcmd != NULL)
7551 stuffReadbuff(eap->nextcmd);
7552 eap->nextcmd = NULL;
7555 if (exmode_was != EXMODE_VIM)
7556 settmode(TMODE_RAW);
7557 RedrawingDisabled = 0;
7558 no_wait_return = 0;
7559 need_wait_return = FALSE;
7560 msg_scroll = 0;
7561 #ifdef FEAT_GUI
7562 hold_gui_events = 0;
7563 #endif
7564 must_redraw = CLEAR;
7566 main_loop(FALSE, TRUE);
7568 RedrawingDisabled = rd;
7569 no_wait_return = nwr;
7570 msg_scroll = ms;
7571 #ifdef FEAT_GUI
7572 hold_gui_events = he;
7573 #endif
7575 return;
7579 if ((eap->cmdidx == CMD_new
7580 || eap->cmdidx == CMD_tabnew
7581 || eap->cmdidx == CMD_tabedit
7582 #ifdef FEAT_VERTSPLIT
7583 || eap->cmdidx == CMD_vnew
7584 #endif
7585 ) && *eap->arg == NUL)
7587 /* ":new" or ":tabnew" without argument: edit an new empty buffer */
7588 setpcmark();
7589 (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
7590 ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
7591 old_curwin == NULL ? curwin : NULL);
7593 else if ((eap->cmdidx != CMD_split
7594 #ifdef FEAT_VERTSPLIT
7595 && eap->cmdidx != CMD_vsplit
7596 #endif
7598 || *eap->arg != NUL
7599 #ifdef FEAT_BROWSE
7600 || cmdmod.browse
7601 #endif
7604 #ifdef FEAT_AUTOCMD
7605 /* Can't edit another file when "curbuf_lock" is set. Only ":edit"
7606 * can bring us here, others are stopped earlier. */
7607 if (*eap->arg != NUL && curbuf_locked())
7608 return;
7609 #endif
7610 n = readonlymode;
7611 if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
7612 readonlymode = TRUE;
7613 else if (eap->cmdidx == CMD_enew)
7614 readonlymode = FALSE; /* 'readonly' doesn't make sense in an
7615 empty buffer */
7616 setpcmark();
7617 if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
7618 NULL, eap,
7619 /* ":edit" goes to first line if Vi compatible */
7620 (*eap->arg == NUL && eap->do_ecmd_lnum == 0
7621 && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
7622 ? ECMD_ONE : eap->do_ecmd_lnum,
7623 (P_HID(curbuf) ? ECMD_HIDE : 0)
7624 + (eap->forceit ? ECMD_FORCEIT : 0)
7625 #ifdef FEAT_LISTCMDS
7626 + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
7627 #endif
7628 , old_curwin == NULL ? curwin : NULL) == FAIL)
7630 /* Editing the file failed. If the window was split, close it. */
7631 #ifdef FEAT_WINDOWS
7632 if (old_curwin != NULL)
7634 need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
7635 if (!need_hide || P_HID(curbuf))
7637 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7638 cleanup_T cs;
7640 /* Reset the error/interrupt/exception state here so that
7641 * aborting() returns FALSE when closing a window. */
7642 enter_cleanup(&cs);
7643 # endif
7644 # ifdef FEAT_GUI
7645 need_mouse_correct = TRUE;
7646 # endif
7647 win_close(curwin, !need_hide && !P_HID(curbuf));
7649 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7650 /* Restore the error/interrupt/exception state if not
7651 * discarded by a new aborting error, interrupt, or
7652 * uncaught exception. */
7653 leave_cleanup(&cs);
7654 # endif
7657 #endif
7659 else if (readonlymode && curbuf->b_nwindows == 1)
7661 /* When editing an already visited buffer, 'readonly' won't be set
7662 * but the previous value is kept. With ":view" and ":sview" we
7663 * want the file to be readonly, except when another window is
7664 * editing the same buffer. */
7665 curbuf->b_p_ro = TRUE;
7667 readonlymode = n;
7669 else
7671 if (eap->do_ecmd_cmd != NULL)
7672 do_cmdline_cmd(eap->do_ecmd_cmd);
7673 #ifdef FEAT_TITLE
7674 n = curwin->w_arg_idx_invalid;
7675 #endif
7676 check_arg_idx(curwin);
7677 #ifdef FEAT_TITLE
7678 if (n != curwin->w_arg_idx_invalid)
7679 maketitle();
7680 #endif
7683 #ifdef FEAT_WINDOWS
7685 * if ":split file" worked, set alternate file name in old window to new
7686 * file
7688 if (old_curwin != NULL
7689 && *eap->arg != NUL
7690 && curwin != old_curwin
7691 && win_valid(old_curwin)
7692 && old_curwin->w_buffer != curbuf
7693 && !cmdmod.keepalt)
7694 old_curwin->w_alt_fnum = curbuf->b_fnum;
7695 #endif
7697 ex_no_reprint = TRUE;
7700 #ifndef FEAT_GUI
7702 * ":gui" and ":gvim" when there is no GUI.
7704 static void
7705 ex_nogui(eap)
7706 exarg_T *eap;
7708 eap->errmsg = e_nogvim;
7710 #endif
7712 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
7713 static void
7714 ex_tearoff(eap)
7715 exarg_T *eap;
7717 gui_make_tearoff(eap->arg);
7719 #endif
7721 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
7722 static void
7723 ex_popup(eap)
7724 exarg_T *eap;
7726 gui_make_popup(eap->arg, eap->forceit);
7728 #endif
7730 static void
7731 ex_swapname(eap)
7732 exarg_T *eap UNUSED;
7734 if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
7735 MSG(_("No swap file"));
7736 else
7737 msg(curbuf->b_ml.ml_mfp->mf_fname);
7741 * ":syncbind" forces all 'scrollbind' windows to have the same relative
7742 * offset.
7743 * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
7745 static void
7746 ex_syncbind(eap)
7747 exarg_T *eap UNUSED;
7749 #ifdef FEAT_SCROLLBIND
7750 win_T *wp;
7751 long topline;
7752 long y;
7753 linenr_T old_linenr = curwin->w_cursor.lnum;
7755 setpcmark();
7758 * determine max topline
7760 if (curwin->w_p_scb)
7762 topline = curwin->w_topline;
7763 for (wp = firstwin; wp; wp = wp->w_next)
7765 if (wp->w_p_scb && wp->w_buffer)
7767 y = wp->w_buffer->b_ml.ml_line_count - p_so;
7768 if (topline > y)
7769 topline = y;
7772 if (topline < 1)
7773 topline = 1;
7775 else
7777 topline = 1;
7782 * set all scrollbind windows to the same topline
7784 wp = curwin;
7785 for (curwin = firstwin; curwin; curwin = curwin->w_next)
7787 if (curwin->w_p_scb)
7789 y = topline - curwin->w_topline;
7790 if (y > 0)
7791 scrollup(y, TRUE);
7792 else
7793 scrolldown(-y, TRUE);
7794 curwin->w_scbind_pos = topline;
7795 redraw_later(VALID);
7796 cursor_correct();
7797 #ifdef FEAT_WINDOWS
7798 curwin->w_redr_status = TRUE;
7799 #endif
7802 curwin = wp;
7803 if (curwin->w_p_scb)
7805 did_syncbind = TRUE;
7806 checkpcmark();
7807 if (old_linenr != curwin->w_cursor.lnum)
7809 char_u ctrl_o[2];
7811 ctrl_o[0] = Ctrl_O;
7812 ctrl_o[1] = 0;
7813 ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
7816 #endif
7820 static void
7821 ex_read(eap)
7822 exarg_T *eap;
7824 int i;
7825 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7826 linenr_T lnum;
7828 if (eap->usefilter) /* :r!cmd */
7829 do_bang(1, eap, FALSE, FALSE, TRUE);
7830 else
7832 if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
7833 return;
7835 #ifdef FEAT_BROWSE
7836 if (cmdmod.browse)
7838 char_u *browseFile;
7840 browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
7841 NULL, NULL, NULL, curbuf);
7842 if (browseFile != NULL)
7844 i = readfile(browseFile, NULL,
7845 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7846 vim_free(browseFile);
7848 else
7849 i = OK;
7851 else
7852 #endif
7853 if (*eap->arg == NUL)
7855 if (check_fname() == FAIL) /* check for no file name */
7856 return;
7857 i = readfile(curbuf->b_ffname, curbuf->b_fname,
7858 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7860 else
7862 if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
7863 (void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
7864 i = readfile(eap->arg, NULL,
7865 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7868 if (i == FAIL)
7870 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7871 if (!aborting())
7872 #endif
7873 EMSG2(_(e_notopen), eap->arg);
7875 else
7877 if (empty && exmode_active)
7879 /* Delete the empty line that remains. Historically ex does
7880 * this but vi doesn't. */
7881 if (eap->line2 == 0)
7882 lnum = curbuf->b_ml.ml_line_count;
7883 else
7884 lnum = 1;
7885 if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
7887 ml_delete(lnum, FALSE);
7888 if (curwin->w_cursor.lnum > 1
7889 && curwin->w_cursor.lnum >= lnum)
7890 --curwin->w_cursor.lnum;
7891 deleted_lines_mark(lnum, 1L);
7894 redraw_curbuf_later(VALID);
7899 static char_u *prev_dir = NULL;
7901 #if defined(EXITFREE) || defined(PROTO)
7902 void
7903 free_cd_dir()
7905 vim_free(prev_dir);
7906 prev_dir = NULL;
7908 vim_free(globaldir);
7909 globaldir = NULL;
7911 #endif
7915 * ":cd", ":lcd", ":chdir" and ":lchdir".
7917 void
7918 ex_cd(eap)
7919 exarg_T *eap;
7921 char_u *new_dir;
7922 char_u *tofree;
7924 new_dir = eap->arg;
7925 #if !defined(UNIX) && !defined(VMS)
7926 /* for non-UNIX ":cd" means: print current directory */
7927 if (*new_dir == NUL)
7928 ex_pwd(NULL);
7929 else
7930 #endif
7932 #ifdef FEAT_AUTOCMD
7933 if (allbuf_locked())
7934 return;
7935 #endif
7936 if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
7937 && !eap->forceit)
7939 EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
7940 return;
7943 /* ":cd -": Change to previous directory */
7944 if (STRCMP(new_dir, "-") == 0)
7946 if (prev_dir == NULL)
7948 EMSG(_("E186: No previous directory"));
7949 return;
7951 new_dir = prev_dir;
7954 /* Save current directory for next ":cd -" */
7955 tofree = prev_dir;
7956 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7957 prev_dir = vim_strsave(NameBuff);
7958 else
7959 prev_dir = NULL;
7961 #if defined(UNIX) || defined(VMS)
7962 /* for UNIX ":cd" means: go to home directory */
7963 if (*new_dir == NUL)
7965 /* use NameBuff for home directory name */
7966 # ifdef VMS
7967 char_u *p;
7969 p = mch_getenv((char_u *)"SYS$LOGIN");
7970 if (p == NULL || *p == NUL) /* empty is the same as not set */
7971 NameBuff[0] = NUL;
7972 else
7973 vim_strncpy(NameBuff, p, MAXPATHL - 1);
7974 # else
7975 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
7976 # endif
7977 new_dir = NameBuff;
7979 #endif
7980 if (new_dir == NULL || vim_chdir(new_dir))
7981 EMSG(_(e_failed));
7982 else
7984 vim_free(curwin->w_localdir);
7985 if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
7987 /* If still in global directory, need to remember current
7988 * directory as global directory. */
7989 if (globaldir == NULL && prev_dir != NULL)
7990 globaldir = vim_strsave(prev_dir);
7991 /* Remember this local directory for the window. */
7992 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7993 curwin->w_localdir = vim_strsave(NameBuff);
7995 else
7997 /* We are now in the global directory, no need to remember its
7998 * name. */
7999 vim_free(globaldir);
8000 globaldir = NULL;
8001 curwin->w_localdir = NULL;
8004 shorten_fnames(TRUE);
8006 /* Echo the new current directory if the command was typed. */
8007 if (KeyTyped || p_verbose >= 5)
8008 ex_pwd(eap);
8010 vim_free(tofree);
8015 * ":pwd".
8017 static void
8018 ex_pwd(eap)
8019 exarg_T *eap UNUSED;
8021 if (mch_dirname(NameBuff, MAXPATHL) == OK)
8023 #ifdef BACKSLASH_IN_FILENAME
8024 slash_adjust(NameBuff);
8025 #endif
8026 msg(NameBuff);
8028 else
8029 EMSG(_("E187: Unknown"));
8033 * ":=".
8035 static void
8036 ex_equal(eap)
8037 exarg_T *eap;
8039 smsg((char_u *)"%ld", (long)eap->line2);
8040 ex_may_print(eap);
8043 static void
8044 ex_sleep(eap)
8045 exarg_T *eap;
8047 int n;
8048 long len;
8050 if (cursor_valid())
8052 n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
8053 if (n >= 0)
8054 windgoto((int)n, curwin->w_wcol);
8057 len = eap->line2;
8058 switch (*eap->arg)
8060 case 'm': break;
8061 case NUL: len *= 1000L; break;
8062 default: EMSG2(_(e_invarg2), eap->arg); return;
8064 do_sleep(len);
8068 * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
8070 void
8071 do_sleep(msec)
8072 long msec;
8074 long done;
8076 cursor_on();
8077 out_flush();
8078 for (done = 0; !got_int && done < msec; done += 1000L)
8080 ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
8081 ui_breakcheck();
8085 static void
8086 do_exmap(eap, isabbrev)
8087 exarg_T *eap;
8088 int isabbrev;
8090 int mode;
8091 char_u *cmdp;
8093 cmdp = eap->cmd;
8094 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
8096 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
8097 eap->arg, mode, isabbrev))
8099 case 1: EMSG(_(e_invarg));
8100 break;
8101 case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
8102 break;
8107 * ":winsize" command (obsolete).
8109 static void
8110 ex_winsize(eap)
8111 exarg_T *eap;
8113 int w, h;
8114 char_u *arg = eap->arg;
8115 char_u *p;
8117 w = getdigits(&arg);
8118 arg = skipwhite(arg);
8119 p = arg;
8120 h = getdigits(&arg);
8121 if (*p != NUL && *arg == NUL)
8122 set_shellsize(w, h, TRUE);
8123 else
8124 EMSG(_("E465: :winsize requires two number arguments"));
8127 #ifdef FEAT_WINDOWS
8128 static void
8129 ex_wincmd(eap)
8130 exarg_T *eap;
8132 int xchar = NUL;
8133 char_u *p;
8135 if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
8137 /* CTRL-W g and CTRL-W CTRL-G have an extra command character */
8138 if (eap->arg[1] == NUL)
8140 EMSG(_(e_invarg));
8141 return;
8143 xchar = eap->arg[1];
8144 p = eap->arg + 2;
8146 else
8147 p = eap->arg + 1;
8149 eap->nextcmd = check_nextcmd(p);
8150 p = skipwhite(p);
8151 if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
8152 EMSG(_(e_invarg));
8153 else
8155 /* Pass flags on for ":vertical wincmd ]". */
8156 postponed_split_flags = cmdmod.split;
8157 postponed_split_tab = cmdmod.tab;
8158 do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
8159 postponed_split_flags = 0;
8160 postponed_split_tab = 0;
8163 #endif
8165 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
8167 * ":winpos".
8169 static void
8170 ex_winpos(eap)
8171 exarg_T *eap;
8173 int x, y;
8174 char_u *arg = eap->arg;
8175 char_u *p;
8177 if (*arg == NUL)
8179 # if defined(FEAT_GUI) || defined(MSWIN)
8180 # ifdef FEAT_GUI
8181 if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
8182 # else
8183 if (mch_get_winpos(&x, &y) != FAIL)
8184 # endif
8186 sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
8187 msg(IObuff);
8189 else
8190 # endif
8191 EMSG(_("E188: Obtaining window position not implemented for this platform"));
8193 else
8195 x = getdigits(&arg);
8196 arg = skipwhite(arg);
8197 p = arg;
8198 y = getdigits(&arg);
8199 if (*p == NUL || *arg != NUL)
8201 EMSG(_("E466: :winpos requires two number arguments"));
8202 return;
8204 # ifdef FEAT_GUI
8205 if (gui.in_use)
8206 gui_mch_set_winpos(x, y);
8207 else if (gui.starting)
8209 /* Remember the coordinates for when the window is opened. */
8210 gui_win_x = x;
8211 gui_win_y = y;
8213 # ifdef HAVE_TGETENT
8214 else
8215 # endif
8216 # else
8217 # ifdef MSWIN
8218 mch_set_winpos(x, y);
8219 # endif
8220 # endif
8221 # ifdef HAVE_TGETENT
8222 if (*T_CWP)
8223 term_set_winpos(x, y);
8224 # endif
8227 #endif
8230 * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
8232 static void
8233 ex_operators(eap)
8234 exarg_T *eap;
8236 oparg_T oa;
8238 clear_oparg(&oa);
8239 oa.regname = eap->regname;
8240 oa.start.lnum = eap->line1;
8241 oa.end.lnum = eap->line2;
8242 oa.line_count = eap->line2 - eap->line1 + 1;
8243 oa.motion_type = MLINE;
8244 #ifdef FEAT_VIRTUALEDIT
8245 virtual_op = FALSE;
8246 #endif
8247 if (eap->cmdidx != CMD_yank) /* position cursor for undo */
8249 setpcmark();
8250 curwin->w_cursor.lnum = eap->line1;
8251 beginline(BL_SOL | BL_FIX);
8254 switch (eap->cmdidx)
8256 case CMD_delete:
8257 oa.op_type = OP_DELETE;
8258 op_delete(&oa);
8259 break;
8261 case CMD_yank:
8262 oa.op_type = OP_YANK;
8263 (void)op_yank(&oa, FALSE, TRUE);
8264 break;
8266 default: /* CMD_rshift or CMD_lshift */
8267 if ((eap->cmdidx == CMD_rshift)
8268 #ifdef FEAT_RIGHTLEFT
8269 ^ curwin->w_p_rl
8270 #endif
8272 oa.op_type = OP_RSHIFT;
8273 else
8274 oa.op_type = OP_LSHIFT;
8275 op_shift(&oa, FALSE, eap->amount);
8276 break;
8278 #ifdef FEAT_VIRTUALEDIT
8279 virtual_op = MAYBE;
8280 #endif
8281 ex_may_print(eap);
8285 * ":put".
8287 static void
8288 ex_put(eap)
8289 exarg_T *eap;
8291 /* ":0put" works like ":1put!". */
8292 if (eap->line2 == 0)
8294 eap->line2 = 1;
8295 eap->forceit = TRUE;
8297 curwin->w_cursor.lnum = eap->line2;
8298 do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
8299 PUT_LINE|PUT_CURSLINE);
8303 * Handle ":copy" and ":move".
8305 static void
8306 ex_copymove(eap)
8307 exarg_T *eap;
8309 long n;
8311 n = get_address(&eap->arg, FALSE, FALSE);
8312 if (eap->arg == NULL) /* error detected */
8314 eap->nextcmd = NULL;
8315 return;
8317 get_flags(eap);
8320 * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
8322 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
8324 EMSG(_(e_invaddr));
8325 return;
8328 if (eap->cmdidx == CMD_move)
8330 if (do_move(eap->line1, eap->line2, n) == FAIL)
8331 return;
8333 else
8334 ex_copy(eap->line1, eap->line2, n);
8335 u_clearline();
8336 beginline(BL_SOL | BL_FIX);
8337 ex_may_print(eap);
8341 * Print the current line if flags were given to the Ex command.
8343 static void
8344 ex_may_print(eap)
8345 exarg_T *eap;
8347 if (eap->flags != 0)
8349 print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
8350 (eap->flags & EXFLAG_LIST));
8351 ex_no_reprint = TRUE;
8356 * ":smagic" and ":snomagic".
8358 static void
8359 ex_submagic(eap)
8360 exarg_T *eap;
8362 int magic_save = p_magic;
8364 p_magic = (eap->cmdidx == CMD_smagic);
8365 do_sub(eap);
8366 p_magic = magic_save;
8370 * ":join".
8372 static void
8373 ex_join(eap)
8374 exarg_T *eap;
8376 curwin->w_cursor.lnum = eap->line1;
8377 if (eap->line1 == eap->line2)
8379 if (eap->addr_count >= 2) /* :2,2join does nothing */
8380 return;
8381 if (eap->line2 == curbuf->b_ml.ml_line_count)
8383 beep_flush();
8384 return;
8386 ++eap->line2;
8388 do_do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
8389 beginline(BL_WHITE | BL_FIX);
8390 ex_may_print(eap);
8394 * ":[addr]@r" or ":[addr]*r": execute register
8396 static void
8397 ex_at(eap)
8398 exarg_T *eap;
8400 int c;
8401 int prev_len = typebuf.tb_len;
8403 curwin->w_cursor.lnum = eap->line2;
8405 #ifdef USE_ON_FLY_SCROLL
8406 dont_scroll = TRUE; /* disallow scrolling here */
8407 #endif
8409 /* get the register name. No name means to use the previous one */
8410 c = *eap->arg;
8411 if (c == NUL || (c == '*' && *eap->cmd == '*'))
8412 c = '@';
8413 /* Put the register in the typeahead buffer with the "silent" flag. */
8414 if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
8415 == FAIL)
8417 beep_flush();
8419 else
8421 int save_efr = exec_from_reg;
8423 exec_from_reg = TRUE;
8426 * Execute from the typeahead buffer.
8427 * Continue until the stuff buffer is empty and all added characters
8428 * have been consumed.
8430 while (!stuff_empty() || typebuf.tb_len > prev_len)
8431 (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
8433 exec_from_reg = save_efr;
8438 * ":!".
8440 static void
8441 ex_bang(eap)
8442 exarg_T *eap;
8444 do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
8448 * ":undo".
8450 static void
8451 ex_undo(eap)
8452 exarg_T *eap UNUSED;
8454 if (eap->addr_count == 1) /* :undo 123 */
8455 undo_time(eap->line2, FALSE, TRUE);
8456 else
8457 u_undo(1);
8460 #ifdef FEAT_PERSISTENT_UNDO
8461 void
8462 ex_wundo(eap)
8463 exarg_T *eap;
8465 char_u *name = eap->arg;
8466 u_wundo(name, curbuf);
8469 void
8470 ex_rundo(eap)
8471 exarg_T *eap;
8473 char_u *name = eap->arg;
8474 u_rundo(name, 0);
8476 #endif
8479 * ":redo".
8481 static void
8482 ex_redo(eap)
8483 exarg_T *eap UNUSED;
8485 u_redo(1);
8489 * ":earlier" and ":later".
8491 static void
8492 ex_later(eap)
8493 exarg_T *eap;
8495 long count = 0;
8496 int sec = FALSE;
8497 char_u *p = eap->arg;
8499 if (*p == NUL)
8500 count = 1;
8501 else if (isdigit(*p))
8503 count = getdigits(&p);
8504 switch (*p)
8506 case 's': ++p; sec = TRUE; break;
8507 case 'm': ++p; sec = TRUE; count *= 60; break;
8508 case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
8512 if (*p != NUL)
8513 EMSG2(_(e_invarg2), eap->arg);
8514 else
8515 undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, FALSE);
8519 * ":redir": start/stop redirection.
8521 static void
8522 ex_redir(eap)
8523 exarg_T *eap;
8525 char *mode;
8526 char_u *fname;
8527 char_u *arg = eap->arg;
8529 if (STRICMP(eap->arg, "END") == 0)
8530 close_redir();
8531 else
8533 if (*arg == '>')
8535 ++arg;
8536 if (*arg == '>')
8538 ++arg;
8539 mode = "a";
8541 else
8542 mode = "w";
8543 arg = skipwhite(arg);
8545 close_redir();
8547 /* Expand environment variables and "~/". */
8548 fname = expand_env_save(arg);
8549 if (fname == NULL)
8550 return;
8551 #ifdef FEAT_BROWSE
8552 if (cmdmod.browse)
8554 char_u *browseFile;
8556 browseFile = do_browse(BROWSE_SAVE,
8557 (char_u *)_("Save Redirection"),
8558 fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
8559 if (browseFile == NULL)
8560 return; /* operation cancelled */
8561 vim_free(fname);
8562 fname = browseFile;
8563 eap->forceit = TRUE; /* since dialog already asked */
8565 #endif
8567 redir_fd = open_exfile(fname, eap->forceit, mode);
8568 vim_free(fname);
8570 #ifdef FEAT_EVAL
8571 else if (*arg == '@')
8573 /* redirect to a register a-z (resp. A-Z for appending) */
8574 close_redir();
8575 ++arg;
8576 if (ASCII_ISALPHA(*arg)
8577 # ifdef FEAT_CLIPBOARD
8578 || *arg == '*'
8579 || *arg == '+'
8580 # endif
8581 || *arg == '"')
8583 redir_reg = *arg++;
8584 if (*arg == '>' && arg[1] == '>') /* append */
8585 arg += 2;
8586 else
8588 /* Can use both "@a" and "@a>". */
8589 if (*arg == '>')
8590 arg++;
8591 /* Make register empty when not using @A-@Z and the
8592 * command is valid. */
8593 if (*arg == NUL && !isupper(redir_reg))
8594 write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
8597 if (*arg != NUL)
8599 redir_reg = 0;
8600 EMSG2(_(e_invarg2), eap->arg);
8603 else if (*arg == '=' && arg[1] == '>')
8605 int append;
8607 /* redirect to a variable */
8608 close_redir();
8609 arg += 2;
8611 if (*arg == '>')
8613 ++arg;
8614 append = TRUE;
8616 else
8617 append = FALSE;
8619 if (var_redir_start(skipwhite(arg), append) == OK)
8620 redir_vname = 1;
8622 #endif
8624 /* TODO: redirect to a buffer */
8626 else
8627 EMSG2(_(e_invarg2), eap->arg);
8630 /* Make sure redirection is not off. Can happen for cmdline completion
8631 * that indirectly invokes a command to catch its output. */
8632 if (redir_fd != NULL
8633 #ifdef FEAT_EVAL
8634 || redir_reg || redir_vname
8635 #endif
8637 redir_off = FALSE;
8641 * ":redraw": force redraw
8643 static void
8644 ex_redraw(eap)
8645 exarg_T *eap;
8647 int r = RedrawingDisabled;
8648 int p = p_lz;
8650 RedrawingDisabled = 0;
8651 p_lz = FALSE;
8652 update_topline();
8653 update_screen(eap->forceit ? CLEAR :
8654 #ifdef FEAT_VISUAL
8655 VIsual_active ? INVERTED :
8656 #endif
8658 #ifdef FEAT_TITLE
8659 if (need_maketitle)
8660 maketitle();
8661 #endif
8662 RedrawingDisabled = r;
8663 p_lz = p;
8665 /* Reset msg_didout, so that a message that's there is overwritten. */
8666 msg_didout = FALSE;
8667 msg_col = 0;
8669 out_flush();
8673 * ":redrawstatus": force redraw of status line(s)
8675 static void
8676 ex_redrawstatus(eap)
8677 exarg_T *eap UNUSED;
8679 #if defined(FEAT_WINDOWS)
8680 int r = RedrawingDisabled;
8681 int p = p_lz;
8683 RedrawingDisabled = 0;
8684 p_lz = FALSE;
8685 if (eap->forceit)
8686 status_redraw_all();
8687 else
8688 status_redraw_curbuf();
8689 update_screen(
8690 # ifdef FEAT_VISUAL
8691 VIsual_active ? INVERTED :
8692 # endif
8694 RedrawingDisabled = r;
8695 p_lz = p;
8696 out_flush();
8697 #endif
8700 static void
8701 close_redir()
8703 if (redir_fd != NULL)
8705 fclose(redir_fd);
8706 redir_fd = NULL;
8708 #ifdef FEAT_EVAL
8709 redir_reg = 0;
8710 if (redir_vname)
8712 var_redir_stop();
8713 redir_vname = 0;
8715 #endif
8718 #if defined(FEAT_SESSION) && defined(USE_CRNL)
8719 # define MKSESSION_NL
8720 static int mksession_nl = FALSE; /* use NL only in put_eol() */
8721 #endif
8724 * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
8726 static void
8727 ex_mkrc(eap)
8728 exarg_T *eap;
8730 FILE *fd;
8731 int failed = FALSE;
8732 char_u *fname;
8733 #ifdef FEAT_BROWSE
8734 char_u *browseFile = NULL;
8735 #endif
8736 #ifdef FEAT_SESSION
8737 int view_session = FALSE;
8738 int using_vdir = FALSE; /* using 'viewdir'? */
8739 char_u *viewFile = NULL;
8740 unsigned *flagp;
8741 #endif
8743 if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
8745 #ifdef FEAT_SESSION
8746 view_session = TRUE;
8747 #else
8748 ex_ni(eap);
8749 return;
8750 #endif
8753 #ifdef FEAT_SESSION
8754 /* Use the short file name until ":lcd" is used. We also don't use the
8755 * short file name when 'acd' is set, that is checked later. */
8756 did_lcd = FALSE;
8758 /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
8759 if (eap->cmdidx == CMD_mkview
8760 && (*eap->arg == NUL
8761 || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
8763 eap->forceit = TRUE;
8764 fname = get_view_file(*eap->arg);
8765 if (fname == NULL)
8766 return;
8767 viewFile = fname;
8768 using_vdir = TRUE;
8770 else
8771 #endif
8772 if (*eap->arg != NUL)
8773 fname = eap->arg;
8774 else if (eap->cmdidx == CMD_mkvimrc)
8775 fname = (char_u *)VIMRC_FILE;
8776 #ifdef FEAT_SESSION
8777 else if (eap->cmdidx == CMD_mksession)
8778 fname = (char_u *)SESSION_FILE;
8779 #endif
8780 else
8781 fname = (char_u *)EXRC_FILE;
8783 #ifdef FEAT_BROWSE
8784 if (cmdmod.browse)
8786 browseFile = do_browse(BROWSE_SAVE,
8787 # ifdef FEAT_SESSION
8788 eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
8789 eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
8790 # endif
8791 (char_u *)_("Save Setup"),
8792 fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
8793 if (browseFile == NULL)
8794 goto theend;
8795 fname = browseFile;
8796 eap->forceit = TRUE; /* since dialog already asked */
8798 #endif
8800 #if defined(FEAT_SESSION) && defined(vim_mkdir)
8801 /* When using 'viewdir' may have to create the directory. */
8802 if (using_vdir && !mch_isdir(p_vdir))
8803 vim_mkdir_emsg(p_vdir, 0755);
8804 #endif
8806 fd = open_exfile(fname, eap->forceit, WRITEBIN);
8807 if (fd != NULL)
8809 #ifdef FEAT_SESSION
8810 if (eap->cmdidx == CMD_mkview)
8811 flagp = &vop_flags;
8812 else
8813 flagp = &ssop_flags;
8814 #endif
8816 #ifdef MKSESSION_NL
8817 /* "unix" in 'sessionoptions': use NL line separator */
8818 if (view_session && (*flagp & SSOP_UNIX))
8819 mksession_nl = TRUE;
8820 #endif
8822 /* Write the version command for :mkvimrc */
8823 if (eap->cmdidx == CMD_mkvimrc)
8824 (void)put_line(fd, "version 6.0");
8826 #ifdef FEAT_SESSION
8827 if (eap->cmdidx == CMD_mksession)
8829 if (put_line(fd, "let SessionLoad = 1") == FAIL)
8830 failed = TRUE;
8833 if (eap->cmdidx != CMD_mkview)
8834 #endif
8836 /* Write setting 'compatible' first, because it has side effects.
8837 * For that same reason only do it when needed. */
8838 if (p_cp)
8839 (void)put_line(fd, "if !&cp | set cp | endif");
8840 else
8841 (void)put_line(fd, "if &cp | set nocp | endif");
8844 #ifdef FEAT_SESSION
8845 if (!view_session
8846 || (eap->cmdidx == CMD_mksession
8847 && (*flagp & SSOP_OPTIONS)))
8848 #endif
8849 failed |= (makemap(fd, NULL) == FAIL
8850 || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
8852 #ifdef FEAT_SESSION
8853 if (!failed && view_session)
8855 if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
8856 failed = TRUE;
8857 if (eap->cmdidx == CMD_mksession)
8859 char_u dirnow[MAXPATHL]; /* current directory */
8862 * Change to session file's dir.
8864 if (mch_dirname(dirnow, MAXPATHL) == FAIL
8865 || mch_chdir((char *)dirnow) != 0)
8866 *dirnow = NUL;
8867 if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
8869 if (vim_chdirfile(fname) == OK)
8870 shorten_fnames(TRUE);
8872 else if (*dirnow != NUL
8873 && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
8875 if (mch_chdir((char *)globaldir) == 0)
8876 shorten_fnames(TRUE);
8879 failed |= (makeopens(fd, dirnow) == FAIL);
8881 /* restore original dir */
8882 if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
8883 || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
8885 if (mch_chdir((char *)dirnow) != 0)
8886 EMSG(_(e_prev_dir));
8887 shorten_fnames(TRUE);
8890 else
8892 failed |= (put_view(fd, curwin, !using_vdir, flagp,
8893 -1) == FAIL);
8895 if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
8896 == FAIL)
8897 failed = TRUE;
8898 if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
8899 failed = TRUE;
8900 if (eap->cmdidx == CMD_mksession)
8902 if (put_line(fd, "unlet SessionLoad") == FAIL)
8903 failed = TRUE;
8906 #endif
8907 if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
8908 failed = TRUE;
8910 failed |= fclose(fd);
8912 if (failed)
8913 EMSG(_(e_write));
8914 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
8915 else if (eap->cmdidx == CMD_mksession)
8917 /* successful session write - set this_session var */
8918 char_u tbuf[MAXPATHL];
8920 if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
8921 set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
8923 #endif
8924 #ifdef MKSESSION_NL
8925 mksession_nl = FALSE;
8926 #endif
8929 #ifdef FEAT_BROWSE
8930 theend:
8931 vim_free(browseFile);
8932 #endif
8933 #ifdef FEAT_SESSION
8934 vim_free(viewFile);
8935 #endif
8938 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
8939 || defined(PROTO)
8941 vim_mkdir_emsg(name, prot)
8942 char_u *name;
8943 int prot UNUSED;
8945 if (vim_mkdir(name, prot) != 0)
8947 EMSG2(_("E739: Cannot create directory: %s"), name);
8948 return FAIL;
8950 return OK;
8952 #endif
8955 * Open a file for writing for an Ex command, with some checks.
8956 * Return file descriptor, or NULL on failure.
8958 FILE *
8959 open_exfile(fname, forceit, mode)
8960 char_u *fname;
8961 int forceit;
8962 char *mode; /* "w" for create new file or "a" for append */
8964 FILE *fd;
8966 #ifdef UNIX
8967 /* with Unix it is possible to open a directory */
8968 if (mch_isdir(fname))
8970 EMSG2(_(e_isadir2), fname);
8971 return NULL;
8973 #endif
8974 if (!forceit && *mode != 'a' && vim_fexists(fname))
8976 EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
8977 return NULL;
8980 if ((fd = mch_fopen((char *)fname, mode)) == NULL)
8981 EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
8983 return fd;
8987 * ":mark" and ":k".
8989 static void
8990 ex_mark(eap)
8991 exarg_T *eap;
8993 pos_T pos;
8995 if (*eap->arg == NUL) /* No argument? */
8996 EMSG(_(e_argreq));
8997 else if (eap->arg[1] != NUL) /* more than one character? */
8998 EMSG(_(e_trailing));
8999 else
9001 pos = curwin->w_cursor; /* save curwin->w_cursor */
9002 curwin->w_cursor.lnum = eap->line2;
9003 beginline(BL_WHITE | BL_FIX);
9004 if (setmark(*eap->arg) == FAIL) /* set mark */
9005 EMSG(_("E191: Argument must be a letter or forward/backward quote"));
9006 curwin->w_cursor = pos; /* restore curwin->w_cursor */
9011 * Update w_topline, w_leftcol and the cursor position.
9013 void
9014 update_topline_cursor()
9016 check_cursor(); /* put cursor on valid line */
9017 update_topline();
9018 if (!curwin->w_p_wrap)
9019 validate_cursor();
9020 update_curswant();
9023 #ifdef FEAT_EX_EXTRA
9025 * ":normal[!] {commands}": Execute normal mode commands.
9027 static void
9028 ex_normal(eap)
9029 exarg_T *eap;
9031 int save_msg_scroll = msg_scroll;
9032 int save_restart_edit = restart_edit;
9033 int save_msg_didout = msg_didout;
9034 int save_State = State;
9035 tasave_T tabuf;
9036 int save_insertmode = p_im;
9037 int save_finish_op = finish_op;
9038 int save_opcount = opcount;
9039 #ifdef FEAT_MBYTE
9040 char_u *arg = NULL;
9041 int l;
9042 char_u *p;
9043 #endif
9045 if (ex_normal_lock > 0)
9047 EMSG(_(e_secure));
9048 return;
9050 if (ex_normal_busy >= p_mmd)
9052 EMSG(_("E192: Recursive use of :normal too deep"));
9053 return;
9055 ++ex_normal_busy;
9057 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
9058 restart_edit = 0; /* don't go to Insert mode */
9059 p_im = FALSE; /* don't use 'insertmode' */
9061 #ifdef FEAT_MBYTE
9063 * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
9064 * this for the K_SPECIAL leading byte, otherwise special keys will not
9065 * work.
9067 if (has_mbyte)
9069 int len = 0;
9071 /* Count the number of characters to be escaped. */
9072 for (p = eap->arg; *p != NUL; ++p)
9074 # ifdef FEAT_GUI
9075 if (*p == CSI) /* leadbyte CSI */
9076 len += 2;
9077 # endif
9078 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9079 if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */
9080 # ifdef FEAT_GUI
9081 || *p == CSI
9082 # endif
9084 len += 2;
9086 if (len > 0)
9088 arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
9089 if (arg != NULL)
9091 len = 0;
9092 for (p = eap->arg; *p != NUL; ++p)
9094 arg[len++] = *p;
9095 # ifdef FEAT_GUI
9096 if (*p == CSI)
9098 arg[len++] = KS_EXTRA;
9099 arg[len++] = (int)KE_CSI;
9101 # endif
9102 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9104 arg[len++] = *++p;
9105 if (*p == K_SPECIAL)
9107 arg[len++] = KS_SPECIAL;
9108 arg[len++] = KE_FILLER;
9110 # ifdef FEAT_GUI
9111 else if (*p == CSI)
9113 arg[len++] = KS_EXTRA;
9114 arg[len++] = (int)KE_CSI;
9116 # endif
9118 arg[len] = NUL;
9123 #endif
9126 * Save the current typeahead. This is required to allow using ":normal"
9127 * from an event handler and makes sure we don't hang when the argument
9128 * ends with half a command.
9130 save_typeahead(&tabuf);
9131 if (tabuf.typebuf_valid)
9134 * Repeat the :normal command for each line in the range. When no
9135 * range given, execute it just once, without positioning the cursor
9136 * first.
9140 if (eap->addr_count != 0)
9142 curwin->w_cursor.lnum = eap->line1++;
9143 curwin->w_cursor.col = 0;
9146 exec_normal_cmd(
9147 #ifdef FEAT_MBYTE
9148 arg != NULL ? arg :
9149 #endif
9150 eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
9152 while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
9155 /* Might not return to the main loop when in an event handler. */
9156 update_topline_cursor();
9158 /* Restore the previous typeahead. */
9159 restore_typeahead(&tabuf);
9161 --ex_normal_busy;
9162 msg_scroll = save_msg_scroll;
9163 restart_edit = save_restart_edit;
9164 p_im = save_insertmode;
9165 finish_op = save_finish_op;
9166 opcount = save_opcount;
9167 msg_didout |= save_msg_didout; /* don't reset msg_didout now */
9169 /* Restore the state (needed when called from a function executed for
9170 * 'indentexpr'). */
9171 State = save_State;
9172 #ifdef FEAT_MBYTE
9173 vim_free(arg);
9174 #endif
9178 * ":startinsert", ":startreplace" and ":startgreplace"
9180 static void
9181 ex_startinsert(eap)
9182 exarg_T *eap;
9184 if (eap->forceit)
9186 coladvance((colnr_T)MAXCOL);
9187 curwin->w_curswant = MAXCOL;
9188 curwin->w_set_curswant = FALSE;
9191 /* Ignore the command when already in Insert mode. Inserting an
9192 * expression register that invokes a function can do this. */
9193 if (State & INSERT)
9194 return;
9196 if (eap->cmdidx == CMD_startinsert)
9197 restart_edit = 'a';
9198 else if (eap->cmdidx == CMD_startreplace)
9199 restart_edit = 'R';
9200 else
9201 restart_edit = 'V';
9203 if (!eap->forceit)
9205 if (eap->cmdidx == CMD_startinsert)
9206 restart_edit = 'i';
9207 curwin->w_curswant = 0; /* avoid MAXCOL */
9212 * ":stopinsert"
9214 static void
9215 ex_stopinsert(eap)
9216 exarg_T *eap UNUSED;
9218 restart_edit = 0;
9219 stop_insert_mode = TRUE;
9221 #endif
9223 #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO)
9225 * Execute normal mode command "cmd".
9226 * "remap" can be REMAP_NONE or REMAP_YES.
9228 void
9229 exec_normal_cmd(cmd, remap, silent)
9230 char_u *cmd;
9231 int remap;
9232 int silent;
9234 oparg_T oa;
9237 * Stuff the argument into the typeahead buffer.
9238 * Execute normal_cmd() until there is no typeahead left.
9240 clear_oparg(&oa);
9241 finish_op = FALSE;
9242 ins_typebuf(cmd, remap, 0, TRUE, silent);
9243 while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
9244 && !got_int)
9246 update_topline_cursor();
9247 normal_cmd(&oa, FALSE); /* execute a Normal mode cmd */
9250 #endif
9252 #ifdef FEAT_FIND_ID
9253 static void
9254 ex_checkpath(eap)
9255 exarg_T *eap;
9257 find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
9258 eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
9259 (linenr_T)1, (linenr_T)MAXLNUM);
9262 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
9264 * ":psearch"
9266 static void
9267 ex_psearch(eap)
9268 exarg_T *eap;
9270 g_do_tagpreview = p_pvh;
9271 ex_findpat(eap);
9272 g_do_tagpreview = 0;
9274 #endif
9276 static void
9277 ex_findpat(eap)
9278 exarg_T *eap;
9280 int whole = TRUE;
9281 long n;
9282 char_u *p;
9283 int action;
9285 switch (cmdnames[eap->cmdidx].cmd_name[2])
9287 case 'e': /* ":psearch", ":isearch" and ":dsearch" */
9288 if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
9289 action = ACTION_GOTO;
9290 else
9291 action = ACTION_SHOW;
9292 break;
9293 case 'i': /* ":ilist" and ":dlist" */
9294 action = ACTION_SHOW_ALL;
9295 break;
9296 case 'u': /* ":ijump" and ":djump" */
9297 action = ACTION_GOTO;
9298 break;
9299 default: /* ":isplit" and ":dsplit" */
9300 action = ACTION_SPLIT;
9301 break;
9304 n = 1;
9305 if (vim_isdigit(*eap->arg)) /* get count */
9307 n = getdigits(&eap->arg);
9308 eap->arg = skipwhite(eap->arg);
9310 if (*eap->arg == '/') /* Match regexp, not just whole words */
9312 whole = FALSE;
9313 ++eap->arg;
9314 p = skip_regexp(eap->arg, '/', p_magic, NULL);
9315 if (*p)
9317 *p++ = NUL;
9318 p = skipwhite(p);
9320 /* Check for trailing illegal characters */
9321 if (!ends_excmd(*p))
9322 eap->errmsg = e_trailing;
9323 else
9324 eap->nextcmd = check_nextcmd(p);
9327 if (!eap->skip)
9328 find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
9329 whole, !eap->forceit,
9330 *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY,
9331 n, action, eap->line1, eap->line2);
9333 #endif
9335 #ifdef FEAT_WINDOWS
9337 # ifdef FEAT_QUICKFIX
9339 * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
9341 static void
9342 ex_ptag(eap)
9343 exarg_T *eap;
9345 g_do_tagpreview = p_pvh;
9346 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9350 * ":pedit"
9352 static void
9353 ex_pedit(eap)
9354 exarg_T *eap;
9356 win_T *curwin_save = curwin;
9358 g_do_tagpreview = p_pvh;
9359 prepare_tagpreview(TRUE);
9360 keep_help_flag = curwin_save->w_buffer->b_help;
9361 do_exedit(eap, NULL);
9362 keep_help_flag = FALSE;
9363 if (curwin != curwin_save && win_valid(curwin_save))
9365 /* Return cursor to where we were */
9366 validate_cursor();
9367 redraw_later(VALID);
9368 win_enter(curwin_save, TRUE);
9370 g_do_tagpreview = 0;
9372 # endif
9375 * ":stag", ":stselect" and ":stjump".
9377 static void
9378 ex_stag(eap)
9379 exarg_T *eap;
9381 postponed_split = -1;
9382 postponed_split_flags = cmdmod.split;
9383 postponed_split_tab = cmdmod.tab;
9384 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9385 postponed_split_flags = 0;
9386 postponed_split_tab = 0;
9388 #endif
9391 * ":tag", ":tselect", ":tjump", ":tnext", etc.
9393 static void
9394 ex_tag(eap)
9395 exarg_T *eap;
9397 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
9400 static void
9401 ex_tag_cmd(eap, name)
9402 exarg_T *eap;
9403 char_u *name;
9405 int cmd;
9407 switch (name[1])
9409 case 'j': cmd = DT_JUMP; /* ":tjump" */
9410 break;
9411 case 's': cmd = DT_SELECT; /* ":tselect" */
9412 break;
9413 case 'p': cmd = DT_PREV; /* ":tprevious" */
9414 break;
9415 case 'N': cmd = DT_PREV; /* ":tNext" */
9416 break;
9417 case 'n': cmd = DT_NEXT; /* ":tnext" */
9418 break;
9419 case 'o': cmd = DT_POP; /* ":pop" */
9420 break;
9421 case 'f': /* ":tfirst" */
9422 case 'r': cmd = DT_FIRST; /* ":trewind" */
9423 break;
9424 case 'l': cmd = DT_LAST; /* ":tlast" */
9425 break;
9426 default: /* ":tag" */
9427 #ifdef FEAT_CSCOPE
9428 if (p_cst && *eap->arg != NUL)
9430 do_cstag(eap);
9431 return;
9433 #endif
9434 cmd = DT_TAG;
9435 break;
9438 if (name[0] == 'l')
9440 #ifndef FEAT_QUICKFIX
9441 ex_ni(eap);
9442 return;
9443 #else
9444 cmd = DT_LTAG;
9445 #endif
9448 do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
9449 eap->forceit, TRUE);
9453 * Check "str" for starting with a special cmdline variable.
9454 * If found return one of the SPEC_ values and set "*usedlen" to the length of
9455 * the variable. Otherwise return -1 and "*usedlen" is unchanged.
9458 find_cmdline_var(src, usedlen)
9459 char_u *src;
9460 int *usedlen;
9462 int len;
9463 int i;
9464 static char *(spec_str[]) = {
9465 "%",
9466 #define SPEC_PERC 0
9467 "#",
9468 #define SPEC_HASH 1
9469 "<cword>", /* cursor word */
9470 #define SPEC_CWORD 2
9471 "<cWORD>", /* cursor WORD */
9472 #define SPEC_CCWORD 3
9473 "<cfile>", /* cursor path name */
9474 #define SPEC_CFILE 4
9475 "<sfile>", /* ":so" file name */
9476 #define SPEC_SFILE 5
9477 #ifdef FEAT_AUTOCMD
9478 "<afile>", /* autocommand file name */
9479 # define SPEC_AFILE 6
9480 "<abuf>", /* autocommand buffer number */
9481 # define SPEC_ABUF 7
9482 "<amatch>", /* autocommand match name */
9483 # define SPEC_AMATCH 8
9484 #endif
9485 #ifdef FEAT_CLIENTSERVER
9486 "<client>"
9487 # define SPEC_CLIENT 9
9488 #endif
9491 for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i)
9493 len = (int)STRLEN(spec_str[i]);
9494 if (STRNCMP(src, spec_str[i], len) == 0)
9496 *usedlen = len;
9497 return i;
9500 return -1;
9504 * Evaluate cmdline variables.
9506 * change '%' to curbuf->b_ffname
9507 * '#' to curwin->w_altfile
9508 * '<cword>' to word under the cursor
9509 * '<cWORD>' to WORD under the cursor
9510 * '<cfile>' to path name under the cursor
9511 * '<sfile>' to sourced file name
9512 * '<afile>' to file name for autocommand
9513 * '<abuf>' to buffer number for autocommand
9514 * '<amatch>' to matching name for autocommand
9516 * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
9517 * "" for error without a message) and NULL is returned.
9518 * Returns an allocated string if a valid match was found.
9519 * Returns NULL if no match was found. "usedlen" then still contains the
9520 * number of characters to skip.
9522 char_u *
9523 eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped)
9524 char_u *src; /* pointer into commandline */
9525 char_u *srcstart; /* beginning of valid memory for src */
9526 int *usedlen; /* characters after src that are used */
9527 linenr_T *lnump; /* line number for :e command, or NULL */
9528 char_u **errormsg; /* pointer to error message */
9529 int *escaped; /* return value has escaped white space (can
9530 * be NULL) */
9532 int i;
9533 char_u *s;
9534 char_u *result;
9535 char_u *resultbuf = NULL;
9536 int resultlen;
9537 buf_T *buf;
9538 int valid = VALID_HEAD + VALID_PATH; /* assume valid result */
9539 int spec_idx;
9540 #ifdef FEAT_MODIFY_FNAME
9541 int skip_mod = FALSE;
9542 #endif
9544 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
9545 char_u strbuf[30];
9546 #endif
9548 *errormsg = NULL;
9549 if (escaped != NULL)
9550 *escaped = FALSE;
9553 * Check if there is something to do.
9555 spec_idx = find_cmdline_var(src, usedlen);
9556 if (spec_idx < 0) /* no match */
9558 *usedlen = 1;
9559 return NULL;
9563 * Skip when preceded with a backslash "\%" and "\#".
9564 * Note: In "\\%" the % is also not recognized!
9566 if (src > srcstart && src[-1] == '\\')
9568 *usedlen = 0;
9569 STRMOVE(src - 1, src); /* remove backslash */
9570 return NULL;
9574 * word or WORD under cursor
9576 if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
9578 resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
9579 (FIND_IDENT|FIND_STRING) : FIND_STRING);
9580 if (resultlen == 0)
9582 *errormsg = (char_u *)"";
9583 return NULL;
9588 * '#': Alternate file name
9589 * '%': Current file name
9590 * File name under the cursor
9591 * File name for autocommand
9592 * and following modifiers
9594 else
9596 switch (spec_idx)
9598 case SPEC_PERC: /* '%': current file */
9599 if (curbuf->b_fname == NULL)
9601 result = (char_u *)"";
9602 valid = 0; /* Must have ":p:h" to be valid */
9604 else
9605 #ifdef RISCOS
9606 /* Always use the full path for RISC OS if possible. */
9607 result = curbuf->b_ffname;
9608 if (result == NULL)
9609 result = curbuf->b_fname;
9610 #else
9611 result = curbuf->b_fname;
9612 #endif
9613 break;
9615 case SPEC_HASH: /* '#' or "#99": alternate file */
9616 if (src[1] == '#') /* "##": the argument list */
9618 result = arg_all();
9619 resultbuf = result;
9620 *usedlen = 2;
9621 if (escaped != NULL)
9622 *escaped = TRUE;
9623 #ifdef FEAT_MODIFY_FNAME
9624 skip_mod = TRUE;
9625 #endif
9626 break;
9628 s = src + 1;
9629 if (*s == '<') /* "#<99" uses v:oldfiles */
9630 ++s;
9631 i = (int)getdigits(&s);
9632 *usedlen = (int)(s - src); /* length of what we expand */
9634 if (src[1] == '<')
9636 if (*usedlen < 2)
9638 /* Should we give an error message for #<text? */
9639 *usedlen = 1;
9640 return NULL;
9642 #ifdef FEAT_EVAL
9643 result = list_find_str(get_vim_var_list(VV_OLDFILES),
9644 (long)i);
9645 if (result == NULL)
9647 *errormsg = (char_u *)"";
9648 return NULL;
9650 #else
9651 *errormsg = (char_u *)_("E809: #< is not available without the +eval feature");
9652 return NULL;
9653 #endif
9655 else
9657 buf = buflist_findnr(i);
9658 if (buf == NULL)
9660 *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
9661 return NULL;
9663 if (lnump != NULL)
9664 *lnump = ECMD_LAST;
9665 if (buf->b_fname == NULL)
9667 result = (char_u *)"";
9668 valid = 0; /* Must have ":p:h" to be valid */
9670 else
9671 result = buf->b_fname;
9673 break;
9675 #ifdef FEAT_SEARCHPATH
9676 case SPEC_CFILE: /* file name under cursor */
9677 result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
9678 if (result == NULL)
9680 *errormsg = (char_u *)"";
9681 return NULL;
9683 resultbuf = result; /* remember allocated string */
9684 break;
9685 #endif
9687 #ifdef FEAT_AUTOCMD
9688 case SPEC_AFILE: /* file name for autocommand */
9689 result = autocmd_fname;
9690 if (result != NULL && !autocmd_fname_full)
9692 /* Still need to turn the fname into a full path. It is
9693 * postponed to avoid a delay when <afile> is not used. */
9694 autocmd_fname_full = TRUE;
9695 result = FullName_save(autocmd_fname, FALSE);
9696 vim_free(autocmd_fname);
9697 autocmd_fname = result;
9699 if (result == NULL)
9701 *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
9702 return NULL;
9704 result = shorten_fname1(result);
9705 break;
9707 case SPEC_ABUF: /* buffer number for autocommand */
9708 if (autocmd_bufnr <= 0)
9710 *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
9711 return NULL;
9713 sprintf((char *)strbuf, "%d", autocmd_bufnr);
9714 result = strbuf;
9715 break;
9717 case SPEC_AMATCH: /* match name for autocommand */
9718 result = autocmd_match;
9719 if (result == NULL)
9721 *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
9722 return NULL;
9724 break;
9726 #endif
9727 case SPEC_SFILE: /* file name for ":so" command */
9728 result = sourcing_name;
9729 if (result == NULL)
9731 *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
9732 return NULL;
9734 break;
9735 #if defined(FEAT_CLIENTSERVER)
9736 case SPEC_CLIENT: /* Source of last submitted input */
9737 sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
9738 (long_u)clientWindow);
9739 result = strbuf;
9740 break;
9741 #endif
9744 resultlen = (int)STRLEN(result); /* length of new string */
9745 if (src[*usedlen] == '<') /* remove the file name extension */
9747 ++*usedlen;
9748 #ifdef RISCOS
9749 if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
9750 #else
9751 if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
9752 #endif
9753 resultlen = (int)(s - result);
9755 #ifdef FEAT_MODIFY_FNAME
9756 else if (!skip_mod)
9758 valid |= modify_fname(src, usedlen, &result, &resultbuf,
9759 &resultlen);
9760 if (result == NULL)
9762 *errormsg = (char_u *)"";
9763 return NULL;
9766 #endif
9769 if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
9771 if (valid != VALID_HEAD + VALID_PATH)
9772 /* xgettext:no-c-format */
9773 *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
9774 else
9775 *errormsg = (char_u *)_("E500: Evaluates to an empty string");
9776 result = NULL;
9778 else
9779 result = vim_strnsave(result, resultlen);
9780 vim_free(resultbuf);
9781 return result;
9785 * Concatenate all files in the argument list, separated by spaces, and return
9786 * it in one allocated string.
9787 * Spaces and backslashes in the file names are escaped with a backslash.
9788 * Returns NULL when out of memory.
9790 static char_u *
9791 arg_all()
9793 int len;
9794 int idx;
9795 char_u *retval = NULL;
9796 char_u *p;
9799 * Do this loop two times:
9800 * first time: compute the total length
9801 * second time: concatenate the names
9803 for (;;)
9805 len = 0;
9806 for (idx = 0; idx < ARGCOUNT; ++idx)
9808 p = alist_name(&ARGLIST[idx]);
9809 if (p != NULL)
9811 if (len > 0)
9813 /* insert a space in between names */
9814 if (retval != NULL)
9815 retval[len] = ' ';
9816 ++len;
9818 for ( ; *p != NUL; ++p)
9820 if (*p == ' ' || *p == '\\')
9822 /* insert a backslash */
9823 if (retval != NULL)
9824 retval[len] = '\\';
9825 ++len;
9827 if (retval != NULL)
9828 retval[len] = *p;
9829 ++len;
9834 /* second time: break here */
9835 if (retval != NULL)
9837 retval[len] = NUL;
9838 break;
9841 /* allocate memory */
9842 retval = alloc((unsigned)len + 1);
9843 if (retval == NULL)
9844 break;
9847 return retval;
9850 #if defined(FEAT_AUTOCMD) || defined(PROTO)
9852 * Expand the <sfile> string in "arg".
9854 * Returns an allocated string, or NULL for any error.
9856 char_u *
9857 expand_sfile(arg)
9858 char_u *arg;
9860 char_u *errormsg;
9861 int len;
9862 char_u *result;
9863 char_u *newres;
9864 char_u *repl;
9865 int srclen;
9866 char_u *p;
9868 result = vim_strsave(arg);
9869 if (result == NULL)
9870 return NULL;
9872 for (p = result; *p; )
9874 if (STRNCMP(p, "<sfile>", 7) != 0)
9875 ++p;
9876 else
9878 /* replace "<sfile>" with the sourced file name, and do ":" stuff */
9879 repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
9880 if (errormsg != NULL)
9882 if (*errormsg)
9883 emsg(errormsg);
9884 vim_free(result);
9885 return NULL;
9887 if (repl == NULL) /* no match (cannot happen) */
9889 p += srclen;
9890 continue;
9892 len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
9893 newres = alloc(len);
9894 if (newres == NULL)
9896 vim_free(repl);
9897 vim_free(result);
9898 return NULL;
9900 mch_memmove(newres, result, (size_t)(p - result));
9901 STRCPY(newres + (p - result), repl);
9902 len = (int)STRLEN(newres);
9903 STRCAT(newres, p + srclen);
9904 vim_free(repl);
9905 vim_free(result);
9906 result = newres;
9907 p = newres + len; /* continue after the match */
9911 return result;
9913 #endif
9915 #ifdef FEAT_SESSION
9916 static int ses_winsizes __ARGS((FILE *fd, int restore_size,
9917 win_T *tab_firstwin));
9918 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
9919 static frame_T *ses_skipframe __ARGS((frame_T *fr));
9920 static int ses_do_frame __ARGS((frame_T *fr));
9921 static int ses_do_win __ARGS((win_T *wp));
9922 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
9923 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
9924 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
9927 * Write openfile commands for the current buffers to an .exrc file.
9928 * Return FAIL on error, OK otherwise.
9930 static int
9931 makeopens(fd, dirnow)
9932 FILE *fd;
9933 char_u *dirnow; /* Current directory name */
9935 buf_T *buf;
9936 int only_save_windows = TRUE;
9937 int nr;
9938 int cnr = 1;
9939 int restore_size = TRUE;
9940 win_T *wp;
9941 char_u *sname;
9942 win_T *edited_win = NULL;
9943 int tabnr;
9944 win_T *tab_firstwin;
9945 frame_T *tab_topframe;
9946 int cur_arg_idx = 0;
9947 int next_arg_idx = 0;
9949 if (ssop_flags & SSOP_BUFFERS)
9950 only_save_windows = FALSE; /* Save ALL buffers */
9953 * Begin by setting the this_session variable, and then other
9954 * sessionable variables.
9956 #ifdef FEAT_EVAL
9957 if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
9958 return FAIL;
9959 if (ssop_flags & SSOP_GLOBALS)
9960 if (store_session_globals(fd) == FAIL)
9961 return FAIL;
9962 #endif
9965 * Close all windows but one.
9967 if (put_line(fd, "silent only") == FAIL)
9968 return FAIL;
9971 * Now a :cd command to the session directory or the current directory
9973 if (ssop_flags & SSOP_SESDIR)
9975 if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
9976 == FAIL)
9977 return FAIL;
9979 else if (ssop_flags & SSOP_CURDIR)
9981 sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
9982 if (sname == NULL
9983 || fputs("cd ", fd) < 0
9984 || ses_put_fname(fd, sname, &ssop_flags) == FAIL
9985 || put_eol(fd) == FAIL)
9987 vim_free(sname);
9988 return FAIL;
9990 vim_free(sname);
9994 * If there is an empty, unnamed buffer we will wipe it out later.
9995 * Remember the buffer number.
9997 if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
9998 return FAIL;
9999 if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL)
10000 return FAIL;
10001 if (put_line(fd, "endif") == FAIL)
10002 return FAIL;
10005 * Now save the current files, current buffer first.
10007 if (put_line(fd, "set shortmess=aoO") == FAIL)
10008 return FAIL;
10010 /* Now put the other buffers into the buffer list */
10011 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
10013 if (!(only_save_windows && buf->b_nwindows == 0)
10014 && !(buf->b_help && !(ssop_flags & SSOP_HELP))
10015 && buf->b_fname != NULL
10016 && buf->b_p_bl)
10018 if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
10019 : buf->b_wininfo->wi_fpos.lnum) < 0
10020 || ses_fname(fd, buf, &ssop_flags) == FAIL)
10021 return FAIL;
10025 /* the global argument list */
10026 if (ses_arglist(fd, "args", &global_alist.al_ga,
10027 !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
10028 return FAIL;
10030 if (ssop_flags & SSOP_RESIZE)
10032 /* Note: after the restore we still check it worked!*/
10033 if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
10034 || put_eol(fd) == FAIL)
10035 return FAIL;
10038 #ifdef FEAT_GUI
10039 if (gui.in_use && (ssop_flags & SSOP_WINPOS))
10041 int x, y;
10043 if (gui_mch_get_winpos(&x, &y) == OK)
10045 /* Note: after the restore we still check it worked!*/
10046 if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
10047 return FAIL;
10050 #endif
10053 * May repeat putting Windows for each tab, when "tabpages" is in
10054 * 'sessionoptions'.
10055 * Don't use goto_tabpage(), it may change directory and trigger
10056 * autocommands.
10058 tab_firstwin = firstwin; /* first window in tab page "tabnr" */
10059 tab_topframe = topframe;
10060 for (tabnr = 1; ; ++tabnr)
10062 int need_tabnew = FALSE;
10064 if ((ssop_flags & SSOP_TABPAGES))
10066 tabpage_T *tp = find_tabpage(tabnr);
10068 if (tp == NULL)
10069 break; /* done all tab pages */
10070 if (tp == curtab)
10072 tab_firstwin = firstwin;
10073 tab_topframe = topframe;
10075 else
10077 tab_firstwin = tp->tp_firstwin;
10078 tab_topframe = tp->tp_topframe;
10080 if (tabnr > 1)
10081 need_tabnew = TRUE;
10085 * Before creating the window layout, try loading one file. If this
10086 * is aborted we don't end up with a number of useless windows.
10087 * This may have side effects! (e.g., compressed or network file).
10089 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10091 if (ses_do_win(wp)
10092 && wp->w_buffer->b_ffname != NULL
10093 && !wp->w_buffer->b_help
10094 #ifdef FEAT_QUICKFIX
10095 && !bt_nofile(wp->w_buffer)
10096 #endif
10099 if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
10100 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
10101 return FAIL;
10102 need_tabnew = FALSE;
10103 if (!wp->w_arg_idx_invalid)
10104 edited_win = wp;
10105 break;
10109 /* If no file got edited create an empty tab page. */
10110 if (need_tabnew && put_line(fd, "tabnew") == FAIL)
10111 return FAIL;
10114 * Save current window layout.
10116 if (put_line(fd, "set splitbelow splitright") == FAIL)
10117 return FAIL;
10118 if (ses_win_rec(fd, tab_topframe) == FAIL)
10119 return FAIL;
10120 if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
10121 return FAIL;
10122 if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
10123 return FAIL;
10126 * Check if window sizes can be restored (no windows omitted).
10127 * Remember the window number of the current window after restoring.
10129 nr = 0;
10130 for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
10132 if (ses_do_win(wp))
10133 ++nr;
10134 else
10135 restore_size = FALSE;
10136 if (curwin == wp)
10137 cnr = nr;
10140 /* Go to the first window. */
10141 if (put_line(fd, "wincmd t") == FAIL)
10142 return FAIL;
10145 * If more than one window, see if sizes can be restored.
10146 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
10147 * resized when moving between windows.
10148 * Do this before restoring the view, so that the topline and the
10149 * cursor can be set. This is done again below.
10151 if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
10152 return FAIL;
10153 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10154 return FAIL;
10157 * Restore the view of the window (options, file, cursor, etc.).
10159 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10161 if (!ses_do_win(wp))
10162 continue;
10163 if (put_view(fd, wp, wp != edited_win, &ssop_flags,
10164 cur_arg_idx) == FAIL)
10165 return FAIL;
10166 if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
10167 return FAIL;
10168 next_arg_idx = wp->w_arg_idx;
10171 /* The argument index in the first tab page is zero, need to set it in
10172 * each window. For further tab pages it's the window where we do
10173 * "tabedit". */
10174 cur_arg_idx = next_arg_idx;
10177 * Restore cursor to the current window if it's not the first one.
10179 if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
10180 || put_eol(fd) == FAIL))
10181 return FAIL;
10184 * Restore window sizes again after jumping around in windows, because
10185 * the current window has a minimum size while others may not.
10187 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10188 return FAIL;
10190 /* Don't continue in another tab page when doing only the current one
10191 * or when at the last tab page. */
10192 if (!(ssop_flags & SSOP_TABPAGES))
10193 break;
10196 if (ssop_flags & SSOP_TABPAGES)
10198 if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
10199 || put_eol(fd) == FAIL)
10200 return FAIL;
10204 * Wipe out an empty unnamed buffer we started in.
10206 if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
10207 return FAIL;
10208 if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL)
10209 return FAIL;
10210 if (put_line(fd, "endif") == FAIL)
10211 return FAIL;
10212 if (put_line(fd, "unlet! s:wipebuf") == FAIL)
10213 return FAIL;
10215 /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
10216 if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
10217 p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
10218 return FAIL;
10221 * Lastly, execute the x.vim file if it exists.
10223 if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
10224 || put_line(fd, "if file_readable(s:sx)") == FAIL
10225 || put_line(fd, " exe \"source \" . fnameescape(s:sx)") == FAIL
10226 || put_line(fd, "endif") == FAIL)
10227 return FAIL;
10229 return OK;
10232 static int
10233 ses_winsizes(fd, restore_size, tab_firstwin)
10234 FILE *fd;
10235 int restore_size;
10236 win_T *tab_firstwin;
10238 int n = 0;
10239 win_T *wp;
10241 if (restore_size && (ssop_flags & SSOP_WINSIZE))
10243 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10245 if (!ses_do_win(wp))
10246 continue;
10247 ++n;
10249 /* restore height when not full height */
10250 if (wp->w_height + wp->w_status_height < topframe->fr_height
10251 && (fprintf(fd,
10252 "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
10253 n, (long)wp->w_height, Rows / 2, Rows) < 0
10254 || put_eol(fd) == FAIL))
10255 return FAIL;
10257 /* restore width when not full width */
10258 if (wp->w_width < Columns && (fprintf(fd,
10259 "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
10260 n, (long)wp->w_width, Columns / 2, Columns) < 0
10261 || put_eol(fd) == FAIL))
10262 return FAIL;
10265 else
10267 /* Just equalise window sizes */
10268 if (put_line(fd, "wincmd =") == FAIL)
10269 return FAIL;
10271 return OK;
10275 * Write commands to "fd" to recursively create windows for frame "fr",
10276 * horizontally and vertically split.
10277 * After the commands the last window in the frame is the current window.
10278 * Returns FAIL when writing the commands to "fd" fails.
10280 static int
10281 ses_win_rec(fd, fr)
10282 FILE *fd;
10283 frame_T *fr;
10285 frame_T *frc;
10286 int count = 0;
10288 if (fr->fr_layout != FR_LEAF)
10290 /* Find first frame that's not skipped and then create a window for
10291 * each following one (first frame is already there). */
10292 frc = ses_skipframe(fr->fr_child);
10293 if (frc != NULL)
10294 while ((frc = ses_skipframe(frc->fr_next)) != NULL)
10296 /* Make window as big as possible so that we have lots of room
10297 * to split. */
10298 if (put_line(fd, "wincmd _ | wincmd |") == FAIL
10299 || put_line(fd, fr->fr_layout == FR_COL
10300 ? "split" : "vsplit") == FAIL)
10301 return FAIL;
10302 ++count;
10305 /* Go back to the first window. */
10306 if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
10307 ? "%dwincmd k" : "%dwincmd h", count) < 0
10308 || put_eol(fd) == FAIL))
10309 return FAIL;
10311 /* Recursively create frames/windows in each window of this column or
10312 * row. */
10313 frc = ses_skipframe(fr->fr_child);
10314 while (frc != NULL)
10316 ses_win_rec(fd, frc);
10317 frc = ses_skipframe(frc->fr_next);
10318 /* Go to next window. */
10319 if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
10320 return FAIL;
10323 return OK;
10327 * Skip frames that don't contain windows we want to save in the Session.
10328 * Returns NULL when there none.
10330 static frame_T *
10331 ses_skipframe(fr)
10332 frame_T *fr;
10334 frame_T *frc;
10336 for (frc = fr; frc != NULL; frc = frc->fr_next)
10337 if (ses_do_frame(frc))
10338 break;
10339 return frc;
10343 * Return TRUE if frame "fr" has a window somewhere that we want to save in
10344 * the Session.
10346 static int
10347 ses_do_frame(fr)
10348 frame_T *fr;
10350 frame_T *frc;
10352 if (fr->fr_layout == FR_LEAF)
10353 return ses_do_win(fr->fr_win);
10354 for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
10355 if (ses_do_frame(frc))
10356 return TRUE;
10357 return FALSE;
10361 * Return non-zero if window "wp" is to be stored in the Session.
10363 static int
10364 ses_do_win(wp)
10365 win_T *wp;
10367 if (wp->w_buffer->b_fname == NULL
10368 #ifdef FEAT_QUICKFIX
10369 /* When 'buftype' is "nofile" can't restore the window contents. */
10370 || bt_nofile(wp->w_buffer)
10371 #endif
10373 return (ssop_flags & SSOP_BLANK);
10374 if (wp->w_buffer->b_help)
10375 return (ssop_flags & SSOP_HELP);
10376 return TRUE;
10380 * Write commands to "fd" to restore the view of a window.
10381 * Caller must make sure 'scrolloff' is zero.
10383 static int
10384 put_view(fd, wp, add_edit, flagp, current_arg_idx)
10385 FILE *fd;
10386 win_T *wp;
10387 int add_edit; /* add ":edit" command to view */
10388 unsigned *flagp; /* vop_flags or ssop_flags */
10389 int current_arg_idx; /* current argument index of the window, use
10390 * -1 if unknown */
10392 win_T *save_curwin;
10393 int f;
10394 int do_cursor;
10395 int did_next = FALSE;
10397 /* Always restore cursor position for ":mksession". For ":mkview" only
10398 * when 'viewoptions' contains "cursor". */
10399 do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
10402 * Local argument list.
10404 if (wp->w_alist == &global_alist)
10406 if (put_line(fd, "argglobal") == FAIL)
10407 return FAIL;
10409 else
10411 if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
10412 flagp == &vop_flags
10413 || !(*flagp & SSOP_CURDIR)
10414 || wp->w_localdir != NULL, flagp) == FAIL)
10415 return FAIL;
10418 /* Only when part of a session: restore the argument index. Some
10419 * arguments may have been deleted, check if the index is valid. */
10420 if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx <= WARGCOUNT(wp)
10421 && flagp == &ssop_flags)
10423 if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
10424 || put_eol(fd) == FAIL)
10425 return FAIL;
10426 did_next = TRUE;
10429 /* Edit the file. Skip this when ":next" already did it. */
10430 if (add_edit && (!did_next || wp->w_arg_idx_invalid))
10433 * Load the file.
10435 if (wp->w_buffer->b_ffname != NULL
10436 #ifdef FEAT_QUICKFIX
10437 && !bt_nofile(wp->w_buffer)
10438 #endif
10442 * Editing a file in this buffer: use ":edit file".
10443 * This may have side effects! (e.g., compressed or network file).
10445 if (fputs("edit ", fd) < 0
10446 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10447 return FAIL;
10449 else
10451 /* No file in this buffer, just make it empty. */
10452 if (put_line(fd, "enew") == FAIL)
10453 return FAIL;
10454 #ifdef FEAT_QUICKFIX
10455 if (wp->w_buffer->b_ffname != NULL)
10457 /* The buffer does have a name, but it's not a file name. */
10458 if (fputs("file ", fd) < 0
10459 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10460 return FAIL;
10462 #endif
10463 do_cursor = FALSE;
10468 * Local mappings and abbreviations.
10470 if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10471 && makemap(fd, wp->w_buffer) == FAIL)
10472 return FAIL;
10475 * Local options. Need to go to the window temporarily.
10476 * Store only local values when using ":mkview" and when ":mksession" is
10477 * used and 'sessionoptions' doesn't include "options".
10478 * Some folding options are always stored when "folds" is included,
10479 * otherwise the folds would not be restored correctly.
10481 save_curwin = curwin;
10482 curwin = wp;
10483 curbuf = curwin->w_buffer;
10484 if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10485 f = makeset(fd, OPT_LOCAL,
10486 flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
10487 #ifdef FEAT_FOLDING
10488 else if (*flagp & SSOP_FOLDS)
10489 f = makefoldset(fd);
10490 #endif
10491 else
10492 f = OK;
10493 curwin = save_curwin;
10494 curbuf = curwin->w_buffer;
10495 if (f == FAIL)
10496 return FAIL;
10498 #ifdef FEAT_FOLDING
10500 * Save Folds when 'buftype' is empty and for help files.
10502 if ((*flagp & SSOP_FOLDS)
10503 && wp->w_buffer->b_ffname != NULL
10504 # ifdef FEAT_QUICKFIX
10505 && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help)
10506 # endif
10509 if (put_folds(fd, wp) == FAIL)
10510 return FAIL;
10512 #endif
10515 * Set the cursor after creating folds, since that moves the cursor.
10517 if (do_cursor)
10520 /* Restore the cursor line in the file and relatively in the
10521 * window. Don't use "G", it changes the jumplist. */
10522 if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
10523 (long)wp->w_cursor.lnum,
10524 (long)(wp->w_cursor.lnum - wp->w_topline),
10525 (long)wp->w_height / 2, (long)wp->w_height) < 0
10526 || put_eol(fd) == FAIL
10527 || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
10528 || put_line(fd, "exe s:l") == FAIL
10529 || put_line(fd, "normal! zt") == FAIL
10530 || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
10531 || put_eol(fd) == FAIL)
10532 return FAIL;
10533 /* Restore the cursor column and left offset when not wrapping. */
10534 if (wp->w_cursor.col == 0)
10536 if (put_line(fd, "normal! 0") == FAIL)
10537 return FAIL;
10539 else
10541 if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
10543 if (fprintf(fd,
10544 "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
10545 (long)wp->w_cursor.col,
10546 (long)(wp->w_cursor.col - wp->w_leftcol),
10547 (long)wp->w_width / 2, (long)wp->w_width) < 0
10548 || put_eol(fd) == FAIL
10549 || put_line(fd, "if s:c > 0") == FAIL
10550 || fprintf(fd,
10551 " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
10552 (long)wp->w_cursor.col) < 0
10553 || put_eol(fd) == FAIL
10554 || put_line(fd, "else") == FAIL
10555 || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0
10556 || put_eol(fd) == FAIL
10557 || put_line(fd, "endif") == FAIL)
10558 return FAIL;
10560 else
10562 if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
10563 || put_eol(fd) == FAIL)
10564 return FAIL;
10570 * Local directory.
10572 if (wp->w_localdir != NULL)
10574 if (fputs("lcd ", fd) < 0
10575 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
10576 || put_eol(fd) == FAIL)
10577 return FAIL;
10578 did_lcd = TRUE;
10581 return OK;
10585 * Write an argument list to the session file.
10586 * Returns FAIL if writing fails.
10588 static int
10589 ses_arglist(fd, cmd, gap, fullname, flagp)
10590 FILE *fd;
10591 char *cmd;
10592 garray_T *gap;
10593 int fullname; /* TRUE: use full path name */
10594 unsigned *flagp;
10596 int i;
10597 char_u buf[MAXPATHL];
10598 char_u *s;
10600 if (gap->ga_len == 0)
10601 return put_line(fd, "silent! argdel *");
10602 if (fputs(cmd, fd) < 0)
10603 return FAIL;
10604 for (i = 0; i < gap->ga_len; ++i)
10606 /* NULL file names are skipped (only happens when out of memory). */
10607 s = alist_name(&((aentry_T *)gap->ga_data)[i]);
10608 if (s != NULL)
10610 if (fullname)
10612 (void)vim_FullName(s, buf, MAXPATHL, FALSE);
10613 s = buf;
10615 if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
10616 return FAIL;
10619 return put_eol(fd);
10623 * Write a buffer name to the session file.
10624 * Also ends the line.
10625 * Returns FAIL if writing fails.
10627 static int
10628 ses_fname(fd, buf, flagp)
10629 FILE *fd;
10630 buf_T *buf;
10631 unsigned *flagp;
10633 char_u *name;
10635 /* Use the short file name if the current directory is known at the time
10636 * the session file will be sourced.
10637 * Don't do this for ":mkview", we don't know the current directory.
10638 * Don't do this after ":lcd", we don't keep track of what the current
10639 * directory is. */
10640 if (buf->b_sfname != NULL
10641 && flagp == &ssop_flags
10642 && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
10643 #ifdef FEAT_AUTOCHDIR
10644 && !p_acd
10645 #endif
10646 && !did_lcd)
10647 name = buf->b_sfname;
10648 else
10649 name = buf->b_ffname;
10650 if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
10651 return FAIL;
10652 return OK;
10656 * Write a file name to the session file.
10657 * Takes care of the "slash" option in 'sessionoptions' and escapes special
10658 * characters.
10659 * Returns FAIL if writing fails.
10661 static int
10662 ses_put_fname(fd, name, flagp)
10663 FILE *fd;
10664 char_u *name;
10665 unsigned *flagp;
10667 char_u *sname;
10668 int retval = OK;
10669 int c;
10671 sname = home_replace_save(NULL, name);
10672 if (sname != NULL)
10673 name = sname;
10674 while (*name != NUL)
10676 #ifdef FEAT_MBYTE
10678 int l;
10680 if (has_mbyte && (l = (*mb_ptr2len)(name)) > 1)
10682 /* copy a multibyte char */
10683 while (--l >= 0)
10685 if (putc(*name, fd) != *name)
10686 retval = FAIL;
10687 ++name;
10689 continue;
10692 #endif
10693 c = *name++;
10694 if (c == '\\' && (*flagp & SSOP_SLASH))
10695 /* change a backslash to a forward slash */
10696 c = '/';
10697 else if ((vim_strchr(escape_chars, c) != NULL
10698 #ifdef BACKSLASH_IN_FILENAME
10699 && c != '\\'
10700 #endif
10701 ) || c == '#' || c == '%')
10703 /* escape a special character with a backslash */
10704 if (putc('\\', fd) != '\\')
10705 retval = FAIL;
10707 if (putc(c, fd) != c)
10708 retval = FAIL;
10710 vim_free(sname);
10711 return retval;
10715 * ":loadview [nr]"
10717 static void
10718 ex_loadview(eap)
10719 exarg_T *eap;
10721 char_u *fname;
10723 fname = get_view_file(*eap->arg);
10724 if (fname != NULL)
10726 do_source(fname, FALSE, DOSO_NONE);
10727 vim_free(fname);
10732 * Get the name of the view file for the current buffer.
10734 static char_u *
10735 get_view_file(c)
10736 int c;
10738 int len = 0;
10739 char_u *p, *s;
10740 char_u *retval;
10741 char_u *sname;
10743 if (curbuf->b_ffname == NULL)
10745 EMSG(_(e_noname));
10746 return NULL;
10748 sname = home_replace_save(NULL, curbuf->b_ffname);
10749 if (sname == NULL)
10750 return NULL;
10753 * We want a file name without separators, because we're not going to make
10754 * a directory.
10755 * "normal" path separator -> "=+"
10756 * "=" -> "=="
10757 * ":" path separator -> "=-"
10759 for (p = sname; *p; ++p)
10760 if (*p == '=' || vim_ispathsep(*p))
10761 ++len;
10762 retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
10763 if (retval != NULL)
10765 STRCPY(retval, p_vdir);
10766 add_pathsep(retval);
10767 s = retval + STRLEN(retval);
10768 for (p = sname; *p; ++p)
10770 if (*p == '=')
10772 *s++ = '=';
10773 *s++ = '=';
10775 else if (vim_ispathsep(*p))
10777 *s++ = '=';
10778 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
10779 || defined(VMS)
10780 if (*p == ':')
10781 *s++ = '-';
10782 else
10783 #endif
10784 *s++ = '+';
10786 else
10787 *s++ = *p;
10789 *s++ = '=';
10790 *s++ = c;
10791 STRCPY(s, ".vim");
10794 vim_free(sname);
10795 return retval;
10798 #endif /* FEAT_SESSION */
10801 * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
10802 * Return FAIL for a write error.
10805 put_eol(fd)
10806 FILE *fd;
10808 if (
10809 #ifdef USE_CRNL
10811 # ifdef MKSESSION_NL
10812 !mksession_nl &&
10813 # endif
10814 (putc('\r', fd) < 0)) ||
10815 #endif
10816 (putc('\n', fd) < 0))
10817 return FAIL;
10818 return OK;
10822 * Write a line to "fd".
10823 * Return FAIL for a write error.
10826 put_line(fd, s)
10827 FILE *fd;
10828 char *s;
10830 if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
10831 return FAIL;
10832 return OK;
10835 #ifdef FEAT_VIMINFO
10837 * ":rviminfo" and ":wviminfo".
10839 static void
10840 ex_viminfo(eap)
10841 exarg_T *eap;
10843 char_u *save_viminfo;
10845 save_viminfo = p_viminfo;
10846 if (*p_viminfo == NUL)
10847 p_viminfo = (char_u *)"'100";
10848 if (eap->cmdidx == CMD_rviminfo)
10850 if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
10851 | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
10852 EMSG(_("E195: Cannot open viminfo file for reading"));
10854 else
10855 write_viminfo(eap->arg, eap->forceit);
10856 p_viminfo = save_viminfo;
10858 #endif
10860 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
10862 * Make a dialog message in "buff[IOSIZE]".
10863 * "format" must contain "%s".
10865 void
10866 dialog_msg(buff, format, fname)
10867 char_u *buff;
10868 char *format;
10869 char_u *fname;
10871 if (fname == NULL)
10872 fname = (char_u *)_("Untitled");
10873 vim_snprintf((char *)buff, IOSIZE, format, fname);
10875 #endif
10878 * ":behave {mswin,xterm}"
10880 static void
10881 ex_behave(eap)
10882 exarg_T *eap;
10884 if (STRCMP(eap->arg, "mswin") == 0)
10886 set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
10887 set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
10888 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
10889 set_option_value((char_u *)"keymodel", 0L,
10890 (char_u *)"startsel,stopsel", 0);
10892 else if (STRCMP(eap->arg, "xterm") == 0)
10894 set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
10895 set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
10896 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
10897 set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
10899 else
10900 EMSG2(_(e_invarg2), eap->arg);
10903 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10905 * Function given to ExpandGeneric() to obtain the possible arguments of the
10906 * ":behave {mswin,xterm}" command.
10908 char_u *
10909 get_behave_arg(xp, idx)
10910 expand_T *xp UNUSED;
10911 int idx;
10913 if (idx == 0)
10914 return (char_u *)"mswin";
10915 if (idx == 1)
10916 return (char_u *)"xterm";
10917 return NULL;
10919 #endif
10921 #ifdef FEAT_AUTOCMD
10922 static int filetype_detect = FALSE;
10923 static int filetype_plugin = FALSE;
10924 static int filetype_indent = FALSE;
10927 * ":filetype [plugin] [indent] {on,off,detect}"
10928 * on: Load the filetype.vim file to install autocommands for file types.
10929 * off: Load the ftoff.vim file to remove all autocommands for file types.
10930 * plugin on: load filetype.vim and ftplugin.vim
10931 * plugin off: load ftplugof.vim
10932 * indent on: load filetype.vim and indent.vim
10933 * indent off: load indoff.vim
10935 static void
10936 ex_filetype(eap)
10937 exarg_T *eap;
10939 char_u *arg = eap->arg;
10940 int plugin = FALSE;
10941 int indent = FALSE;
10943 if (*eap->arg == NUL)
10945 /* Print current status. */
10946 smsg((char_u *)"filetype detection:%s plugin:%s indent:%s",
10947 filetype_detect ? "ON" : "OFF",
10948 filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
10949 filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
10950 return;
10953 /* Accept "plugin" and "indent" in any order. */
10954 for (;;)
10956 if (STRNCMP(arg, "plugin", 6) == 0)
10958 plugin = TRUE;
10959 arg = skipwhite(arg + 6);
10960 continue;
10962 if (STRNCMP(arg, "indent", 6) == 0)
10964 indent = TRUE;
10965 arg = skipwhite(arg + 6);
10966 continue;
10968 break;
10970 if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
10972 if (*arg == 'o' || !filetype_detect)
10974 source_runtime((char_u *)FILETYPE_FILE, TRUE);
10975 filetype_detect = TRUE;
10976 if (plugin)
10978 source_runtime((char_u *)FTPLUGIN_FILE, TRUE);
10979 filetype_plugin = TRUE;
10981 if (indent)
10983 source_runtime((char_u *)INDENT_FILE, TRUE);
10984 filetype_indent = TRUE;
10987 if (*arg == 'd')
10989 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
10990 do_modelines(0);
10993 else if (STRCMP(arg, "off") == 0)
10995 if (plugin || indent)
10997 if (plugin)
10999 source_runtime((char_u *)FTPLUGOF_FILE, TRUE);
11000 filetype_plugin = FALSE;
11002 if (indent)
11004 source_runtime((char_u *)INDOFF_FILE, TRUE);
11005 filetype_indent = FALSE;
11008 else
11010 source_runtime((char_u *)FTOFF_FILE, TRUE);
11011 filetype_detect = FALSE;
11014 else
11015 EMSG2(_(e_invarg2), arg);
11019 * ":setfiletype {name}"
11021 static void
11022 ex_setfiletype(eap)
11023 exarg_T *eap;
11025 if (!did_filetype)
11026 set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
11028 #endif
11030 static void
11031 ex_digraphs(eap)
11032 exarg_T *eap UNUSED;
11034 #ifdef FEAT_DIGRAPHS
11035 if (*eap->arg != NUL)
11036 putdigraph(eap->arg);
11037 else
11038 listdigraphs();
11039 #else
11040 EMSG(_("E196: No digraphs in this version"));
11041 #endif
11044 static void
11045 ex_set(eap)
11046 exarg_T *eap;
11048 int flags = 0;
11050 if (eap->cmdidx == CMD_setlocal)
11051 flags = OPT_LOCAL;
11052 else if (eap->cmdidx == CMD_setglobal)
11053 flags = OPT_GLOBAL;
11054 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
11055 if (cmdmod.browse && flags == 0)
11056 ex_options(eap);
11057 else
11058 #endif
11059 (void)do_set(eap->arg, flags);
11062 #ifdef FEAT_SEARCH_EXTRA
11064 * ":nohlsearch"
11066 static void
11067 ex_nohlsearch(eap)
11068 exarg_T *eap UNUSED;
11070 no_hlsearch = TRUE;
11071 redraw_all_later(SOME_VALID);
11075 * ":[N]match {group} {pattern}"
11076 * Sets nextcmd to the start of the next command, if any. Also called when
11077 * skipping commands to find the next command.
11079 static void
11080 ex_match(eap)
11081 exarg_T *eap;
11083 char_u *p;
11084 char_u *g = NULL;
11085 char_u *end;
11086 int c;
11087 int id;
11089 if (eap->line2 <= 3)
11090 id = eap->line2;
11091 else
11093 EMSG(e_invcmd);
11094 return;
11097 /* First clear any old pattern. */
11098 if (!eap->skip)
11099 match_delete(curwin, id, FALSE);
11101 if (ends_excmd(*eap->arg))
11102 end = eap->arg;
11103 else if ((STRNICMP(eap->arg, "none", 4) == 0
11104 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
11105 end = eap->arg + 4;
11106 else
11108 p = skiptowhite(eap->arg);
11109 if (!eap->skip)
11110 g = vim_strnsave(eap->arg, (int)(p - eap->arg));
11111 p = skipwhite(p);
11112 if (*p == NUL)
11114 /* There must be two arguments. */
11115 EMSG2(_(e_invarg2), eap->arg);
11116 return;
11118 end = skip_regexp(p + 1, *p, TRUE, NULL);
11119 if (!eap->skip)
11121 if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
11123 eap->errmsg = e_trailing;
11124 return;
11126 if (*end != *p)
11128 EMSG2(_(e_invarg2), p);
11129 return;
11132 c = *end;
11133 *end = NUL;
11134 match_add(curwin, g, p + 1, 10, id);
11135 vim_free(g);
11136 *end = c;
11139 eap->nextcmd = find_nextcmd(end);
11141 #endif
11143 #ifdef FEAT_CRYPT
11145 * ":X": Get crypt key
11147 static void
11148 ex_X(eap)
11149 exarg_T *eap UNUSED;
11151 (void)get_crypt_key(TRUE, TRUE);
11153 #endif
11155 #ifdef FEAT_FOLDING
11156 static void
11157 ex_fold(eap)
11158 exarg_T *eap;
11160 if (foldManualAllowed(TRUE))
11161 foldCreate(eap->line1, eap->line2);
11164 static void
11165 ex_foldopen(eap)
11166 exarg_T *eap;
11168 opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
11169 eap->forceit, FALSE);
11172 static void
11173 ex_folddo(eap)
11174 exarg_T *eap;
11176 linenr_T lnum;
11178 /* First set the marks for all lines closed/open. */
11179 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
11180 if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
11181 ml_setmarked(lnum);
11183 /* Execute the command on the marked lines. */
11184 global_exe(eap->arg);
11185 ml_clearmarked(); /* clear rest of the marks */
11187 #endif