Merge branch 'vim-with-runtime' into feat/persistent-undo
[vim_extended.git] / src / ex_docmd.c
blobfaa803888619fd289eb66641b709f1d30204dfa8
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 int bad_char_idx;
4700 char_u *p;
4701 #endif
4703 /* ":edit ++[no]bin[ary] file" */
4704 if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4706 if (*arg == 'n')
4708 arg += 2;
4709 eap->force_bin = FORCE_NOBIN;
4711 else
4712 eap->force_bin = FORCE_BIN;
4713 if (!checkforcmd(&arg, "binary", 3))
4714 return FAIL;
4715 eap->arg = skipwhite(arg);
4716 return OK;
4719 /* ":read ++edit file" */
4720 if (STRNCMP(arg, "edit", 4) == 0)
4722 eap->read_edit = TRUE;
4723 eap->arg = skipwhite(arg + 4);
4724 return OK;
4727 if (STRNCMP(arg, "ff", 2) == 0)
4729 arg += 2;
4730 pp = &eap->force_ff;
4732 else if (STRNCMP(arg, "fileformat", 10) == 0)
4734 arg += 10;
4735 pp = &eap->force_ff;
4737 #ifdef FEAT_MBYTE
4738 else if (STRNCMP(arg, "enc", 3) == 0)
4740 arg += 3;
4741 pp = &eap->force_enc;
4743 else if (STRNCMP(arg, "encoding", 8) == 0)
4745 arg += 8;
4746 pp = &eap->force_enc;
4748 else if (STRNCMP(arg, "bad", 3) == 0)
4750 arg += 3;
4751 pp = &bad_char_idx;
4753 #endif
4755 if (pp == NULL || *arg != '=')
4756 return FAIL;
4758 ++arg;
4759 *pp = (int)(arg - eap->cmd);
4760 arg = skip_cmd_arg(arg, FALSE);
4761 eap->arg = skipwhite(arg);
4762 *arg = NUL;
4764 #ifdef FEAT_MBYTE
4765 if (pp == &eap->force_ff)
4767 #endif
4768 if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4769 return FAIL;
4770 #ifdef FEAT_MBYTE
4772 else if (pp == &eap->force_enc)
4774 /* Make 'fileencoding' lower case. */
4775 for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4776 *p = TOLOWER_ASC(*p);
4778 else
4780 /* Check ++bad= argument. Must be a single-byte character, "keep" or
4781 * "drop". */
4782 p = eap->cmd + bad_char_idx;
4783 if (STRICMP(p, "keep") == 0)
4784 eap->bad_char = BAD_KEEP;
4785 else if (STRICMP(p, "drop") == 0)
4786 eap->bad_char = BAD_DROP;
4787 else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
4788 eap->bad_char = *p;
4789 else
4790 return FAIL;
4792 #endif
4794 return OK;
4798 * ":abbreviate" and friends.
4800 static void
4801 ex_abbreviate(eap)
4802 exarg_T *eap;
4804 do_exmap(eap, TRUE); /* almost the same as mapping */
4808 * ":map" and friends.
4810 static void
4811 ex_map(eap)
4812 exarg_T *eap;
4815 * If we are sourcing .exrc or .vimrc in current directory we
4816 * print the mappings for security reasons.
4818 if (secure)
4820 secure = 2;
4821 msg_outtrans(eap->cmd);
4822 msg_putchar('\n');
4824 do_exmap(eap, FALSE);
4828 * ":unmap" and friends.
4830 static void
4831 ex_unmap(eap)
4832 exarg_T *eap;
4834 do_exmap(eap, FALSE);
4838 * ":mapclear" and friends.
4840 static void
4841 ex_mapclear(eap)
4842 exarg_T *eap;
4844 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4848 * ":abclear" and friends.
4850 static void
4851 ex_abclear(eap)
4852 exarg_T *eap;
4854 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4857 #ifdef FEAT_AUTOCMD
4858 static void
4859 ex_autocmd(eap)
4860 exarg_T *eap;
4863 * Disallow auto commands from .exrc and .vimrc in current
4864 * directory for security reasons.
4866 if (secure)
4868 secure = 2;
4869 eap->errmsg = e_curdir;
4871 else if (eap->cmdidx == CMD_autocmd)
4872 do_autocmd(eap->arg, eap->forceit);
4873 else
4874 do_augroup(eap->arg, eap->forceit);
4878 * ":doautocmd": Apply the automatic commands to the current buffer.
4880 static void
4881 ex_doautocmd(eap)
4882 exarg_T *eap;
4884 (void)do_doautocmd(eap->arg, TRUE);
4885 do_modelines(0);
4887 #endif
4889 #ifdef FEAT_LISTCMDS
4891 * :[N]bunload[!] [N] [bufname] unload buffer
4892 * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4893 * :[N]bwipeout[!] [N] [bufname] delete buffer really
4895 static void
4896 ex_bunload(eap)
4897 exarg_T *eap;
4899 eap->errmsg = do_bufdel(
4900 eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4901 : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4902 : DOBUF_UNLOAD, eap->arg,
4903 eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4907 * :[N]buffer [N] to buffer N
4908 * :[N]sbuffer [N] to buffer N
4910 static void
4911 ex_buffer(eap)
4912 exarg_T *eap;
4914 if (*eap->arg)
4915 eap->errmsg = e_trailing;
4916 else
4918 if (eap->addr_count == 0) /* default is current buffer */
4919 goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4920 else
4921 goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4926 * :[N]bmodified [N] to next mod. buffer
4927 * :[N]sbmodified [N] to next mod. buffer
4929 static void
4930 ex_bmodified(eap)
4931 exarg_T *eap;
4933 goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4937 * :[N]bnext [N] to next buffer
4938 * :[N]sbnext [N] split and to next buffer
4940 static void
4941 ex_bnext(eap)
4942 exarg_T *eap;
4944 goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4948 * :[N]bNext [N] to previous buffer
4949 * :[N]bprevious [N] to previous buffer
4950 * :[N]sbNext [N] split and to previous buffer
4951 * :[N]sbprevious [N] split and to previous buffer
4953 static void
4954 ex_bprevious(eap)
4955 exarg_T *eap;
4957 goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4961 * :brewind to first buffer
4962 * :bfirst to first buffer
4963 * :sbrewind split and to first buffer
4964 * :sbfirst split and to first buffer
4966 static void
4967 ex_brewind(eap)
4968 exarg_T *eap;
4970 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4974 * :blast to last buffer
4975 * :sblast split and to last buffer
4977 static void
4978 ex_blast(eap)
4979 exarg_T *eap;
4981 goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4983 #endif
4986 ends_excmd(c)
4987 int c;
4989 return (c == NUL || c == '|' || c == '"' || c == '\n');
4992 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
4993 || defined(PROTO)
4995 * Return the next command, after the first '|' or '\n'.
4996 * Return NULL if not found.
4998 char_u *
4999 find_nextcmd(p)
5000 char_u *p;
5002 while (*p != '|' && *p != '\n')
5004 if (*p == NUL)
5005 return NULL;
5006 ++p;
5008 return (p + 1);
5010 #endif
5013 * Check if *p is a separator between Ex commands.
5014 * Return NULL if it isn't, (p + 1) if it is.
5016 char_u *
5017 check_nextcmd(p)
5018 char_u *p;
5020 p = skipwhite(p);
5021 if (*p == '|' || *p == '\n')
5022 return (p + 1);
5023 else
5024 return NULL;
5028 * - if there are more files to edit
5029 * - and this is the last window
5030 * - and forceit not used
5031 * - and not repeated twice on a row
5032 * return FAIL and give error message if 'message' TRUE
5033 * return OK otherwise
5035 static int
5036 check_more(message, forceit)
5037 int message; /* when FALSE check only, no messages */
5038 int forceit;
5040 int n = ARGCOUNT - curwin->w_arg_idx - 1;
5042 if (!forceit && only_one_window()
5043 && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5045 if (message)
5047 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5048 if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5050 char_u buff[IOSIZE];
5052 if (n == 1)
5053 STRCPY(buff, _("1 more file to edit. Quit anyway?"));
5054 else
5055 vim_snprintf((char *)buff, IOSIZE,
5056 _("%d more files to edit. Quit anyway?"), n);
5057 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5058 return OK;
5059 return FAIL;
5061 #endif
5062 if (n == 1)
5063 EMSG(_("E173: 1 more file to edit"));
5064 else
5065 EMSGN(_("E173: %ld more files to edit"), n);
5066 quitmore = 2; /* next try to quit is allowed */
5068 return FAIL;
5070 return OK;
5073 #ifdef FEAT_CMDL_COMPL
5075 * Function given to ExpandGeneric() to obtain the list of command names.
5077 char_u *
5078 get_command_name(xp, idx)
5079 expand_T *xp UNUSED;
5080 int idx;
5082 if (idx >= (int)CMD_SIZE)
5083 # ifdef FEAT_USR_CMDS
5084 return get_user_command_name(idx);
5085 # else
5086 return NULL;
5087 # endif
5088 return cmdnames[idx].cmd_name;
5090 #endif
5092 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5093 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));
5094 static void uc_list __ARGS((char_u *name, size_t name_len));
5095 static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
5096 static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp));
5097 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));
5099 static int
5100 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
5101 char_u *name;
5102 size_t name_len;
5103 char_u *rep;
5104 long argt;
5105 long def;
5106 int flags;
5107 int compl;
5108 char_u *compl_arg;
5109 int force;
5111 ucmd_T *cmd = NULL;
5112 char_u *p;
5113 int i;
5114 int cmp = 1;
5115 char_u *rep_buf = NULL;
5116 garray_T *gap;
5118 replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5119 if (rep_buf == NULL)
5121 /* Can't replace termcodes - try using the string as is */
5122 rep_buf = vim_strsave(rep);
5124 /* Give up if out of memory */
5125 if (rep_buf == NULL)
5126 return FAIL;
5129 /* get address of growarray: global or in curbuf */
5130 if (flags & UC_BUFFER)
5132 gap = &curbuf->b_ucmds;
5133 if (gap->ga_itemsize == 0)
5134 ga_init2(gap, (int)sizeof(ucmd_T), 4);
5136 else
5137 gap = &ucmds;
5139 /* Search for the command in the already defined commands. */
5140 for (i = 0; i < gap->ga_len; ++i)
5142 size_t len;
5144 cmd = USER_CMD_GA(gap, i);
5145 len = STRLEN(cmd->uc_name);
5146 cmp = STRNCMP(name, cmd->uc_name, name_len);
5147 if (cmp == 0)
5149 if (name_len < len)
5150 cmp = -1;
5151 else if (name_len > len)
5152 cmp = 1;
5155 if (cmp == 0)
5157 if (!force)
5159 EMSG(_("E174: Command already exists: add ! to replace it"));
5160 goto fail;
5163 vim_free(cmd->uc_rep);
5164 cmd->uc_rep = NULL;
5165 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5166 vim_free(cmd->uc_compl_arg);
5167 cmd->uc_compl_arg = NULL;
5168 #endif
5169 break;
5172 /* Stop as soon as we pass the name to add */
5173 if (cmp < 0)
5174 break;
5177 /* Extend the array unless we're replacing an existing command */
5178 if (cmp != 0)
5180 if (ga_grow(gap, 1) != OK)
5181 goto fail;
5182 if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5183 goto fail;
5185 cmd = USER_CMD_GA(gap, i);
5186 mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5188 ++gap->ga_len;
5190 cmd->uc_name = p;
5193 cmd->uc_rep = rep_buf;
5194 cmd->uc_argt = argt;
5195 cmd->uc_def = def;
5196 cmd->uc_compl = compl;
5197 #ifdef FEAT_EVAL
5198 cmd->uc_scriptID = current_SID;
5199 # ifdef FEAT_CMDL_COMPL
5200 cmd->uc_compl_arg = compl_arg;
5201 # endif
5202 #endif
5204 return OK;
5206 fail:
5207 vim_free(rep_buf);
5208 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5209 vim_free(compl_arg);
5210 #endif
5211 return FAIL;
5215 * List of names for completion for ":command" with the EXPAND_ flag.
5216 * Must be alphabetical for completion.
5218 static struct
5220 int expand;
5221 char *name;
5222 } command_complete[] =
5224 {EXPAND_AUGROUP, "augroup"},
5225 {EXPAND_BUFFERS, "buffer"},
5226 {EXPAND_COMMANDS, "command"},
5227 #if defined(FEAT_CSCOPE)
5228 {EXPAND_CSCOPE, "cscope"},
5229 #endif
5230 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5231 {EXPAND_USER_DEFINED, "custom"},
5232 {EXPAND_USER_LIST, "customlist"},
5233 #endif
5234 {EXPAND_DIRECTORIES, "dir"},
5235 {EXPAND_ENV_VARS, "environment"},
5236 {EXPAND_EVENTS, "event"},
5237 {EXPAND_EXPRESSION, "expression"},
5238 {EXPAND_FILES, "file"},
5239 {EXPAND_FUNCTIONS, "function"},
5240 {EXPAND_HELP, "help"},
5241 {EXPAND_HIGHLIGHT, "highlight"},
5242 {EXPAND_MAPPINGS, "mapping"},
5243 {EXPAND_MENUS, "menu"},
5244 {EXPAND_SETTINGS, "option"},
5245 {EXPAND_SHELLCMD, "shellcmd"},
5246 #if defined(FEAT_SIGNS)
5247 {EXPAND_SIGN, "sign"},
5248 #endif
5249 {EXPAND_TAGS, "tag"},
5250 {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5251 {EXPAND_USER_VARS, "var"},
5252 {0, NULL}
5255 static void
5256 uc_list(name, name_len)
5257 char_u *name;
5258 size_t name_len;
5260 int i, j;
5261 int found = FALSE;
5262 ucmd_T *cmd;
5263 int len;
5264 long a;
5265 garray_T *gap;
5267 gap = &curbuf->b_ucmds;
5268 for (;;)
5270 for (i = 0; i < gap->ga_len; ++i)
5272 cmd = USER_CMD_GA(gap, i);
5273 a = (long)cmd->uc_argt;
5275 /* Skip commands which don't match the requested prefix */
5276 if (STRNCMP(name, cmd->uc_name, name_len) != 0)
5277 continue;
5279 /* Put out the title first time */
5280 if (!found)
5281 MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition"));
5282 found = TRUE;
5283 msg_putchar('\n');
5284 if (got_int)
5285 break;
5287 /* Special cases */
5288 msg_putchar(a & BANG ? '!' : ' ');
5289 msg_putchar(a & REGSTR ? '"' : ' ');
5290 msg_putchar(gap != &ucmds ? 'b' : ' ');
5291 msg_putchar(' ');
5293 msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
5294 len = (int)STRLEN(cmd->uc_name) + 4;
5296 do {
5297 msg_putchar(' ');
5298 ++len;
5299 } while (len < 16);
5301 len = 0;
5303 /* Arguments */
5304 switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
5306 case 0: IObuff[len++] = '0'; break;
5307 case (EXTRA): IObuff[len++] = '*'; break;
5308 case (EXTRA|NOSPC): IObuff[len++] = '?'; break;
5309 case (EXTRA|NEEDARG): IObuff[len++] = '+'; break;
5310 case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
5313 do {
5314 IObuff[len++] = ' ';
5315 } while (len < 5);
5317 /* Range */
5318 if (a & (RANGE|COUNT))
5320 if (a & COUNT)
5322 /* -count=N */
5323 sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
5324 len += (int)STRLEN(IObuff + len);
5326 else if (a & DFLALL)
5327 IObuff[len++] = '%';
5328 else if (cmd->uc_def >= 0)
5330 /* -range=N */
5331 sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
5332 len += (int)STRLEN(IObuff + len);
5334 else
5335 IObuff[len++] = '.';
5338 do {
5339 IObuff[len++] = ' ';
5340 } while (len < 11);
5342 /* Completion */
5343 for (j = 0; command_complete[j].expand != 0; ++j)
5344 if (command_complete[j].expand == cmd->uc_compl)
5346 STRCPY(IObuff + len, command_complete[j].name);
5347 len += (int)STRLEN(IObuff + len);
5348 break;
5351 do {
5352 IObuff[len++] = ' ';
5353 } while (len < 21);
5355 IObuff[len] = '\0';
5356 msg_outtrans(IObuff);
5358 msg_outtrans_special(cmd->uc_rep, FALSE);
5359 #ifdef FEAT_EVAL
5360 if (p_verbose > 0)
5361 last_set_msg(cmd->uc_scriptID);
5362 #endif
5363 out_flush();
5364 ui_breakcheck();
5365 if (got_int)
5366 break;
5368 if (gap == &ucmds || i < gap->ga_len)
5369 break;
5370 gap = &ucmds;
5373 if (!found)
5374 MSG(_("No user-defined commands found"));
5377 static char_u *
5378 uc_fun_cmd()
5380 static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
5381 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
5382 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
5383 0xb9, 0x7f, 0};
5384 int i;
5386 for (i = 0; fcmd[i]; ++i)
5387 IObuff[i] = fcmd[i] - 0x40;
5388 IObuff[i] = 0;
5389 return IObuff;
5392 static int
5393 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
5394 char_u *attr;
5395 size_t len;
5396 long *argt;
5397 long *def;
5398 int *flags;
5399 int *compl;
5400 char_u **compl_arg;
5402 char_u *p;
5404 if (len == 0)
5406 EMSG(_("E175: No attribute specified"));
5407 return FAIL;
5410 /* First, try the simple attributes (no arguments) */
5411 if (STRNICMP(attr, "bang", len) == 0)
5412 *argt |= BANG;
5413 else if (STRNICMP(attr, "buffer", len) == 0)
5414 *flags |= UC_BUFFER;
5415 else if (STRNICMP(attr, "register", len) == 0)
5416 *argt |= REGSTR;
5417 else if (STRNICMP(attr, "bar", len) == 0)
5418 *argt |= TRLBAR;
5419 else
5421 int i;
5422 char_u *val = NULL;
5423 size_t vallen = 0;
5424 size_t attrlen = len;
5426 /* Look for the attribute name - which is the part before any '=' */
5427 for (i = 0; i < (int)len; ++i)
5429 if (attr[i] == '=')
5431 val = &attr[i + 1];
5432 vallen = len - i - 1;
5433 attrlen = i;
5434 break;
5438 if (STRNICMP(attr, "nargs", attrlen) == 0)
5440 if (vallen == 1)
5442 if (*val == '0')
5443 /* Do nothing - this is the default */;
5444 else if (*val == '1')
5445 *argt |= (EXTRA | NOSPC | NEEDARG);
5446 else if (*val == '*')
5447 *argt |= EXTRA;
5448 else if (*val == '?')
5449 *argt |= (EXTRA | NOSPC);
5450 else if (*val == '+')
5451 *argt |= (EXTRA | NEEDARG);
5452 else
5453 goto wrong_nargs;
5455 else
5457 wrong_nargs:
5458 EMSG(_("E176: Invalid number of arguments"));
5459 return FAIL;
5462 else if (STRNICMP(attr, "range", attrlen) == 0)
5464 *argt |= RANGE;
5465 if (vallen == 1 && *val == '%')
5466 *argt |= DFLALL;
5467 else if (val != NULL)
5469 p = val;
5470 if (*def >= 0)
5472 two_count:
5473 EMSG(_("E177: Count cannot be specified twice"));
5474 return FAIL;
5477 *def = getdigits(&p);
5478 *argt |= (ZEROR | NOTADR);
5480 if (p != val + vallen || vallen == 0)
5482 invalid_count:
5483 EMSG(_("E178: Invalid default value for count"));
5484 return FAIL;
5488 else if (STRNICMP(attr, "count", attrlen) == 0)
5490 *argt |= (COUNT | ZEROR | RANGE | NOTADR);
5492 if (val != NULL)
5494 p = val;
5495 if (*def >= 0)
5496 goto two_count;
5498 *def = getdigits(&p);
5500 if (p != val + vallen)
5501 goto invalid_count;
5504 if (*def < 0)
5505 *def = 0;
5507 else if (STRNICMP(attr, "complete", attrlen) == 0)
5509 if (val == NULL)
5511 EMSG(_("E179: argument required for -complete"));
5512 return FAIL;
5515 if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
5516 == FAIL)
5517 return FAIL;
5519 else
5521 char_u ch = attr[len];
5522 attr[len] = '\0';
5523 EMSG2(_("E181: Invalid attribute: %s"), attr);
5524 attr[len] = ch;
5525 return FAIL;
5529 return OK;
5533 * ":command ..."
5535 static void
5536 ex_command(eap)
5537 exarg_T *eap;
5539 char_u *name;
5540 char_u *end;
5541 char_u *p;
5542 long argt = 0;
5543 long def = -1;
5544 int flags = 0;
5545 int compl = EXPAND_NOTHING;
5546 char_u *compl_arg = NULL;
5547 int has_attr = (eap->arg[0] == '-');
5549 p = eap->arg;
5551 /* Check for attributes */
5552 while (*p == '-')
5554 ++p;
5555 end = skiptowhite(p);
5556 if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5557 == FAIL)
5558 return;
5559 p = skipwhite(end);
5562 /* Get the name (if any) and skip to the following argument */
5563 name = p;
5564 if (ASCII_ISALPHA(*p))
5565 while (ASCII_ISALNUM(*p))
5566 ++p;
5567 if (!ends_excmd(*p) && !vim_iswhite(*p))
5569 EMSG(_("E182: Invalid command name"));
5570 return;
5572 end = p;
5574 /* If there is nothing after the name, and no attributes were specified,
5575 * we are listing commands
5577 p = skipwhite(end);
5578 if (!has_attr && ends_excmd(*p))
5580 uc_list(name, end - name);
5582 else if (!ASCII_ISUPPER(*name))
5584 EMSG(_("E183: User defined commands must start with an uppercase letter"));
5585 return;
5587 else
5588 uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5589 eap->forceit);
5593 * ":comclear"
5594 * Clear all user commands, global and for current buffer.
5596 void
5597 ex_comclear(eap)
5598 exarg_T *eap UNUSED;
5600 uc_clear(&ucmds);
5601 uc_clear(&curbuf->b_ucmds);
5605 * Clear all user commands for "gap".
5607 void
5608 uc_clear(gap)
5609 garray_T *gap;
5611 int i;
5612 ucmd_T *cmd;
5614 for (i = 0; i < gap->ga_len; ++i)
5616 cmd = USER_CMD_GA(gap, i);
5617 vim_free(cmd->uc_name);
5618 vim_free(cmd->uc_rep);
5619 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5620 vim_free(cmd->uc_compl_arg);
5621 # endif
5623 ga_clear(gap);
5626 static void
5627 ex_delcommand(eap)
5628 exarg_T *eap;
5630 int i = 0;
5631 ucmd_T *cmd = NULL;
5632 int cmp = -1;
5633 garray_T *gap;
5635 gap = &curbuf->b_ucmds;
5636 for (;;)
5638 for (i = 0; i < gap->ga_len; ++i)
5640 cmd = USER_CMD_GA(gap, i);
5641 cmp = STRCMP(eap->arg, cmd->uc_name);
5642 if (cmp <= 0)
5643 break;
5645 if (gap == &ucmds || cmp == 0)
5646 break;
5647 gap = &ucmds;
5650 if (cmp != 0)
5652 EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5653 return;
5656 vim_free(cmd->uc_name);
5657 vim_free(cmd->uc_rep);
5658 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5659 vim_free(cmd->uc_compl_arg);
5660 # endif
5662 --gap->ga_len;
5664 if (i < gap->ga_len)
5665 mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5669 * split and quote args for <f-args>
5671 static char_u *
5672 uc_split_args(arg, lenp)
5673 char_u *arg;
5674 size_t *lenp;
5676 char_u *buf;
5677 char_u *p;
5678 char_u *q;
5679 int len;
5681 /* Precalculate length */
5682 p = arg;
5683 len = 2; /* Initial and final quotes */
5685 while (*p)
5687 if (p[0] == '\\' && p[1] == '\\')
5689 len += 2;
5690 p += 2;
5692 else if (p[0] == '\\' && vim_iswhite(p[1]))
5694 len += 1;
5695 p += 2;
5697 else if (*p == '\\' || *p == '"')
5699 len += 2;
5700 p += 1;
5702 else if (vim_iswhite(*p))
5704 p = skipwhite(p);
5705 if (*p == NUL)
5706 break;
5707 len += 3; /* "," */
5709 else
5711 ++len;
5712 ++p;
5716 buf = alloc(len + 1);
5717 if (buf == NULL)
5719 *lenp = 0;
5720 return buf;
5723 p = arg;
5724 q = buf;
5725 *q++ = '"';
5726 while (*p)
5728 if (p[0] == '\\' && p[1] == '\\')
5730 *q++ = '\\';
5731 *q++ = '\\';
5732 p += 2;
5734 else if (p[0] == '\\' && vim_iswhite(p[1]))
5736 *q++ = p[1];
5737 p += 2;
5739 else if (*p == '\\' || *p == '"')
5741 *q++ = '\\';
5742 *q++ = *p++;
5744 else if (vim_iswhite(*p))
5746 p = skipwhite(p);
5747 if (*p == NUL)
5748 break;
5749 *q++ = '"';
5750 *q++ = ',';
5751 *q++ = '"';
5753 else
5755 *q++ = *p++;
5758 *q++ = '"';
5759 *q = 0;
5761 *lenp = len;
5762 return buf;
5766 * Check for a <> code in a user command.
5767 * "code" points to the '<'. "len" the length of the <> (inclusive).
5768 * "buf" is where the result is to be added.
5769 * "split_buf" points to a buffer used for splitting, caller should free it.
5770 * "split_len" is the length of what "split_buf" contains.
5771 * Returns the length of the replacement, which has been added to "buf".
5772 * Returns -1 if there was no match, and only the "<" has been copied.
5774 static size_t
5775 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5776 char_u *code;
5777 size_t len;
5778 char_u *buf;
5779 ucmd_T *cmd; /* the user command we're expanding */
5780 exarg_T *eap; /* ex arguments */
5781 char_u **split_buf;
5782 size_t *split_len;
5784 size_t result = 0;
5785 char_u *p = code + 1;
5786 size_t l = len - 2;
5787 int quote = 0;
5788 enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5789 ct_LT, ct_NONE } type = ct_NONE;
5791 if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5793 quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5794 p += 2;
5795 l -= 2;
5798 ++l;
5799 if (l <= 1)
5800 type = ct_NONE;
5801 else if (STRNICMP(p, "args>", l) == 0)
5802 type = ct_ARGS;
5803 else if (STRNICMP(p, "bang>", l) == 0)
5804 type = ct_BANG;
5805 else if (STRNICMP(p, "count>", l) == 0)
5806 type = ct_COUNT;
5807 else if (STRNICMP(p, "line1>", l) == 0)
5808 type = ct_LINE1;
5809 else if (STRNICMP(p, "line2>", l) == 0)
5810 type = ct_LINE2;
5811 else if (STRNICMP(p, "lt>", l) == 0)
5812 type = ct_LT;
5813 else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
5814 type = ct_REGISTER;
5816 switch (type)
5818 case ct_ARGS:
5819 /* Simple case first */
5820 if (*eap->arg == NUL)
5822 if (quote == 1)
5824 result = 2;
5825 if (buf != NULL)
5826 STRCPY(buf, "''");
5828 else
5829 result = 0;
5830 break;
5833 /* When specified there is a single argument don't split it.
5834 * Works for ":Cmd %" when % is "a b c". */
5835 if ((eap->argt & NOSPC) && quote == 2)
5836 quote = 1;
5838 switch (quote)
5840 case 0: /* No quoting, no splitting */
5841 result = STRLEN(eap->arg);
5842 if (buf != NULL)
5843 STRCPY(buf, eap->arg);
5844 break;
5845 case 1: /* Quote, but don't split */
5846 result = STRLEN(eap->arg) + 2;
5847 for (p = eap->arg; *p; ++p)
5849 if (*p == '\\' || *p == '"')
5850 ++result;
5853 if (buf != NULL)
5855 *buf++ = '"';
5856 for (p = eap->arg; *p; ++p)
5858 if (*p == '\\' || *p == '"')
5859 *buf++ = '\\';
5860 *buf++ = *p;
5862 *buf = '"';
5865 break;
5866 case 2: /* Quote and split (<f-args>) */
5867 /* This is hard, so only do it once, and cache the result */
5868 if (*split_buf == NULL)
5869 *split_buf = uc_split_args(eap->arg, split_len);
5871 result = *split_len;
5872 if (buf != NULL && result != 0)
5873 STRCPY(buf, *split_buf);
5875 break;
5877 break;
5879 case ct_BANG:
5880 result = eap->forceit ? 1 : 0;
5881 if (quote)
5882 result += 2;
5883 if (buf != NULL)
5885 if (quote)
5886 *buf++ = '"';
5887 if (eap->forceit)
5888 *buf++ = '!';
5889 if (quote)
5890 *buf = '"';
5892 break;
5894 case ct_LINE1:
5895 case ct_LINE2:
5896 case ct_COUNT:
5898 char num_buf[20];
5899 long num = (type == ct_LINE1) ? eap->line1 :
5900 (type == ct_LINE2) ? eap->line2 :
5901 (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5902 size_t num_len;
5904 sprintf(num_buf, "%ld", num);
5905 num_len = STRLEN(num_buf);
5906 result = num_len;
5908 if (quote)
5909 result += 2;
5911 if (buf != NULL)
5913 if (quote)
5914 *buf++ = '"';
5915 STRCPY(buf, num_buf);
5916 buf += num_len;
5917 if (quote)
5918 *buf = '"';
5921 break;
5924 case ct_REGISTER:
5925 result = eap->regname ? 1 : 0;
5926 if (quote)
5927 result += 2;
5928 if (buf != NULL)
5930 if (quote)
5931 *buf++ = '\'';
5932 if (eap->regname)
5933 *buf++ = eap->regname;
5934 if (quote)
5935 *buf = '\'';
5937 break;
5939 case ct_LT:
5940 result = 1;
5941 if (buf != NULL)
5942 *buf = '<';
5943 break;
5945 default:
5946 /* Not recognized: just copy the '<' and return -1. */
5947 result = (size_t)-1;
5948 if (buf != NULL)
5949 *buf = '<';
5950 break;
5953 return result;
5956 static void
5957 do_ucmd(eap)
5958 exarg_T *eap;
5960 char_u *buf;
5961 char_u *p;
5962 char_u *q;
5964 char_u *start;
5965 char_u *end = NULL;
5966 char_u *ksp;
5967 size_t len, totlen;
5969 size_t split_len = 0;
5970 char_u *split_buf = NULL;
5971 ucmd_T *cmd;
5972 #ifdef FEAT_EVAL
5973 scid_T save_current_SID = current_SID;
5974 #endif
5976 if (eap->cmdidx == CMD_USER)
5977 cmd = USER_CMD(eap->useridx);
5978 else
5979 cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5982 * Replace <> in the command by the arguments.
5983 * First round: "buf" is NULL, compute length, allocate "buf".
5984 * Second round: copy result into "buf".
5986 buf = NULL;
5987 for (;;)
5989 p = cmd->uc_rep; /* source */
5990 q = buf; /* destination */
5991 totlen = 0;
5993 for (;;)
5995 start = vim_strchr(p, '<');
5996 if (start != NULL)
5997 end = vim_strchr(start + 1, '>');
5998 if (buf != NULL)
6000 ksp = vim_strchr(p, K_SPECIAL);
6001 if (ksp != NULL && (start == NULL || ksp < start || end == NULL)
6002 && ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)
6003 # ifdef FEAT_GUI
6004 || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI)
6005 # endif
6008 /* K_SPECIAL han been put in the buffer as K_SPECIAL
6009 * KS_SPECIAL KE_FILLER, like for mappings, but
6010 * do_cmdline() doesn't handle that, so convert it back.
6011 * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */
6012 len = ksp - p;
6013 if (len > 0)
6015 mch_memmove(q, p, len);
6016 q += len;
6018 *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI;
6019 p = ksp + 3;
6020 continue;
6024 /* break if there no <item> is found */
6025 if (start == NULL || end == NULL)
6026 break;
6028 /* Include the '>' */
6029 ++end;
6031 /* Take everything up to the '<' */
6032 len = start - p;
6033 if (buf == NULL)
6034 totlen += len;
6035 else
6037 mch_memmove(q, p, len);
6038 q += len;
6041 len = uc_check_code(start, end - start, q, cmd, eap,
6042 &split_buf, &split_len);
6043 if (len == (size_t)-1)
6045 /* no match, continue after '<' */
6046 p = start + 1;
6047 len = 1;
6049 else
6050 p = end;
6051 if (buf == NULL)
6052 totlen += len;
6053 else
6054 q += len;
6056 if (buf != NULL) /* second time here, finished */
6058 STRCPY(q, p);
6059 break;
6062 totlen += STRLEN(p); /* Add on the trailing characters */
6063 buf = alloc((unsigned)(totlen + 1));
6064 if (buf == NULL)
6066 vim_free(split_buf);
6067 return;
6071 #ifdef FEAT_EVAL
6072 current_SID = cmd->uc_scriptID;
6073 #endif
6074 (void)do_cmdline(buf, eap->getline, eap->cookie,
6075 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6076 #ifdef FEAT_EVAL
6077 current_SID = save_current_SID;
6078 #endif
6079 vim_free(buf);
6080 vim_free(split_buf);
6083 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6084 static char_u *
6085 get_user_command_name(idx)
6086 int idx;
6088 return get_user_commands(NULL, idx - (int)CMD_SIZE);
6092 * Function given to ExpandGeneric() to obtain the list of user command names.
6094 char_u *
6095 get_user_commands(xp, idx)
6096 expand_T *xp UNUSED;
6097 int idx;
6099 if (idx < curbuf->b_ucmds.ga_len)
6100 return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
6101 idx -= curbuf->b_ucmds.ga_len;
6102 if (idx < ucmds.ga_len)
6103 return USER_CMD(idx)->uc_name;
6104 return NULL;
6108 * Function given to ExpandGeneric() to obtain the list of user command
6109 * attributes.
6111 char_u *
6112 get_user_cmd_flags(xp, idx)
6113 expand_T *xp UNUSED;
6114 int idx;
6116 static char *user_cmd_flags[] =
6117 {"bang", "bar", "buffer", "complete", "count",
6118 "nargs", "range", "register"};
6120 if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0])))
6121 return NULL;
6122 return (char_u *)user_cmd_flags[idx];
6126 * Function given to ExpandGeneric() to obtain the list of values for -nargs.
6128 char_u *
6129 get_user_cmd_nargs(xp, idx)
6130 expand_T *xp UNUSED;
6131 int idx;
6133 static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
6135 if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0])))
6136 return NULL;
6137 return (char_u *)user_cmd_nargs[idx];
6141 * Function given to ExpandGeneric() to obtain the list of values for -complete.
6143 char_u *
6144 get_user_cmd_complete(xp, idx)
6145 expand_T *xp UNUSED;
6146 int idx;
6148 return (char_u *)command_complete[idx].name;
6150 # endif /* FEAT_CMDL_COMPL */
6152 #endif /* FEAT_USR_CMDS */
6154 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
6156 * Parse a completion argument "value[vallen]".
6157 * The detected completion goes in "*complp", argument type in "*argt".
6158 * When there is an argument, for function and user defined completion, it's
6159 * copied to allocated memory and stored in "*compl_arg".
6160 * Returns FAIL if something is wrong.
6163 parse_compl_arg(value, vallen, complp, argt, compl_arg)
6164 char_u *value;
6165 int vallen;
6166 int *complp;
6167 long *argt;
6168 char_u **compl_arg;
6170 char_u *arg = NULL;
6171 size_t arglen = 0;
6172 int i;
6173 int valend = vallen;
6175 /* Look for any argument part - which is the part after any ',' */
6176 for (i = 0; i < vallen; ++i)
6178 if (value[i] == ',')
6180 arg = &value[i + 1];
6181 arglen = vallen - i - 1;
6182 valend = i;
6183 break;
6187 for (i = 0; command_complete[i].expand != 0; ++i)
6189 if ((int)STRLEN(command_complete[i].name) == valend
6190 && STRNCMP(value, command_complete[i].name, valend) == 0)
6192 *complp = command_complete[i].expand;
6193 if (command_complete[i].expand == EXPAND_BUFFERS)
6194 *argt |= BUFNAME;
6195 else if (command_complete[i].expand == EXPAND_DIRECTORIES
6196 || command_complete[i].expand == EXPAND_FILES)
6197 *argt |= XFILE;
6198 break;
6202 if (command_complete[i].expand == 0)
6204 EMSG2(_("E180: Invalid complete value: %s"), value);
6205 return FAIL;
6208 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6209 if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
6210 && arg != NULL)
6211 # else
6212 if (arg != NULL)
6213 # endif
6215 EMSG(_("E468: Completion argument only allowed for custom completion"));
6216 return FAIL;
6219 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6220 if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
6221 && arg == NULL)
6223 EMSG(_("E467: Custom completion requires a function argument"));
6224 return FAIL;
6227 if (arg != NULL)
6228 *compl_arg = vim_strnsave(arg, (int)arglen);
6229 # endif
6230 return OK;
6232 #endif
6234 static void
6235 ex_colorscheme(eap)
6236 exarg_T *eap;
6238 if (*eap->arg == NUL)
6240 #ifdef FEAT_EVAL
6241 char_u *expr = vim_strsave((char_u *)"g:colors_name");
6242 char_u *p = NULL;
6244 if (expr != NULL)
6246 ++emsg_off;
6247 p = eval_to_string(expr, NULL, FALSE);
6248 --emsg_off;
6249 vim_free(expr);
6251 if (p != NULL)
6253 MSG(p);
6254 vim_free(p);
6256 else
6257 MSG("default");
6258 #else
6259 MSG(_("unknown"));
6260 #endif
6262 else if (load_colors(eap->arg) == FAIL)
6263 EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
6266 static void
6267 ex_highlight(eap)
6268 exarg_T *eap;
6270 if (*eap->arg == NUL && eap->cmd[2] == '!')
6271 MSG(_("Greetings, Vim user!"));
6272 do_highlight(eap->arg, eap->forceit, FALSE);
6277 * Call this function if we thought we were going to exit, but we won't
6278 * (because of an error). May need to restore the terminal mode.
6280 void
6281 not_exiting()
6283 exiting = FALSE;
6284 settmode(TMODE_RAW);
6288 * ":quit": quit current window, quit Vim if closed the last window.
6290 static void
6291 ex_quit(eap)
6292 exarg_T *eap;
6294 #ifdef FEAT_CMDWIN
6295 if (cmdwin_type != 0)
6297 cmdwin_result = Ctrl_C;
6298 return;
6300 #endif
6301 /* Don't quit while editing the command line. */
6302 if (text_locked())
6304 text_locked_msg();
6305 return;
6307 #ifdef FEAT_AUTOCMD
6308 if (curbuf_locked())
6309 return;
6310 #endif
6312 #ifdef FEAT_NETBEANS_INTG
6313 netbeansForcedQuit = eap->forceit;
6314 #endif
6317 * If there are more files or windows we won't exit.
6319 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6320 exiting = TRUE;
6321 if ((!P_HID(curbuf)
6322 && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
6323 || check_more(TRUE, eap->forceit) == FAIL
6324 || (only_one_window() && check_changed_any(eap->forceit)))
6326 not_exiting();
6328 else
6330 #ifdef FEAT_WINDOWS
6331 if (only_one_window()) /* quit last window */
6332 #endif
6333 getout(0);
6334 #ifdef FEAT_WINDOWS
6335 # ifdef FEAT_GUI
6336 need_mouse_correct = TRUE;
6337 # endif
6338 /* close window; may free buffer */
6339 win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
6340 #endif
6345 * ":cquit".
6347 static void
6348 ex_cquit(eap)
6349 exarg_T *eap UNUSED;
6351 getout(1); /* this does not always pass on the exit code to the Manx
6352 compiler. why? */
6356 * ":qall": try to quit all windows
6358 static void
6359 ex_quit_all(eap)
6360 exarg_T *eap;
6362 # ifdef FEAT_CMDWIN
6363 if (cmdwin_type != 0)
6365 if (eap->forceit)
6366 cmdwin_result = K_XF1; /* ex_window() takes care of this */
6367 else
6368 cmdwin_result = K_XF2;
6369 return;
6371 # endif
6373 /* Don't quit while editing the command line. */
6374 if (text_locked())
6376 text_locked_msg();
6377 return;
6379 #ifdef FEAT_AUTOCMD
6380 if (curbuf_locked())
6381 return;
6382 #endif
6384 exiting = TRUE;
6385 if (eap->forceit || !check_changed_any(FALSE))
6386 getout(0);
6387 not_exiting();
6390 #if defined(FEAT_WINDOWS) || defined(PROTO)
6392 * ":close": close current window, unless it is the last one
6394 static void
6395 ex_close(eap)
6396 exarg_T *eap;
6398 # ifdef FEAT_CMDWIN
6399 if (cmdwin_type != 0)
6400 cmdwin_result = K_IGNORE;
6401 else
6402 # endif
6403 if (!text_locked()
6404 #ifdef FEAT_AUTOCMD
6405 && !curbuf_locked()
6406 #endif
6408 ex_win_close(eap->forceit, curwin, NULL);
6411 # ifdef FEAT_QUICKFIX
6413 * ":pclose": Close any preview window.
6415 static void
6416 ex_pclose(eap)
6417 exarg_T *eap;
6419 win_T *win;
6421 for (win = firstwin; win != NULL; win = win->w_next)
6422 if (win->w_p_pvw)
6424 ex_win_close(eap->forceit, win, NULL);
6425 break;
6428 # endif
6431 * Close window "win" and take care of handling closing the last window for a
6432 * modified buffer.
6434 static void
6435 ex_win_close(forceit, win, tp)
6436 int forceit;
6437 win_T *win;
6438 tabpage_T *tp; /* NULL or the tab page "win" is in */
6440 int need_hide;
6441 buf_T *buf = win->w_buffer;
6443 need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
6444 if (need_hide && !P_HID(buf) && !forceit)
6446 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6447 if ((p_confirm || cmdmod.confirm) && p_write)
6449 dialog_changed(buf, FALSE);
6450 if (buf_valid(buf) && bufIsChanged(buf))
6451 return;
6452 need_hide = FALSE;
6454 else
6455 # endif
6457 EMSG(_(e_nowrtmsg));
6458 return;
6462 # ifdef FEAT_GUI
6463 need_mouse_correct = TRUE;
6464 # endif
6466 /* free buffer when not hiding it or when it's a scratch buffer */
6467 if (tp == NULL)
6468 win_close(win, !need_hide && !P_HID(buf));
6469 else
6470 win_close_othertab(win, !need_hide && !P_HID(buf), tp);
6474 * ":tabclose": close current tab page, unless it is the last one.
6475 * ":tabclose N": close tab page N.
6477 static void
6478 ex_tabclose(eap)
6479 exarg_T *eap;
6481 tabpage_T *tp;
6483 # ifdef FEAT_CMDWIN
6484 if (cmdwin_type != 0)
6485 cmdwin_result = K_IGNORE;
6486 else
6487 # endif
6488 if (first_tabpage->tp_next == NULL)
6489 EMSG(_("E784: Cannot close last tab page"));
6490 else
6492 if (eap->addr_count > 0)
6494 tp = find_tabpage((int)eap->line2);
6495 if (tp == NULL)
6497 beep_flush();
6498 return;
6500 if (tp != curtab)
6502 tabpage_close_other(tp, eap->forceit);
6503 return;
6506 if (!text_locked()
6507 #ifdef FEAT_AUTOCMD
6508 && !curbuf_locked()
6509 #endif
6511 tabpage_close(eap->forceit);
6516 * ":tabonly": close all tab pages except the current one
6518 static void
6519 ex_tabonly(eap)
6520 exarg_T *eap;
6522 tabpage_T *tp;
6523 int done;
6525 # ifdef FEAT_CMDWIN
6526 if (cmdwin_type != 0)
6527 cmdwin_result = K_IGNORE;
6528 else
6529 # endif
6530 if (first_tabpage->tp_next == NULL)
6531 MSG(_("Already only one tab page"));
6532 else
6534 /* Repeat this up to a 1000 times, because autocommands may mess
6535 * up the lists. */
6536 for (done = 0; done < 1000; ++done)
6538 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6539 if (tp->tp_topframe != topframe)
6541 tabpage_close_other(tp, eap->forceit);
6542 /* if we failed to close it quit */
6543 if (valid_tabpage(tp))
6544 done = 1000;
6545 /* start over, "tp" is now invalid */
6546 break;
6548 if (first_tabpage->tp_next == NULL)
6549 break;
6555 * Close the current tab page.
6557 void
6558 tabpage_close(forceit)
6559 int forceit;
6561 /* First close all the windows but the current one. If that worked then
6562 * close the last window in this tab, that will close it. */
6563 if (lastwin != firstwin)
6564 close_others(TRUE, forceit);
6565 if (lastwin == firstwin)
6566 ex_win_close(forceit, curwin, NULL);
6567 # ifdef FEAT_GUI
6568 need_mouse_correct = TRUE;
6569 # endif
6573 * Close tab page "tp", which is not the current tab page.
6574 * Note that autocommands may make "tp" invalid.
6575 * Also takes care of the tab pages line disappearing when closing the
6576 * last-but-one tab page.
6578 void
6579 tabpage_close_other(tp, forceit)
6580 tabpage_T *tp;
6581 int forceit;
6583 int done = 0;
6584 win_T *wp;
6585 int h = tabline_height();
6587 /* Limit to 1000 windows, autocommands may add a window while we close
6588 * one. OK, so I'm paranoid... */
6589 while (++done < 1000)
6591 wp = tp->tp_firstwin;
6592 ex_win_close(forceit, wp, tp);
6594 /* Autocommands may delete the tab page under our fingers and we may
6595 * fail to close a window with a modified buffer. */
6596 if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
6597 break;
6600 redraw_tabline = TRUE;
6601 if (h != tabline_height())
6602 shell_new_rows();
6606 * ":only".
6608 static void
6609 ex_only(eap)
6610 exarg_T *eap;
6612 # ifdef FEAT_GUI
6613 need_mouse_correct = TRUE;
6614 # endif
6615 close_others(TRUE, eap->forceit);
6619 * ":all" and ":sall".
6620 * Also used for ":tab drop file ..." after setting the argument list.
6622 void
6623 ex_all(eap)
6624 exarg_T *eap;
6626 if (eap->addr_count == 0)
6627 eap->line2 = 9999;
6628 do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
6630 #endif /* FEAT_WINDOWS */
6632 static void
6633 ex_hide(eap)
6634 exarg_T *eap;
6636 if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
6637 eap->errmsg = e_invarg;
6638 else
6640 /* ":hide" or ":hide | cmd": hide current window */
6641 eap->nextcmd = check_nextcmd(eap->arg);
6642 #ifdef FEAT_WINDOWS
6643 if (!eap->skip)
6645 # ifdef FEAT_GUI
6646 need_mouse_correct = TRUE;
6647 # endif
6648 win_close(curwin, FALSE); /* don't free buffer */
6650 #endif
6655 * ":stop" and ":suspend": Suspend Vim.
6657 static void
6658 ex_stop(eap)
6659 exarg_T *eap;
6662 * Disallow suspending for "rvim".
6664 if (!check_restricted()
6665 #ifdef WIN3264
6667 * Check if external commands are allowed now.
6669 && can_end_termcap_mode(TRUE)
6670 #endif
6673 if (!eap->forceit)
6674 autowrite_all();
6675 windgoto((int)Rows - 1, 0);
6676 out_char('\n');
6677 out_flush();
6678 stoptermcap();
6679 out_flush(); /* needed for SUN to restore xterm buffer */
6680 #ifdef FEAT_TITLE
6681 mch_restore_title(3); /* restore window titles */
6682 #endif
6683 ui_suspend(); /* call machine specific function */
6684 #ifdef FEAT_TITLE
6685 maketitle();
6686 resettitle(); /* force updating the title */
6687 #endif
6688 starttermcap();
6689 scroll_start(); /* scroll screen before redrawing */
6690 redraw_later_clear();
6691 shell_resized(); /* may have resized window */
6696 * ":exit", ":xit" and ":wq": Write file and exit Vim.
6698 static void
6699 ex_exit(eap)
6700 exarg_T *eap;
6702 #ifdef FEAT_CMDWIN
6703 if (cmdwin_type != 0)
6705 cmdwin_result = Ctrl_C;
6706 return;
6708 #endif
6709 /* Don't quit while editing the command line. */
6710 if (text_locked())
6712 text_locked_msg();
6713 return;
6715 #ifdef FEAT_AUTOCMD
6716 if (curbuf_locked())
6717 return;
6718 #endif
6721 * if more files or windows we won't exit
6723 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6724 exiting = TRUE;
6725 if ( ((eap->cmdidx == CMD_wq
6726 || curbufIsChanged())
6727 && do_write(eap) == FAIL)
6728 || check_more(TRUE, eap->forceit) == FAIL
6729 || (only_one_window() && check_changed_any(eap->forceit)))
6731 not_exiting();
6733 else
6735 #ifdef FEAT_WINDOWS
6736 if (only_one_window()) /* quit last window, exit Vim */
6737 #endif
6738 getout(0);
6739 #ifdef FEAT_WINDOWS
6740 # ifdef FEAT_GUI
6741 need_mouse_correct = TRUE;
6742 # endif
6743 /* quit current window, may free buffer */
6744 win_close(curwin, !P_HID(curwin->w_buffer));
6745 #endif
6750 * ":print", ":list", ":number".
6752 static void
6753 ex_print(eap)
6754 exarg_T *eap;
6756 if (curbuf->b_ml.ml_flags & ML_EMPTY)
6757 EMSG(_(e_emptybuf));
6758 else
6760 for ( ;!got_int; ui_breakcheck())
6762 print_line(eap->line1,
6763 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
6764 || (eap->flags & EXFLAG_NR)),
6765 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
6766 if (++eap->line1 > eap->line2)
6767 break;
6768 out_flush(); /* show one line at a time */
6770 setpcmark();
6771 /* put cursor at last line */
6772 curwin->w_cursor.lnum = eap->line2;
6773 beginline(BL_SOL | BL_FIX);
6776 ex_no_reprint = TRUE;
6779 #ifdef FEAT_BYTEOFF
6780 static void
6781 ex_goto(eap)
6782 exarg_T *eap;
6784 goto_byte(eap->line2);
6786 #endif
6789 * ":shell".
6791 static void
6792 ex_shell(eap)
6793 exarg_T *eap UNUSED;
6795 do_shell(NULL, 0);
6798 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6799 || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6800 || defined(FEAT_GUI_MSWIN) \
6801 || defined(FEAT_GUI_MAC) \
6802 || defined(PROTO)
6805 * Handle a file drop. The code is here because a drop is *nearly* like an
6806 * :args command, but not quite (we have a list of exact filenames, so we
6807 * don't want to (a) parse a command line, or (b) expand wildcards. So the
6808 * code is very similar to :args and hence needs access to a lot of the static
6809 * functions in this file.
6811 * The list should be allocated using alloc(), as should each item in the
6812 * list. This function takes over responsibility for freeing the list.
6814 * XXX The list is made into the argument list. This is freed using
6815 * FreeWild(), which does a series of vim_free() calls, unless the two defines
6816 * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6817 * routine _fnexplodefree() is used. This may cause problems, but as the drop
6818 * file functionality is (currently) not in EMX this is not presently a
6819 * problem.
6821 void
6822 handle_drop(filec, filev, split)
6823 int filec; /* the number of files dropped */
6824 char_u **filev; /* the list of files dropped */
6825 int split; /* force splitting the window */
6827 exarg_T ea;
6828 int save_msg_scroll = msg_scroll;
6830 /* Postpone this while editing the command line. */
6831 if (text_locked())
6832 return;
6833 #ifdef FEAT_AUTOCMD
6834 if (curbuf_locked())
6835 return;
6836 #endif
6837 /* When the screen is being updated we should not change buffers and
6838 * windows structures, it may cause freed memory to be used. */
6839 if (updating_screen)
6840 return;
6842 /* Check whether the current buffer is changed. If so, we will need
6843 * to split the current window or data could be lost.
6844 * We don't need to check if the 'hidden' option is set, as in this
6845 * case the buffer won't be lost.
6847 if (!P_HID(curbuf) && !split)
6849 ++emsg_off;
6850 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6851 --emsg_off;
6853 if (split)
6855 # ifdef FEAT_WINDOWS
6856 if (win_split(0, 0) == FAIL)
6857 return;
6858 # ifdef FEAT_SCROLLBIND
6859 curwin->w_p_scb = FALSE;
6860 # endif
6862 /* When splitting the window, create a new alist. Otherwise the
6863 * existing one is overwritten. */
6864 alist_unlink(curwin->w_alist);
6865 alist_new();
6866 # else
6867 return; /* can't split, always fail */
6868 # endif
6872 * Set up the new argument list.
6874 alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
6877 * Move to the first file.
6879 /* Fake up a minimal "next" command for do_argfile() */
6880 vim_memset(&ea, 0, sizeof(ea));
6881 ea.cmd = (char_u *)"next";
6882 do_argfile(&ea, 0);
6884 /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6885 * mode that is not needed here. */
6886 need_start_insertmode = FALSE;
6888 /* Restore msg_scroll, otherwise a following command may cause scrolling
6889 * unexpectedly. The screen will be redrawn by the caller, thus
6890 * msg_scroll being set by displaying a message is irrelevant. */
6891 msg_scroll = save_msg_scroll;
6893 #endif
6896 * Clear an argument list: free all file names and reset it to zero entries.
6898 void
6899 alist_clear(al)
6900 alist_T *al;
6902 while (--al->al_ga.ga_len >= 0)
6903 vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6904 ga_clear(&al->al_ga);
6908 * Init an argument list.
6910 void
6911 alist_init(al)
6912 alist_T *al;
6914 ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6917 #if defined(FEAT_WINDOWS) || defined(PROTO)
6920 * Remove a reference from an argument list.
6921 * Ignored when the argument list is the global one.
6922 * If the argument list is no longer used by any window, free it.
6924 void
6925 alist_unlink(al)
6926 alist_T *al;
6928 if (al != &global_alist && --al->al_refcount <= 0)
6930 alist_clear(al);
6931 vim_free(al);
6935 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6937 * Create a new argument list and use it for the current window.
6939 void
6940 alist_new()
6942 curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6943 if (curwin->w_alist == NULL)
6945 curwin->w_alist = &global_alist;
6946 ++global_alist.al_refcount;
6948 else
6950 curwin->w_alist->al_refcount = 1;
6951 alist_init(curwin->w_alist);
6954 # endif
6955 #endif
6957 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6959 * Expand the file names in the global argument list.
6960 * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
6961 * numbers to be re-used.
6963 void
6964 alist_expand(fnum_list, fnum_len)
6965 int *fnum_list;
6966 int fnum_len;
6968 char_u **old_arg_files;
6969 int old_arg_count;
6970 char_u **new_arg_files;
6971 int new_arg_file_count;
6972 char_u *save_p_su = p_su;
6973 int i;
6975 /* Don't use 'suffixes' here. This should work like the shell did the
6976 * expansion. Also, the vimrc file isn't read yet, thus the user
6977 * can't set the options. */
6978 p_su = empty_option;
6979 old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6980 if (old_arg_files != NULL)
6982 for (i = 0; i < GARGCOUNT; ++i)
6983 old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
6984 old_arg_count = GARGCOUNT;
6985 if (expand_wildcards(old_arg_count, old_arg_files,
6986 &new_arg_file_count, &new_arg_files,
6987 EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6988 && new_arg_file_count > 0)
6990 alist_set(&global_alist, new_arg_file_count, new_arg_files,
6991 TRUE, fnum_list, fnum_len);
6992 FreeWild(old_arg_count, old_arg_files);
6995 p_su = save_p_su;
6997 #endif
7000 * Set the argument list for the current window.
7001 * Takes over the allocated files[] and the allocated fnames in it.
7003 void
7004 alist_set(al, count, files, use_curbuf, fnum_list, fnum_len)
7005 alist_T *al;
7006 int count;
7007 char_u **files;
7008 int use_curbuf;
7009 int *fnum_list;
7010 int fnum_len;
7012 int i;
7014 alist_clear(al);
7015 if (ga_grow(&al->al_ga, count) == OK)
7017 for (i = 0; i < count; ++i)
7019 if (got_int)
7021 /* When adding many buffers this can take a long time. Allow
7022 * interrupting here. */
7023 while (i < count)
7024 vim_free(files[i++]);
7025 break;
7028 /* May set buffer name of a buffer previously used for the
7029 * argument list, so that it's re-used by alist_add. */
7030 if (fnum_list != NULL && i < fnum_len)
7031 buf_set_name(fnum_list[i], files[i]);
7033 alist_add(al, files[i], use_curbuf ? 2 : 1);
7034 ui_breakcheck();
7036 vim_free(files);
7038 else
7039 FreeWild(count, files);
7040 #ifdef FEAT_WINDOWS
7041 if (al == &global_alist)
7042 #endif
7043 arg_had_last = FALSE;
7047 * Add file "fname" to argument list "al".
7048 * "fname" must have been allocated and "al" must have been checked for room.
7050 void
7051 alist_add(al, fname, set_fnum)
7052 alist_T *al;
7053 char_u *fname;
7054 int set_fnum; /* 1: set buffer number; 2: re-use curbuf */
7056 if (fname == NULL) /* don't add NULL file names */
7057 return;
7058 #ifdef BACKSLASH_IN_FILENAME
7059 slash_adjust(fname);
7060 #endif
7061 AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
7062 if (set_fnum > 0)
7063 AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
7064 buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
7065 ++al->al_ga.ga_len;
7068 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7070 * Adjust slashes in file names. Called after 'shellslash' was set.
7072 void
7073 alist_slash_adjust()
7075 int i;
7076 # ifdef FEAT_WINDOWS
7077 win_T *wp;
7078 tabpage_T *tp;
7079 # endif
7081 for (i = 0; i < GARGCOUNT; ++i)
7082 if (GARGLIST[i].ae_fname != NULL)
7083 slash_adjust(GARGLIST[i].ae_fname);
7084 # ifdef FEAT_WINDOWS
7085 FOR_ALL_TAB_WINDOWS(tp, wp)
7086 if (wp->w_alist != &global_alist)
7087 for (i = 0; i < WARGCOUNT(wp); ++i)
7088 if (WARGLIST(wp)[i].ae_fname != NULL)
7089 slash_adjust(WARGLIST(wp)[i].ae_fname);
7090 # endif
7092 #endif
7095 * ":preserve".
7097 static void
7098 ex_preserve(eap)
7099 exarg_T *eap UNUSED;
7101 curbuf->b_flags |= BF_PRESERVED;
7102 ml_preserve(curbuf, TRUE);
7106 * ":recover".
7108 static void
7109 ex_recover(eap)
7110 exarg_T *eap;
7112 /* Set recoverymode right away to avoid the ATTENTION prompt. */
7113 recoverymode = TRUE;
7114 if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
7115 && (*eap->arg == NUL
7116 || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
7117 ml_recover();
7118 recoverymode = FALSE;
7122 * Command modifier used in a wrong way.
7124 static void
7125 ex_wrongmodifier(eap)
7126 exarg_T *eap;
7128 eap->errmsg = e_invcmd;
7131 #ifdef FEAT_WINDOWS
7133 * :sview [+command] file split window with new file, read-only
7134 * :split [[+command] file] split window with current or new file
7135 * :vsplit [[+command] file] split window vertically with current or new file
7136 * :new [[+command] file] split window with no or new file
7137 * :vnew [[+command] file] split vertically window with no or new file
7138 * :sfind [+command] file split window with file in 'path'
7140 * :tabedit open new Tab page with empty window
7141 * :tabedit [+command] file open new Tab page and edit "file"
7142 * :tabnew [[+command] file] just like :tabedit
7143 * :tabfind [+command] file open new Tab page and find "file"
7145 void
7146 ex_splitview(eap)
7147 exarg_T *eap;
7149 win_T *old_curwin = curwin;
7150 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7151 char_u *fname = NULL;
7152 # endif
7153 # ifdef FEAT_BROWSE
7154 int browse_flag = cmdmod.browse;
7155 # endif
7157 # ifndef FEAT_VERTSPLIT
7158 if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
7160 ex_ni(eap);
7161 return;
7163 # endif
7165 # ifdef FEAT_GUI
7166 need_mouse_correct = TRUE;
7167 # endif
7169 # ifdef FEAT_QUICKFIX
7170 /* A ":split" in the quickfix window works like ":new". Don't want two
7171 * quickfix windows. But it's OK when doing ":tab split". */
7172 if (bt_quickfix(curbuf) && cmdmod.tab == 0)
7174 if (eap->cmdidx == CMD_split)
7175 eap->cmdidx = CMD_new;
7176 # ifdef FEAT_VERTSPLIT
7177 if (eap->cmdidx == CMD_vsplit)
7178 eap->cmdidx = CMD_vnew;
7179 # endif
7181 # endif
7183 # ifdef FEAT_SEARCHPATH
7184 if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
7186 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
7187 FNAME_MESS, TRUE, curbuf->b_ffname);
7188 if (fname == NULL)
7189 goto theend;
7190 eap->arg = fname;
7192 # ifdef FEAT_BROWSE
7193 else
7194 # endif
7195 # endif
7196 # ifdef FEAT_BROWSE
7197 if (cmdmod.browse
7198 # ifdef FEAT_VERTSPLIT
7199 && eap->cmdidx != CMD_vnew
7200 # endif
7201 && eap->cmdidx != CMD_new)
7203 # ifdef FEAT_AUTOCMD
7204 if (
7205 # ifdef FEAT_GUI
7206 !gui.in_use &&
7207 # endif
7208 au_has_group((char_u *)"FileExplorer"))
7210 /* No browsing supported but we do have the file explorer:
7211 * Edit the directory. */
7212 if (*eap->arg == NUL || !mch_isdir(eap->arg))
7213 eap->arg = (char_u *)".";
7215 else
7216 # endif
7218 fname = do_browse(0, (char_u *)_("Edit File in new window"),
7219 eap->arg, NULL, NULL, NULL, curbuf);
7220 if (fname == NULL)
7221 goto theend;
7222 eap->arg = fname;
7225 cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */
7226 # endif
7229 * Either open new tab page or split the window.
7231 if (eap->cmdidx == CMD_tabedit
7232 || eap->cmdidx == CMD_tabfind
7233 || eap->cmdidx == CMD_tabnew)
7235 if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
7236 : eap->addr_count == 0 ? 0
7237 : (int)eap->line2 + 1) != FAIL)
7239 do_exedit(eap, old_curwin);
7241 /* set the alternate buffer for the window we came from */
7242 if (curwin != old_curwin
7243 && win_valid(old_curwin)
7244 && old_curwin->w_buffer != curbuf
7245 && !cmdmod.keepalt)
7246 old_curwin->w_alt_fnum = curbuf->b_fnum;
7249 else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
7250 *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
7252 # ifdef FEAT_SCROLLBIND
7253 /* Reset 'scrollbind' when editing another file, but keep it when
7254 * doing ":split" without arguments. */
7255 if (*eap->arg != NUL
7256 # ifdef FEAT_BROWSE
7257 || cmdmod.browse
7258 # endif
7260 curwin->w_p_scb = FALSE;
7261 else
7262 do_check_scrollbind(FALSE);
7263 # endif
7264 do_exedit(eap, old_curwin);
7267 # ifdef FEAT_BROWSE
7268 cmdmod.browse = browse_flag;
7269 # endif
7271 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7272 theend:
7273 vim_free(fname);
7274 # endif
7278 * Open a new tab page.
7280 void
7281 tabpage_new()
7283 exarg_T ea;
7285 vim_memset(&ea, 0, sizeof(ea));
7286 ea.cmdidx = CMD_tabnew;
7287 ea.cmd = (char_u *)"tabn";
7288 ea.arg = (char_u *)"";
7289 ex_splitview(&ea);
7293 * :tabnext command
7295 static void
7296 ex_tabnext(eap)
7297 exarg_T *eap;
7299 switch (eap->cmdidx)
7301 case CMD_tabfirst:
7302 case CMD_tabrewind:
7303 goto_tabpage(1);
7304 break;
7305 case CMD_tablast:
7306 goto_tabpage(9999);
7307 break;
7308 case CMD_tabprevious:
7309 case CMD_tabNext:
7310 goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2);
7311 break;
7312 default: /* CMD_tabnext */
7313 goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2);
7314 break;
7319 * :tabmove command
7321 static void
7322 ex_tabmove(eap)
7323 exarg_T *eap;
7325 tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2);
7329 * :tabs command: List tabs and their contents.
7331 static void
7332 ex_tabs(eap)
7333 exarg_T *eap UNUSED;
7335 tabpage_T *tp;
7336 win_T *wp;
7337 int tabcount = 1;
7339 msg_start();
7340 msg_scroll = TRUE;
7341 for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
7343 msg_putchar('\n');
7344 vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
7345 msg_outtrans_attr(IObuff, hl_attr(HLF_T));
7346 out_flush(); /* output one line at a time */
7347 ui_breakcheck();
7349 if (tp == curtab)
7350 wp = firstwin;
7351 else
7352 wp = tp->tp_firstwin;
7353 for ( ; wp != NULL && !got_int; wp = wp->w_next)
7355 msg_putchar('\n');
7356 msg_putchar(wp == curwin ? '>' : ' ');
7357 msg_putchar(' ');
7358 msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
7359 msg_putchar(' ');
7360 if (buf_spname(wp->w_buffer) != NULL)
7361 STRCPY(IObuff, buf_spname(wp->w_buffer));
7362 else
7363 home_replace(wp->w_buffer, wp->w_buffer->b_fname,
7364 IObuff, IOSIZE, TRUE);
7365 msg_outtrans(IObuff);
7366 out_flush(); /* output one line at a time */
7367 ui_breakcheck();
7372 #endif /* FEAT_WINDOWS */
7375 * ":mode": Set screen mode.
7376 * If no argument given, just get the screen size and redraw.
7378 static void
7379 ex_mode(eap)
7380 exarg_T *eap;
7382 if (*eap->arg == NUL)
7383 shell_resized();
7384 else
7385 mch_screenmode(eap->arg);
7388 #ifdef FEAT_WINDOWS
7390 * ":resize".
7391 * set, increment or decrement current window height
7393 static void
7394 ex_resize(eap)
7395 exarg_T *eap;
7397 int n;
7398 win_T *wp = curwin;
7400 if (eap->addr_count > 0)
7402 n = eap->line2;
7403 for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
7407 #ifdef FEAT_GUI
7408 need_mouse_correct = TRUE;
7409 #endif
7410 n = atol((char *)eap->arg);
7411 #ifdef FEAT_VERTSPLIT
7412 if (cmdmod.split & WSP_VERT)
7414 if (*eap->arg == '-' || *eap->arg == '+')
7415 n += W_WIDTH(curwin);
7416 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7417 n = 9999;
7418 win_setwidth_win((int)n, wp);
7420 else
7421 #endif
7423 if (*eap->arg == '-' || *eap->arg == '+')
7424 n += curwin->w_height;
7425 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7426 n = 9999;
7427 win_setheight_win((int)n, wp);
7430 #endif
7433 * ":find [+command] <file>" command.
7435 static void
7436 ex_find(eap)
7437 exarg_T *eap;
7439 #ifdef FEAT_SEARCHPATH
7440 char_u *fname;
7441 int count;
7443 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
7444 TRUE, curbuf->b_ffname);
7445 if (eap->addr_count > 0)
7447 /* Repeat finding the file "count" times. This matters when it
7448 * appears several times in the path. */
7449 count = eap->line2;
7450 while (fname != NULL && --count > 0)
7452 vim_free(fname);
7453 fname = find_file_in_path(NULL, 0, FNAME_MESS,
7454 FALSE, curbuf->b_ffname);
7458 if (fname != NULL)
7460 eap->arg = fname;
7461 #endif
7462 do_exedit(eap, NULL);
7463 #ifdef FEAT_SEARCHPATH
7464 vim_free(fname);
7466 #endif
7470 * ":open" simulation: for now just work like ":visual".
7472 static void
7473 ex_open(eap)
7474 exarg_T *eap;
7476 regmatch_T regmatch;
7477 char_u *p;
7479 curwin->w_cursor.lnum = eap->line2;
7480 beginline(BL_SOL | BL_FIX);
7481 if (*eap->arg == '/')
7483 /* ":open /pattern/": put cursor in column found with pattern */
7484 ++eap->arg;
7485 p = skip_regexp(eap->arg, '/', p_magic, NULL);
7486 *p = NUL;
7487 regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
7488 if (regmatch.regprog != NULL)
7490 regmatch.rm_ic = p_ic;
7491 p = ml_get_curline();
7492 if (vim_regexec(&regmatch, p, (colnr_T)0))
7493 curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
7494 else
7495 EMSG(_(e_nomatch));
7496 vim_free(regmatch.regprog);
7498 /* Move to the NUL, ignore any other arguments. */
7499 eap->arg += STRLEN(eap->arg);
7501 check_cursor();
7503 eap->cmdidx = CMD_visual;
7504 do_exedit(eap, NULL);
7508 * ":edit", ":badd", ":visual".
7510 static void
7511 ex_edit(eap)
7512 exarg_T *eap;
7514 do_exedit(eap, NULL);
7518 * ":edit <file>" command and alikes.
7520 void
7521 do_exedit(eap, old_curwin)
7522 exarg_T *eap;
7523 win_T *old_curwin; /* curwin before doing a split or NULL */
7525 int n;
7526 #ifdef FEAT_WINDOWS
7527 int need_hide;
7528 #endif
7529 int exmode_was = exmode_active;
7532 * ":vi" command ends Ex mode.
7534 if (exmode_active && (eap->cmdidx == CMD_visual
7535 || eap->cmdidx == CMD_view))
7537 exmode_active = FALSE;
7538 if (*eap->arg == NUL)
7540 /* Special case: ":global/pat/visual\NLvi-commands" */
7541 if (global_busy)
7543 int rd = RedrawingDisabled;
7544 int nwr = no_wait_return;
7545 int ms = msg_scroll;
7546 #ifdef FEAT_GUI
7547 int he = hold_gui_events;
7548 #endif
7550 if (eap->nextcmd != NULL)
7552 stuffReadbuff(eap->nextcmd);
7553 eap->nextcmd = NULL;
7556 if (exmode_was != EXMODE_VIM)
7557 settmode(TMODE_RAW);
7558 RedrawingDisabled = 0;
7559 no_wait_return = 0;
7560 need_wait_return = FALSE;
7561 msg_scroll = 0;
7562 #ifdef FEAT_GUI
7563 hold_gui_events = 0;
7564 #endif
7565 must_redraw = CLEAR;
7567 main_loop(FALSE, TRUE);
7569 RedrawingDisabled = rd;
7570 no_wait_return = nwr;
7571 msg_scroll = ms;
7572 #ifdef FEAT_GUI
7573 hold_gui_events = he;
7574 #endif
7576 return;
7580 if ((eap->cmdidx == CMD_new
7581 || eap->cmdidx == CMD_tabnew
7582 || eap->cmdidx == CMD_tabedit
7583 #ifdef FEAT_VERTSPLIT
7584 || eap->cmdidx == CMD_vnew
7585 #endif
7586 ) && *eap->arg == NUL)
7588 /* ":new" or ":tabnew" without argument: edit an new empty buffer */
7589 setpcmark();
7590 (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
7591 ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
7592 old_curwin == NULL ? curwin : NULL);
7594 else if ((eap->cmdidx != CMD_split
7595 #ifdef FEAT_VERTSPLIT
7596 && eap->cmdidx != CMD_vsplit
7597 #endif
7599 || *eap->arg != NUL
7600 #ifdef FEAT_BROWSE
7601 || cmdmod.browse
7602 #endif
7605 #ifdef FEAT_AUTOCMD
7606 /* Can't edit another file when "curbuf_lock" is set. Only ":edit"
7607 * can bring us here, others are stopped earlier. */
7608 if (*eap->arg != NUL && curbuf_locked())
7609 return;
7610 #endif
7611 n = readonlymode;
7612 if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
7613 readonlymode = TRUE;
7614 else if (eap->cmdidx == CMD_enew)
7615 readonlymode = FALSE; /* 'readonly' doesn't make sense in an
7616 empty buffer */
7617 setpcmark();
7618 if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
7619 NULL, eap,
7620 /* ":edit" goes to first line if Vi compatible */
7621 (*eap->arg == NUL && eap->do_ecmd_lnum == 0
7622 && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
7623 ? ECMD_ONE : eap->do_ecmd_lnum,
7624 (P_HID(curbuf) ? ECMD_HIDE : 0)
7625 + (eap->forceit ? ECMD_FORCEIT : 0)
7626 #ifdef FEAT_LISTCMDS
7627 + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
7628 #endif
7629 , old_curwin == NULL ? curwin : NULL) == FAIL)
7631 /* Editing the file failed. If the window was split, close it. */
7632 #ifdef FEAT_WINDOWS
7633 if (old_curwin != NULL)
7635 need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
7636 if (!need_hide || P_HID(curbuf))
7638 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7639 cleanup_T cs;
7641 /* Reset the error/interrupt/exception state here so that
7642 * aborting() returns FALSE when closing a window. */
7643 enter_cleanup(&cs);
7644 # endif
7645 # ifdef FEAT_GUI
7646 need_mouse_correct = TRUE;
7647 # endif
7648 win_close(curwin, !need_hide && !P_HID(curbuf));
7650 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7651 /* Restore the error/interrupt/exception state if not
7652 * discarded by a new aborting error, interrupt, or
7653 * uncaught exception. */
7654 leave_cleanup(&cs);
7655 # endif
7658 #endif
7660 else if (readonlymode && curbuf->b_nwindows == 1)
7662 /* When editing an already visited buffer, 'readonly' won't be set
7663 * but the previous value is kept. With ":view" and ":sview" we
7664 * want the file to be readonly, except when another window is
7665 * editing the same buffer. */
7666 curbuf->b_p_ro = TRUE;
7668 readonlymode = n;
7670 else
7672 if (eap->do_ecmd_cmd != NULL)
7673 do_cmdline_cmd(eap->do_ecmd_cmd);
7674 #ifdef FEAT_TITLE
7675 n = curwin->w_arg_idx_invalid;
7676 #endif
7677 check_arg_idx(curwin);
7678 #ifdef FEAT_TITLE
7679 if (n != curwin->w_arg_idx_invalid)
7680 maketitle();
7681 #endif
7684 #ifdef FEAT_WINDOWS
7686 * if ":split file" worked, set alternate file name in old window to new
7687 * file
7689 if (old_curwin != NULL
7690 && *eap->arg != NUL
7691 && curwin != old_curwin
7692 && win_valid(old_curwin)
7693 && old_curwin->w_buffer != curbuf
7694 && !cmdmod.keepalt)
7695 old_curwin->w_alt_fnum = curbuf->b_fnum;
7696 #endif
7698 ex_no_reprint = TRUE;
7701 #ifndef FEAT_GUI
7703 * ":gui" and ":gvim" when there is no GUI.
7705 static void
7706 ex_nogui(eap)
7707 exarg_T *eap;
7709 eap->errmsg = e_nogvim;
7711 #endif
7713 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
7714 static void
7715 ex_tearoff(eap)
7716 exarg_T *eap;
7718 gui_make_tearoff(eap->arg);
7720 #endif
7722 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
7723 static void
7724 ex_popup(eap)
7725 exarg_T *eap;
7727 gui_make_popup(eap->arg, eap->forceit);
7729 #endif
7731 static void
7732 ex_swapname(eap)
7733 exarg_T *eap UNUSED;
7735 if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
7736 MSG(_("No swap file"));
7737 else
7738 msg(curbuf->b_ml.ml_mfp->mf_fname);
7742 * ":syncbind" forces all 'scrollbind' windows to have the same relative
7743 * offset.
7744 * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
7746 static void
7747 ex_syncbind(eap)
7748 exarg_T *eap UNUSED;
7750 #ifdef FEAT_SCROLLBIND
7751 win_T *wp;
7752 long topline;
7753 long y;
7754 linenr_T old_linenr = curwin->w_cursor.lnum;
7756 setpcmark();
7759 * determine max topline
7761 if (curwin->w_p_scb)
7763 topline = curwin->w_topline;
7764 for (wp = firstwin; wp; wp = wp->w_next)
7766 if (wp->w_p_scb && wp->w_buffer)
7768 y = wp->w_buffer->b_ml.ml_line_count - p_so;
7769 if (topline > y)
7770 topline = y;
7773 if (topline < 1)
7774 topline = 1;
7776 else
7778 topline = 1;
7783 * set all scrollbind windows to the same topline
7785 wp = curwin;
7786 for (curwin = firstwin; curwin; curwin = curwin->w_next)
7788 if (curwin->w_p_scb)
7790 y = topline - curwin->w_topline;
7791 if (y > 0)
7792 scrollup(y, TRUE);
7793 else
7794 scrolldown(-y, TRUE);
7795 curwin->w_scbind_pos = topline;
7796 redraw_later(VALID);
7797 cursor_correct();
7798 #ifdef FEAT_WINDOWS
7799 curwin->w_redr_status = TRUE;
7800 #endif
7803 curwin = wp;
7804 if (curwin->w_p_scb)
7806 did_syncbind = TRUE;
7807 checkpcmark();
7808 if (old_linenr != curwin->w_cursor.lnum)
7810 char_u ctrl_o[2];
7812 ctrl_o[0] = Ctrl_O;
7813 ctrl_o[1] = 0;
7814 ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
7817 #endif
7821 static void
7822 ex_read(eap)
7823 exarg_T *eap;
7825 int i;
7826 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7827 linenr_T lnum;
7829 if (eap->usefilter) /* :r!cmd */
7830 do_bang(1, eap, FALSE, FALSE, TRUE);
7831 else
7833 if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
7834 return;
7836 #ifdef FEAT_BROWSE
7837 if (cmdmod.browse)
7839 char_u *browseFile;
7841 browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
7842 NULL, NULL, NULL, curbuf);
7843 if (browseFile != NULL)
7845 i = readfile(browseFile, NULL,
7846 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7847 vim_free(browseFile);
7849 else
7850 i = OK;
7852 else
7853 #endif
7854 if (*eap->arg == NUL)
7856 if (check_fname() == FAIL) /* check for no file name */
7857 return;
7858 i = readfile(curbuf->b_ffname, curbuf->b_fname,
7859 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7861 else
7863 if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
7864 (void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
7865 i = readfile(eap->arg, NULL,
7866 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7869 if (i == FAIL)
7871 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7872 if (!aborting())
7873 #endif
7874 EMSG2(_(e_notopen), eap->arg);
7876 else
7878 if (empty && exmode_active)
7880 /* Delete the empty line that remains. Historically ex does
7881 * this but vi doesn't. */
7882 if (eap->line2 == 0)
7883 lnum = curbuf->b_ml.ml_line_count;
7884 else
7885 lnum = 1;
7886 if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
7888 ml_delete(lnum, FALSE);
7889 if (curwin->w_cursor.lnum > 1
7890 && curwin->w_cursor.lnum >= lnum)
7891 --curwin->w_cursor.lnum;
7892 deleted_lines_mark(lnum, 1L);
7895 redraw_curbuf_later(VALID);
7900 static char_u *prev_dir = NULL;
7902 #if defined(EXITFREE) || defined(PROTO)
7903 void
7904 free_cd_dir()
7906 vim_free(prev_dir);
7907 prev_dir = NULL;
7909 vim_free(globaldir);
7910 globaldir = NULL;
7912 #endif
7916 * ":cd", ":lcd", ":chdir" and ":lchdir".
7918 void
7919 ex_cd(eap)
7920 exarg_T *eap;
7922 char_u *new_dir;
7923 char_u *tofree;
7925 new_dir = eap->arg;
7926 #if !defined(UNIX) && !defined(VMS)
7927 /* for non-UNIX ":cd" means: print current directory */
7928 if (*new_dir == NUL)
7929 ex_pwd(NULL);
7930 else
7931 #endif
7933 #ifdef FEAT_AUTOCMD
7934 if (allbuf_locked())
7935 return;
7936 #endif
7937 if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
7938 && !eap->forceit)
7940 EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
7941 return;
7944 /* ":cd -": Change to previous directory */
7945 if (STRCMP(new_dir, "-") == 0)
7947 if (prev_dir == NULL)
7949 EMSG(_("E186: No previous directory"));
7950 return;
7952 new_dir = prev_dir;
7955 /* Save current directory for next ":cd -" */
7956 tofree = prev_dir;
7957 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7958 prev_dir = vim_strsave(NameBuff);
7959 else
7960 prev_dir = NULL;
7962 #if defined(UNIX) || defined(VMS)
7963 /* for UNIX ":cd" means: go to home directory */
7964 if (*new_dir == NUL)
7966 /* use NameBuff for home directory name */
7967 # ifdef VMS
7968 char_u *p;
7970 p = mch_getenv((char_u *)"SYS$LOGIN");
7971 if (p == NULL || *p == NUL) /* empty is the same as not set */
7972 NameBuff[0] = NUL;
7973 else
7974 vim_strncpy(NameBuff, p, MAXPATHL - 1);
7975 # else
7976 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
7977 # endif
7978 new_dir = NameBuff;
7980 #endif
7981 if (new_dir == NULL || vim_chdir(new_dir))
7982 EMSG(_(e_failed));
7983 else
7985 vim_free(curwin->w_localdir);
7986 if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
7988 /* If still in global directory, need to remember current
7989 * directory as global directory. */
7990 if (globaldir == NULL && prev_dir != NULL)
7991 globaldir = vim_strsave(prev_dir);
7992 /* Remember this local directory for the window. */
7993 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7994 curwin->w_localdir = vim_strsave(NameBuff);
7996 else
7998 /* We are now in the global directory, no need to remember its
7999 * name. */
8000 vim_free(globaldir);
8001 globaldir = NULL;
8002 curwin->w_localdir = NULL;
8005 shorten_fnames(TRUE);
8007 /* Echo the new current directory if the command was typed. */
8008 if (KeyTyped || p_verbose >= 5)
8009 ex_pwd(eap);
8011 vim_free(tofree);
8016 * ":pwd".
8018 static void
8019 ex_pwd(eap)
8020 exarg_T *eap UNUSED;
8022 if (mch_dirname(NameBuff, MAXPATHL) == OK)
8024 #ifdef BACKSLASH_IN_FILENAME
8025 slash_adjust(NameBuff);
8026 #endif
8027 msg(NameBuff);
8029 else
8030 EMSG(_("E187: Unknown"));
8034 * ":=".
8036 static void
8037 ex_equal(eap)
8038 exarg_T *eap;
8040 smsg((char_u *)"%ld", (long)eap->line2);
8041 ex_may_print(eap);
8044 static void
8045 ex_sleep(eap)
8046 exarg_T *eap;
8048 int n;
8049 long len;
8051 if (cursor_valid())
8053 n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
8054 if (n >= 0)
8055 windgoto((int)n, curwin->w_wcol);
8058 len = eap->line2;
8059 switch (*eap->arg)
8061 case 'm': break;
8062 case NUL: len *= 1000L; break;
8063 default: EMSG2(_(e_invarg2), eap->arg); return;
8065 do_sleep(len);
8069 * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
8071 void
8072 do_sleep(msec)
8073 long msec;
8075 long done;
8077 cursor_on();
8078 out_flush();
8079 for (done = 0; !got_int && done < msec; done += 1000L)
8081 ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
8082 ui_breakcheck();
8086 static void
8087 do_exmap(eap, isabbrev)
8088 exarg_T *eap;
8089 int isabbrev;
8091 int mode;
8092 char_u *cmdp;
8094 cmdp = eap->cmd;
8095 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
8097 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
8098 eap->arg, mode, isabbrev))
8100 case 1: EMSG(_(e_invarg));
8101 break;
8102 case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
8103 break;
8108 * ":winsize" command (obsolete).
8110 static void
8111 ex_winsize(eap)
8112 exarg_T *eap;
8114 int w, h;
8115 char_u *arg = eap->arg;
8116 char_u *p;
8118 w = getdigits(&arg);
8119 arg = skipwhite(arg);
8120 p = arg;
8121 h = getdigits(&arg);
8122 if (*p != NUL && *arg == NUL)
8123 set_shellsize(w, h, TRUE);
8124 else
8125 EMSG(_("E465: :winsize requires two number arguments"));
8128 #ifdef FEAT_WINDOWS
8129 static void
8130 ex_wincmd(eap)
8131 exarg_T *eap;
8133 int xchar = NUL;
8134 char_u *p;
8136 if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
8138 /* CTRL-W g and CTRL-W CTRL-G have an extra command character */
8139 if (eap->arg[1] == NUL)
8141 EMSG(_(e_invarg));
8142 return;
8144 xchar = eap->arg[1];
8145 p = eap->arg + 2;
8147 else
8148 p = eap->arg + 1;
8150 eap->nextcmd = check_nextcmd(p);
8151 p = skipwhite(p);
8152 if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
8153 EMSG(_(e_invarg));
8154 else
8156 /* Pass flags on for ":vertical wincmd ]". */
8157 postponed_split_flags = cmdmod.split;
8158 postponed_split_tab = cmdmod.tab;
8159 do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
8160 postponed_split_flags = 0;
8161 postponed_split_tab = 0;
8164 #endif
8166 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
8168 * ":winpos".
8170 static void
8171 ex_winpos(eap)
8172 exarg_T *eap;
8174 int x, y;
8175 char_u *arg = eap->arg;
8176 char_u *p;
8178 if (*arg == NUL)
8180 # if defined(FEAT_GUI) || defined(MSWIN)
8181 # ifdef FEAT_GUI
8182 if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
8183 # else
8184 if (mch_get_winpos(&x, &y) != FAIL)
8185 # endif
8187 sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
8188 msg(IObuff);
8190 else
8191 # endif
8192 EMSG(_("E188: Obtaining window position not implemented for this platform"));
8194 else
8196 x = getdigits(&arg);
8197 arg = skipwhite(arg);
8198 p = arg;
8199 y = getdigits(&arg);
8200 if (*p == NUL || *arg != NUL)
8202 EMSG(_("E466: :winpos requires two number arguments"));
8203 return;
8205 # ifdef FEAT_GUI
8206 if (gui.in_use)
8207 gui_mch_set_winpos(x, y);
8208 else if (gui.starting)
8210 /* Remember the coordinates for when the window is opened. */
8211 gui_win_x = x;
8212 gui_win_y = y;
8214 # ifdef HAVE_TGETENT
8215 else
8216 # endif
8217 # else
8218 # ifdef MSWIN
8219 mch_set_winpos(x, y);
8220 # endif
8221 # endif
8222 # ifdef HAVE_TGETENT
8223 if (*T_CWP)
8224 term_set_winpos(x, y);
8225 # endif
8228 #endif
8231 * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
8233 static void
8234 ex_operators(eap)
8235 exarg_T *eap;
8237 oparg_T oa;
8239 clear_oparg(&oa);
8240 oa.regname = eap->regname;
8241 oa.start.lnum = eap->line1;
8242 oa.end.lnum = eap->line2;
8243 oa.line_count = eap->line2 - eap->line1 + 1;
8244 oa.motion_type = MLINE;
8245 #ifdef FEAT_VIRTUALEDIT
8246 virtual_op = FALSE;
8247 #endif
8248 if (eap->cmdidx != CMD_yank) /* position cursor for undo */
8250 setpcmark();
8251 curwin->w_cursor.lnum = eap->line1;
8252 beginline(BL_SOL | BL_FIX);
8255 switch (eap->cmdidx)
8257 case CMD_delete:
8258 oa.op_type = OP_DELETE;
8259 op_delete(&oa);
8260 break;
8262 case CMD_yank:
8263 oa.op_type = OP_YANK;
8264 (void)op_yank(&oa, FALSE, TRUE);
8265 break;
8267 default: /* CMD_rshift or CMD_lshift */
8268 if ((eap->cmdidx == CMD_rshift)
8269 #ifdef FEAT_RIGHTLEFT
8270 ^ curwin->w_p_rl
8271 #endif
8273 oa.op_type = OP_RSHIFT;
8274 else
8275 oa.op_type = OP_LSHIFT;
8276 op_shift(&oa, FALSE, eap->amount);
8277 break;
8279 #ifdef FEAT_VIRTUALEDIT
8280 virtual_op = MAYBE;
8281 #endif
8282 ex_may_print(eap);
8286 * ":put".
8288 static void
8289 ex_put(eap)
8290 exarg_T *eap;
8292 /* ":0put" works like ":1put!". */
8293 if (eap->line2 == 0)
8295 eap->line2 = 1;
8296 eap->forceit = TRUE;
8298 curwin->w_cursor.lnum = eap->line2;
8299 do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
8300 PUT_LINE|PUT_CURSLINE);
8304 * Handle ":copy" and ":move".
8306 static void
8307 ex_copymove(eap)
8308 exarg_T *eap;
8310 long n;
8312 n = get_address(&eap->arg, FALSE, FALSE);
8313 if (eap->arg == NULL) /* error detected */
8315 eap->nextcmd = NULL;
8316 return;
8318 get_flags(eap);
8321 * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
8323 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
8325 EMSG(_(e_invaddr));
8326 return;
8329 if (eap->cmdidx == CMD_move)
8331 if (do_move(eap->line1, eap->line2, n) == FAIL)
8332 return;
8334 else
8335 ex_copy(eap->line1, eap->line2, n);
8336 u_clearline();
8337 beginline(BL_SOL | BL_FIX);
8338 ex_may_print(eap);
8342 * Print the current line if flags were given to the Ex command.
8344 static void
8345 ex_may_print(eap)
8346 exarg_T *eap;
8348 if (eap->flags != 0)
8350 print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
8351 (eap->flags & EXFLAG_LIST));
8352 ex_no_reprint = TRUE;
8357 * ":smagic" and ":snomagic".
8359 static void
8360 ex_submagic(eap)
8361 exarg_T *eap;
8363 int magic_save = p_magic;
8365 p_magic = (eap->cmdidx == CMD_smagic);
8366 do_sub(eap);
8367 p_magic = magic_save;
8371 * ":join".
8373 static void
8374 ex_join(eap)
8375 exarg_T *eap;
8377 curwin->w_cursor.lnum = eap->line1;
8378 if (eap->line1 == eap->line2)
8380 if (eap->addr_count >= 2) /* :2,2join does nothing */
8381 return;
8382 if (eap->line2 == curbuf->b_ml.ml_line_count)
8384 beep_flush();
8385 return;
8387 ++eap->line2;
8389 do_do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
8390 beginline(BL_WHITE | BL_FIX);
8391 ex_may_print(eap);
8395 * ":[addr]@r" or ":[addr]*r": execute register
8397 static void
8398 ex_at(eap)
8399 exarg_T *eap;
8401 int c;
8402 int prev_len = typebuf.tb_len;
8404 curwin->w_cursor.lnum = eap->line2;
8406 #ifdef USE_ON_FLY_SCROLL
8407 dont_scroll = TRUE; /* disallow scrolling here */
8408 #endif
8410 /* get the register name. No name means to use the previous one */
8411 c = *eap->arg;
8412 if (c == NUL || (c == '*' && *eap->cmd == '*'))
8413 c = '@';
8414 /* Put the register in the typeahead buffer with the "silent" flag. */
8415 if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
8416 == FAIL)
8418 beep_flush();
8420 else
8422 int save_efr = exec_from_reg;
8424 exec_from_reg = TRUE;
8427 * Execute from the typeahead buffer.
8428 * Continue until the stuff buffer is empty and all added characters
8429 * have been consumed.
8431 while (!stuff_empty() || typebuf.tb_len > prev_len)
8432 (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
8434 exec_from_reg = save_efr;
8439 * ":!".
8441 static void
8442 ex_bang(eap)
8443 exarg_T *eap;
8445 do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
8449 * ":undo".
8451 static void
8452 ex_undo(eap)
8453 exarg_T *eap UNUSED;
8455 if (eap->addr_count == 1) /* :undo 123 */
8456 undo_time(eap->line2, FALSE, TRUE);
8457 else
8458 u_undo(1);
8461 #ifdef FEAT_PERSISTENT_UNDO
8462 void
8463 ex_wundo(eap)
8464 exarg_T *eap;
8466 char_u *name = eap->arg;
8467 u_wundo(name, curbuf);
8470 void
8471 ex_rundo(eap)
8472 exarg_T *eap;
8474 char_u *name = eap->arg;
8475 u_rundo(name, 0);
8477 #endif
8480 * ":redo".
8482 static void
8483 ex_redo(eap)
8484 exarg_T *eap UNUSED;
8486 u_redo(1);
8490 * ":earlier" and ":later".
8492 static void
8493 ex_later(eap)
8494 exarg_T *eap;
8496 long count = 0;
8497 int sec = FALSE;
8498 char_u *p = eap->arg;
8500 if (*p == NUL)
8501 count = 1;
8502 else if (isdigit(*p))
8504 count = getdigits(&p);
8505 switch (*p)
8507 case 's': ++p; sec = TRUE; break;
8508 case 'm': ++p; sec = TRUE; count *= 60; break;
8509 case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
8513 if (*p != NUL)
8514 EMSG2(_(e_invarg2), eap->arg);
8515 else
8516 undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, FALSE);
8520 * ":redir": start/stop redirection.
8522 static void
8523 ex_redir(eap)
8524 exarg_T *eap;
8526 char *mode;
8527 char_u *fname;
8528 char_u *arg = eap->arg;
8530 if (STRICMP(eap->arg, "END") == 0)
8531 close_redir();
8532 else
8534 if (*arg == '>')
8536 ++arg;
8537 if (*arg == '>')
8539 ++arg;
8540 mode = "a";
8542 else
8543 mode = "w";
8544 arg = skipwhite(arg);
8546 close_redir();
8548 /* Expand environment variables and "~/". */
8549 fname = expand_env_save(arg);
8550 if (fname == NULL)
8551 return;
8552 #ifdef FEAT_BROWSE
8553 if (cmdmod.browse)
8555 char_u *browseFile;
8557 browseFile = do_browse(BROWSE_SAVE,
8558 (char_u *)_("Save Redirection"),
8559 fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
8560 if (browseFile == NULL)
8561 return; /* operation cancelled */
8562 vim_free(fname);
8563 fname = browseFile;
8564 eap->forceit = TRUE; /* since dialog already asked */
8566 #endif
8568 redir_fd = open_exfile(fname, eap->forceit, mode);
8569 vim_free(fname);
8571 #ifdef FEAT_EVAL
8572 else if (*arg == '@')
8574 /* redirect to a register a-z (resp. A-Z for appending) */
8575 close_redir();
8576 ++arg;
8577 if (ASCII_ISALPHA(*arg)
8578 # ifdef FEAT_CLIPBOARD
8579 || *arg == '*'
8580 || *arg == '+'
8581 # endif
8582 || *arg == '"')
8584 redir_reg = *arg++;
8585 if (*arg == '>' && arg[1] == '>') /* append */
8586 arg += 2;
8587 else
8589 /* Can use both "@a" and "@a>". */
8590 if (*arg == '>')
8591 arg++;
8592 /* Make register empty when not using @A-@Z and the
8593 * command is valid. */
8594 if (*arg == NUL && !isupper(redir_reg))
8595 write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
8598 if (*arg != NUL)
8600 redir_reg = 0;
8601 EMSG2(_(e_invarg2), eap->arg);
8604 else if (*arg == '=' && arg[1] == '>')
8606 int append;
8608 /* redirect to a variable */
8609 close_redir();
8610 arg += 2;
8612 if (*arg == '>')
8614 ++arg;
8615 append = TRUE;
8617 else
8618 append = FALSE;
8620 if (var_redir_start(skipwhite(arg), append) == OK)
8621 redir_vname = 1;
8623 #endif
8625 /* TODO: redirect to a buffer */
8627 else
8628 EMSG2(_(e_invarg2), eap->arg);
8631 /* Make sure redirection is not off. Can happen for cmdline completion
8632 * that indirectly invokes a command to catch its output. */
8633 if (redir_fd != NULL
8634 #ifdef FEAT_EVAL
8635 || redir_reg || redir_vname
8636 #endif
8638 redir_off = FALSE;
8642 * ":redraw": force redraw
8644 static void
8645 ex_redraw(eap)
8646 exarg_T *eap;
8648 int r = RedrawingDisabled;
8649 int p = p_lz;
8651 RedrawingDisabled = 0;
8652 p_lz = FALSE;
8653 update_topline();
8654 update_screen(eap->forceit ? CLEAR :
8655 #ifdef FEAT_VISUAL
8656 VIsual_active ? INVERTED :
8657 #endif
8659 #ifdef FEAT_TITLE
8660 if (need_maketitle)
8661 maketitle();
8662 #endif
8663 RedrawingDisabled = r;
8664 p_lz = p;
8666 /* Reset msg_didout, so that a message that's there is overwritten. */
8667 msg_didout = FALSE;
8668 msg_col = 0;
8670 out_flush();
8674 * ":redrawstatus": force redraw of status line(s)
8676 static void
8677 ex_redrawstatus(eap)
8678 exarg_T *eap UNUSED;
8680 #if defined(FEAT_WINDOWS)
8681 int r = RedrawingDisabled;
8682 int p = p_lz;
8684 RedrawingDisabled = 0;
8685 p_lz = FALSE;
8686 if (eap->forceit)
8687 status_redraw_all();
8688 else
8689 status_redraw_curbuf();
8690 update_screen(
8691 # ifdef FEAT_VISUAL
8692 VIsual_active ? INVERTED :
8693 # endif
8695 RedrawingDisabled = r;
8696 p_lz = p;
8697 out_flush();
8698 #endif
8701 static void
8702 close_redir()
8704 if (redir_fd != NULL)
8706 fclose(redir_fd);
8707 redir_fd = NULL;
8709 #ifdef FEAT_EVAL
8710 redir_reg = 0;
8711 if (redir_vname)
8713 var_redir_stop();
8714 redir_vname = 0;
8716 #endif
8719 #if defined(FEAT_SESSION) && defined(USE_CRNL)
8720 # define MKSESSION_NL
8721 static int mksession_nl = FALSE; /* use NL only in put_eol() */
8722 #endif
8725 * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
8727 static void
8728 ex_mkrc(eap)
8729 exarg_T *eap;
8731 FILE *fd;
8732 int failed = FALSE;
8733 char_u *fname;
8734 #ifdef FEAT_BROWSE
8735 char_u *browseFile = NULL;
8736 #endif
8737 #ifdef FEAT_SESSION
8738 int view_session = FALSE;
8739 int using_vdir = FALSE; /* using 'viewdir'? */
8740 char_u *viewFile = NULL;
8741 unsigned *flagp;
8742 #endif
8744 if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
8746 #ifdef FEAT_SESSION
8747 view_session = TRUE;
8748 #else
8749 ex_ni(eap);
8750 return;
8751 #endif
8754 #ifdef FEAT_SESSION
8755 /* Use the short file name until ":lcd" is used. We also don't use the
8756 * short file name when 'acd' is set, that is checked later. */
8757 did_lcd = FALSE;
8759 /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
8760 if (eap->cmdidx == CMD_mkview
8761 && (*eap->arg == NUL
8762 || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
8764 eap->forceit = TRUE;
8765 fname = get_view_file(*eap->arg);
8766 if (fname == NULL)
8767 return;
8768 viewFile = fname;
8769 using_vdir = TRUE;
8771 else
8772 #endif
8773 if (*eap->arg != NUL)
8774 fname = eap->arg;
8775 else if (eap->cmdidx == CMD_mkvimrc)
8776 fname = (char_u *)VIMRC_FILE;
8777 #ifdef FEAT_SESSION
8778 else if (eap->cmdidx == CMD_mksession)
8779 fname = (char_u *)SESSION_FILE;
8780 #endif
8781 else
8782 fname = (char_u *)EXRC_FILE;
8784 #ifdef FEAT_BROWSE
8785 if (cmdmod.browse)
8787 browseFile = do_browse(BROWSE_SAVE,
8788 # ifdef FEAT_SESSION
8789 eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
8790 eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
8791 # endif
8792 (char_u *)_("Save Setup"),
8793 fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
8794 if (browseFile == NULL)
8795 goto theend;
8796 fname = browseFile;
8797 eap->forceit = TRUE; /* since dialog already asked */
8799 #endif
8801 #if defined(FEAT_SESSION) && defined(vim_mkdir)
8802 /* When using 'viewdir' may have to create the directory. */
8803 if (using_vdir && !mch_isdir(p_vdir))
8804 vim_mkdir_emsg(p_vdir, 0755);
8805 #endif
8807 fd = open_exfile(fname, eap->forceit, WRITEBIN);
8808 if (fd != NULL)
8810 #ifdef FEAT_SESSION
8811 if (eap->cmdidx == CMD_mkview)
8812 flagp = &vop_flags;
8813 else
8814 flagp = &ssop_flags;
8815 #endif
8817 #ifdef MKSESSION_NL
8818 /* "unix" in 'sessionoptions': use NL line separator */
8819 if (view_session && (*flagp & SSOP_UNIX))
8820 mksession_nl = TRUE;
8821 #endif
8823 /* Write the version command for :mkvimrc */
8824 if (eap->cmdidx == CMD_mkvimrc)
8825 (void)put_line(fd, "version 6.0");
8827 #ifdef FEAT_SESSION
8828 if (eap->cmdidx == CMD_mksession)
8830 if (put_line(fd, "let SessionLoad = 1") == FAIL)
8831 failed = TRUE;
8834 if (eap->cmdidx != CMD_mkview)
8835 #endif
8837 /* Write setting 'compatible' first, because it has side effects.
8838 * For that same reason only do it when needed. */
8839 if (p_cp)
8840 (void)put_line(fd, "if !&cp | set cp | endif");
8841 else
8842 (void)put_line(fd, "if &cp | set nocp | endif");
8845 #ifdef FEAT_SESSION
8846 if (!view_session
8847 || (eap->cmdidx == CMD_mksession
8848 && (*flagp & SSOP_OPTIONS)))
8849 #endif
8850 failed |= (makemap(fd, NULL) == FAIL
8851 || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
8853 #ifdef FEAT_SESSION
8854 if (!failed && view_session)
8856 if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
8857 failed = TRUE;
8858 if (eap->cmdidx == CMD_mksession)
8860 char_u dirnow[MAXPATHL]; /* current directory */
8863 * Change to session file's dir.
8865 if (mch_dirname(dirnow, MAXPATHL) == FAIL
8866 || mch_chdir((char *)dirnow) != 0)
8867 *dirnow = NUL;
8868 if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
8870 if (vim_chdirfile(fname) == OK)
8871 shorten_fnames(TRUE);
8873 else if (*dirnow != NUL
8874 && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
8876 if (mch_chdir((char *)globaldir) == 0)
8877 shorten_fnames(TRUE);
8880 failed |= (makeopens(fd, dirnow) == FAIL);
8882 /* restore original dir */
8883 if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
8884 || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
8886 if (mch_chdir((char *)dirnow) != 0)
8887 EMSG(_(e_prev_dir));
8888 shorten_fnames(TRUE);
8891 else
8893 failed |= (put_view(fd, curwin, !using_vdir, flagp,
8894 -1) == FAIL);
8896 if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
8897 == FAIL)
8898 failed = TRUE;
8899 if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
8900 failed = TRUE;
8901 if (eap->cmdidx == CMD_mksession)
8903 if (put_line(fd, "unlet SessionLoad") == FAIL)
8904 failed = TRUE;
8907 #endif
8908 if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
8909 failed = TRUE;
8911 failed |= fclose(fd);
8913 if (failed)
8914 EMSG(_(e_write));
8915 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
8916 else if (eap->cmdidx == CMD_mksession)
8918 /* successful session write - set this_session var */
8919 char_u tbuf[MAXPATHL];
8921 if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
8922 set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
8924 #endif
8925 #ifdef MKSESSION_NL
8926 mksession_nl = FALSE;
8927 #endif
8930 #ifdef FEAT_BROWSE
8931 theend:
8932 vim_free(browseFile);
8933 #endif
8934 #ifdef FEAT_SESSION
8935 vim_free(viewFile);
8936 #endif
8939 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
8940 || defined(PROTO)
8942 vim_mkdir_emsg(name, prot)
8943 char_u *name;
8944 int prot UNUSED;
8946 if (vim_mkdir(name, prot) != 0)
8948 EMSG2(_("E739: Cannot create directory: %s"), name);
8949 return FAIL;
8951 return OK;
8953 #endif
8956 * Open a file for writing for an Ex command, with some checks.
8957 * Return file descriptor, or NULL on failure.
8959 FILE *
8960 open_exfile(fname, forceit, mode)
8961 char_u *fname;
8962 int forceit;
8963 char *mode; /* "w" for create new file or "a" for append */
8965 FILE *fd;
8967 #ifdef UNIX
8968 /* with Unix it is possible to open a directory */
8969 if (mch_isdir(fname))
8971 EMSG2(_(e_isadir2), fname);
8972 return NULL;
8974 #endif
8975 if (!forceit && *mode != 'a' && vim_fexists(fname))
8977 EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
8978 return NULL;
8981 if ((fd = mch_fopen((char *)fname, mode)) == NULL)
8982 EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
8984 return fd;
8988 * ":mark" and ":k".
8990 static void
8991 ex_mark(eap)
8992 exarg_T *eap;
8994 pos_T pos;
8996 if (*eap->arg == NUL) /* No argument? */
8997 EMSG(_(e_argreq));
8998 else if (eap->arg[1] != NUL) /* more than one character? */
8999 EMSG(_(e_trailing));
9000 else
9002 pos = curwin->w_cursor; /* save curwin->w_cursor */
9003 curwin->w_cursor.lnum = eap->line2;
9004 beginline(BL_WHITE | BL_FIX);
9005 if (setmark(*eap->arg) == FAIL) /* set mark */
9006 EMSG(_("E191: Argument must be a letter or forward/backward quote"));
9007 curwin->w_cursor = pos; /* restore curwin->w_cursor */
9012 * Update w_topline, w_leftcol and the cursor position.
9014 void
9015 update_topline_cursor()
9017 check_cursor(); /* put cursor on valid line */
9018 update_topline();
9019 if (!curwin->w_p_wrap)
9020 validate_cursor();
9021 update_curswant();
9024 #ifdef FEAT_EX_EXTRA
9026 * ":normal[!] {commands}": Execute normal mode commands.
9028 static void
9029 ex_normal(eap)
9030 exarg_T *eap;
9032 int save_msg_scroll = msg_scroll;
9033 int save_restart_edit = restart_edit;
9034 int save_msg_didout = msg_didout;
9035 int save_State = State;
9036 tasave_T tabuf;
9037 int save_insertmode = p_im;
9038 int save_finish_op = finish_op;
9039 int save_opcount = opcount;
9040 #ifdef FEAT_MBYTE
9041 char_u *arg = NULL;
9042 int l;
9043 char_u *p;
9044 #endif
9046 if (ex_normal_lock > 0)
9048 EMSG(_(e_secure));
9049 return;
9051 if (ex_normal_busy >= p_mmd)
9053 EMSG(_("E192: Recursive use of :normal too deep"));
9054 return;
9056 ++ex_normal_busy;
9058 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
9059 restart_edit = 0; /* don't go to Insert mode */
9060 p_im = FALSE; /* don't use 'insertmode' */
9062 #ifdef FEAT_MBYTE
9064 * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
9065 * this for the K_SPECIAL leading byte, otherwise special keys will not
9066 * work.
9068 if (has_mbyte)
9070 int len = 0;
9072 /* Count the number of characters to be escaped. */
9073 for (p = eap->arg; *p != NUL; ++p)
9075 # ifdef FEAT_GUI
9076 if (*p == CSI) /* leadbyte CSI */
9077 len += 2;
9078 # endif
9079 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9080 if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */
9081 # ifdef FEAT_GUI
9082 || *p == CSI
9083 # endif
9085 len += 2;
9087 if (len > 0)
9089 arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
9090 if (arg != NULL)
9092 len = 0;
9093 for (p = eap->arg; *p != NUL; ++p)
9095 arg[len++] = *p;
9096 # ifdef FEAT_GUI
9097 if (*p == CSI)
9099 arg[len++] = KS_EXTRA;
9100 arg[len++] = (int)KE_CSI;
9102 # endif
9103 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9105 arg[len++] = *++p;
9106 if (*p == K_SPECIAL)
9108 arg[len++] = KS_SPECIAL;
9109 arg[len++] = KE_FILLER;
9111 # ifdef FEAT_GUI
9112 else if (*p == CSI)
9114 arg[len++] = KS_EXTRA;
9115 arg[len++] = (int)KE_CSI;
9117 # endif
9119 arg[len] = NUL;
9124 #endif
9127 * Save the current typeahead. This is required to allow using ":normal"
9128 * from an event handler and makes sure we don't hang when the argument
9129 * ends with half a command.
9131 save_typeahead(&tabuf);
9132 if (tabuf.typebuf_valid)
9135 * Repeat the :normal command for each line in the range. When no
9136 * range given, execute it just once, without positioning the cursor
9137 * first.
9141 if (eap->addr_count != 0)
9143 curwin->w_cursor.lnum = eap->line1++;
9144 curwin->w_cursor.col = 0;
9147 exec_normal_cmd(
9148 #ifdef FEAT_MBYTE
9149 arg != NULL ? arg :
9150 #endif
9151 eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
9153 while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
9156 /* Might not return to the main loop when in an event handler. */
9157 update_topline_cursor();
9159 /* Restore the previous typeahead. */
9160 restore_typeahead(&tabuf);
9162 --ex_normal_busy;
9163 msg_scroll = save_msg_scroll;
9164 restart_edit = save_restart_edit;
9165 p_im = save_insertmode;
9166 finish_op = save_finish_op;
9167 opcount = save_opcount;
9168 msg_didout |= save_msg_didout; /* don't reset msg_didout now */
9170 /* Restore the state (needed when called from a function executed for
9171 * 'indentexpr'). */
9172 State = save_State;
9173 #ifdef FEAT_MBYTE
9174 vim_free(arg);
9175 #endif
9179 * ":startinsert", ":startreplace" and ":startgreplace"
9181 static void
9182 ex_startinsert(eap)
9183 exarg_T *eap;
9185 if (eap->forceit)
9187 coladvance((colnr_T)MAXCOL);
9188 curwin->w_curswant = MAXCOL;
9189 curwin->w_set_curswant = FALSE;
9192 /* Ignore the command when already in Insert mode. Inserting an
9193 * expression register that invokes a function can do this. */
9194 if (State & INSERT)
9195 return;
9197 if (eap->cmdidx == CMD_startinsert)
9198 restart_edit = 'a';
9199 else if (eap->cmdidx == CMD_startreplace)
9200 restart_edit = 'R';
9201 else
9202 restart_edit = 'V';
9204 if (!eap->forceit)
9206 if (eap->cmdidx == CMD_startinsert)
9207 restart_edit = 'i';
9208 curwin->w_curswant = 0; /* avoid MAXCOL */
9213 * ":stopinsert"
9215 static void
9216 ex_stopinsert(eap)
9217 exarg_T *eap UNUSED;
9219 restart_edit = 0;
9220 stop_insert_mode = TRUE;
9222 #endif
9224 #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO)
9226 * Execute normal mode command "cmd".
9227 * "remap" can be REMAP_NONE or REMAP_YES.
9229 void
9230 exec_normal_cmd(cmd, remap, silent)
9231 char_u *cmd;
9232 int remap;
9233 int silent;
9235 oparg_T oa;
9238 * Stuff the argument into the typeahead buffer.
9239 * Execute normal_cmd() until there is no typeahead left.
9241 clear_oparg(&oa);
9242 finish_op = FALSE;
9243 ins_typebuf(cmd, remap, 0, TRUE, silent);
9244 while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
9245 && !got_int)
9247 update_topline_cursor();
9248 normal_cmd(&oa, FALSE); /* execute a Normal mode cmd */
9251 #endif
9253 #ifdef FEAT_FIND_ID
9254 static void
9255 ex_checkpath(eap)
9256 exarg_T *eap;
9258 find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
9259 eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
9260 (linenr_T)1, (linenr_T)MAXLNUM);
9263 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
9265 * ":psearch"
9267 static void
9268 ex_psearch(eap)
9269 exarg_T *eap;
9271 g_do_tagpreview = p_pvh;
9272 ex_findpat(eap);
9273 g_do_tagpreview = 0;
9275 #endif
9277 static void
9278 ex_findpat(eap)
9279 exarg_T *eap;
9281 int whole = TRUE;
9282 long n;
9283 char_u *p;
9284 int action;
9286 switch (cmdnames[eap->cmdidx].cmd_name[2])
9288 case 'e': /* ":psearch", ":isearch" and ":dsearch" */
9289 if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
9290 action = ACTION_GOTO;
9291 else
9292 action = ACTION_SHOW;
9293 break;
9294 case 'i': /* ":ilist" and ":dlist" */
9295 action = ACTION_SHOW_ALL;
9296 break;
9297 case 'u': /* ":ijump" and ":djump" */
9298 action = ACTION_GOTO;
9299 break;
9300 default: /* ":isplit" and ":dsplit" */
9301 action = ACTION_SPLIT;
9302 break;
9305 n = 1;
9306 if (vim_isdigit(*eap->arg)) /* get count */
9308 n = getdigits(&eap->arg);
9309 eap->arg = skipwhite(eap->arg);
9311 if (*eap->arg == '/') /* Match regexp, not just whole words */
9313 whole = FALSE;
9314 ++eap->arg;
9315 p = skip_regexp(eap->arg, '/', p_magic, NULL);
9316 if (*p)
9318 *p++ = NUL;
9319 p = skipwhite(p);
9321 /* Check for trailing illegal characters */
9322 if (!ends_excmd(*p))
9323 eap->errmsg = e_trailing;
9324 else
9325 eap->nextcmd = check_nextcmd(p);
9328 if (!eap->skip)
9329 find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
9330 whole, !eap->forceit,
9331 *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY,
9332 n, action, eap->line1, eap->line2);
9334 #endif
9336 #ifdef FEAT_WINDOWS
9338 # ifdef FEAT_QUICKFIX
9340 * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
9342 static void
9343 ex_ptag(eap)
9344 exarg_T *eap;
9346 g_do_tagpreview = p_pvh;
9347 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9351 * ":pedit"
9353 static void
9354 ex_pedit(eap)
9355 exarg_T *eap;
9357 win_T *curwin_save = curwin;
9359 g_do_tagpreview = p_pvh;
9360 prepare_tagpreview(TRUE);
9361 keep_help_flag = curwin_save->w_buffer->b_help;
9362 do_exedit(eap, NULL);
9363 keep_help_flag = FALSE;
9364 if (curwin != curwin_save && win_valid(curwin_save))
9366 /* Return cursor to where we were */
9367 validate_cursor();
9368 redraw_later(VALID);
9369 win_enter(curwin_save, TRUE);
9371 g_do_tagpreview = 0;
9373 # endif
9376 * ":stag", ":stselect" and ":stjump".
9378 static void
9379 ex_stag(eap)
9380 exarg_T *eap;
9382 postponed_split = -1;
9383 postponed_split_flags = cmdmod.split;
9384 postponed_split_tab = cmdmod.tab;
9385 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9386 postponed_split_flags = 0;
9387 postponed_split_tab = 0;
9389 #endif
9392 * ":tag", ":tselect", ":tjump", ":tnext", etc.
9394 static void
9395 ex_tag(eap)
9396 exarg_T *eap;
9398 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
9401 static void
9402 ex_tag_cmd(eap, name)
9403 exarg_T *eap;
9404 char_u *name;
9406 int cmd;
9408 switch (name[1])
9410 case 'j': cmd = DT_JUMP; /* ":tjump" */
9411 break;
9412 case 's': cmd = DT_SELECT; /* ":tselect" */
9413 break;
9414 case 'p': cmd = DT_PREV; /* ":tprevious" */
9415 break;
9416 case 'N': cmd = DT_PREV; /* ":tNext" */
9417 break;
9418 case 'n': cmd = DT_NEXT; /* ":tnext" */
9419 break;
9420 case 'o': cmd = DT_POP; /* ":pop" */
9421 break;
9422 case 'f': /* ":tfirst" */
9423 case 'r': cmd = DT_FIRST; /* ":trewind" */
9424 break;
9425 case 'l': cmd = DT_LAST; /* ":tlast" */
9426 break;
9427 default: /* ":tag" */
9428 #ifdef FEAT_CSCOPE
9429 if (p_cst && *eap->arg != NUL)
9431 do_cstag(eap);
9432 return;
9434 #endif
9435 cmd = DT_TAG;
9436 break;
9439 if (name[0] == 'l')
9441 #ifndef FEAT_QUICKFIX
9442 ex_ni(eap);
9443 return;
9444 #else
9445 cmd = DT_LTAG;
9446 #endif
9449 do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
9450 eap->forceit, TRUE);
9454 * Check "str" for starting with a special cmdline variable.
9455 * If found return one of the SPEC_ values and set "*usedlen" to the length of
9456 * the variable. Otherwise return -1 and "*usedlen" is unchanged.
9459 find_cmdline_var(src, usedlen)
9460 char_u *src;
9461 int *usedlen;
9463 int len;
9464 int i;
9465 static char *(spec_str[]) = {
9466 "%",
9467 #define SPEC_PERC 0
9468 "#",
9469 #define SPEC_HASH 1
9470 "<cword>", /* cursor word */
9471 #define SPEC_CWORD 2
9472 "<cWORD>", /* cursor WORD */
9473 #define SPEC_CCWORD 3
9474 "<cfile>", /* cursor path name */
9475 #define SPEC_CFILE 4
9476 "<sfile>", /* ":so" file name */
9477 #define SPEC_SFILE 5
9478 #ifdef FEAT_AUTOCMD
9479 "<afile>", /* autocommand file name */
9480 # define SPEC_AFILE 6
9481 "<abuf>", /* autocommand buffer number */
9482 # define SPEC_ABUF 7
9483 "<amatch>", /* autocommand match name */
9484 # define SPEC_AMATCH 8
9485 #endif
9486 #ifdef FEAT_CLIENTSERVER
9487 "<client>"
9488 # define SPEC_CLIENT 9
9489 #endif
9492 for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i)
9494 len = (int)STRLEN(spec_str[i]);
9495 if (STRNCMP(src, spec_str[i], len) == 0)
9497 *usedlen = len;
9498 return i;
9501 return -1;
9505 * Evaluate cmdline variables.
9507 * change '%' to curbuf->b_ffname
9508 * '#' to curwin->w_altfile
9509 * '<cword>' to word under the cursor
9510 * '<cWORD>' to WORD under the cursor
9511 * '<cfile>' to path name under the cursor
9512 * '<sfile>' to sourced file name
9513 * '<afile>' to file name for autocommand
9514 * '<abuf>' to buffer number for autocommand
9515 * '<amatch>' to matching name for autocommand
9517 * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
9518 * "" for error without a message) and NULL is returned.
9519 * Returns an allocated string if a valid match was found.
9520 * Returns NULL if no match was found. "usedlen" then still contains the
9521 * number of characters to skip.
9523 char_u *
9524 eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped)
9525 char_u *src; /* pointer into commandline */
9526 char_u *srcstart; /* beginning of valid memory for src */
9527 int *usedlen; /* characters after src that are used */
9528 linenr_T *lnump; /* line number for :e command, or NULL */
9529 char_u **errormsg; /* pointer to error message */
9530 int *escaped; /* return value has escaped white space (can
9531 * be NULL) */
9533 int i;
9534 char_u *s;
9535 char_u *result;
9536 char_u *resultbuf = NULL;
9537 int resultlen;
9538 buf_T *buf;
9539 int valid = VALID_HEAD + VALID_PATH; /* assume valid result */
9540 int spec_idx;
9541 #ifdef FEAT_MODIFY_FNAME
9542 int skip_mod = FALSE;
9543 #endif
9545 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
9546 char_u strbuf[30];
9547 #endif
9549 *errormsg = NULL;
9550 if (escaped != NULL)
9551 *escaped = FALSE;
9554 * Check if there is something to do.
9556 spec_idx = find_cmdline_var(src, usedlen);
9557 if (spec_idx < 0) /* no match */
9559 *usedlen = 1;
9560 return NULL;
9564 * Skip when preceded with a backslash "\%" and "\#".
9565 * Note: In "\\%" the % is also not recognized!
9567 if (src > srcstart && src[-1] == '\\')
9569 *usedlen = 0;
9570 STRMOVE(src - 1, src); /* remove backslash */
9571 return NULL;
9575 * word or WORD under cursor
9577 if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
9579 resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
9580 (FIND_IDENT|FIND_STRING) : FIND_STRING);
9581 if (resultlen == 0)
9583 *errormsg = (char_u *)"";
9584 return NULL;
9589 * '#': Alternate file name
9590 * '%': Current file name
9591 * File name under the cursor
9592 * File name for autocommand
9593 * and following modifiers
9595 else
9597 switch (spec_idx)
9599 case SPEC_PERC: /* '%': current file */
9600 if (curbuf->b_fname == NULL)
9602 result = (char_u *)"";
9603 valid = 0; /* Must have ":p:h" to be valid */
9605 else
9606 #ifdef RISCOS
9607 /* Always use the full path for RISC OS if possible. */
9608 result = curbuf->b_ffname;
9609 if (result == NULL)
9610 result = curbuf->b_fname;
9611 #else
9612 result = curbuf->b_fname;
9613 #endif
9614 break;
9616 case SPEC_HASH: /* '#' or "#99": alternate file */
9617 if (src[1] == '#') /* "##": the argument list */
9619 result = arg_all();
9620 resultbuf = result;
9621 *usedlen = 2;
9622 if (escaped != NULL)
9623 *escaped = TRUE;
9624 #ifdef FEAT_MODIFY_FNAME
9625 skip_mod = TRUE;
9626 #endif
9627 break;
9629 s = src + 1;
9630 if (*s == '<') /* "#<99" uses v:oldfiles */
9631 ++s;
9632 i = (int)getdigits(&s);
9633 *usedlen = (int)(s - src); /* length of what we expand */
9635 if (src[1] == '<')
9637 if (*usedlen < 2)
9639 /* Should we give an error message for #<text? */
9640 *usedlen = 1;
9641 return NULL;
9643 #ifdef FEAT_EVAL
9644 result = list_find_str(get_vim_var_list(VV_OLDFILES),
9645 (long)i);
9646 if (result == NULL)
9648 *errormsg = (char_u *)"";
9649 return NULL;
9651 #else
9652 *errormsg = (char_u *)_("E809: #< is not available without the +eval feature");
9653 return NULL;
9654 #endif
9656 else
9658 buf = buflist_findnr(i);
9659 if (buf == NULL)
9661 *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
9662 return NULL;
9664 if (lnump != NULL)
9665 *lnump = ECMD_LAST;
9666 if (buf->b_fname == NULL)
9668 result = (char_u *)"";
9669 valid = 0; /* Must have ":p:h" to be valid */
9671 else
9672 result = buf->b_fname;
9674 break;
9676 #ifdef FEAT_SEARCHPATH
9677 case SPEC_CFILE: /* file name under cursor */
9678 result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
9679 if (result == NULL)
9681 *errormsg = (char_u *)"";
9682 return NULL;
9684 resultbuf = result; /* remember allocated string */
9685 break;
9686 #endif
9688 #ifdef FEAT_AUTOCMD
9689 case SPEC_AFILE: /* file name for autocommand */
9690 result = autocmd_fname;
9691 if (result != NULL && !autocmd_fname_full)
9693 /* Still need to turn the fname into a full path. It is
9694 * postponed to avoid a delay when <afile> is not used. */
9695 autocmd_fname_full = TRUE;
9696 result = FullName_save(autocmd_fname, FALSE);
9697 vim_free(autocmd_fname);
9698 autocmd_fname = result;
9700 if (result == NULL)
9702 *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
9703 return NULL;
9705 result = shorten_fname1(result);
9706 break;
9708 case SPEC_ABUF: /* buffer number for autocommand */
9709 if (autocmd_bufnr <= 0)
9711 *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
9712 return NULL;
9714 sprintf((char *)strbuf, "%d", autocmd_bufnr);
9715 result = strbuf;
9716 break;
9718 case SPEC_AMATCH: /* match name for autocommand */
9719 result = autocmd_match;
9720 if (result == NULL)
9722 *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
9723 return NULL;
9725 break;
9727 #endif
9728 case SPEC_SFILE: /* file name for ":so" command */
9729 result = sourcing_name;
9730 if (result == NULL)
9732 *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
9733 return NULL;
9735 break;
9736 #if defined(FEAT_CLIENTSERVER)
9737 case SPEC_CLIENT: /* Source of last submitted input */
9738 sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
9739 (long_u)clientWindow);
9740 result = strbuf;
9741 break;
9742 #endif
9745 resultlen = (int)STRLEN(result); /* length of new string */
9746 if (src[*usedlen] == '<') /* remove the file name extension */
9748 ++*usedlen;
9749 #ifdef RISCOS
9750 if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
9751 #else
9752 if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
9753 #endif
9754 resultlen = (int)(s - result);
9756 #ifdef FEAT_MODIFY_FNAME
9757 else if (!skip_mod)
9759 valid |= modify_fname(src, usedlen, &result, &resultbuf,
9760 &resultlen);
9761 if (result == NULL)
9763 *errormsg = (char_u *)"";
9764 return NULL;
9767 #endif
9770 if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
9772 if (valid != VALID_HEAD + VALID_PATH)
9773 /* xgettext:no-c-format */
9774 *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
9775 else
9776 *errormsg = (char_u *)_("E500: Evaluates to an empty string");
9777 result = NULL;
9779 else
9780 result = vim_strnsave(result, resultlen);
9781 vim_free(resultbuf);
9782 return result;
9786 * Concatenate all files in the argument list, separated by spaces, and return
9787 * it in one allocated string.
9788 * Spaces and backslashes in the file names are escaped with a backslash.
9789 * Returns NULL when out of memory.
9791 static char_u *
9792 arg_all()
9794 int len;
9795 int idx;
9796 char_u *retval = NULL;
9797 char_u *p;
9800 * Do this loop two times:
9801 * first time: compute the total length
9802 * second time: concatenate the names
9804 for (;;)
9806 len = 0;
9807 for (idx = 0; idx < ARGCOUNT; ++idx)
9809 p = alist_name(&ARGLIST[idx]);
9810 if (p != NULL)
9812 if (len > 0)
9814 /* insert a space in between names */
9815 if (retval != NULL)
9816 retval[len] = ' ';
9817 ++len;
9819 for ( ; *p != NUL; ++p)
9821 if (*p == ' ' || *p == '\\')
9823 /* insert a backslash */
9824 if (retval != NULL)
9825 retval[len] = '\\';
9826 ++len;
9828 if (retval != NULL)
9829 retval[len] = *p;
9830 ++len;
9835 /* second time: break here */
9836 if (retval != NULL)
9838 retval[len] = NUL;
9839 break;
9842 /* allocate memory */
9843 retval = alloc((unsigned)len + 1);
9844 if (retval == NULL)
9845 break;
9848 return retval;
9851 #if defined(FEAT_AUTOCMD) || defined(PROTO)
9853 * Expand the <sfile> string in "arg".
9855 * Returns an allocated string, or NULL for any error.
9857 char_u *
9858 expand_sfile(arg)
9859 char_u *arg;
9861 char_u *errormsg;
9862 int len;
9863 char_u *result;
9864 char_u *newres;
9865 char_u *repl;
9866 int srclen;
9867 char_u *p;
9869 result = vim_strsave(arg);
9870 if (result == NULL)
9871 return NULL;
9873 for (p = result; *p; )
9875 if (STRNCMP(p, "<sfile>", 7) != 0)
9876 ++p;
9877 else
9879 /* replace "<sfile>" with the sourced file name, and do ":" stuff */
9880 repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
9881 if (errormsg != NULL)
9883 if (*errormsg)
9884 emsg(errormsg);
9885 vim_free(result);
9886 return NULL;
9888 if (repl == NULL) /* no match (cannot happen) */
9890 p += srclen;
9891 continue;
9893 len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
9894 newres = alloc(len);
9895 if (newres == NULL)
9897 vim_free(repl);
9898 vim_free(result);
9899 return NULL;
9901 mch_memmove(newres, result, (size_t)(p - result));
9902 STRCPY(newres + (p - result), repl);
9903 len = (int)STRLEN(newres);
9904 STRCAT(newres, p + srclen);
9905 vim_free(repl);
9906 vim_free(result);
9907 result = newres;
9908 p = newres + len; /* continue after the match */
9912 return result;
9914 #endif
9916 #ifdef FEAT_SESSION
9917 static int ses_winsizes __ARGS((FILE *fd, int restore_size,
9918 win_T *tab_firstwin));
9919 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
9920 static frame_T *ses_skipframe __ARGS((frame_T *fr));
9921 static int ses_do_frame __ARGS((frame_T *fr));
9922 static int ses_do_win __ARGS((win_T *wp));
9923 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
9924 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
9925 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
9928 * Write openfile commands for the current buffers to an .exrc file.
9929 * Return FAIL on error, OK otherwise.
9931 static int
9932 makeopens(fd, dirnow)
9933 FILE *fd;
9934 char_u *dirnow; /* Current directory name */
9936 buf_T *buf;
9937 int only_save_windows = TRUE;
9938 int nr;
9939 int cnr = 1;
9940 int restore_size = TRUE;
9941 win_T *wp;
9942 char_u *sname;
9943 win_T *edited_win = NULL;
9944 int tabnr;
9945 win_T *tab_firstwin;
9946 frame_T *tab_topframe;
9947 int cur_arg_idx = 0;
9948 int next_arg_idx = 0;
9950 if (ssop_flags & SSOP_BUFFERS)
9951 only_save_windows = FALSE; /* Save ALL buffers */
9954 * Begin by setting the this_session variable, and then other
9955 * sessionable variables.
9957 #ifdef FEAT_EVAL
9958 if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
9959 return FAIL;
9960 if (ssop_flags & SSOP_GLOBALS)
9961 if (store_session_globals(fd) == FAIL)
9962 return FAIL;
9963 #endif
9966 * Close all windows but one.
9968 if (put_line(fd, "silent only") == FAIL)
9969 return FAIL;
9972 * Now a :cd command to the session directory or the current directory
9974 if (ssop_flags & SSOP_SESDIR)
9976 if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
9977 == FAIL)
9978 return FAIL;
9980 else if (ssop_flags & SSOP_CURDIR)
9982 sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
9983 if (sname == NULL
9984 || fputs("cd ", fd) < 0
9985 || ses_put_fname(fd, sname, &ssop_flags) == FAIL
9986 || put_eol(fd) == FAIL)
9988 vim_free(sname);
9989 return FAIL;
9991 vim_free(sname);
9995 * If there is an empty, unnamed buffer we will wipe it out later.
9996 * Remember the buffer number.
9998 if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
9999 return FAIL;
10000 if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL)
10001 return FAIL;
10002 if (put_line(fd, "endif") == FAIL)
10003 return FAIL;
10006 * Now save the current files, current buffer first.
10008 if (put_line(fd, "set shortmess=aoO") == FAIL)
10009 return FAIL;
10011 /* Now put the other buffers into the buffer list */
10012 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
10014 if (!(only_save_windows && buf->b_nwindows == 0)
10015 && !(buf->b_help && !(ssop_flags & SSOP_HELP))
10016 && buf->b_fname != NULL
10017 && buf->b_p_bl)
10019 if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
10020 : buf->b_wininfo->wi_fpos.lnum) < 0
10021 || ses_fname(fd, buf, &ssop_flags) == FAIL)
10022 return FAIL;
10026 /* the global argument list */
10027 if (ses_arglist(fd, "args", &global_alist.al_ga,
10028 !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
10029 return FAIL;
10031 if (ssop_flags & SSOP_RESIZE)
10033 /* Note: after the restore we still check it worked!*/
10034 if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
10035 || put_eol(fd) == FAIL)
10036 return FAIL;
10039 #ifdef FEAT_GUI
10040 if (gui.in_use && (ssop_flags & SSOP_WINPOS))
10042 int x, y;
10044 if (gui_mch_get_winpos(&x, &y) == OK)
10046 /* Note: after the restore we still check it worked!*/
10047 if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
10048 return FAIL;
10051 #endif
10054 * May repeat putting Windows for each tab, when "tabpages" is in
10055 * 'sessionoptions'.
10056 * Don't use goto_tabpage(), it may change directory and trigger
10057 * autocommands.
10059 tab_firstwin = firstwin; /* first window in tab page "tabnr" */
10060 tab_topframe = topframe;
10061 for (tabnr = 1; ; ++tabnr)
10063 int need_tabnew = FALSE;
10065 if ((ssop_flags & SSOP_TABPAGES))
10067 tabpage_T *tp = find_tabpage(tabnr);
10069 if (tp == NULL)
10070 break; /* done all tab pages */
10071 if (tp == curtab)
10073 tab_firstwin = firstwin;
10074 tab_topframe = topframe;
10076 else
10078 tab_firstwin = tp->tp_firstwin;
10079 tab_topframe = tp->tp_topframe;
10081 if (tabnr > 1)
10082 need_tabnew = TRUE;
10086 * Before creating the window layout, try loading one file. If this
10087 * is aborted we don't end up with a number of useless windows.
10088 * This may have side effects! (e.g., compressed or network file).
10090 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10092 if (ses_do_win(wp)
10093 && wp->w_buffer->b_ffname != NULL
10094 && !wp->w_buffer->b_help
10095 #ifdef FEAT_QUICKFIX
10096 && !bt_nofile(wp->w_buffer)
10097 #endif
10100 if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
10101 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
10102 return FAIL;
10103 need_tabnew = FALSE;
10104 if (!wp->w_arg_idx_invalid)
10105 edited_win = wp;
10106 break;
10110 /* If no file got edited create an empty tab page. */
10111 if (need_tabnew && put_line(fd, "tabnew") == FAIL)
10112 return FAIL;
10115 * Save current window layout.
10117 if (put_line(fd, "set splitbelow splitright") == FAIL)
10118 return FAIL;
10119 if (ses_win_rec(fd, tab_topframe) == FAIL)
10120 return FAIL;
10121 if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
10122 return FAIL;
10123 if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
10124 return FAIL;
10127 * Check if window sizes can be restored (no windows omitted).
10128 * Remember the window number of the current window after restoring.
10130 nr = 0;
10131 for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
10133 if (ses_do_win(wp))
10134 ++nr;
10135 else
10136 restore_size = FALSE;
10137 if (curwin == wp)
10138 cnr = nr;
10141 /* Go to the first window. */
10142 if (put_line(fd, "wincmd t") == FAIL)
10143 return FAIL;
10146 * If more than one window, see if sizes can be restored.
10147 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
10148 * resized when moving between windows.
10149 * Do this before restoring the view, so that the topline and the
10150 * cursor can be set. This is done again below.
10152 if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
10153 return FAIL;
10154 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10155 return FAIL;
10158 * Restore the view of the window (options, file, cursor, etc.).
10160 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10162 if (!ses_do_win(wp))
10163 continue;
10164 if (put_view(fd, wp, wp != edited_win, &ssop_flags,
10165 cur_arg_idx) == FAIL)
10166 return FAIL;
10167 if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
10168 return FAIL;
10169 next_arg_idx = wp->w_arg_idx;
10172 /* The argument index in the first tab page is zero, need to set it in
10173 * each window. For further tab pages it's the window where we do
10174 * "tabedit". */
10175 cur_arg_idx = next_arg_idx;
10178 * Restore cursor to the current window if it's not the first one.
10180 if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
10181 || put_eol(fd) == FAIL))
10182 return FAIL;
10185 * Restore window sizes again after jumping around in windows, because
10186 * the current window has a minimum size while others may not.
10188 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10189 return FAIL;
10191 /* Don't continue in another tab page when doing only the current one
10192 * or when at the last tab page. */
10193 if (!(ssop_flags & SSOP_TABPAGES))
10194 break;
10197 if (ssop_flags & SSOP_TABPAGES)
10199 if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
10200 || put_eol(fd) == FAIL)
10201 return FAIL;
10205 * Wipe out an empty unnamed buffer we started in.
10207 if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
10208 return FAIL;
10209 if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL)
10210 return FAIL;
10211 if (put_line(fd, "endif") == FAIL)
10212 return FAIL;
10213 if (put_line(fd, "unlet! s:wipebuf") == FAIL)
10214 return FAIL;
10216 /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
10217 if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
10218 p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
10219 return FAIL;
10222 * Lastly, execute the x.vim file if it exists.
10224 if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
10225 || put_line(fd, "if file_readable(s:sx)") == FAIL
10226 || put_line(fd, " exe \"source \" . fnameescape(s:sx)") == FAIL
10227 || put_line(fd, "endif") == FAIL)
10228 return FAIL;
10230 return OK;
10233 static int
10234 ses_winsizes(fd, restore_size, tab_firstwin)
10235 FILE *fd;
10236 int restore_size;
10237 win_T *tab_firstwin;
10239 int n = 0;
10240 win_T *wp;
10242 if (restore_size && (ssop_flags & SSOP_WINSIZE))
10244 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10246 if (!ses_do_win(wp))
10247 continue;
10248 ++n;
10250 /* restore height when not full height */
10251 if (wp->w_height + wp->w_status_height < topframe->fr_height
10252 && (fprintf(fd,
10253 "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
10254 n, (long)wp->w_height, Rows / 2, Rows) < 0
10255 || put_eol(fd) == FAIL))
10256 return FAIL;
10258 /* restore width when not full width */
10259 if (wp->w_width < Columns && (fprintf(fd,
10260 "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
10261 n, (long)wp->w_width, Columns / 2, Columns) < 0
10262 || put_eol(fd) == FAIL))
10263 return FAIL;
10266 else
10268 /* Just equalise window sizes */
10269 if (put_line(fd, "wincmd =") == FAIL)
10270 return FAIL;
10272 return OK;
10276 * Write commands to "fd" to recursively create windows for frame "fr",
10277 * horizontally and vertically split.
10278 * After the commands the last window in the frame is the current window.
10279 * Returns FAIL when writing the commands to "fd" fails.
10281 static int
10282 ses_win_rec(fd, fr)
10283 FILE *fd;
10284 frame_T *fr;
10286 frame_T *frc;
10287 int count = 0;
10289 if (fr->fr_layout != FR_LEAF)
10291 /* Find first frame that's not skipped and then create a window for
10292 * each following one (first frame is already there). */
10293 frc = ses_skipframe(fr->fr_child);
10294 if (frc != NULL)
10295 while ((frc = ses_skipframe(frc->fr_next)) != NULL)
10297 /* Make window as big as possible so that we have lots of room
10298 * to split. */
10299 if (put_line(fd, "wincmd _ | wincmd |") == FAIL
10300 || put_line(fd, fr->fr_layout == FR_COL
10301 ? "split" : "vsplit") == FAIL)
10302 return FAIL;
10303 ++count;
10306 /* Go back to the first window. */
10307 if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
10308 ? "%dwincmd k" : "%dwincmd h", count) < 0
10309 || put_eol(fd) == FAIL))
10310 return FAIL;
10312 /* Recursively create frames/windows in each window of this column or
10313 * row. */
10314 frc = ses_skipframe(fr->fr_child);
10315 while (frc != NULL)
10317 ses_win_rec(fd, frc);
10318 frc = ses_skipframe(frc->fr_next);
10319 /* Go to next window. */
10320 if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
10321 return FAIL;
10324 return OK;
10328 * Skip frames that don't contain windows we want to save in the Session.
10329 * Returns NULL when there none.
10331 static frame_T *
10332 ses_skipframe(fr)
10333 frame_T *fr;
10335 frame_T *frc;
10337 for (frc = fr; frc != NULL; frc = frc->fr_next)
10338 if (ses_do_frame(frc))
10339 break;
10340 return frc;
10344 * Return TRUE if frame "fr" has a window somewhere that we want to save in
10345 * the Session.
10347 static int
10348 ses_do_frame(fr)
10349 frame_T *fr;
10351 frame_T *frc;
10353 if (fr->fr_layout == FR_LEAF)
10354 return ses_do_win(fr->fr_win);
10355 for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
10356 if (ses_do_frame(frc))
10357 return TRUE;
10358 return FALSE;
10362 * Return non-zero if window "wp" is to be stored in the Session.
10364 static int
10365 ses_do_win(wp)
10366 win_T *wp;
10368 if (wp->w_buffer->b_fname == NULL
10369 #ifdef FEAT_QUICKFIX
10370 /* When 'buftype' is "nofile" can't restore the window contents. */
10371 || bt_nofile(wp->w_buffer)
10372 #endif
10374 return (ssop_flags & SSOP_BLANK);
10375 if (wp->w_buffer->b_help)
10376 return (ssop_flags & SSOP_HELP);
10377 return TRUE;
10381 * Write commands to "fd" to restore the view of a window.
10382 * Caller must make sure 'scrolloff' is zero.
10384 static int
10385 put_view(fd, wp, add_edit, flagp, current_arg_idx)
10386 FILE *fd;
10387 win_T *wp;
10388 int add_edit; /* add ":edit" command to view */
10389 unsigned *flagp; /* vop_flags or ssop_flags */
10390 int current_arg_idx; /* current argument index of the window, use
10391 * -1 if unknown */
10393 win_T *save_curwin;
10394 int f;
10395 int do_cursor;
10396 int did_next = FALSE;
10398 /* Always restore cursor position for ":mksession". For ":mkview" only
10399 * when 'viewoptions' contains "cursor". */
10400 do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
10403 * Local argument list.
10405 if (wp->w_alist == &global_alist)
10407 if (put_line(fd, "argglobal") == FAIL)
10408 return FAIL;
10410 else
10412 if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
10413 flagp == &vop_flags
10414 || !(*flagp & SSOP_CURDIR)
10415 || wp->w_localdir != NULL, flagp) == FAIL)
10416 return FAIL;
10419 /* Only when part of a session: restore the argument index. Some
10420 * arguments may have been deleted, check if the index is valid. */
10421 if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx <= WARGCOUNT(wp)
10422 && flagp == &ssop_flags)
10424 if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
10425 || put_eol(fd) == FAIL)
10426 return FAIL;
10427 did_next = TRUE;
10430 /* Edit the file. Skip this when ":next" already did it. */
10431 if (add_edit && (!did_next || wp->w_arg_idx_invalid))
10434 * Load the file.
10436 if (wp->w_buffer->b_ffname != NULL
10437 #ifdef FEAT_QUICKFIX
10438 && !bt_nofile(wp->w_buffer)
10439 #endif
10443 * Editing a file in this buffer: use ":edit file".
10444 * This may have side effects! (e.g., compressed or network file).
10446 if (fputs("edit ", fd) < 0
10447 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10448 return FAIL;
10450 else
10452 /* No file in this buffer, just make it empty. */
10453 if (put_line(fd, "enew") == FAIL)
10454 return FAIL;
10455 #ifdef FEAT_QUICKFIX
10456 if (wp->w_buffer->b_ffname != NULL)
10458 /* The buffer does have a name, but it's not a file name. */
10459 if (fputs("file ", fd) < 0
10460 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10461 return FAIL;
10463 #endif
10464 do_cursor = FALSE;
10469 * Local mappings and abbreviations.
10471 if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10472 && makemap(fd, wp->w_buffer) == FAIL)
10473 return FAIL;
10476 * Local options. Need to go to the window temporarily.
10477 * Store only local values when using ":mkview" and when ":mksession" is
10478 * used and 'sessionoptions' doesn't include "options".
10479 * Some folding options are always stored when "folds" is included,
10480 * otherwise the folds would not be restored correctly.
10482 save_curwin = curwin;
10483 curwin = wp;
10484 curbuf = curwin->w_buffer;
10485 if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10486 f = makeset(fd, OPT_LOCAL,
10487 flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
10488 #ifdef FEAT_FOLDING
10489 else if (*flagp & SSOP_FOLDS)
10490 f = makefoldset(fd);
10491 #endif
10492 else
10493 f = OK;
10494 curwin = save_curwin;
10495 curbuf = curwin->w_buffer;
10496 if (f == FAIL)
10497 return FAIL;
10499 #ifdef FEAT_FOLDING
10501 * Save Folds when 'buftype' is empty and for help files.
10503 if ((*flagp & SSOP_FOLDS)
10504 && wp->w_buffer->b_ffname != NULL
10505 # ifdef FEAT_QUICKFIX
10506 && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help)
10507 # endif
10510 if (put_folds(fd, wp) == FAIL)
10511 return FAIL;
10513 #endif
10516 * Set the cursor after creating folds, since that moves the cursor.
10518 if (do_cursor)
10521 /* Restore the cursor line in the file and relatively in the
10522 * window. Don't use "G", it changes the jumplist. */
10523 if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
10524 (long)wp->w_cursor.lnum,
10525 (long)(wp->w_cursor.lnum - wp->w_topline),
10526 (long)wp->w_height / 2, (long)wp->w_height) < 0
10527 || put_eol(fd) == FAIL
10528 || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
10529 || put_line(fd, "exe s:l") == FAIL
10530 || put_line(fd, "normal! zt") == FAIL
10531 || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
10532 || put_eol(fd) == FAIL)
10533 return FAIL;
10534 /* Restore the cursor column and left offset when not wrapping. */
10535 if (wp->w_cursor.col == 0)
10537 if (put_line(fd, "normal! 0") == FAIL)
10538 return FAIL;
10540 else
10542 if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
10544 if (fprintf(fd,
10545 "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
10546 (long)wp->w_cursor.col,
10547 (long)(wp->w_cursor.col - wp->w_leftcol),
10548 (long)wp->w_width / 2, (long)wp->w_width) < 0
10549 || put_eol(fd) == FAIL
10550 || put_line(fd, "if s:c > 0") == FAIL
10551 || fprintf(fd,
10552 " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
10553 (long)wp->w_cursor.col) < 0
10554 || put_eol(fd) == FAIL
10555 || put_line(fd, "else") == FAIL
10556 || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0
10557 || put_eol(fd) == FAIL
10558 || put_line(fd, "endif") == FAIL)
10559 return FAIL;
10561 else
10563 if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
10564 || put_eol(fd) == FAIL)
10565 return FAIL;
10571 * Local directory.
10573 if (wp->w_localdir != NULL)
10575 if (fputs("lcd ", fd) < 0
10576 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
10577 || put_eol(fd) == FAIL)
10578 return FAIL;
10579 did_lcd = TRUE;
10582 return OK;
10586 * Write an argument list to the session file.
10587 * Returns FAIL if writing fails.
10589 static int
10590 ses_arglist(fd, cmd, gap, fullname, flagp)
10591 FILE *fd;
10592 char *cmd;
10593 garray_T *gap;
10594 int fullname; /* TRUE: use full path name */
10595 unsigned *flagp;
10597 int i;
10598 char_u buf[MAXPATHL];
10599 char_u *s;
10601 if (gap->ga_len == 0)
10602 return put_line(fd, "silent! argdel *");
10603 if (fputs(cmd, fd) < 0)
10604 return FAIL;
10605 for (i = 0; i < gap->ga_len; ++i)
10607 /* NULL file names are skipped (only happens when out of memory). */
10608 s = alist_name(&((aentry_T *)gap->ga_data)[i]);
10609 if (s != NULL)
10611 if (fullname)
10613 (void)vim_FullName(s, buf, MAXPATHL, FALSE);
10614 s = buf;
10616 if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
10617 return FAIL;
10620 return put_eol(fd);
10624 * Write a buffer name to the session file.
10625 * Also ends the line.
10626 * Returns FAIL if writing fails.
10628 static int
10629 ses_fname(fd, buf, flagp)
10630 FILE *fd;
10631 buf_T *buf;
10632 unsigned *flagp;
10634 char_u *name;
10636 /* Use the short file name if the current directory is known at the time
10637 * the session file will be sourced.
10638 * Don't do this for ":mkview", we don't know the current directory.
10639 * Don't do this after ":lcd", we don't keep track of what the current
10640 * directory is. */
10641 if (buf->b_sfname != NULL
10642 && flagp == &ssop_flags
10643 && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
10644 #ifdef FEAT_AUTOCHDIR
10645 && !p_acd
10646 #endif
10647 && !did_lcd)
10648 name = buf->b_sfname;
10649 else
10650 name = buf->b_ffname;
10651 if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
10652 return FAIL;
10653 return OK;
10657 * Write a file name to the session file.
10658 * Takes care of the "slash" option in 'sessionoptions' and escapes special
10659 * characters.
10660 * Returns FAIL if writing fails.
10662 static int
10663 ses_put_fname(fd, name, flagp)
10664 FILE *fd;
10665 char_u *name;
10666 unsigned *flagp;
10668 char_u *sname;
10669 int retval = OK;
10670 int c;
10672 sname = home_replace_save(NULL, name);
10673 if (sname != NULL)
10674 name = sname;
10675 while (*name != NUL)
10677 #ifdef FEAT_MBYTE
10679 int l;
10681 if (has_mbyte && (l = (*mb_ptr2len)(name)) > 1)
10683 /* copy a multibyte char */
10684 while (--l >= 0)
10686 if (putc(*name, fd) != *name)
10687 retval = FAIL;
10688 ++name;
10690 continue;
10693 #endif
10694 c = *name++;
10695 if (c == '\\' && (*flagp & SSOP_SLASH))
10696 /* change a backslash to a forward slash */
10697 c = '/';
10698 else if ((vim_strchr(escape_chars, c) != NULL
10699 #ifdef BACKSLASH_IN_FILENAME
10700 && c != '\\'
10701 #endif
10702 ) || c == '#' || c == '%')
10704 /* escape a special character with a backslash */
10705 if (putc('\\', fd) != '\\')
10706 retval = FAIL;
10708 if (putc(c, fd) != c)
10709 retval = FAIL;
10711 vim_free(sname);
10712 return retval;
10716 * ":loadview [nr]"
10718 static void
10719 ex_loadview(eap)
10720 exarg_T *eap;
10722 char_u *fname;
10724 fname = get_view_file(*eap->arg);
10725 if (fname != NULL)
10727 do_source(fname, FALSE, DOSO_NONE);
10728 vim_free(fname);
10733 * Get the name of the view file for the current buffer.
10735 static char_u *
10736 get_view_file(c)
10737 int c;
10739 int len = 0;
10740 char_u *p, *s;
10741 char_u *retval;
10742 char_u *sname;
10744 if (curbuf->b_ffname == NULL)
10746 EMSG(_(e_noname));
10747 return NULL;
10749 sname = home_replace_save(NULL, curbuf->b_ffname);
10750 if (sname == NULL)
10751 return NULL;
10754 * We want a file name without separators, because we're not going to make
10755 * a directory.
10756 * "normal" path separator -> "=+"
10757 * "=" -> "=="
10758 * ":" path separator -> "=-"
10760 for (p = sname; *p; ++p)
10761 if (*p == '=' || vim_ispathsep(*p))
10762 ++len;
10763 retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
10764 if (retval != NULL)
10766 STRCPY(retval, p_vdir);
10767 add_pathsep(retval);
10768 s = retval + STRLEN(retval);
10769 for (p = sname; *p; ++p)
10771 if (*p == '=')
10773 *s++ = '=';
10774 *s++ = '=';
10776 else if (vim_ispathsep(*p))
10778 *s++ = '=';
10779 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
10780 || defined(VMS)
10781 if (*p == ':')
10782 *s++ = '-';
10783 else
10784 #endif
10785 *s++ = '+';
10787 else
10788 *s++ = *p;
10790 *s++ = '=';
10791 *s++ = c;
10792 STRCPY(s, ".vim");
10795 vim_free(sname);
10796 return retval;
10799 #endif /* FEAT_SESSION */
10802 * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
10803 * Return FAIL for a write error.
10806 put_eol(fd)
10807 FILE *fd;
10809 if (
10810 #ifdef USE_CRNL
10812 # ifdef MKSESSION_NL
10813 !mksession_nl &&
10814 # endif
10815 (putc('\r', fd) < 0)) ||
10816 #endif
10817 (putc('\n', fd) < 0))
10818 return FAIL;
10819 return OK;
10823 * Write a line to "fd".
10824 * Return FAIL for a write error.
10827 put_line(fd, s)
10828 FILE *fd;
10829 char *s;
10831 if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
10832 return FAIL;
10833 return OK;
10836 #ifdef FEAT_VIMINFO
10838 * ":rviminfo" and ":wviminfo".
10840 static void
10841 ex_viminfo(eap)
10842 exarg_T *eap;
10844 char_u *save_viminfo;
10846 save_viminfo = p_viminfo;
10847 if (*p_viminfo == NUL)
10848 p_viminfo = (char_u *)"'100";
10849 if (eap->cmdidx == CMD_rviminfo)
10851 if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
10852 | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
10853 EMSG(_("E195: Cannot open viminfo file for reading"));
10855 else
10856 write_viminfo(eap->arg, eap->forceit);
10857 p_viminfo = save_viminfo;
10859 #endif
10861 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
10863 * Make a dialog message in "buff[IOSIZE]".
10864 * "format" must contain "%s".
10866 void
10867 dialog_msg(buff, format, fname)
10868 char_u *buff;
10869 char *format;
10870 char_u *fname;
10872 if (fname == NULL)
10873 fname = (char_u *)_("Untitled");
10874 vim_snprintf((char *)buff, IOSIZE, format, fname);
10876 #endif
10879 * ":behave {mswin,xterm}"
10881 static void
10882 ex_behave(eap)
10883 exarg_T *eap;
10885 if (STRCMP(eap->arg, "mswin") == 0)
10887 set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
10888 set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
10889 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
10890 set_option_value((char_u *)"keymodel", 0L,
10891 (char_u *)"startsel,stopsel", 0);
10893 else if (STRCMP(eap->arg, "xterm") == 0)
10895 set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
10896 set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
10897 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
10898 set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
10900 else
10901 EMSG2(_(e_invarg2), eap->arg);
10904 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10906 * Function given to ExpandGeneric() to obtain the possible arguments of the
10907 * ":behave {mswin,xterm}" command.
10909 char_u *
10910 get_behave_arg(xp, idx)
10911 expand_T *xp UNUSED;
10912 int idx;
10914 if (idx == 0)
10915 return (char_u *)"mswin";
10916 if (idx == 1)
10917 return (char_u *)"xterm";
10918 return NULL;
10920 #endif
10922 #ifdef FEAT_AUTOCMD
10923 static int filetype_detect = FALSE;
10924 static int filetype_plugin = FALSE;
10925 static int filetype_indent = FALSE;
10928 * ":filetype [plugin] [indent] {on,off,detect}"
10929 * on: Load the filetype.vim file to install autocommands for file types.
10930 * off: Load the ftoff.vim file to remove all autocommands for file types.
10931 * plugin on: load filetype.vim and ftplugin.vim
10932 * plugin off: load ftplugof.vim
10933 * indent on: load filetype.vim and indent.vim
10934 * indent off: load indoff.vim
10936 static void
10937 ex_filetype(eap)
10938 exarg_T *eap;
10940 char_u *arg = eap->arg;
10941 int plugin = FALSE;
10942 int indent = FALSE;
10944 if (*eap->arg == NUL)
10946 /* Print current status. */
10947 smsg((char_u *)"filetype detection:%s plugin:%s indent:%s",
10948 filetype_detect ? "ON" : "OFF",
10949 filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
10950 filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
10951 return;
10954 /* Accept "plugin" and "indent" in any order. */
10955 for (;;)
10957 if (STRNCMP(arg, "plugin", 6) == 0)
10959 plugin = TRUE;
10960 arg = skipwhite(arg + 6);
10961 continue;
10963 if (STRNCMP(arg, "indent", 6) == 0)
10965 indent = TRUE;
10966 arg = skipwhite(arg + 6);
10967 continue;
10969 break;
10971 if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
10973 if (*arg == 'o' || !filetype_detect)
10975 source_runtime((char_u *)FILETYPE_FILE, TRUE);
10976 filetype_detect = TRUE;
10977 if (plugin)
10979 source_runtime((char_u *)FTPLUGIN_FILE, TRUE);
10980 filetype_plugin = TRUE;
10982 if (indent)
10984 source_runtime((char_u *)INDENT_FILE, TRUE);
10985 filetype_indent = TRUE;
10988 if (*arg == 'd')
10990 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
10991 do_modelines(0);
10994 else if (STRCMP(arg, "off") == 0)
10996 if (plugin || indent)
10998 if (plugin)
11000 source_runtime((char_u *)FTPLUGOF_FILE, TRUE);
11001 filetype_plugin = FALSE;
11003 if (indent)
11005 source_runtime((char_u *)INDOFF_FILE, TRUE);
11006 filetype_indent = FALSE;
11009 else
11011 source_runtime((char_u *)FTOFF_FILE, TRUE);
11012 filetype_detect = FALSE;
11015 else
11016 EMSG2(_(e_invarg2), arg);
11020 * ":setfiletype {name}"
11022 static void
11023 ex_setfiletype(eap)
11024 exarg_T *eap;
11026 if (!did_filetype)
11027 set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
11029 #endif
11031 static void
11032 ex_digraphs(eap)
11033 exarg_T *eap UNUSED;
11035 #ifdef FEAT_DIGRAPHS
11036 if (*eap->arg != NUL)
11037 putdigraph(eap->arg);
11038 else
11039 listdigraphs();
11040 #else
11041 EMSG(_("E196: No digraphs in this version"));
11042 #endif
11045 static void
11046 ex_set(eap)
11047 exarg_T *eap;
11049 int flags = 0;
11051 if (eap->cmdidx == CMD_setlocal)
11052 flags = OPT_LOCAL;
11053 else if (eap->cmdidx == CMD_setglobal)
11054 flags = OPT_GLOBAL;
11055 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
11056 if (cmdmod.browse && flags == 0)
11057 ex_options(eap);
11058 else
11059 #endif
11060 (void)do_set(eap->arg, flags);
11063 #ifdef FEAT_SEARCH_EXTRA
11065 * ":nohlsearch"
11067 static void
11068 ex_nohlsearch(eap)
11069 exarg_T *eap UNUSED;
11071 no_hlsearch = TRUE;
11072 redraw_all_later(SOME_VALID);
11076 * ":[N]match {group} {pattern}"
11077 * Sets nextcmd to the start of the next command, if any. Also called when
11078 * skipping commands to find the next command.
11080 static void
11081 ex_match(eap)
11082 exarg_T *eap;
11084 char_u *p;
11085 char_u *g = NULL;
11086 char_u *end;
11087 int c;
11088 int id;
11090 if (eap->line2 <= 3)
11091 id = eap->line2;
11092 else
11094 EMSG(e_invcmd);
11095 return;
11098 /* First clear any old pattern. */
11099 if (!eap->skip)
11100 match_delete(curwin, id, FALSE);
11102 if (ends_excmd(*eap->arg))
11103 end = eap->arg;
11104 else if ((STRNICMP(eap->arg, "none", 4) == 0
11105 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
11106 end = eap->arg + 4;
11107 else
11109 p = skiptowhite(eap->arg);
11110 if (!eap->skip)
11111 g = vim_strnsave(eap->arg, (int)(p - eap->arg));
11112 p = skipwhite(p);
11113 if (*p == NUL)
11115 /* There must be two arguments. */
11116 EMSG2(_(e_invarg2), eap->arg);
11117 return;
11119 end = skip_regexp(p + 1, *p, TRUE, NULL);
11120 if (!eap->skip)
11122 if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
11124 eap->errmsg = e_trailing;
11125 return;
11127 if (*end != *p)
11129 EMSG2(_(e_invarg2), p);
11130 return;
11133 c = *end;
11134 *end = NUL;
11135 match_add(curwin, g, p + 1, 10, id);
11136 vim_free(g);
11137 *end = c;
11140 eap->nextcmd = find_nextcmd(end);
11142 #endif
11144 #ifdef FEAT_CRYPT
11146 * ":X": Get crypt key
11148 static void
11149 ex_X(eap)
11150 exarg_T *eap UNUSED;
11152 (void)get_crypt_key(TRUE, TRUE);
11154 #endif
11156 #ifdef FEAT_FOLDING
11157 static void
11158 ex_fold(eap)
11159 exarg_T *eap;
11161 if (foldManualAllowed(TRUE))
11162 foldCreate(eap->line1, eap->line2);
11165 static void
11166 ex_foldopen(eap)
11167 exarg_T *eap;
11169 opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
11170 eap->forceit, FALSE);
11173 static void
11174 ex_folddo(eap)
11175 exarg_T *eap;
11177 linenr_T lnum;
11179 /* First set the marks for all lines closed/open. */
11180 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
11181 if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
11182 ml_setmarked(lnum);
11184 /* Execute the command on the marked lines. */
11185 global_exe(eap->arg);
11186 ml_clearmarked(); /* clear rest of the marks */
11188 #endif