Merge branch 'vim-with-runtime'
[vim_extended.git] / src / ex_docmd.c
blobeb15b2aeae544419f33b1bdd28587ea043871b5b
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 # define ex_csettitle ex_ni
125 #endif
126 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL)
127 # define ex_cexpr ex_ni
128 #endif
130 static int check_more __ARGS((int, int));
131 static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file));
132 static void get_flags __ARGS((exarg_T *eap));
133 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
134 || !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME) || !defined(FEAT_ECL)
135 # define HAVE_EX_SCRIPT_NI
136 static void ex_script_ni __ARGS((exarg_T *eap));
137 #endif
138 static char_u *invalid_range __ARGS((exarg_T *eap));
139 static void correct_range __ARGS((exarg_T *eap));
140 #ifdef FEAT_QUICKFIX
141 static char_u *replace_makeprg __ARGS((exarg_T *eap, char_u *p, char_u **cmdlinep));
142 #endif
143 static char_u *repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep));
144 static void ex_highlight __ARGS((exarg_T *eap));
145 static void ex_colorscheme __ARGS((exarg_T *eap));
146 static void ex_quit __ARGS((exarg_T *eap));
147 static void ex_cquit __ARGS((exarg_T *eap));
148 static void ex_quit_all __ARGS((exarg_T *eap));
149 #ifdef FEAT_WINDOWS
150 static void ex_close __ARGS((exarg_T *eap));
151 static void ex_win_close __ARGS((int forceit, win_T *win, tabpage_T *tp));
152 static void ex_only __ARGS((exarg_T *eap));
153 static void ex_resize __ARGS((exarg_T *eap));
154 static void ex_stag __ARGS((exarg_T *eap));
155 static void ex_tabclose __ARGS((exarg_T *eap));
156 static void ex_tabonly __ARGS((exarg_T *eap));
157 static void ex_tabnext __ARGS((exarg_T *eap));
158 static void ex_tabmove __ARGS((exarg_T *eap));
159 static void ex_tabs __ARGS((exarg_T *eap));
160 #else
161 # define ex_close ex_ni
162 # define ex_only ex_ni
163 # define ex_all ex_ni
164 # define ex_resize ex_ni
165 # define ex_splitview ex_ni
166 # define ex_stag ex_ni
167 # define ex_tabnext ex_ni
168 # define ex_tabmove ex_ni
169 # define ex_tabs ex_ni
170 # define ex_tabclose ex_ni
171 # define ex_tabonly ex_ni
172 #endif
173 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
174 static void ex_pclose __ARGS((exarg_T *eap));
175 static void ex_ptag __ARGS((exarg_T *eap));
176 static void ex_pedit __ARGS((exarg_T *eap));
177 #else
178 # define ex_pclose ex_ni
179 # define ex_ptag ex_ni
180 # define ex_pedit ex_ni
181 #endif
182 static void ex_hide __ARGS((exarg_T *eap));
183 static void ex_stop __ARGS((exarg_T *eap));
184 static void ex_exit __ARGS((exarg_T *eap));
185 static void ex_print __ARGS((exarg_T *eap));
186 #ifdef FEAT_BYTEOFF
187 static void ex_goto __ARGS((exarg_T *eap));
188 #else
189 # define ex_goto ex_ni
190 #endif
191 static void ex_shell __ARGS((exarg_T *eap));
192 static void ex_preserve __ARGS((exarg_T *eap));
193 static void ex_recover __ARGS((exarg_T *eap));
194 #ifndef FEAT_LISTCMDS
195 # define ex_argedit ex_ni
196 # define ex_argadd ex_ni
197 # define ex_argdelete ex_ni
198 # define ex_listdo ex_ni
199 #endif
200 static void ex_mode __ARGS((exarg_T *eap));
201 static void ex_wrongmodifier __ARGS((exarg_T *eap));
202 static void ex_find __ARGS((exarg_T *eap));
203 static void ex_open __ARGS((exarg_T *eap));
204 static void ex_edit __ARGS((exarg_T *eap));
205 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
206 # define ex_drop ex_ni
207 #endif
208 #ifndef FEAT_GUI
209 # define ex_gui ex_nogui
210 static void ex_nogui __ARGS((exarg_T *eap));
211 #endif
212 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
213 static void ex_tearoff __ARGS((exarg_T *eap));
214 #else
215 # define ex_tearoff ex_ni
216 #endif
217 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
218 static void ex_popup __ARGS((exarg_T *eap));
219 #else
220 # define ex_popup ex_ni
221 #endif
222 #ifndef FEAT_GUI_MSWIN
223 # define ex_simalt ex_ni
224 #endif
225 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
226 # define gui_mch_find_dialog ex_ni
227 # define gui_mch_replace_dialog ex_ni
228 #endif
229 #if !defined(FEAT_GUI_GTK)
230 # define ex_helpfind ex_ni
231 #endif
232 #ifndef FEAT_CSCOPE
233 # define do_cscope ex_ni
234 # define do_scscope ex_ni
235 # define do_cstag ex_ni
236 #endif
237 #ifndef FEAT_SYN_HL
238 # define ex_syntax ex_ni
239 #endif
240 #ifndef FEAT_SPELL
241 # define ex_spell ex_ni
242 # define ex_mkspell ex_ni
243 # define ex_spelldump ex_ni
244 # define ex_spellinfo ex_ni
245 # define ex_spellrepall ex_ni
246 #endif
247 #ifndef FEAT_PERSISTENT_UNDO
248 # define ex_rundo ex_ni
249 # define ex_wundo ex_ni
250 #endif
251 #ifndef FEAT_LUA
252 # define ex_lua ex_script_ni
253 # define ex_luado ex_ni
254 # define ex_luafile ex_ni
255 #endif
256 #ifndef FEAT_MZSCHEME
257 # define ex_mzscheme ex_script_ni
258 # define ex_mzfile ex_ni
259 #endif
260 #ifndef FEAT_PERL
261 # define ex_perl ex_script_ni
262 # define ex_perldo ex_ni
263 #endif
264 #ifndef FEAT_PYTHON
265 # define ex_python ex_script_ni
266 # define ex_pyfile ex_ni
267 #endif
268 #ifndef FEAT_TCL
269 # define ex_tcl ex_script_ni
270 # define ex_tcldo ex_ni
271 # define ex_tclfile ex_ni
272 #endif
273 #ifndef FEAT_RUBY
274 # define ex_ruby ex_script_ni
275 # define ex_rubydo ex_ni
276 # define ex_rubyfile ex_ni
277 #endif
278 #ifndef FEAT_ECL
279 # define ex_ecl ex_script_ni
280 #endif
281 #ifndef FEAT_SNIFF
282 # define ex_sniff ex_ni
283 #endif
284 #ifndef FEAT_KEYMAP
285 # define ex_loadkeymap ex_ni
286 #endif
287 static void ex_swapname __ARGS((exarg_T *eap));
288 static void ex_syncbind __ARGS((exarg_T *eap));
289 static void ex_read __ARGS((exarg_T *eap));
290 static void ex_pwd __ARGS((exarg_T *eap));
291 static void ex_equal __ARGS((exarg_T *eap));
292 static void ex_sleep __ARGS((exarg_T *eap));
293 static void do_exmap __ARGS((exarg_T *eap, int isabbrev));
294 static void ex_winsize __ARGS((exarg_T *eap));
295 #ifdef FEAT_WINDOWS
296 static void ex_wincmd __ARGS((exarg_T *eap));
297 #else
298 # define ex_wincmd ex_ni
299 #endif
300 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
301 static void ex_winpos __ARGS((exarg_T *eap));
302 #else
303 # define ex_winpos ex_ni
304 #endif
305 static void ex_operators __ARGS((exarg_T *eap));
306 static void ex_put __ARGS((exarg_T *eap));
307 static void ex_copymove __ARGS((exarg_T *eap));
308 static void ex_may_print __ARGS((exarg_T *eap));
309 static void ex_submagic __ARGS((exarg_T *eap));
310 static void ex_join __ARGS((exarg_T *eap));
311 static void ex_at __ARGS((exarg_T *eap));
312 static void ex_bang __ARGS((exarg_T *eap));
313 static void ex_undo __ARGS((exarg_T *eap));
314 #ifdef FEAT_PERSISTENT_UNDO
315 static void ex_wundo __ARGS((exarg_T *eap));
316 static void ex_rundo __ARGS((exarg_T *eap));
317 #endif
318 static void ex_redo __ARGS((exarg_T *eap));
319 static void ex_later __ARGS((exarg_T *eap));
320 static void ex_redir __ARGS((exarg_T *eap));
321 static void ex_redraw __ARGS((exarg_T *eap));
322 static void ex_redrawstatus __ARGS((exarg_T *eap));
323 static void close_redir __ARGS((void));
324 static void ex_mkrc __ARGS((exarg_T *eap));
325 static void ex_mark __ARGS((exarg_T *eap));
326 #ifdef FEAT_USR_CMDS
327 static char_u *uc_fun_cmd __ARGS((void));
328 static char_u *find_ucmd __ARGS((exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl));
329 #endif
330 #ifdef FEAT_EX_EXTRA
331 static void ex_normal __ARGS((exarg_T *eap));
332 static void ex_startinsert __ARGS((exarg_T *eap));
333 static void ex_stopinsert __ARGS((exarg_T *eap));
334 #else
335 # define ex_normal ex_ni
336 # define ex_align ex_ni
337 # define ex_retab ex_ni
338 # define ex_startinsert ex_ni
339 # define ex_stopinsert ex_ni
340 # define ex_helptags ex_ni
341 # define ex_sort ex_ni
342 #endif
343 #ifdef FEAT_FIND_ID
344 static void ex_checkpath __ARGS((exarg_T *eap));
345 static void ex_findpat __ARGS((exarg_T *eap));
346 #else
347 # define ex_findpat ex_ni
348 # define ex_checkpath ex_ni
349 #endif
350 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
351 static void ex_psearch __ARGS((exarg_T *eap));
352 #else
353 # define ex_psearch ex_ni
354 #endif
355 static void ex_tag __ARGS((exarg_T *eap));
356 static void ex_tag_cmd __ARGS((exarg_T *eap, char_u *name));
357 #ifndef FEAT_EVAL
358 # define ex_scriptnames ex_ni
359 # define ex_finish ex_ni
360 # define ex_echo ex_ni
361 # define ex_echohl ex_ni
362 # define ex_execute ex_ni
363 # define ex_call ex_ni
364 # define ex_if ex_ni
365 # define ex_endif ex_ni
366 # define ex_else ex_ni
367 # define ex_while ex_ni
368 # define ex_for ex_ni
369 # define ex_continue ex_ni
370 # define ex_break ex_ni
371 # define ex_endwhile ex_ni
372 # define ex_endfor ex_ni
373 # define ex_throw ex_ni
374 # define ex_try ex_ni
375 # define ex_catch ex_ni
376 # define ex_finally ex_ni
377 # define ex_endtry ex_ni
378 # define ex_endfunction ex_ni
379 # define ex_let ex_ni
380 # define ex_unlet ex_ni
381 # define ex_lockvar ex_ni
382 # define ex_unlockvar ex_ni
383 # define ex_function ex_ni
384 # define ex_delfunction ex_ni
385 # define ex_return ex_ni
386 # define ex_oldfiles ex_ni
387 #endif
388 static char_u *arg_all __ARGS((void));
389 #ifdef FEAT_SESSION
390 static int makeopens __ARGS((FILE *fd, char_u *dirnow));
391 static int put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx));
392 static void ex_loadview __ARGS((exarg_T *eap));
393 static char_u *get_view_file __ARGS((int c));
394 static int did_lcd; /* whether ":lcd" was produced for a session */
395 #else
396 # define ex_loadview ex_ni
397 #endif
398 #ifndef FEAT_EVAL
399 # define ex_compiler ex_ni
400 #endif
401 #ifdef FEAT_VIMINFO
402 static void ex_viminfo __ARGS((exarg_T *eap));
403 #else
404 # define ex_viminfo ex_ni
405 #endif
406 static void ex_behave __ARGS((exarg_T *eap));
407 #ifdef FEAT_AUTOCMD
408 static void ex_filetype __ARGS((exarg_T *eap));
409 static void ex_setfiletype __ARGS((exarg_T *eap));
410 #else
411 # define ex_filetype ex_ni
412 # define ex_setfiletype ex_ni
413 #endif
414 #ifndef FEAT_DIFF
415 # define ex_diffoff ex_ni
416 # define ex_diffpatch ex_ni
417 # define ex_diffgetput ex_ni
418 # define ex_diffsplit ex_ni
419 # define ex_diffthis ex_ni
420 # define ex_diffupdate ex_ni
421 #endif
422 static void ex_digraphs __ARGS((exarg_T *eap));
423 static void ex_set __ARGS((exarg_T *eap));
424 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
425 # define ex_options ex_ni
426 #endif
427 #ifdef FEAT_SEARCH_EXTRA
428 static void ex_nohlsearch __ARGS((exarg_T *eap));
429 static void ex_match __ARGS((exarg_T *eap));
430 #else
431 # define ex_nohlsearch ex_ni
432 # define ex_match ex_ni
433 #endif
434 #ifdef FEAT_CRYPT
435 static void ex_X __ARGS((exarg_T *eap));
436 #else
437 # define ex_X ex_ni
438 #endif
439 #ifdef FEAT_FOLDING
440 static void ex_fold __ARGS((exarg_T *eap));
441 static void ex_foldopen __ARGS((exarg_T *eap));
442 static void ex_folddo __ARGS((exarg_T *eap));
443 #else
444 # define ex_fold ex_ni
445 # define ex_foldopen ex_ni
446 # define ex_folddo ex_ni
447 #endif
448 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
449 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
450 # define ex_language ex_ni
451 #endif
452 #ifndef FEAT_SIGNS
453 # define ex_sign ex_ni
454 #endif
455 #ifndef FEAT_SUN_WORKSHOP
456 # define ex_wsverb ex_ni
457 #endif
458 #ifndef FEAT_NETBEANS_INTG
459 # define ex_nbkey ex_ni
460 #endif
462 #ifndef FEAT_EVAL
463 # define ex_debug ex_ni
464 # define ex_breakadd ex_ni
465 # define ex_debuggreedy ex_ni
466 # define ex_breakdel ex_ni
467 # define ex_breaklist ex_ni
468 #endif
470 #ifndef FEAT_CMDHIST
471 # define ex_history ex_ni
472 #endif
473 #ifndef FEAT_JUMPLIST
474 # define ex_jumps ex_ni
475 # define ex_changes ex_ni
476 #endif
478 #ifndef FEAT_PROFILE
479 # define ex_profile ex_ni
480 #endif
483 * Declare cmdnames[].
485 #define DO_DECLARE_EXCMD
486 #include "ex_cmds.h"
489 * Table used to quickly search for a command, based on its first character.
491 static cmdidx_T cmdidxs[27] =
493 CMD_append,
494 CMD_buffer,
495 CMD_change,
496 CMD_delete,
497 CMD_edit,
498 CMD_file,
499 CMD_global,
500 CMD_help,
501 CMD_insert,
502 CMD_join,
503 CMD_k,
504 CMD_list,
505 CMD_move,
506 CMD_next,
507 CMD_open,
508 CMD_print,
509 CMD_quit,
510 CMD_read,
511 CMD_substitute,
512 CMD_t,
513 CMD_undo,
514 CMD_vglobal,
515 CMD_write,
516 CMD_xit,
517 CMD_yank,
518 CMD_z,
519 CMD_bang
522 static char_u dollar_command[2] = {'$', 0};
525 #ifdef FEAT_EVAL
526 /* Struct for storing a line inside a while/for loop */
527 typedef struct
529 char_u *line; /* command line */
530 linenr_T lnum; /* sourcing_lnum of the line */
531 } wcmd_T;
534 * Structure used to store info for line position in a while or for loop.
535 * This is required, because do_one_cmd() may invoke ex_function(), which
536 * reads more lines that may come from the while/for loop.
538 struct loop_cookie
540 garray_T *lines_gap; /* growarray with line info */
541 int current_line; /* last read line from growarray */
542 int repeating; /* TRUE when looping a second time */
543 /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
544 char_u *(*getline) __ARGS((int, void *, int));
545 void *cookie;
548 static char_u *get_loop_line __ARGS((int c, void *cookie, int indent));
549 static int store_loop_line __ARGS((garray_T *gap, char_u *line));
550 static void free_cmdlines __ARGS((garray_T *gap));
552 /* Struct to save a few things while debugging. Used in do_cmdline() only. */
553 struct dbg_stuff
555 int trylevel;
556 int force_abort;
557 except_T *caught_stack;
558 char_u *vv_exception;
559 char_u *vv_throwpoint;
560 int did_emsg;
561 int got_int;
562 int did_throw;
563 int need_rethrow;
564 int check_cstack;
565 except_T *current_exception;
568 static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp));
569 static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp));
571 static void
572 save_dbg_stuff(dsp)
573 struct dbg_stuff *dsp;
575 dsp->trylevel = trylevel; trylevel = 0;
576 dsp->force_abort = force_abort; force_abort = FALSE;
577 dsp->caught_stack = caught_stack; caught_stack = NULL;
578 dsp->vv_exception = v_exception(NULL);
579 dsp->vv_throwpoint = v_throwpoint(NULL);
581 /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
582 dsp->did_emsg = did_emsg; did_emsg = FALSE;
583 dsp->got_int = got_int; got_int = FALSE;
584 dsp->did_throw = did_throw; did_throw = FALSE;
585 dsp->need_rethrow = need_rethrow; need_rethrow = FALSE;
586 dsp->check_cstack = check_cstack; check_cstack = FALSE;
587 dsp->current_exception = current_exception; current_exception = NULL;
590 static void
591 restore_dbg_stuff(dsp)
592 struct dbg_stuff *dsp;
594 suppress_errthrow = FALSE;
595 trylevel = dsp->trylevel;
596 force_abort = dsp->force_abort;
597 caught_stack = dsp->caught_stack;
598 (void)v_exception(dsp->vv_exception);
599 (void)v_throwpoint(dsp->vv_throwpoint);
600 did_emsg = dsp->did_emsg;
601 got_int = dsp->got_int;
602 did_throw = dsp->did_throw;
603 need_rethrow = dsp->need_rethrow;
604 check_cstack = dsp->check_cstack;
605 current_exception = dsp->current_exception;
607 #endif
611 * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
612 * command is given.
614 void
615 do_exmode(improved)
616 int improved; /* TRUE for "improved Ex" mode */
618 int save_msg_scroll;
619 int prev_msg_row;
620 linenr_T prev_line;
621 int changedtick;
623 if (improved)
624 exmode_active = EXMODE_VIM;
625 else
626 exmode_active = EXMODE_NORMAL;
627 State = NORMAL;
629 /* When using ":global /pat/ visual" and then "Q" we return to continue
630 * the :global command. */
631 if (global_busy)
632 return;
634 save_msg_scroll = msg_scroll;
635 ++RedrawingDisabled; /* don't redisplay the window */
636 ++no_wait_return; /* don't wait for return */
637 #ifdef FEAT_GUI
638 /* Ignore scrollbar and mouse events in Ex mode */
639 ++hold_gui_events;
640 #endif
641 #ifdef FEAT_SNIFF
642 want_sniff_request = 0; /* No K_SNIFF wanted */
643 #endif
645 MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode."));
646 while (exmode_active)
648 #ifdef FEAT_EX_EXTRA
649 /* Check for a ":normal" command and no more characters left. */
650 if (ex_normal_busy > 0 && typebuf.tb_len == 0)
652 exmode_active = FALSE;
653 break;
655 #endif
656 msg_scroll = TRUE;
657 need_wait_return = FALSE;
658 ex_pressedreturn = FALSE;
659 ex_no_reprint = FALSE;
660 changedtick = curbuf->b_changedtick;
661 prev_msg_row = msg_row;
662 prev_line = curwin->w_cursor.lnum;
663 #ifdef FEAT_SNIFF
664 ProcessSniffRequests();
665 #endif
666 if (improved)
668 cmdline_row = msg_row;
669 do_cmdline(NULL, getexline, NULL, 0);
671 else
672 do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
673 lines_left = Rows - 1;
675 if ((prev_line != curwin->w_cursor.lnum
676 || changedtick != curbuf->b_changedtick) && !ex_no_reprint)
678 if (curbuf->b_ml.ml_flags & ML_EMPTY)
679 EMSG(_(e_emptybuf));
680 else
682 if (ex_pressedreturn)
684 /* go up one line, to overwrite the ":<CR>" line, so the
685 * output doesn't contain empty lines. */
686 msg_row = prev_msg_row;
687 if (prev_msg_row == Rows - 1)
688 msg_row--;
690 msg_col = 0;
691 print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE);
692 msg_clr_eos();
695 else if (ex_pressedreturn && !ex_no_reprint) /* must be at EOF */
697 if (curbuf->b_ml.ml_flags & ML_EMPTY)
698 EMSG(_(e_emptybuf));
699 else
700 EMSG(_("E501: At end-of-file"));
704 #ifdef FEAT_GUI
705 --hold_gui_events;
706 #endif
707 --RedrawingDisabled;
708 --no_wait_return;
709 update_screen(CLEAR);
710 need_wait_return = FALSE;
711 msg_scroll = save_msg_scroll;
715 * Execute a simple command line. Used for translated commands like "*".
718 do_cmdline_cmd(cmd)
719 char_u *cmd;
721 return do_cmdline(cmd, NULL, NULL,
722 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
726 * do_cmdline(): execute one Ex command line
728 * 1. Execute "cmdline" when it is not NULL.
729 * If "cmdline" is NULL, or more lines are needed, getline() is used.
730 * 2. Split up in parts separated with '|'.
732 * This function can be called recursively!
734 * flags:
735 * DOCMD_VERBOSE - The command will be included in the error message.
736 * DOCMD_NOWAIT - Don't call wait_return() and friends.
737 * DOCMD_REPEAT - Repeat execution until getline() returns NULL.
738 * DOCMD_KEYTYPED - Don't reset KeyTyped.
739 * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
740 * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
742 * return FAIL if cmdline could not be executed, OK otherwise
745 do_cmdline(cmdline, getline, cookie, flags)
746 char_u *cmdline;
747 char_u *(*getline) __ARGS((int, void *, int));
748 void *cookie; /* argument for getline() */
749 int flags;
751 char_u *next_cmdline; /* next cmd to execute */
752 char_u *cmdline_copy = NULL; /* copy of cmd line */
753 int used_getline = FALSE; /* used "getline" to obtain command */
754 static int recursive = 0; /* recursive depth */
755 int msg_didout_before_start = 0;
756 int count = 0; /* line number count */
757 int did_inc = FALSE; /* incremented RedrawingDisabled */
758 int retval = OK;
759 #ifdef FEAT_EVAL
760 struct condstack cstack; /* conditional stack */
761 garray_T lines_ga; /* keep lines for ":while"/":for" */
762 int current_line = 0; /* active line in lines_ga */
763 char_u *fname = NULL; /* function or script name */
764 linenr_T *breakpoint = NULL; /* ptr to breakpoint field in cookie */
765 int *dbg_tick = NULL; /* ptr to dbg_tick field in cookie */
766 struct dbg_stuff debug_saved; /* saved things for debug mode */
767 int initial_trylevel;
768 struct msglist **saved_msg_list = NULL;
769 struct msglist *private_msg_list;
771 /* "getline" and "cookie" passed to do_one_cmd() */
772 char_u *(*cmd_getline) __ARGS((int, void *, int));
773 void *cmd_cookie;
774 struct loop_cookie cmd_loop_cookie;
775 void *real_cookie;
776 int getline_is_func;
777 #else
778 # define cmd_getline getline
779 # define cmd_cookie cookie
780 #endif
781 static int call_depth = 0; /* recursiveness */
783 #ifdef FEAT_EVAL
784 /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
785 * location for storing error messages to be converted to an exception.
786 * This ensures that the do_errthrow() call in do_one_cmd() does not
787 * combine the messages stored by an earlier invocation of do_one_cmd()
788 * with the command name of the later one. This would happen when
789 * BufWritePost autocommands are executed after a write error. */
790 saved_msg_list = msg_list;
791 msg_list = &private_msg_list;
792 private_msg_list = NULL;
793 #endif
795 /* It's possible to create an endless loop with ":execute", catch that
796 * here. The value of 200 allows nested function calls, ":source", etc. */
797 if (call_depth == 200)
799 EMSG(_("E169: Command too recursive"));
800 #ifdef FEAT_EVAL
801 /* When converting to an exception, we do not include the command name
802 * since this is not an error of the specific command. */
803 do_errthrow((struct condstack *)NULL, (char_u *)NULL);
804 msg_list = saved_msg_list;
805 #endif
806 return FAIL;
808 ++call_depth;
810 #ifdef FEAT_EVAL
811 cstack.cs_idx = -1;
812 cstack.cs_looplevel = 0;
813 cstack.cs_trylevel = 0;
814 cstack.cs_emsg_silent_list = NULL;
815 cstack.cs_lflags = 0;
816 ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
818 real_cookie = getline_cookie(getline, cookie);
820 /* Inside a function use a higher nesting level. */
821 getline_is_func = getline_equal(getline, cookie, get_func_line);
822 if (getline_is_func && ex_nesting_level == func_level(real_cookie))
823 ++ex_nesting_level;
825 /* Get the function or script name and the address where the next breakpoint
826 * line and the debug tick for a function or script are stored. */
827 if (getline_is_func)
829 fname = func_name(real_cookie);
830 breakpoint = func_breakpoint(real_cookie);
831 dbg_tick = func_dbg_tick(real_cookie);
833 else if (getline_equal(getline, cookie, getsourceline))
835 fname = sourcing_name;
836 breakpoint = source_breakpoint(real_cookie);
837 dbg_tick = source_dbg_tick(real_cookie);
841 * Initialize "force_abort" and "suppress_errthrow" at the top level.
843 if (!recursive)
845 force_abort = FALSE;
846 suppress_errthrow = FALSE;
850 * If requested, store and reset the global values controlling the
851 * exception handling (used when debugging). Otherwise clear it to avoid
852 * a bogus compiler warning when the optimizer uses inline functions...
854 if (flags & DOCMD_EXCRESET)
855 save_dbg_stuff(&debug_saved);
856 else
857 memset(&debug_saved, 0, 1);
859 initial_trylevel = trylevel;
862 * "did_throw" will be set to TRUE when an exception is being thrown.
864 did_throw = FALSE;
865 #endif
867 * "did_emsg" will be set to TRUE when emsg() is used, in which case we
868 * cancel the whole command line, and any if/endif or loop.
869 * If force_abort is set, we cancel everything.
871 did_emsg = FALSE;
874 * KeyTyped is only set when calling vgetc(). Reset it here when not
875 * calling vgetc() (sourced command lines).
877 if (!(flags & DOCMD_KEYTYPED) && !getline_equal(getline, cookie, getexline))
878 KeyTyped = FALSE;
881 * Continue executing command lines:
882 * - when inside an ":if", ":while" or ":for"
883 * - for multiple commands on one line, separated with '|'
884 * - when repeating until there are no more lines (for ":source")
886 next_cmdline = cmdline;
889 #ifdef FEAT_EVAL
890 getline_is_func = getline_equal(getline, cookie, get_func_line);
891 #endif
893 /* stop skipping cmds for an error msg after all endif/while/for */
894 if (next_cmdline == NULL
895 #ifdef FEAT_EVAL
896 && !force_abort
897 && cstack.cs_idx < 0
898 && !(getline_is_func && func_has_abort(real_cookie))
899 #endif
901 did_emsg = FALSE;
904 * 1. If repeating a line in a loop, get a line from lines_ga.
905 * 2. If no line given: Get an allocated line with getline().
906 * 3. If a line is given: Make a copy, so we can mess with it.
909 #ifdef FEAT_EVAL
910 /* 1. If repeating, get a previous line from lines_ga. */
911 if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
913 /* Each '|' separated command is stored separately in lines_ga, to
914 * be able to jump to it. Don't use next_cmdline now. */
915 vim_free(cmdline_copy);
916 cmdline_copy = NULL;
918 /* Check if a function has returned or, unless it has an unclosed
919 * try conditional, aborted. */
920 if (getline_is_func)
922 # ifdef FEAT_PROFILE
923 if (do_profiling == PROF_YES)
924 func_line_end(real_cookie);
925 # endif
926 if (func_has_ended(real_cookie))
928 retval = FAIL;
929 break;
932 #ifdef FEAT_PROFILE
933 else if (do_profiling == PROF_YES
934 && getline_equal(getline, cookie, getsourceline))
935 script_line_end();
936 #endif
938 /* Check if a sourced file hit a ":finish" command. */
939 if (source_finished(getline, cookie))
941 retval = FAIL;
942 break;
945 /* If breakpoints have been added/deleted need to check for it. */
946 if (breakpoint != NULL && dbg_tick != NULL
947 && *dbg_tick != debug_tick)
949 *breakpoint = dbg_find_breakpoint(
950 getline_equal(getline, cookie, getsourceline),
951 fname, sourcing_lnum);
952 *dbg_tick = debug_tick;
955 next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
956 sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
958 /* Did we encounter a breakpoint? */
959 if (breakpoint != NULL && *breakpoint != 0
960 && *breakpoint <= sourcing_lnum)
962 dbg_breakpoint(fname, sourcing_lnum);
963 /* Find next breakpoint. */
964 *breakpoint = dbg_find_breakpoint(
965 getline_equal(getline, cookie, getsourceline),
966 fname, sourcing_lnum);
967 *dbg_tick = debug_tick;
969 # ifdef FEAT_PROFILE
970 if (do_profiling == PROF_YES)
972 if (getline_is_func)
973 func_line_start(real_cookie);
974 else if (getline_equal(getline, cookie, getsourceline))
975 script_line_start();
977 # endif
980 if (cstack.cs_looplevel > 0)
982 /* Inside a while/for loop we need to store the lines and use them
983 * again. Pass a different "getline" function to do_one_cmd()
984 * below, so that it stores lines in or reads them from
985 * "lines_ga". Makes it possible to define a function inside a
986 * while/for loop. */
987 cmd_getline = get_loop_line;
988 cmd_cookie = (void *)&cmd_loop_cookie;
989 cmd_loop_cookie.lines_gap = &lines_ga;
990 cmd_loop_cookie.current_line = current_line;
991 cmd_loop_cookie.getline = getline;
992 cmd_loop_cookie.cookie = cookie;
993 cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
995 else
997 cmd_getline = getline;
998 cmd_cookie = cookie;
1000 #endif
1002 /* 2. If no line given, get an allocated line with getline(). */
1003 if (next_cmdline == NULL)
1006 * Need to set msg_didout for the first line after an ":if",
1007 * otherwise the ":if" will be overwritten.
1009 if (count == 1 && getline_equal(getline, cookie, getexline))
1010 msg_didout = TRUE;
1011 if (getline == NULL || (next_cmdline = getline(':', cookie,
1012 #ifdef FEAT_EVAL
1013 cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
1014 #else
1016 #endif
1017 )) == NULL)
1019 /* Don't call wait_return for aborted command line. The NULL
1020 * returned for the end of a sourced file or executed function
1021 * doesn't do this. */
1022 if (KeyTyped && !(flags & DOCMD_REPEAT))
1023 need_wait_return = FALSE;
1024 retval = FAIL;
1025 break;
1027 used_getline = TRUE;
1030 * Keep the first typed line. Clear it when more lines are typed.
1032 if (flags & DOCMD_KEEPLINE)
1034 vim_free(repeat_cmdline);
1035 if (count == 0)
1036 repeat_cmdline = vim_strsave(next_cmdline);
1037 else
1038 repeat_cmdline = NULL;
1042 /* 3. Make a copy of the command so we can mess with it. */
1043 else if (cmdline_copy == NULL)
1045 next_cmdline = vim_strsave(next_cmdline);
1046 if (next_cmdline == NULL)
1048 EMSG(_(e_outofmem));
1049 retval = FAIL;
1050 break;
1053 cmdline_copy = next_cmdline;
1055 #ifdef FEAT_EVAL
1057 * Save the current line when inside a ":while" or ":for", and when
1058 * the command looks like a ":while" or ":for", because we may need it
1059 * later. When there is a '|' and another command, it is stored
1060 * separately, because we need to be able to jump back to it from an
1061 * :endwhile/:endfor.
1063 if (current_line == lines_ga.ga_len
1064 && (cstack.cs_looplevel || has_loop_cmd(next_cmdline)))
1066 if (store_loop_line(&lines_ga, next_cmdline) == FAIL)
1068 retval = FAIL;
1069 break;
1072 did_endif = FALSE;
1073 #endif
1075 if (count++ == 0)
1078 * All output from the commands is put below each other, without
1079 * waiting for a return. Don't do this when executing commands
1080 * from a script or when being called recursive (e.g. for ":e
1081 * +command file").
1083 if (!(flags & DOCMD_NOWAIT) && !recursive)
1085 msg_didout_before_start = msg_didout;
1086 msg_didany = FALSE; /* no output yet */
1087 msg_start();
1088 msg_scroll = TRUE; /* put messages below each other */
1089 ++no_wait_return; /* dont wait for return until finished */
1090 ++RedrawingDisabled;
1091 did_inc = TRUE;
1095 if (p_verbose >= 15 && sourcing_name != NULL)
1097 ++no_wait_return;
1098 verbose_enter_scroll();
1100 smsg((char_u *)_("line %ld: %s"),
1101 (long)sourcing_lnum, cmdline_copy);
1102 if (msg_silent == 0)
1103 msg_puts((char_u *)"\n"); /* don't overwrite this */
1105 verbose_leave_scroll();
1106 --no_wait_return;
1110 * 2. Execute one '|' separated command.
1111 * do_one_cmd() will return NULL if there is no trailing '|'.
1112 * "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1114 ++recursive;
1115 next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1116 #ifdef FEAT_EVAL
1117 &cstack,
1118 #endif
1119 cmd_getline, cmd_cookie);
1120 --recursive;
1122 #ifdef FEAT_EVAL
1123 if (cmd_cookie == (void *)&cmd_loop_cookie)
1124 /* Use "current_line" from "cmd_loop_cookie", it may have been
1125 * incremented when defining a function. */
1126 current_line = cmd_loop_cookie.current_line;
1127 #endif
1129 if (next_cmdline == NULL)
1131 vim_free(cmdline_copy);
1132 cmdline_copy = NULL;
1133 #ifdef FEAT_CMDHIST
1135 * If the command was typed, remember it for the ':' register.
1136 * Do this AFTER executing the command to make :@: work.
1138 if (getline_equal(getline, cookie, getexline)
1139 && new_last_cmdline != NULL)
1141 vim_free(last_cmdline);
1142 last_cmdline = new_last_cmdline;
1143 new_last_cmdline = NULL;
1145 #endif
1147 else
1149 /* need to copy the command after the '|' to cmdline_copy, for the
1150 * next do_one_cmd() */
1151 STRMOVE(cmdline_copy, next_cmdline);
1152 next_cmdline = cmdline_copy;
1156 #ifdef FEAT_EVAL
1157 /* reset did_emsg for a function that is not aborted by an error */
1158 if (did_emsg && !force_abort
1159 && getline_equal(getline, cookie, get_func_line)
1160 && !func_has_abort(real_cookie))
1161 did_emsg = FALSE;
1163 if (cstack.cs_looplevel > 0)
1165 ++current_line;
1168 * An ":endwhile", ":endfor" and ":continue" is handled here.
1169 * If we were executing commands, jump back to the ":while" or
1170 * ":for".
1171 * If we were not executing commands, decrement cs_looplevel.
1173 if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
1175 cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
1177 /* Jump back to the matching ":while" or ":for". Be careful
1178 * not to use a cs_line[] from an entry that isn't a ":while"
1179 * or ":for": It would make "current_line" invalid and can
1180 * cause a crash. */
1181 if (!did_emsg && !got_int && !did_throw
1182 && cstack.cs_idx >= 0
1183 && (cstack.cs_flags[cstack.cs_idx]
1184 & (CSF_WHILE | CSF_FOR))
1185 && cstack.cs_line[cstack.cs_idx] >= 0
1186 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1188 current_line = cstack.cs_line[cstack.cs_idx];
1189 /* remember we jumped there */
1190 cstack.cs_lflags |= CSL_HAD_LOOP;
1191 line_breakcheck(); /* check if CTRL-C typed */
1193 /* Check for the next breakpoint at or after the ":while"
1194 * or ":for". */
1195 if (breakpoint != NULL)
1197 *breakpoint = dbg_find_breakpoint(
1198 getline_equal(getline, cookie, getsourceline),
1199 fname,
1200 ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1201 *dbg_tick = debug_tick;
1204 else
1206 /* can only get here with ":endwhile" or ":endfor" */
1207 if (cstack.cs_idx >= 0)
1208 rewind_conditionals(&cstack, cstack.cs_idx - 1,
1209 CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
1214 * For a ":while" or ":for" we need to remember the line number.
1216 else if (cstack.cs_lflags & CSL_HAD_LOOP)
1218 cstack.cs_lflags &= ~CSL_HAD_LOOP;
1219 cstack.cs_line[cstack.cs_idx] = current_line - 1;
1224 * When not inside any ":while" loop, clear remembered lines.
1226 if (cstack.cs_looplevel == 0)
1228 if (lines_ga.ga_len > 0)
1230 sourcing_lnum =
1231 ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1232 free_cmdlines(&lines_ga);
1234 current_line = 0;
1238 * A ":finally" makes did_emsg, got_int, and did_throw pending for
1239 * being restored at the ":endtry". Reset them here and set the
1240 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
1241 * This includes the case where a missing ":endif", ":endwhile" or
1242 * ":endfor" was detected by the ":finally" itself.
1244 if (cstack.cs_lflags & CSL_HAD_FINA)
1246 cstack.cs_lflags &= ~CSL_HAD_FINA;
1247 report_make_pending(cstack.cs_pending[cstack.cs_idx]
1248 & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1249 did_throw ? (void *)current_exception : NULL);
1250 did_emsg = got_int = did_throw = FALSE;
1251 cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1254 /* Update global "trylevel" for recursive calls to do_cmdline() from
1255 * within this loop. */
1256 trylevel = initial_trylevel + cstack.cs_trylevel;
1259 * If the outermost try conditional (across function calls and sourced
1260 * files) is aborted because of an error, an interrupt, or an uncaught
1261 * exception, cancel everything. If it is left normally, reset
1262 * force_abort to get the non-EH compatible abortion behavior for
1263 * the rest of the script.
1265 if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1266 force_abort = FALSE;
1268 /* Convert an interrupt to an exception if appropriate. */
1269 (void)do_intthrow(&cstack);
1270 #endif /* FEAT_EVAL */
1274 * Continue executing command lines when:
1275 * - no CTRL-C typed, no aborting error, no exception thrown or try
1276 * conditionals need to be checked for executing finally clauses or
1277 * catching an interrupt exception
1278 * - didn't get an error message or lines are not typed
1279 * - there is a command after '|', inside a :if, :while, :for or :try, or
1280 * looping for ":source" command or function call.
1282 while (!((got_int
1283 #ifdef FEAT_EVAL
1284 || (did_emsg && force_abort) || did_throw
1285 #endif
1287 #ifdef FEAT_EVAL
1288 && cstack.cs_trylevel == 0
1289 #endif
1291 && !(did_emsg && used_getline
1292 && (getline_equal(getline, cookie, getexmodeline)
1293 || getline_equal(getline, cookie, getexline)))
1294 && (next_cmdline != NULL
1295 #ifdef FEAT_EVAL
1296 || cstack.cs_idx >= 0
1297 #endif
1298 || (flags & DOCMD_REPEAT)));
1300 vim_free(cmdline_copy);
1301 #ifdef FEAT_EVAL
1302 free_cmdlines(&lines_ga);
1303 ga_clear(&lines_ga);
1305 if (cstack.cs_idx >= 0)
1308 * If a sourced file or executed function ran to its end, report the
1309 * unclosed conditional.
1311 if (!got_int && !did_throw
1312 && ((getline_equal(getline, cookie, getsourceline)
1313 && !source_finished(getline, cookie))
1314 || (getline_equal(getline, cookie, get_func_line)
1315 && !func_has_ended(real_cookie))))
1317 if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1318 EMSG(_(e_endtry));
1319 else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1320 EMSG(_(e_endwhile));
1321 else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
1322 EMSG(_(e_endfor));
1323 else
1324 EMSG(_(e_endif));
1328 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1329 * ":endtry" in a sourced file or executed function. If the try
1330 * conditional is in its finally clause, ignore anything pending.
1331 * If it is in a catch clause, finish the caught exception.
1332 * Also cleanup any "cs_forinfo" structures.
1336 int idx = cleanup_conditionals(&cstack, 0, TRUE);
1338 if (idx >= 0)
1339 --idx; /* remove try block not in its finally clause */
1340 rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
1341 &cstack.cs_looplevel);
1343 while (cstack.cs_idx >= 0);
1344 trylevel = initial_trylevel;
1347 /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
1348 * lack was reported above and the error message is to be converted to an
1349 * exception, do this now after rewinding the cstack. */
1350 do_errthrow(&cstack, getline_equal(getline, cookie, get_func_line)
1351 ? (char_u *)"endfunction" : (char_u *)NULL);
1353 if (trylevel == 0)
1356 * When an exception is being thrown out of the outermost try
1357 * conditional, discard the uncaught exception, disable the conversion
1358 * of interrupts or errors to exceptions, and ensure that no more
1359 * commands are executed.
1361 if (did_throw)
1363 void *p = NULL;
1364 char_u *saved_sourcing_name;
1365 int saved_sourcing_lnum;
1366 struct msglist *messages = NULL, *next;
1369 * If the uncaught exception is a user exception, report it as an
1370 * error. If it is an error exception, display the saved error
1371 * message now. For an interrupt exception, do nothing; the
1372 * interrupt message is given elsewhere.
1374 switch (current_exception->type)
1376 case ET_USER:
1377 vim_snprintf((char *)IObuff, IOSIZE,
1378 _("E605: Exception not caught: %s"),
1379 current_exception->value);
1380 p = vim_strsave(IObuff);
1381 break;
1382 case ET_ERROR:
1383 messages = current_exception->messages;
1384 current_exception->messages = NULL;
1385 break;
1386 case ET_INTERRUPT:
1387 break;
1388 default:
1389 p = vim_strsave((char_u *)_(e_internal));
1392 saved_sourcing_name = sourcing_name;
1393 saved_sourcing_lnum = sourcing_lnum;
1394 sourcing_name = current_exception->throw_name;
1395 sourcing_lnum = current_exception->throw_lnum;
1396 current_exception->throw_name = NULL;
1398 discard_current_exception(); /* uses IObuff if 'verbose' */
1399 suppress_errthrow = TRUE;
1400 force_abort = TRUE;
1402 if (messages != NULL)
1406 next = messages->next;
1407 emsg(messages->msg);
1408 vim_free(messages->msg);
1409 vim_free(messages);
1410 messages = next;
1412 while (messages != NULL);
1414 else if (p != NULL)
1416 emsg(p);
1417 vim_free(p);
1419 vim_free(sourcing_name);
1420 sourcing_name = saved_sourcing_name;
1421 sourcing_lnum = saved_sourcing_lnum;
1425 * On an interrupt or an aborting error not converted to an exception,
1426 * disable the conversion of errors to exceptions. (Interrupts are not
1427 * converted any more, here.) This enables also the interrupt message
1428 * when force_abort is set and did_emsg unset in case of an interrupt
1429 * from a finally clause after an error.
1431 else if (got_int || (did_emsg && force_abort))
1432 suppress_errthrow = TRUE;
1436 * The current cstack will be freed when do_cmdline() returns. An uncaught
1437 * exception will have to be rethrown in the previous cstack. If a function
1438 * has just returned or a script file was just finished and the previous
1439 * cstack belongs to the same function or, respectively, script file, it
1440 * will have to be checked for finally clauses to be executed due to the
1441 * ":return" or ":finish". This is done in do_one_cmd().
1443 if (did_throw)
1444 need_rethrow = TRUE;
1445 if ((getline_equal(getline, cookie, getsourceline)
1446 && ex_nesting_level > source_level(real_cookie))
1447 || (getline_equal(getline, cookie, get_func_line)
1448 && ex_nesting_level > func_level(real_cookie) + 1))
1450 if (!did_throw)
1451 check_cstack = TRUE;
1453 else
1455 /* When leaving a function, reduce nesting level. */
1456 if (getline_equal(getline, cookie, get_func_line))
1457 --ex_nesting_level;
1459 * Go to debug mode when returning from a function in which we are
1460 * single-stepping.
1462 if ((getline_equal(getline, cookie, getsourceline)
1463 || getline_equal(getline, cookie, get_func_line))
1464 && ex_nesting_level + 1 <= debug_break_level)
1465 do_debug(getline_equal(getline, cookie, getsourceline)
1466 ? (char_u *)_("End of sourced file")
1467 : (char_u *)_("End of function"));
1471 * Restore the exception environment (done after returning from the
1472 * debugger).
1474 if (flags & DOCMD_EXCRESET)
1475 restore_dbg_stuff(&debug_saved);
1477 msg_list = saved_msg_list;
1478 #endif /* FEAT_EVAL */
1481 * If there was too much output to fit on the command line, ask the user to
1482 * hit return before redrawing the screen. With the ":global" command we do
1483 * this only once after the command is finished.
1485 if (did_inc)
1487 --RedrawingDisabled;
1488 --no_wait_return;
1489 msg_scroll = FALSE;
1492 * When just finished an ":if"-":else" which was typed, no need to
1493 * wait for hit-return. Also for an error situation.
1495 if (retval == FAIL
1496 #ifdef FEAT_EVAL
1497 || (did_endif && KeyTyped && !did_emsg)
1498 #endif
1501 need_wait_return = FALSE;
1502 msg_didany = FALSE; /* don't wait when restarting edit */
1504 else if (need_wait_return)
1507 * The msg_start() above clears msg_didout. The wait_return we do
1508 * here should not overwrite the command that may be shown before
1509 * doing that.
1511 msg_didout |= msg_didout_before_start;
1512 wait_return(FALSE);
1516 #ifndef FEAT_EVAL
1518 * Reset if_level, in case a sourced script file contains more ":if" than
1519 * ":endif" (could be ":if x | foo | endif").
1521 if_level = 0;
1522 #endif
1524 --call_depth;
1525 return retval;
1528 #ifdef FEAT_EVAL
1530 * Obtain a line when inside a ":while" or ":for" loop.
1532 static char_u *
1533 get_loop_line(c, cookie, indent)
1534 int c;
1535 void *cookie;
1536 int indent;
1538 struct loop_cookie *cp = (struct loop_cookie *)cookie;
1539 wcmd_T *wp;
1540 char_u *line;
1542 if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1544 if (cp->repeating)
1545 return NULL; /* trying to read past ":endwhile"/":endfor" */
1547 /* First time inside the ":while"/":for": get line normally. */
1548 if (cp->getline == NULL)
1549 line = getcmdline(c, 0L, indent);
1550 else
1551 line = cp->getline(c, cp->cookie, indent);
1552 if (line != NULL && store_loop_line(cp->lines_gap, line) == OK)
1553 ++cp->current_line;
1555 return line;
1558 KeyTyped = FALSE;
1559 ++cp->current_line;
1560 wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1561 sourcing_lnum = wp->lnum;
1562 return vim_strsave(wp->line);
1566 * Store a line in "gap" so that a ":while" loop can execute it again.
1568 static int
1569 store_loop_line(gap, line)
1570 garray_T *gap;
1571 char_u *line;
1573 if (ga_grow(gap, 1) == FAIL)
1574 return FAIL;
1575 ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1576 ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1577 ++gap->ga_len;
1578 return OK;
1582 * Free the lines stored for a ":while" or ":for" loop.
1584 static void
1585 free_cmdlines(gap)
1586 garray_T *gap;
1588 while (gap->ga_len > 0)
1590 vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1591 --gap->ga_len;
1594 #endif
1597 * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals
1598 * "func". * Otherwise return TRUE when "fgetline" equals "func".
1601 getline_equal(fgetline, cookie, func)
1602 char_u *(*fgetline) __ARGS((int, void *, int));
1603 void *cookie UNUSED; /* argument for fgetline() */
1604 char_u *(*func) __ARGS((int, void *, int));
1606 #ifdef FEAT_EVAL
1607 char_u *(*gp) __ARGS((int, void *, int));
1608 struct loop_cookie *cp;
1610 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1611 * function that's originally used to obtain the lines. This may be
1612 * nested several levels. */
1613 gp = fgetline;
1614 cp = (struct loop_cookie *)cookie;
1615 while (gp == get_loop_line)
1617 gp = cp->getline;
1618 cp = cp->cookie;
1620 return gp == func;
1621 #else
1622 return fgetline == func;
1623 #endif
1626 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1628 * If "fgetline" is get_loop_line(), return the cookie used by the original
1629 * getline function. Otherwise return "cookie".
1631 void *
1632 getline_cookie(fgetline, cookie)
1633 char_u *(*fgetline) __ARGS((int, void *, int)) UNUSED;
1634 void *cookie; /* argument for fgetline() */
1636 # ifdef FEAT_EVAL
1637 char_u *(*gp) __ARGS((int, void *, int));
1638 struct loop_cookie *cp;
1640 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1641 * cookie that's originally used to obtain the lines. This may be nested
1642 * several levels. */
1643 gp = fgetline;
1644 cp = (struct loop_cookie *)cookie;
1645 while (gp == get_loop_line)
1647 gp = cp->getline;
1648 cp = cp->cookie;
1650 return cp;
1651 # else
1652 return cookie;
1653 # endif
1655 #endif
1658 * Execute one Ex command.
1660 * If 'sourcing' is TRUE, the command will be included in the error message.
1662 * 1. skip comment lines and leading space
1663 * 2. handle command modifiers
1664 * 3. parse range
1665 * 4. parse command
1666 * 5. parse arguments
1667 * 6. switch on command name
1669 * Note: "fgetline" can be NULL.
1671 * This function may be called recursively!
1673 #if (_MSC_VER == 1200)
1675 * Avoid optimisation bug in VC++ version 6.0
1677 #pragma optimize( "g", off )
1678 #endif
1679 static char_u *
1680 do_one_cmd(cmdlinep, sourcing,
1681 #ifdef FEAT_EVAL
1682 cstack,
1683 #endif
1684 fgetline, cookie)
1685 char_u **cmdlinep;
1686 int sourcing;
1687 #ifdef FEAT_EVAL
1688 struct condstack *cstack;
1689 #endif
1690 char_u *(*fgetline) __ARGS((int, void *, int));
1691 void *cookie; /* argument for fgetline() */
1693 char_u *p;
1694 linenr_T lnum;
1695 long n;
1696 char_u *errormsg = NULL; /* error message */
1697 exarg_T ea; /* Ex command arguments */
1698 long verbose_save = -1;
1699 int save_msg_scroll = msg_scroll;
1700 int save_msg_silent = -1;
1701 int did_esilent = 0;
1702 #ifdef HAVE_SANDBOX
1703 int did_sandbox = FALSE;
1704 #endif
1705 cmdmod_T save_cmdmod;
1706 int ni; /* set when Not Implemented */
1708 vim_memset(&ea, 0, sizeof(ea));
1709 ea.line1 = 1;
1710 ea.line2 = 1;
1711 #ifdef FEAT_EVAL
1712 ++ex_nesting_level;
1713 #endif
1715 /* when not editing the last file :q has to be typed twice */
1716 if (quitmore
1717 #ifdef FEAT_EVAL
1718 /* avoid that a function call in 'statusline' does this */
1719 && !getline_equal(fgetline, cookie, get_func_line)
1720 #endif
1722 --quitmore;
1725 * Reset browse, confirm, etc.. They are restored when returning, for
1726 * recursive calls.
1728 save_cmdmod = cmdmod;
1729 vim_memset(&cmdmod, 0, sizeof(cmdmod));
1731 /* "#!anything" is handled like a comment. */
1732 if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!')
1733 goto doend;
1736 * Repeat until no more command modifiers are found.
1738 ea.cmd = *cmdlinep;
1739 for (;;)
1742 * 1. skip comment lines and leading white space and colons
1744 while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1745 ++ea.cmd;
1747 /* in ex mode, an empty line works like :+ */
1748 if (*ea.cmd == NUL && exmode_active
1749 && (getline_equal(fgetline, cookie, getexmodeline)
1750 || getline_equal(fgetline, cookie, getexline))
1751 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1753 ea.cmd = (char_u *)"+";
1754 ex_pressedreturn = TRUE;
1757 /* ignore comment and empty lines */
1758 if (*ea.cmd == '"')
1759 goto doend;
1760 if (*ea.cmd == NUL)
1762 ex_pressedreturn = TRUE;
1763 goto doend;
1767 * 2. handle command modifiers.
1769 p = ea.cmd;
1770 if (VIM_ISDIGIT(*ea.cmd))
1771 p = skipwhite(skipdigits(ea.cmd));
1772 switch (*p)
1774 /* When adding an entry, also modify cmd_exists(). */
1775 case 'a': if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1776 break;
1777 #ifdef FEAT_WINDOWS
1778 cmdmod.split |= WSP_ABOVE;
1779 #endif
1780 continue;
1782 case 'b': if (checkforcmd(&ea.cmd, "belowright", 3))
1784 #ifdef FEAT_WINDOWS
1785 cmdmod.split |= WSP_BELOW;
1786 #endif
1787 continue;
1789 if (checkforcmd(&ea.cmd, "browse", 3))
1791 #ifdef FEAT_BROWSE_CMD
1792 cmdmod.browse = TRUE;
1793 #endif
1794 continue;
1796 if (!checkforcmd(&ea.cmd, "botright", 2))
1797 break;
1798 #ifdef FEAT_WINDOWS
1799 cmdmod.split |= WSP_BOT;
1800 #endif
1801 continue;
1803 case 'c': if (!checkforcmd(&ea.cmd, "confirm", 4))
1804 break;
1805 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1806 cmdmod.confirm = TRUE;
1807 #endif
1808 continue;
1810 case 'k': if (checkforcmd(&ea.cmd, "keepmarks", 3))
1812 cmdmod.keepmarks = TRUE;
1813 continue;
1815 if (checkforcmd(&ea.cmd, "keepalt", 5))
1817 cmdmod.keepalt = TRUE;
1818 continue;
1820 if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1821 break;
1822 cmdmod.keepjumps = TRUE;
1823 continue;
1825 /* ":hide" and ":hide | cmd" are not modifiers */
1826 case 'h': if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1827 || *p == NUL || ends_excmd(*p))
1828 break;
1829 ea.cmd = p;
1830 cmdmod.hide = TRUE;
1831 continue;
1833 case 'l': if (checkforcmd(&ea.cmd, "lockmarks", 3))
1835 cmdmod.lockmarks = TRUE;
1836 continue;
1839 if (!checkforcmd(&ea.cmd, "leftabove", 5))
1840 break;
1841 #ifdef FEAT_WINDOWS
1842 cmdmod.split |= WSP_ABOVE;
1843 #endif
1844 continue;
1846 case 'n': if (!checkforcmd(&ea.cmd, "noautocmd", 3))
1847 break;
1848 #ifdef FEAT_AUTOCMD
1849 if (cmdmod.save_ei == NULL)
1851 /* Set 'eventignore' to "all". Restore the
1852 * existing option value later. */
1853 cmdmod.save_ei = vim_strsave(p_ei);
1854 set_string_option_direct((char_u *)"ei", -1,
1855 (char_u *)"all", OPT_FREE, SID_NONE);
1857 #endif
1858 continue;
1860 case 'r': if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1861 break;
1862 #ifdef FEAT_WINDOWS
1863 cmdmod.split |= WSP_BELOW;
1864 #endif
1865 continue;
1867 case 's': if (checkforcmd(&ea.cmd, "sandbox", 3))
1869 #ifdef HAVE_SANDBOX
1870 if (!did_sandbox)
1871 ++sandbox;
1872 did_sandbox = TRUE;
1873 #endif
1874 continue;
1876 if (!checkforcmd(&ea.cmd, "silent", 3))
1877 break;
1878 if (save_msg_silent == -1)
1879 save_msg_silent = msg_silent;
1880 ++msg_silent;
1881 if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1]))
1883 /* ":silent!", but not "silent !cmd" */
1884 ea.cmd = skipwhite(ea.cmd + 1);
1885 ++emsg_silent;
1886 ++did_esilent;
1888 continue;
1890 case 't': if (checkforcmd(&p, "tab", 3))
1892 #ifdef FEAT_WINDOWS
1893 if (vim_isdigit(*ea.cmd))
1894 cmdmod.tab = atoi((char *)ea.cmd) + 1;
1895 else
1896 cmdmod.tab = tabpage_index(curtab) + 1;
1897 ea.cmd = p;
1898 #endif
1899 continue;
1901 if (!checkforcmd(&ea.cmd, "topleft", 2))
1902 break;
1903 #ifdef FEAT_WINDOWS
1904 cmdmod.split |= WSP_TOP;
1905 #endif
1906 continue;
1908 case 'u': if (!checkforcmd(&ea.cmd, "unsilent", 3))
1909 break;
1910 if (save_msg_silent == -1)
1911 save_msg_silent = msg_silent;
1912 msg_silent = 0;
1913 continue;
1915 case 'v': if (checkforcmd(&ea.cmd, "vertical", 4))
1917 #ifdef FEAT_VERTSPLIT
1918 cmdmod.split |= WSP_VERT;
1919 #endif
1920 continue;
1922 if (!checkforcmd(&p, "verbose", 4))
1923 break;
1924 if (verbose_save < 0)
1925 verbose_save = p_verbose;
1926 if (vim_isdigit(*ea.cmd))
1927 p_verbose = atoi((char *)ea.cmd);
1928 else
1929 p_verbose = 1;
1930 ea.cmd = p;
1931 continue;
1933 break;
1936 #ifdef FEAT_EVAL
1937 ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
1938 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
1939 #else
1940 ea.skip = (if_level > 0);
1941 #endif
1943 #ifdef FEAT_EVAL
1944 # ifdef FEAT_PROFILE
1945 /* Count this line for profiling if ea.skip is FALSE. */
1946 if (do_profiling == PROF_YES && !ea.skip)
1948 if (getline_equal(fgetline, cookie, get_func_line))
1949 func_line_exec(getline_cookie(fgetline, cookie));
1950 else if (getline_equal(fgetline, cookie, getsourceline))
1951 script_line_exec();
1953 #endif
1955 /* May go to debug mode. If this happens and the ">quit" debug command is
1956 * used, throw an interrupt exception and skip the next command. */
1957 dbg_check_breakpoint(&ea);
1958 if (!ea.skip && got_int)
1960 ea.skip = TRUE;
1961 (void)do_intthrow(cstack);
1963 #endif
1966 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
1968 * where 'addr' is:
1970 * % (entire file)
1971 * $ [+-NUM]
1972 * 'x [+-NUM] (where x denotes a currently defined mark)
1973 * . [+-NUM]
1974 * [+-NUM]..
1975 * NUM
1977 * The ea.cmd pointer is updated to point to the first character following the
1978 * range spec. If an initial address is found, but no second, the upper bound
1979 * is equal to the lower.
1982 /* repeat for all ',' or ';' separated addresses */
1983 for (;;)
1985 ea.line1 = ea.line2;
1986 ea.line2 = curwin->w_cursor.lnum; /* default is current line number */
1987 ea.cmd = skipwhite(ea.cmd);
1988 lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0);
1989 if (ea.cmd == NULL) /* error detected */
1990 goto doend;
1991 if (lnum == MAXLNUM)
1993 if (*ea.cmd == '%') /* '%' - all lines */
1995 ++ea.cmd;
1996 ea.line1 = 1;
1997 ea.line2 = curbuf->b_ml.ml_line_count;
1998 ++ea.addr_count;
2000 /* '*' - visual area */
2001 else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
2003 pos_T *fp;
2005 ++ea.cmd;
2006 if (!ea.skip)
2008 fp = getmark('<', FALSE);
2009 if (check_mark(fp) == FAIL)
2010 goto doend;
2011 ea.line1 = fp->lnum;
2012 fp = getmark('>', FALSE);
2013 if (check_mark(fp) == FAIL)
2014 goto doend;
2015 ea.line2 = fp->lnum;
2016 ++ea.addr_count;
2020 else
2021 ea.line2 = lnum;
2022 ea.addr_count++;
2024 if (*ea.cmd == ';')
2026 if (!ea.skip)
2027 curwin->w_cursor.lnum = ea.line2;
2029 else if (*ea.cmd != ',')
2030 break;
2031 ++ea.cmd;
2034 /* One address given: set start and end lines */
2035 if (ea.addr_count == 1)
2037 ea.line1 = ea.line2;
2038 /* ... but only implicit: really no address given */
2039 if (lnum == MAXLNUM)
2040 ea.addr_count = 0;
2043 /* Don't leave the cursor on an illegal line (caused by ';') */
2044 check_cursor_lnum();
2047 * 4. parse command
2051 * Skip ':' and any white space
2053 ea.cmd = skipwhite(ea.cmd);
2054 while (*ea.cmd == ':')
2055 ea.cmd = skipwhite(ea.cmd + 1);
2058 * If we got a line, but no command, then go to the line.
2059 * If we find a '|' or '\n' we set ea.nextcmd.
2061 if (*ea.cmd == NUL || *ea.cmd == '"' ||
2062 (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
2065 * strange vi behaviour:
2066 * ":3" jumps to line 3
2067 * ":3|..." prints line 3
2068 * ":|" prints current line
2070 if (ea.skip) /* skip this if inside :if */
2071 goto doend;
2072 if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2))
2074 ea.cmdidx = CMD_print;
2075 ea.argt = RANGE+COUNT+TRLBAR;
2076 if ((errormsg = invalid_range(&ea)) == NULL)
2078 correct_range(&ea);
2079 ex_print(&ea);
2082 else if (ea.addr_count != 0)
2084 if (ea.line2 > curbuf->b_ml.ml_line_count)
2086 /* With '-' in 'cpoptions' a line number past the file is an
2087 * error, otherwise put it at the end of the file. */
2088 if (vim_strchr(p_cpo, CPO_MINUS) != NULL)
2089 ea.line2 = -1;
2090 else
2091 ea.line2 = curbuf->b_ml.ml_line_count;
2094 if (ea.line2 < 0)
2095 errormsg = (char_u *)_(e_invrange);
2096 else
2098 if (ea.line2 == 0)
2099 curwin->w_cursor.lnum = 1;
2100 else
2101 curwin->w_cursor.lnum = ea.line2;
2102 beginline(BL_SOL | BL_FIX);
2105 goto doend;
2108 /* Find the command and let "p" point to after it. */
2109 p = find_command(&ea, NULL);
2111 #ifdef FEAT_USR_CMDS
2112 if (p == NULL)
2114 if (!ea.skip)
2115 errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
2116 goto doend;
2118 /* Check for wrong commands. */
2119 if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78)
2121 errormsg = uc_fun_cmd();
2122 goto doend;
2124 #endif
2125 if (ea.cmdidx == CMD_SIZE)
2127 if (!ea.skip)
2129 STRCPY(IObuff, _("E492: Not an editor command"));
2130 if (!sourcing)
2132 STRCAT(IObuff, ": ");
2133 STRNCAT(IObuff, *cmdlinep, 40);
2135 errormsg = IObuff;
2137 goto doend;
2140 ni = (
2141 #ifdef FEAT_USR_CMDS
2142 !USER_CMDIDX(ea.cmdidx) &&
2143 #endif
2144 (cmdnames[ea.cmdidx].cmd_func == ex_ni
2145 #ifdef HAVE_EX_SCRIPT_NI
2146 || cmdnames[ea.cmdidx].cmd_func == ex_script_ni
2147 #endif
2150 #ifndef FEAT_EVAL
2152 * When the expression evaluation is disabled, recognize the ":if" and
2153 * ":endif" commands and ignore everything in between it.
2155 if (ea.cmdidx == CMD_if)
2156 ++if_level;
2157 if (if_level)
2159 if (ea.cmdidx == CMD_endif)
2160 --if_level;
2161 goto doend;
2164 #endif
2166 /* forced commands */
2167 if (*p == '!' && ea.cmdidx != CMD_substitute
2168 && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic)
2170 ++p;
2171 ea.forceit = TRUE;
2173 else
2174 ea.forceit = FALSE;
2177 * 5. parse arguments
2179 #ifdef FEAT_USR_CMDS
2180 if (!USER_CMDIDX(ea.cmdidx))
2181 #endif
2182 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
2184 if (!ea.skip)
2186 #ifdef HAVE_SANDBOX
2187 if (sandbox != 0 && !(ea.argt & SBOXOK))
2189 /* Command not allowed in sandbox. */
2190 errormsg = (char_u *)_(e_sandbox);
2191 goto doend;
2193 #endif
2194 if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2196 /* Command not allowed in non-'modifiable' buffer */
2197 errormsg = (char_u *)_(e_modifiable);
2198 goto doend;
2201 if (text_locked() && !(ea.argt & CMDWIN)
2202 # ifdef FEAT_USR_CMDS
2203 && !USER_CMDIDX(ea.cmdidx)
2204 # endif
2207 /* Command not allowed when editing the command line. */
2208 #ifdef FEAT_CMDWIN
2209 if (cmdwin_type != 0)
2210 errormsg = (char_u *)_(e_cmdwin);
2211 else
2212 #endif
2213 errormsg = (char_u *)_(e_secure);
2214 goto doend;
2216 #ifdef FEAT_AUTOCMD
2217 /* Disallow editing another buffer when "curbuf_lock" is set.
2218 * Do allow ":edit" (check for argument later).
2219 * Do allow ":checktime" (it's postponed). */
2220 if (!(ea.argt & CMDWIN)
2221 && ea.cmdidx != CMD_edit
2222 && ea.cmdidx != CMD_checktime
2223 # ifdef FEAT_USR_CMDS
2224 && !USER_CMDIDX(ea.cmdidx)
2225 # endif
2226 && curbuf_locked())
2227 goto doend;
2228 #endif
2230 if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2232 /* no range allowed */
2233 errormsg = (char_u *)_(e_norange);
2234 goto doend;
2238 if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */
2240 errormsg = (char_u *)_(e_nobang);
2241 goto doend;
2245 * Don't complain about the range if it is not used
2246 * (could happen if line_count is accidentally set to 0).
2248 if (!ea.skip && !ni)
2251 * If the range is backwards, ask for confirmation and, if given, swap
2252 * ea.line1 & ea.line2 so it's forwards again.
2253 * When global command is busy, don't ask, will fail below.
2255 if (!global_busy && ea.line1 > ea.line2)
2257 if (msg_silent == 0)
2259 if (sourcing || exmode_active)
2261 errormsg = (char_u *)_("E493: Backwards range given");
2262 goto doend;
2264 if (ask_yesno((char_u *)
2265 _("Backwards range given, OK to swap"), FALSE) != 'y')
2266 goto doend;
2268 lnum = ea.line1;
2269 ea.line1 = ea.line2;
2270 ea.line2 = lnum;
2272 if ((errormsg = invalid_range(&ea)) != NULL)
2273 goto doend;
2276 if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2277 ea.line2 = 1;
2279 correct_range(&ea);
2281 #ifdef FEAT_FOLDING
2282 if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy)
2284 /* Put the first line at the start of a closed fold, put the last line
2285 * at the end of a closed fold. */
2286 (void)hasFolding(ea.line1, &ea.line1, NULL);
2287 (void)hasFolding(ea.line2, NULL, &ea.line2);
2289 #endif
2291 #ifdef FEAT_QUICKFIX
2293 * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2294 * option here, so things like % get expanded.
2296 p = replace_makeprg(&ea, p, cmdlinep);
2297 if (p == NULL)
2298 goto doend;
2299 #endif
2302 * Skip to start of argument.
2303 * Don't do this for the ":!" command, because ":!! -l" needs the space.
2305 if (ea.cmdidx == CMD_bang)
2306 ea.arg = p;
2307 else
2308 ea.arg = skipwhite(p);
2311 * Check for "++opt=val" argument.
2312 * Must be first, allow ":w ++enc=utf8 !cmd"
2314 if (ea.argt & ARGOPT)
2315 while (ea.arg[0] == '+' && ea.arg[1] == '+')
2316 if (getargopt(&ea) == FAIL && !ni)
2318 errormsg = (char_u *)_(e_invarg);
2319 goto doend;
2322 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2324 if (*ea.arg == '>') /* append */
2326 if (*++ea.arg != '>') /* typed wrong */
2328 errormsg = (char_u *)_("E494: Use w or w>>");
2329 goto doend;
2331 ea.arg = skipwhite(ea.arg + 1);
2332 ea.append = TRUE;
2334 else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
2336 ++ea.arg;
2337 ea.usefilter = TRUE;
2341 if (ea.cmdidx == CMD_read)
2343 if (ea.forceit)
2345 ea.usefilter = TRUE; /* :r! filter if ea.forceit */
2346 ea.forceit = FALSE;
2348 else if (*ea.arg == '!') /* :r !filter */
2350 ++ea.arg;
2351 ea.usefilter = TRUE;
2355 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2357 ea.amount = 1;
2358 while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */
2360 ++ea.arg;
2361 ++ea.amount;
2363 ea.arg = skipwhite(ea.arg);
2367 * Check for "+command" argument, before checking for next command.
2368 * Don't do this for ":read !cmd" and ":write !cmd".
2370 if ((ea.argt & EDITCMD) && !ea.usefilter)
2371 ea.do_ecmd_cmd = getargcmd(&ea.arg);
2374 * Check for '|' to separate commands and '"' to start comments.
2375 * Don't do this for ":read !cmd" and ":write !cmd".
2377 if ((ea.argt & TRLBAR) && !ea.usefilter)
2378 separate_nextcmd(&ea);
2381 * Check for <newline> to end a shell command.
2382 * Also do this for ":read !cmd", ":write !cmd" and ":global".
2383 * Any others?
2385 else if (ea.cmdidx == CMD_bang
2386 || ea.cmdidx == CMD_global
2387 || ea.cmdidx == CMD_vglobal
2388 || ea.usefilter)
2390 for (p = ea.arg; *p; ++p)
2392 /* Remove one backslash before a newline, so that it's possible to
2393 * pass a newline to the shell and also a newline that is preceded
2394 * with a backslash. This makes it impossible to end a shell
2395 * command in a backslash, but that doesn't appear useful.
2396 * Halving the number of backslashes is incompatible with previous
2397 * versions. */
2398 if (*p == '\\' && p[1] == '\n')
2399 STRMOVE(p, p + 1);
2400 else if (*p == '\n')
2402 ea.nextcmd = p + 1;
2403 *p = NUL;
2404 break;
2409 if ((ea.argt & DFLALL) && ea.addr_count == 0)
2411 ea.line1 = 1;
2412 ea.line2 = curbuf->b_ml.ml_line_count;
2415 /* accept numbered register only when no count allowed (:put) */
2416 if ( (ea.argt & REGSTR)
2417 && *ea.arg != NUL
2418 #ifdef FEAT_USR_CMDS
2419 && valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2420 && USER_CMDIDX(ea.cmdidx)))
2421 /* Do not allow register = for user commands */
2422 && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2423 #else
2424 && valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put)
2425 #endif
2426 && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2428 ea.regname = *ea.arg++;
2429 #ifdef FEAT_EVAL
2430 /* for '=' register: accept the rest of the line as an expression */
2431 if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2433 set_expr_line(vim_strsave(ea.arg));
2434 ea.arg += STRLEN(ea.arg);
2436 #endif
2437 ea.arg = skipwhite(ea.arg);
2441 * Check for a count. When accepting a BUFNAME, don't use "123foo" as a
2442 * count, it's a buffer name.
2444 if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2445 && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2446 || vim_iswhite(*p)))
2448 n = getdigits(&ea.arg);
2449 ea.arg = skipwhite(ea.arg);
2450 if (n <= 0 && !ni && (ea.argt & ZEROR) == 0)
2452 errormsg = (char_u *)_(e_zerocount);
2453 goto doend;
2455 if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */
2457 ea.line2 = n;
2458 if (ea.addr_count == 0)
2459 ea.addr_count = 1;
2461 else
2463 ea.line1 = ea.line2;
2464 ea.line2 += n - 1;
2465 ++ea.addr_count;
2467 * Be vi compatible: no error message for out of range.
2469 if (ea.line2 > curbuf->b_ml.ml_line_count)
2470 ea.line2 = curbuf->b_ml.ml_line_count;
2475 * Check for flags: 'l', 'p' and '#'.
2477 if (ea.argt & EXFLAGS)
2478 get_flags(&ea);
2479 /* no arguments allowed */
2480 if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2481 && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0))
2483 errormsg = (char_u *)_(e_trailing);
2484 goto doend;
2487 if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2489 errormsg = (char_u *)_(e_argreq);
2490 goto doend;
2493 #ifdef FEAT_EVAL
2495 * Skip the command when it's not going to be executed.
2496 * The commands like :if, :endif, etc. always need to be executed.
2497 * Also make an exception for commands that handle a trailing command
2498 * themselves.
2500 if (ea.skip)
2502 switch (ea.cmdidx)
2504 /* commands that need evaluation */
2505 case CMD_while:
2506 case CMD_endwhile:
2507 case CMD_for:
2508 case CMD_endfor:
2509 case CMD_if:
2510 case CMD_elseif:
2511 case CMD_else:
2512 case CMD_endif:
2513 case CMD_try:
2514 case CMD_catch:
2515 case CMD_finally:
2516 case CMD_endtry:
2517 case CMD_function:
2518 break;
2520 /* Commands that handle '|' themselves. Check: A command should
2521 * either have the TRLBAR flag, appear in this list or appear in
2522 * the list at ":help :bar". */
2523 case CMD_aboveleft:
2524 case CMD_and:
2525 case CMD_belowright:
2526 case CMD_botright:
2527 case CMD_browse:
2528 case CMD_call:
2529 case CMD_confirm:
2530 case CMD_delfunction:
2531 case CMD_djump:
2532 case CMD_dlist:
2533 case CMD_dsearch:
2534 case CMD_dsplit:
2535 case CMD_echo:
2536 case CMD_echoerr:
2537 case CMD_echomsg:
2538 case CMD_echon:
2539 case CMD_ecl:
2540 case CMD_execute:
2541 case CMD_help:
2542 case CMD_hide:
2543 case CMD_ijump:
2544 case CMD_ilist:
2545 case CMD_isearch:
2546 case CMD_isplit:
2547 case CMD_keepalt:
2548 case CMD_keepjumps:
2549 case CMD_keepmarks:
2550 case CMD_leftabove:
2551 case CMD_let:
2552 case CMD_lockmarks:
2553 case CMD_lua:
2554 case CMD_match:
2555 case CMD_mzscheme:
2556 case CMD_perl:
2557 case CMD_psearch:
2558 case CMD_python:
2559 case CMD_return:
2560 case CMD_rightbelow:
2561 case CMD_ruby:
2562 case CMD_silent:
2563 case CMD_smagic:
2564 case CMD_snomagic:
2565 case CMD_substitute:
2566 case CMD_syntax:
2567 case CMD_tab:
2568 case CMD_tcl:
2569 case CMD_throw:
2570 case CMD_tilde:
2571 case CMD_topleft:
2572 case CMD_unlet:
2573 case CMD_verbose:
2574 case CMD_vertical:
2575 break;
2577 default: goto doend;
2580 #endif
2582 if (ea.argt & XFILE)
2584 if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2585 goto doend;
2588 #ifdef FEAT_LISTCMDS
2590 * Accept buffer name. Cannot be used at the same time with a buffer
2591 * number. Don't do this for a user command.
2593 if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2594 # ifdef FEAT_USR_CMDS
2595 && !USER_CMDIDX(ea.cmdidx)
2596 # endif
2600 * :bdelete, :bwipeout and :bunload take several arguments, separated
2601 * by spaces: find next space (skipping over escaped characters).
2602 * The others take one argument: ignore trailing spaces.
2604 if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2605 || ea.cmdidx == CMD_bunload)
2606 p = skiptowhite_esc(ea.arg);
2607 else
2609 p = ea.arg + STRLEN(ea.arg);
2610 while (p > ea.arg && vim_iswhite(p[-1]))
2611 --p;
2613 ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE);
2614 if (ea.line2 < 0) /* failed */
2615 goto doend;
2616 ea.addr_count = 1;
2617 ea.arg = skipwhite(p);
2619 #endif
2622 * 6. switch on command name
2624 * The "ea" structure holds the arguments that can be used.
2626 ea.cmdlinep = cmdlinep;
2627 ea.getline = fgetline;
2628 ea.cookie = cookie;
2629 #ifdef FEAT_EVAL
2630 ea.cstack = cstack;
2631 #endif
2633 #ifdef FEAT_USR_CMDS
2634 if (USER_CMDIDX(ea.cmdidx))
2637 * Execute a user-defined command.
2639 do_ucmd(&ea);
2641 else
2642 #endif
2645 * Call the function to execute the command.
2647 ea.errmsg = NULL;
2648 (cmdnames[ea.cmdidx].cmd_func)(&ea);
2649 if (ea.errmsg != NULL)
2650 errormsg = (char_u *)_(ea.errmsg);
2653 #ifdef FEAT_EVAL
2655 * If the command just executed called do_cmdline(), any throw or ":return"
2656 * or ":finish" encountered there must also check the cstack of the still
2657 * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught
2658 * exception, or reanimate a returned function or finished script file and
2659 * return or finish it again.
2661 if (need_rethrow)
2662 do_throw(cstack);
2663 else if (check_cstack)
2665 if (source_finished(fgetline, cookie))
2666 do_finish(&ea, TRUE);
2667 else if (getline_equal(fgetline, cookie, get_func_line)
2668 && current_func_returned())
2669 do_return(&ea, TRUE, FALSE, NULL);
2671 need_rethrow = check_cstack = FALSE;
2672 #endif
2674 doend:
2675 if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */
2676 curwin->w_cursor.lnum = 1;
2678 if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2680 if (sourcing)
2682 if (errormsg != IObuff)
2684 STRCPY(IObuff, errormsg);
2685 errormsg = IObuff;
2687 STRCAT(errormsg, ": ");
2688 STRNCAT(errormsg, *cmdlinep, IOSIZE - STRLEN(IObuff) - 1);
2690 emsg(errormsg);
2692 #ifdef FEAT_EVAL
2693 do_errthrow(cstack,
2694 (ea.cmdidx != CMD_SIZE
2695 # ifdef FEAT_USR_CMDS
2696 && !USER_CMDIDX(ea.cmdidx)
2697 # endif
2698 ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
2699 #endif
2701 if (verbose_save >= 0)
2702 p_verbose = verbose_save;
2703 #ifdef FEAT_AUTOCMD
2704 if (cmdmod.save_ei != NULL)
2706 /* Restore 'eventignore' to the value before ":noautocmd". */
2707 set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei,
2708 OPT_FREE, SID_NONE);
2709 free_string_option(cmdmod.save_ei);
2711 #endif
2713 cmdmod = save_cmdmod;
2715 if (save_msg_silent != -1)
2717 /* messages could be enabled for a serious error, need to check if the
2718 * counters don't become negative */
2719 if (!did_emsg || msg_silent > save_msg_silent)
2720 msg_silent = save_msg_silent;
2721 emsg_silent -= did_esilent;
2722 if (emsg_silent < 0)
2723 emsg_silent = 0;
2724 /* Restore msg_scroll, it's set by file I/O commands, even when no
2725 * message is actually displayed. */
2726 msg_scroll = save_msg_scroll;
2728 /* "silent reg" or "silent echo x" inside "redir" leaves msg_col
2729 * somewhere in the line. Put it back in the first column. */
2730 if (redirecting())
2731 msg_col = 0;
2734 #ifdef HAVE_SANDBOX
2735 if (did_sandbox)
2736 --sandbox;
2737 #endif
2739 if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */
2740 ea.nextcmd = NULL;
2742 #ifdef FEAT_EVAL
2743 --ex_nesting_level;
2744 #endif
2746 return ea.nextcmd;
2748 #if (_MSC_VER == 1200)
2749 #pragma optimize( "", on )
2750 #endif
2753 * Check for an Ex command with optional tail.
2754 * If there is a match advance "pp" to the argument and return TRUE.
2757 checkforcmd(pp, cmd, len)
2758 char_u **pp; /* start of command */
2759 char *cmd; /* name of command */
2760 int len; /* required length */
2762 int i;
2764 for (i = 0; cmd[i] != NUL; ++i)
2765 if (((char_u *)cmd)[i] != (*pp)[i])
2766 break;
2767 if (i >= len && !isalpha((*pp)[i]))
2769 *pp = skipwhite(*pp + i);
2770 return TRUE;
2772 return FALSE;
2776 * Find an Ex command by its name, either built-in or user.
2777 * Start of the name can be found at eap->cmd.
2778 * Returns pointer to char after the command name.
2779 * "full" is set to TRUE if the whole command name matched.
2780 * Returns NULL for an ambiguous user command.
2782 static char_u *
2783 find_command(eap, full)
2784 exarg_T *eap;
2785 int *full UNUSED;
2787 int len;
2788 char_u *p;
2789 int i;
2792 * Isolate the command and search for it in the command table.
2793 * Exceptions:
2794 * - the 'k' command can directly be followed by any character.
2795 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2796 * but :sre[wind] is another command, as are :scrip[tnames],
2797 * :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
2798 * - the "d" command can directly be followed by 'l' or 'p' flag.
2800 p = eap->cmd;
2801 if (*p == 'k')
2803 eap->cmdidx = CMD_k;
2804 ++p;
2806 else if (p[0] == 's'
2807 && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r'
2808 && p[3] != 'i' && p[4] != 'p')
2809 || p[1] == 'g'
2810 || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
2811 || p[1] == 'I'
2812 || (p[1] == 'r' && p[2] != 'e')))
2814 eap->cmdidx = CMD_substitute;
2815 ++p;
2817 else
2819 while (ASCII_ISALPHA(*p))
2820 ++p;
2821 /* check for non-alpha command */
2822 if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2823 ++p;
2824 len = (int)(p - eap->cmd);
2825 if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p'))
2827 /* Check for ":dl", ":dell", etc. to ":deletel": that's
2828 * :delete with the 'l' flag. Same for 'p'. */
2829 for (i = 0; i < len; ++i)
2830 if (eap->cmd[i] != ((char_u *)"delete")[i])
2831 break;
2832 if (i == len - 1)
2834 --len;
2835 if (p[-1] == 'l')
2836 eap->flags |= EXFLAG_LIST;
2837 else
2838 eap->flags |= EXFLAG_PRINT;
2842 if (ASCII_ISLOWER(*eap->cmd))
2843 eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)];
2844 else
2845 eap->cmdidx = cmdidxs[26];
2847 for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
2848 eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
2849 if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
2850 (size_t)len) == 0)
2852 #ifdef FEAT_EVAL
2853 if (full != NULL
2854 && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
2855 *full = TRUE;
2856 #endif
2857 break;
2860 #ifdef FEAT_USR_CMDS
2861 /* Look for a user defined command as a last resort */
2862 if (eap->cmdidx == CMD_SIZE && *eap->cmd >= 'A' && *eap->cmd <= 'Z')
2864 /* User defined commands may contain digits. */
2865 while (ASCII_ISALNUM(*p))
2866 ++p;
2867 p = find_ucmd(eap, p, full, NULL, NULL);
2869 #endif
2870 if (p == eap->cmd)
2871 eap->cmdidx = CMD_SIZE;
2874 return p;
2877 #ifdef FEAT_USR_CMDS
2879 * Search for a user command that matches "eap->cmd".
2880 * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
2881 * Return a pointer to just after the command.
2882 * Return NULL if there is no matching command.
2884 static char_u *
2885 find_ucmd(eap, p, full, xp, compl)
2886 exarg_T *eap;
2887 char_u *p; /* end of the command (possibly including count) */
2888 int *full; /* set to TRUE for a full match */
2889 expand_T *xp; /* used for completion, NULL otherwise */
2890 int *compl; /* completion flags or NULL */
2892 int len = (int)(p - eap->cmd);
2893 int j, k, matchlen = 0;
2894 ucmd_T *uc;
2895 int found = FALSE;
2896 int possible = FALSE;
2897 char_u *cp, *np; /* Point into typed cmd and test name */
2898 garray_T *gap;
2899 int amb_local = FALSE; /* Found ambiguous buffer-local command,
2900 only full match global is accepted. */
2903 * Look for buffer-local user commands first, then global ones.
2905 gap = &curbuf->b_ucmds;
2906 for (;;)
2908 for (j = 0; j < gap->ga_len; ++j)
2910 uc = USER_CMD_GA(gap, j);
2911 cp = eap->cmd;
2912 np = uc->uc_name;
2913 k = 0;
2914 while (k < len && *np != NUL && *cp++ == *np++)
2915 k++;
2916 if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
2918 /* If finding a second match, the command is ambiguous. But
2919 * not if a buffer-local command wasn't a full match and a
2920 * global command is a full match. */
2921 if (k == len && found && *np != NUL)
2923 if (gap == &ucmds)
2924 return NULL;
2925 amb_local = TRUE;
2928 if (!found || (k == len && *np == NUL))
2930 /* If we matched up to a digit, then there could
2931 * be another command including the digit that we
2932 * should use instead.
2934 if (k == len)
2935 found = TRUE;
2936 else
2937 possible = TRUE;
2939 if (gap == &ucmds)
2940 eap->cmdidx = CMD_USER;
2941 else
2942 eap->cmdidx = CMD_USER_BUF;
2943 eap->argt = (long)uc->uc_argt;
2944 eap->useridx = j;
2946 # ifdef FEAT_CMDL_COMPL
2947 if (compl != NULL)
2948 *compl = uc->uc_compl;
2949 # ifdef FEAT_EVAL
2950 if (xp != NULL)
2952 xp->xp_arg = uc->uc_compl_arg;
2953 xp->xp_scriptID = uc->uc_scriptID;
2955 # endif
2956 # endif
2957 /* Do not search for further abbreviations
2958 * if this is an exact match. */
2959 matchlen = k;
2960 if (k == len && *np == NUL)
2962 if (full != NULL)
2963 *full = TRUE;
2964 amb_local = FALSE;
2965 break;
2971 /* Stop if we found a full match or searched all. */
2972 if (j < gap->ga_len || gap == &ucmds)
2973 break;
2974 gap = &ucmds;
2977 /* Only found ambiguous matches. */
2978 if (amb_local)
2980 if (xp != NULL)
2981 xp->xp_context = EXPAND_UNSUCCESSFUL;
2982 return NULL;
2985 /* The match we found may be followed immediately by a number. Move "p"
2986 * back to point to it. */
2987 if (found || possible)
2988 return p + (matchlen - len);
2989 return p;
2991 #endif
2993 #if defined(FEAT_EVAL) || defined(PROTO)
2994 static struct cmdmod
2996 char *name;
2997 int minlen;
2998 int has_count; /* :123verbose :3tab */
2999 } cmdmods[] = {
3000 {"aboveleft", 3, FALSE},
3001 {"belowright", 3, FALSE},
3002 {"botright", 2, FALSE},
3003 {"browse", 3, FALSE},
3004 {"confirm", 4, FALSE},
3005 {"hide", 3, FALSE},
3006 {"keepalt", 5, FALSE},
3007 {"keepjumps", 5, FALSE},
3008 {"keepmarks", 3, FALSE},
3009 {"leftabove", 5, FALSE},
3010 {"lockmarks", 3, FALSE},
3011 {"noautocmd", 3, FALSE},
3012 {"rightbelow", 6, FALSE},
3013 {"sandbox", 3, FALSE},
3014 {"silent", 3, FALSE},
3015 {"tab", 3, TRUE},
3016 {"topleft", 2, FALSE},
3017 {"unsilent", 3, FALSE},
3018 {"verbose", 4, TRUE},
3019 {"vertical", 4, FALSE},
3023 * Return length of a command modifier (including optional count).
3024 * Return zero when it's not a modifier.
3027 modifier_len(cmd)
3028 char_u *cmd;
3030 int i, j;
3031 char_u *p = cmd;
3033 if (VIM_ISDIGIT(*cmd))
3034 p = skipwhite(skipdigits(cmd));
3035 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3037 for (j = 0; p[j] != NUL; ++j)
3038 if (p[j] != cmdmods[i].name[j])
3039 break;
3040 if (!isalpha(p[j]) && j >= cmdmods[i].minlen
3041 && (p == cmd || cmdmods[i].has_count))
3042 return j + (int)(p - cmd);
3044 return 0;
3048 * Return > 0 if an Ex command "name" exists.
3049 * Return 2 if there is an exact match.
3050 * Return 3 if there is an ambiguous match.
3053 cmd_exists(name)
3054 char_u *name;
3056 exarg_T ea;
3057 int full = FALSE;
3058 int i;
3059 int j;
3060 char_u *p;
3062 /* Check command modifiers. */
3063 for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i)
3065 for (j = 0; name[j] != NUL; ++j)
3066 if (name[j] != cmdmods[i].name[j])
3067 break;
3068 if (name[j] == NUL && j >= cmdmods[i].minlen)
3069 return (cmdmods[i].name[j] == NUL ? 2 : 1);
3072 /* Check built-in commands and user defined commands.
3073 * For ":2match" and ":3match" we need to skip the number. */
3074 ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3075 ea.cmdidx = (cmdidx_T)0;
3076 p = find_command(&ea, &full);
3077 if (p == NULL)
3078 return 3;
3079 if (vim_isdigit(*name) && ea.cmdidx != CMD_match)
3080 return 0;
3081 if (*skipwhite(p) != NUL)
3082 return 0; /* trailing garbage */
3083 return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
3085 #endif
3088 * This is all pretty much copied from do_one_cmd(), with all the extra stuff
3089 * we don't need/want deleted. Maybe this could be done better if we didn't
3090 * repeat all this stuff. The only problem is that they may not stay
3091 * perfectly compatible with each other, but then the command line syntax
3092 * probably won't change that much -- webb.
3094 char_u *
3095 set_one_cmd_context(xp, buff)
3096 expand_T *xp;
3097 char_u *buff; /* buffer for command string */
3099 char_u *p;
3100 char_u *cmd, *arg;
3101 int len = 0;
3102 exarg_T ea;
3103 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3104 int compl = EXPAND_NOTHING;
3105 #endif
3106 #ifdef FEAT_CMDL_COMPL
3107 int delim;
3108 #endif
3109 int forceit = FALSE;
3110 int usefilter = FALSE; /* filter instead of file name */
3112 ExpandInit(xp);
3113 xp->xp_pattern = buff;
3114 xp->xp_context = EXPAND_COMMANDS; /* Default until we get past command */
3115 ea.argt = 0;
3118 * 2. skip comment lines and leading space, colons or bars
3120 for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
3122 xp->xp_pattern = cmd;
3124 if (*cmd == NUL)
3125 return NULL;
3126 if (*cmd == '"') /* ignore comment lines */
3128 xp->xp_context = EXPAND_NOTHING;
3129 return NULL;
3133 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
3135 cmd = skip_range(cmd, &xp->xp_context);
3138 * 4. parse command
3140 xp->xp_pattern = cmd;
3141 if (*cmd == NUL)
3142 return NULL;
3143 if (*cmd == '"')
3145 xp->xp_context = EXPAND_NOTHING;
3146 return NULL;
3149 if (*cmd == '|' || *cmd == '\n')
3150 return cmd + 1; /* There's another command */
3153 * Isolate the command and search for it in the command table.
3154 * Exceptions:
3155 * - the 'k' command can directly be followed by any character, but
3156 * do accept "keepmarks", "keepalt" and "keepjumps".
3157 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3159 if (*cmd == 'k' && cmd[1] != 'e')
3161 ea.cmdidx = CMD_k;
3162 p = cmd + 1;
3164 else
3166 p = cmd;
3167 while (ASCII_ISALPHA(*p) || *p == '*') /* Allow * wild card */
3168 ++p;
3169 /* check for non-alpha command */
3170 if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3171 ++p;
3172 len = (int)(p - cmd);
3174 if (len == 0)
3176 xp->xp_context = EXPAND_UNSUCCESSFUL;
3177 return NULL;
3179 for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE;
3180 ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1))
3181 if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd,
3182 (size_t)len) == 0)
3183 break;
3185 #ifdef FEAT_USR_CMDS
3186 if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3187 while (ASCII_ISALNUM(*p) || *p == '*') /* Allow * wild card */
3188 ++p;
3189 #endif
3193 * If the cursor is touching the command, and it ends in an alpha-numeric
3194 * character, complete the command name.
3196 if (*p == NUL && ASCII_ISALNUM(p[-1]))
3197 return NULL;
3199 if (ea.cmdidx == CMD_SIZE)
3201 if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
3203 ea.cmdidx = CMD_substitute;
3204 p = cmd + 1;
3206 #ifdef FEAT_USR_CMDS
3207 else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3209 ea.cmd = cmd;
3210 p = find_ucmd(&ea, p, NULL, xp,
3211 # if defined(FEAT_CMDL_COMPL)
3212 &compl
3213 # else
3214 NULL
3215 # endif
3217 if (p == NULL)
3218 ea.cmdidx = CMD_SIZE; /* ambiguous user command */
3220 #endif
3222 if (ea.cmdidx == CMD_SIZE)
3224 /* Not still touching the command and it was an illegal one */
3225 xp->xp_context = EXPAND_UNSUCCESSFUL;
3226 return NULL;
3229 xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3231 if (*p == '!') /* forced commands */
3233 forceit = TRUE;
3234 ++p;
3238 * 5. parse arguments
3240 #ifdef FEAT_USR_CMDS
3241 if (!USER_CMDIDX(ea.cmdidx))
3242 #endif
3243 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
3245 arg = skipwhite(p);
3247 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
3249 if (*arg == '>') /* append */
3251 if (*++arg == '>')
3252 ++arg;
3253 arg = skipwhite(arg);
3255 else if (*arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
3257 ++arg;
3258 usefilter = TRUE;
3262 if (ea.cmdidx == CMD_read)
3264 usefilter = forceit; /* :r! filter if forced */
3265 if (*arg == '!') /* :r !filter */
3267 ++arg;
3268 usefilter = TRUE;
3272 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
3274 while (*arg == *cmd) /* allow any number of '>' or '<' */
3275 ++arg;
3276 arg = skipwhite(arg);
3279 /* Does command allow "+command"? */
3280 if ((ea.argt & EDITCMD) && !usefilter && *arg == '+')
3282 /* Check if we're in the +command */
3283 p = arg + 1;
3284 arg = skip_cmd_arg(arg, FALSE);
3286 /* Still touching the command after '+'? */
3287 if (*arg == NUL)
3288 return p;
3290 /* Skip space(s) after +command to get to the real argument */
3291 arg = skipwhite(arg);
3295 * Check for '|' to separate commands and '"' to start comments.
3296 * Don't do this for ":read !cmd" and ":write !cmd".
3298 if ((ea.argt & TRLBAR) && !usefilter)
3300 p = arg;
3301 /* ":redir @" is not the start of a comment */
3302 if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3303 p += 2;
3304 while (*p)
3306 if (*p == Ctrl_V)
3308 if (p[1] != NUL)
3309 ++p;
3311 else if ( (*p == '"' && !(ea.argt & NOTRLCOM))
3312 || *p == '|' || *p == '\n')
3314 if (*(p - 1) != '\\')
3316 if (*p == '|' || *p == '\n')
3317 return p + 1;
3318 return NULL; /* It's a comment */
3321 mb_ptr_adv(p);
3325 /* no arguments allowed */
3326 if (!(ea.argt & EXTRA) && *arg != NUL &&
3327 vim_strchr((char_u *)"|\"", *arg) == NULL)
3328 return NULL;
3330 /* Find start of last argument (argument just before cursor): */
3331 p = buff + STRLEN(buff);
3332 while (p != arg && *p != ' ' && *p != TAB)
3333 p--;
3334 if (*p == ' ' || *p == TAB)
3335 p++;
3336 xp->xp_pattern = p;
3338 if (ea.argt & XFILE)
3340 int c;
3341 int in_quote = FALSE;
3342 char_u *bow = NULL; /* Beginning of word */
3345 * Allow spaces within back-quotes to count as part of the argument
3346 * being expanded.
3348 xp->xp_pattern = skipwhite(arg);
3349 p = xp->xp_pattern;
3350 while (*p != NUL)
3352 #ifdef FEAT_MBYTE
3353 if (has_mbyte)
3354 c = mb_ptr2char(p);
3355 else
3356 #endif
3357 c = *p;
3358 if (c == '\\' && p[1] != NUL)
3359 ++p;
3360 else if (c == '`')
3362 if (!in_quote)
3364 xp->xp_pattern = p;
3365 bow = p + 1;
3367 in_quote = !in_quote;
3369 /* An argument can contain just about everything, except
3370 * characters that end the command and white space. */
3371 else if (c == '|' || c == '\n' || c == '"' || (vim_iswhite(c)
3372 #ifdef SPACE_IN_FILENAME
3373 && (!(ea.argt & NOSPC) || usefilter)
3374 #endif
3377 len = 0; /* avoid getting stuck when space is in 'isfname' */
3378 while (*p != NUL)
3380 #ifdef FEAT_MBYTE
3381 if (has_mbyte)
3382 c = mb_ptr2char(p);
3383 else
3384 #endif
3385 c = *p;
3386 if (c == '`' || vim_isfilec_or_wc(c))
3387 break;
3388 #ifdef FEAT_MBYTE
3389 if (has_mbyte)
3390 len = (*mb_ptr2len)(p);
3391 else
3392 #endif
3393 len = 1;
3394 mb_ptr_adv(p);
3396 if (in_quote)
3397 bow = p;
3398 else
3399 xp->xp_pattern = p;
3400 p -= len;
3402 mb_ptr_adv(p);
3406 * If we are still inside the quotes, and we passed a space, just
3407 * expand from there.
3409 if (bow != NULL && in_quote)
3410 xp->xp_pattern = bow;
3411 xp->xp_context = EXPAND_FILES;
3413 #ifndef BACKSLASH_IN_FILENAME
3414 /* For a shell command more chars need to be escaped. */
3415 if (usefilter || ea.cmdidx == CMD_bang)
3417 xp->xp_shell = TRUE;
3419 /* When still after the command name expand executables. */
3420 if (xp->xp_pattern == skipwhite(arg))
3421 xp->xp_context = EXPAND_SHELLCMD;
3423 #endif
3425 /* Check for environment variable */
3426 if (*xp->xp_pattern == '$'
3427 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3428 || *xp->xp_pattern == '%'
3429 #endif
3432 for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3433 if (!vim_isIDc(*p))
3434 break;
3435 if (*p == NUL)
3437 xp->xp_context = EXPAND_ENV_VARS;
3438 ++xp->xp_pattern;
3439 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3440 /* Avoid that the assignment uses EXPAND_FILES again. */
3441 if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
3442 compl = EXPAND_ENV_VARS;
3443 #endif
3449 * 6. switch on command name
3451 switch (ea.cmdidx)
3453 case CMD_cd:
3454 case CMD_chdir:
3455 case CMD_lcd:
3456 case CMD_lchdir:
3457 if (xp->xp_context == EXPAND_FILES)
3458 xp->xp_context = EXPAND_DIRECTORIES;
3459 break;
3460 case CMD_help:
3461 xp->xp_context = EXPAND_HELP;
3462 xp->xp_pattern = arg;
3463 break;
3465 /* Command modifiers: return the argument.
3466 * Also for commands with an argument that is a command. */
3467 case CMD_aboveleft:
3468 case CMD_argdo:
3469 case CMD_belowright:
3470 case CMD_botright:
3471 case CMD_browse:
3472 case CMD_bufdo:
3473 case CMD_confirm:
3474 case CMD_debug:
3475 case CMD_folddoclosed:
3476 case CMD_folddoopen:
3477 case CMD_hide:
3478 case CMD_keepalt:
3479 case CMD_keepjumps:
3480 case CMD_keepmarks:
3481 case CMD_leftabove:
3482 case CMD_lockmarks:
3483 case CMD_rightbelow:
3484 case CMD_sandbox:
3485 case CMD_silent:
3486 case CMD_tab:
3487 case CMD_topleft:
3488 case CMD_verbose:
3489 case CMD_vertical:
3490 case CMD_windo:
3491 return arg;
3493 #ifdef FEAT_CMDL_COMPL
3494 # ifdef FEAT_SEARCH_EXTRA
3495 case CMD_match:
3496 if (*arg == NUL || !ends_excmd(*arg))
3498 /* also complete "None" */
3499 set_context_in_echohl_cmd(xp, arg);
3500 arg = skipwhite(skiptowhite(arg));
3501 if (*arg != NUL)
3503 xp->xp_context = EXPAND_NOTHING;
3504 arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3507 return find_nextcmd(arg);
3508 # endif
3511 * All completion for the +cmdline_compl feature goes here.
3514 # ifdef FEAT_USR_CMDS
3515 case CMD_command:
3516 /* Check for attributes */
3517 while (*arg == '-')
3519 arg++; /* Skip "-" */
3520 p = skiptowhite(arg);
3521 if (*p == NUL)
3523 /* Cursor is still in the attribute */
3524 p = vim_strchr(arg, '=');
3525 if (p == NULL)
3527 /* No "=", so complete attribute names */
3528 xp->xp_context = EXPAND_USER_CMD_FLAGS;
3529 xp->xp_pattern = arg;
3530 return NULL;
3533 /* For the -complete and -nargs attributes, we complete
3534 * their arguments as well.
3536 if (STRNICMP(arg, "complete", p - arg) == 0)
3538 xp->xp_context = EXPAND_USER_COMPLETE;
3539 xp->xp_pattern = p + 1;
3540 return NULL;
3542 else if (STRNICMP(arg, "nargs", p - arg) == 0)
3544 xp->xp_context = EXPAND_USER_NARGS;
3545 xp->xp_pattern = p + 1;
3546 return NULL;
3548 return NULL;
3550 arg = skipwhite(p);
3553 /* After the attributes comes the new command name */
3554 p = skiptowhite(arg);
3555 if (*p == NUL)
3557 xp->xp_context = EXPAND_USER_COMMANDS;
3558 xp->xp_pattern = arg;
3559 break;
3562 /* And finally comes a normal command */
3563 return skipwhite(p);
3565 case CMD_delcommand:
3566 xp->xp_context = EXPAND_USER_COMMANDS;
3567 xp->xp_pattern = arg;
3568 break;
3569 # endif
3571 case CMD_global:
3572 case CMD_vglobal:
3573 delim = *arg; /* get the delimiter */
3574 if (delim)
3575 ++arg; /* skip delimiter if there is one */
3577 while (arg[0] != NUL && arg[0] != delim)
3579 if (arg[0] == '\\' && arg[1] != NUL)
3580 ++arg;
3581 ++arg;
3583 if (arg[0] != NUL)
3584 return arg + 1;
3585 break;
3586 case CMD_and:
3587 case CMD_substitute:
3588 delim = *arg;
3589 if (delim)
3591 /* skip "from" part */
3592 ++arg;
3593 arg = skip_regexp(arg, delim, p_magic, NULL);
3595 /* skip "to" part */
3596 while (arg[0] != NUL && arg[0] != delim)
3598 if (arg[0] == '\\' && arg[1] != NUL)
3599 ++arg;
3600 ++arg;
3602 if (arg[0] != NUL) /* skip delimiter */
3603 ++arg;
3604 while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
3605 ++arg;
3606 if (arg[0] != NUL)
3607 return arg;
3608 break;
3609 case CMD_isearch:
3610 case CMD_dsearch:
3611 case CMD_ilist:
3612 case CMD_dlist:
3613 case CMD_ijump:
3614 case CMD_psearch:
3615 case CMD_djump:
3616 case CMD_isplit:
3617 case CMD_dsplit:
3618 arg = skipwhite(skipdigits(arg)); /* skip count */
3619 if (*arg == '/') /* Match regexp, not just whole words */
3621 for (++arg; *arg && *arg != '/'; arg++)
3622 if (*arg == '\\' && arg[1] != NUL)
3623 arg++;
3624 if (*arg)
3626 arg = skipwhite(arg + 1);
3628 /* Check for trailing illegal characters */
3629 if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
3630 xp->xp_context = EXPAND_NOTHING;
3631 else
3632 return arg;
3635 break;
3636 #ifdef FEAT_AUTOCMD
3637 case CMD_autocmd:
3638 return set_context_in_autocmd(xp, arg, FALSE);
3640 case CMD_doautocmd:
3641 case CMD_doautoall:
3642 return set_context_in_autocmd(xp, arg, TRUE);
3643 #endif
3644 case CMD_set:
3645 set_context_in_set_cmd(xp, arg, 0);
3646 break;
3647 case CMD_setglobal:
3648 set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
3649 break;
3650 case CMD_setlocal:
3651 set_context_in_set_cmd(xp, arg, OPT_LOCAL);
3652 break;
3653 case CMD_tag:
3654 case CMD_stag:
3655 case CMD_ptag:
3656 case CMD_ltag:
3657 case CMD_tselect:
3658 case CMD_stselect:
3659 case CMD_ptselect:
3660 case CMD_tjump:
3661 case CMD_stjump:
3662 case CMD_ptjump:
3663 if (*p_wop != NUL)
3664 xp->xp_context = EXPAND_TAGS_LISTFILES;
3665 else
3666 xp->xp_context = EXPAND_TAGS;
3667 xp->xp_pattern = arg;
3668 break;
3669 case CMD_augroup:
3670 xp->xp_context = EXPAND_AUGROUP;
3671 xp->xp_pattern = arg;
3672 break;
3673 #ifdef FEAT_SYN_HL
3674 case CMD_syntax:
3675 set_context_in_syntax_cmd(xp, arg);
3676 break;
3677 #endif
3678 #ifdef FEAT_EVAL
3679 case CMD_let:
3680 case CMD_if:
3681 case CMD_elseif:
3682 case CMD_while:
3683 case CMD_for:
3684 case CMD_echo:
3685 case CMD_echon:
3686 case CMD_execute:
3687 case CMD_echomsg:
3688 case CMD_echoerr:
3689 case CMD_call:
3690 case CMD_return:
3691 set_context_for_expression(xp, arg, ea.cmdidx);
3692 break;
3694 case CMD_unlet:
3695 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3696 arg = xp->xp_pattern + 1;
3697 xp->xp_context = EXPAND_USER_VARS;
3698 xp->xp_pattern = arg;
3699 break;
3701 case CMD_function:
3702 case CMD_delfunction:
3703 xp->xp_context = EXPAND_USER_FUNC;
3704 xp->xp_pattern = arg;
3705 break;
3707 case CMD_echohl:
3708 set_context_in_echohl_cmd(xp, arg);
3709 break;
3710 #endif
3711 case CMD_highlight:
3712 set_context_in_highlight_cmd(xp, arg);
3713 break;
3714 #ifdef FEAT_CSCOPE
3715 case CMD_cscope:
3716 case CMD_lcscope:
3717 case CMD_scscope:
3718 set_context_in_cscope_cmd(xp, arg, ea.cmdidx);
3719 break;
3720 #endif
3721 #ifdef FEAT_SIGNS
3722 case CMD_sign:
3723 set_context_in_sign_cmd(xp, arg);
3724 break;
3725 #endif
3726 #ifdef FEAT_LISTCMDS
3727 case CMD_bdelete:
3728 case CMD_bwipeout:
3729 case CMD_bunload:
3730 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3731 arg = xp->xp_pattern + 1;
3732 /*FALLTHROUGH*/
3733 case CMD_buffer:
3734 case CMD_sbuffer:
3735 case CMD_checktime:
3736 xp->xp_context = EXPAND_BUFFERS;
3737 xp->xp_pattern = arg;
3738 break;
3739 #endif
3740 #ifdef FEAT_USR_CMDS
3741 case CMD_USER:
3742 case CMD_USER_BUF:
3743 if (compl != EXPAND_NOTHING)
3745 /* XFILE: file names are handled above */
3746 if (!(ea.argt & XFILE))
3748 # ifdef FEAT_MENU
3749 if (compl == EXPAND_MENUS)
3750 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3751 # endif
3752 if (compl == EXPAND_COMMANDS)
3753 return arg;
3754 if (compl == EXPAND_MAPPINGS)
3755 return set_context_in_map_cmd(xp, (char_u *)"map",
3756 arg, forceit, FALSE, FALSE, CMD_map);
3757 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3758 arg = xp->xp_pattern + 1;
3759 xp->xp_pattern = arg;
3761 xp->xp_context = compl;
3763 break;
3764 #endif
3765 case CMD_map: case CMD_noremap:
3766 case CMD_nmap: case CMD_nnoremap:
3767 case CMD_vmap: case CMD_vnoremap:
3768 case CMD_omap: case CMD_onoremap:
3769 case CMD_imap: case CMD_inoremap:
3770 case CMD_cmap: case CMD_cnoremap:
3771 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3772 FALSE, FALSE, ea.cmdidx);
3773 case CMD_unmap:
3774 case CMD_nunmap:
3775 case CMD_vunmap:
3776 case CMD_ounmap:
3777 case CMD_iunmap:
3778 case CMD_cunmap:
3779 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3780 FALSE, TRUE, ea.cmdidx);
3781 case CMD_abbreviate: case CMD_noreabbrev:
3782 case CMD_cabbrev: case CMD_cnoreabbrev:
3783 case CMD_iabbrev: case CMD_inoreabbrev:
3784 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3785 TRUE, FALSE, ea.cmdidx);
3786 case CMD_unabbreviate:
3787 case CMD_cunabbrev:
3788 case CMD_iunabbrev:
3789 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3790 TRUE, TRUE, ea.cmdidx);
3791 #ifdef FEAT_MENU
3792 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
3793 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
3794 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
3795 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
3796 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
3797 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
3798 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
3799 case CMD_tmenu: case CMD_tunmenu:
3800 case CMD_popup: case CMD_tearoff: case CMD_emenu:
3801 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3802 #endif
3804 case CMD_colorscheme:
3805 xp->xp_context = EXPAND_COLORS;
3806 xp->xp_pattern = arg;
3807 break;
3809 case CMD_compiler:
3810 xp->xp_context = EXPAND_COMPILER;
3811 xp->xp_pattern = arg;
3812 break;
3814 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
3815 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
3816 case CMD_language:
3817 if (*skiptowhite(arg) == NUL)
3819 xp->xp_context = EXPAND_LANGUAGE;
3820 xp->xp_pattern = arg;
3822 else
3823 xp->xp_context = EXPAND_NOTHING;
3824 break;
3825 #endif
3826 #if defined(FEAT_PROFILE)
3827 case CMD_profile:
3828 set_context_in_profile_cmd(xp, arg);
3829 break;
3830 #endif
3831 case CMD_behave:
3832 xp->xp_context = EXPAND_BEHAVE;
3833 break;
3835 #endif /* FEAT_CMDL_COMPL */
3837 default:
3838 break;
3840 return NULL;
3844 * skip a range specifier of the form: addr [,addr] [;addr] ..
3846 * Backslashed delimiters after / or ? will be skipped, and commands will
3847 * not be expanded between /'s and ?'s or after "'".
3849 * Also skip white space and ":" characters.
3850 * Returns the "cmd" pointer advanced to beyond the range.
3852 char_u *
3853 skip_range(cmd, ctx)
3854 char_u *cmd;
3855 int *ctx; /* pointer to xp_context or NULL */
3857 unsigned delim;
3859 while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;", *cmd) != NULL)
3861 if (*cmd == '\'')
3863 if (*++cmd == NUL && ctx != NULL)
3864 *ctx = EXPAND_NOTHING;
3866 else if (*cmd == '/' || *cmd == '?')
3868 delim = *cmd++;
3869 while (*cmd != NUL && *cmd != delim)
3870 if (*cmd++ == '\\' && *cmd != NUL)
3871 ++cmd;
3872 if (*cmd == NUL && ctx != NULL)
3873 *ctx = EXPAND_NOTHING;
3875 if (*cmd != NUL)
3876 ++cmd;
3879 /* Skip ":" and white space. */
3880 while (*cmd == ':')
3881 cmd = skipwhite(cmd + 1);
3883 return cmd;
3887 * get a single EX address
3889 * Set ptr to the next character after the part that was interpreted.
3890 * Set ptr to NULL when an error is encountered.
3892 * Return MAXLNUM when no Ex address was found.
3894 static linenr_T
3895 get_address(ptr, skip, to_other_file)
3896 char_u **ptr;
3897 int skip; /* only skip the address, don't use it */
3898 int to_other_file; /* flag: may jump to other file */
3900 int c;
3901 int i;
3902 long n;
3903 char_u *cmd;
3904 pos_T pos;
3905 pos_T *fp;
3906 linenr_T lnum;
3908 cmd = skipwhite(*ptr);
3909 lnum = MAXLNUM;
3912 switch (*cmd)
3914 case '.': /* '.' - Cursor position */
3915 ++cmd;
3916 lnum = curwin->w_cursor.lnum;
3917 break;
3919 case '$': /* '$' - last line */
3920 ++cmd;
3921 lnum = curbuf->b_ml.ml_line_count;
3922 break;
3924 case '\'': /* ''' - mark */
3925 if (*++cmd == NUL)
3927 cmd = NULL;
3928 goto error;
3930 if (skip)
3931 ++cmd;
3932 else
3934 /* Only accept a mark in another file when it is
3935 * used by itself: ":'M". */
3936 fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
3937 ++cmd;
3938 if (fp == (pos_T *)-1)
3939 /* Jumped to another file. */
3940 lnum = curwin->w_cursor.lnum;
3941 else
3943 if (check_mark(fp) == FAIL)
3945 cmd = NULL;
3946 goto error;
3948 lnum = fp->lnum;
3951 break;
3953 case '/':
3954 case '?': /* '/' or '?' - search */
3955 c = *cmd++;
3956 if (skip) /* skip "/pat/" */
3958 cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
3959 if (*cmd == c)
3960 ++cmd;
3962 else
3964 pos = curwin->w_cursor; /* save curwin->w_cursor */
3966 * When '/' or '?' follows another address, start
3967 * from there.
3969 if (lnum != MAXLNUM)
3970 curwin->w_cursor.lnum = lnum;
3972 * Start a forward search at the end of the line.
3973 * Start a backward search at the start of the line.
3974 * This makes sure we never match in the current
3975 * line, and can match anywhere in the
3976 * next/previous line.
3978 if (c == '/')
3979 curwin->w_cursor.col = MAXCOL;
3980 else
3981 curwin->w_cursor.col = 0;
3982 searchcmdlen = 0;
3983 if (!do_search(NULL, c, cmd, 1L,
3984 SEARCH_HIS | SEARCH_MSG, NULL))
3986 curwin->w_cursor = pos;
3987 cmd = NULL;
3988 goto error;
3990 lnum = curwin->w_cursor.lnum;
3991 curwin->w_cursor = pos;
3992 /* adjust command string pointer */
3993 cmd += searchcmdlen;
3995 break;
3997 case '\\': /* "\?", "\/" or "\&", repeat search */
3998 ++cmd;
3999 if (*cmd == '&')
4000 i = RE_SUBST;
4001 else if (*cmd == '?' || *cmd == '/')
4002 i = RE_SEARCH;
4003 else
4005 EMSG(_(e_backslash));
4006 cmd = NULL;
4007 goto error;
4010 if (!skip)
4013 * When search follows another address, start from
4014 * there.
4016 if (lnum != MAXLNUM)
4017 pos.lnum = lnum;
4018 else
4019 pos.lnum = curwin->w_cursor.lnum;
4022 * Start the search just like for the above
4023 * do_search().
4025 if (*cmd != '?')
4026 pos.col = MAXCOL;
4027 else
4028 pos.col = 0;
4029 if (searchit(curwin, curbuf, &pos,
4030 *cmd == '?' ? BACKWARD : FORWARD,
4031 (char_u *)"", 1L, SEARCH_MSG,
4032 i, (linenr_T)0, NULL) != FAIL)
4033 lnum = pos.lnum;
4034 else
4036 cmd = NULL;
4037 goto error;
4040 ++cmd;
4041 break;
4043 default:
4044 if (VIM_ISDIGIT(*cmd)) /* absolute line number */
4045 lnum = getdigits(&cmd);
4048 for (;;)
4050 cmd = skipwhite(cmd);
4051 if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
4052 break;
4054 if (lnum == MAXLNUM)
4055 lnum = curwin->w_cursor.lnum; /* "+1" is same as ".+1" */
4056 if (VIM_ISDIGIT(*cmd))
4057 i = '+'; /* "number" is same as "+number" */
4058 else
4059 i = *cmd++;
4060 if (!VIM_ISDIGIT(*cmd)) /* '+' is '+1', but '+0' is not '+1' */
4061 n = 1;
4062 else
4063 n = getdigits(&cmd);
4064 if (i == '-')
4065 lnum -= n;
4066 else
4067 lnum += n;
4069 } while (*cmd == '/' || *cmd == '?');
4071 error:
4072 *ptr = cmd;
4073 return lnum;
4077 * Get flags from an Ex command argument.
4079 static void
4080 get_flags(eap)
4081 exarg_T *eap;
4083 while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL)
4085 if (*eap->arg == 'l')
4086 eap->flags |= EXFLAG_LIST;
4087 else if (*eap->arg == 'p')
4088 eap->flags |= EXFLAG_PRINT;
4089 else
4090 eap->flags |= EXFLAG_NR;
4091 eap->arg = skipwhite(eap->arg + 1);
4096 * Function called for command which is Not Implemented. NI!
4098 void
4099 ex_ni(eap)
4100 exarg_T *eap;
4102 if (!eap->skip)
4103 eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
4106 #ifdef HAVE_EX_SCRIPT_NI
4108 * Function called for script command which is Not Implemented. NI!
4109 * Skips over ":perl <<EOF" constructs.
4111 static void
4112 ex_script_ni(eap)
4113 exarg_T *eap;
4115 if (!eap->skip)
4116 ex_ni(eap);
4117 else
4118 vim_free(script_get(eap, eap->arg));
4120 #endif
4123 * Check range in Ex command for validity.
4124 * Return NULL when valid, error message when invalid.
4126 static char_u *
4127 invalid_range(eap)
4128 exarg_T *eap;
4130 if ( eap->line1 < 0
4131 || eap->line2 < 0
4132 || eap->line1 > eap->line2
4133 || ((eap->argt & RANGE)
4134 && !(eap->argt & NOTADR)
4135 && eap->line2 > curbuf->b_ml.ml_line_count
4136 #ifdef FEAT_DIFF
4137 + (eap->cmdidx == CMD_diffget)
4138 #endif
4140 return (char_u *)_(e_invrange);
4141 return NULL;
4145 * Correct the range for zero line number, if required.
4147 static void
4148 correct_range(eap)
4149 exarg_T *eap;
4151 if (!(eap->argt & ZEROR)) /* zero in range not allowed */
4153 if (eap->line1 == 0)
4154 eap->line1 = 1;
4155 if (eap->line2 == 0)
4156 eap->line2 = 1;
4160 #ifdef FEAT_QUICKFIX
4161 static char_u *skip_grep_pat __ARGS((exarg_T *eap));
4164 * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
4165 * pattern. Otherwise return eap->arg.
4167 static char_u *
4168 skip_grep_pat(eap)
4169 exarg_T *eap;
4171 char_u *p = eap->arg;
4173 if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
4174 || eap->cmdidx == CMD_vimgrepadd
4175 || eap->cmdidx == CMD_lvimgrepadd
4176 || grep_internal(eap->cmdidx)))
4178 p = skip_vimgrep_pat(p, NULL, NULL);
4179 if (p == NULL)
4180 p = eap->arg;
4182 return p;
4186 * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
4187 * in the command line, so that things like % get expanded.
4189 static char_u *
4190 replace_makeprg(eap, p, cmdlinep)
4191 exarg_T *eap;
4192 char_u *p;
4193 char_u **cmdlinep;
4195 char_u *new_cmdline;
4196 char_u *program;
4197 char_u *pos;
4198 char_u *ptr;
4199 int len;
4200 int i;
4203 * Don't do it when ":vimgrep" is used for ":grep".
4205 if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake
4206 || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4207 || eap->cmdidx == CMD_grepadd
4208 || eap->cmdidx == CMD_lgrepadd)
4209 && !grep_internal(eap->cmdidx))
4211 if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4212 || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd)
4214 if (*curbuf->b_p_gp == NUL)
4215 program = p_gp;
4216 else
4217 program = curbuf->b_p_gp;
4219 else
4221 if (*curbuf->b_p_mp == NUL)
4222 program = p_mp;
4223 else
4224 program = curbuf->b_p_mp;
4227 p = skipwhite(p);
4229 if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4231 /* replace $* by given arguments */
4232 i = 1;
4233 while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
4234 ++i;
4235 len = (int)STRLEN(p);
4236 new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
4237 if (new_cmdline == NULL)
4238 return NULL; /* out of memory */
4239 ptr = new_cmdline;
4240 while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4242 i = (int)(pos - program);
4243 STRNCPY(ptr, program, i);
4244 STRCPY(ptr += i, p);
4245 ptr += len;
4246 program = pos + 2;
4248 STRCPY(ptr, program);
4250 else
4252 new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
4253 if (new_cmdline == NULL)
4254 return NULL; /* out of memory */
4255 STRCPY(new_cmdline, program);
4256 STRCAT(new_cmdline, " ");
4257 STRCAT(new_cmdline, p);
4259 msg_make(p);
4261 /* 'eap->cmd' is not set here, because it is not used at CMD_make */
4262 vim_free(*cmdlinep);
4263 *cmdlinep = new_cmdline;
4264 p = new_cmdline;
4266 return p;
4268 #endif
4271 * Expand file name in Ex command argument.
4272 * Return FAIL for failure, OK otherwise.
4275 expand_filename(eap, cmdlinep, errormsgp)
4276 exarg_T *eap;
4277 char_u **cmdlinep;
4278 char_u **errormsgp;
4280 int has_wildcards; /* need to expand wildcards */
4281 char_u *repl;
4282 int srclen;
4283 char_u *p;
4284 int n;
4285 int escaped;
4287 #ifdef FEAT_QUICKFIX
4288 /* Skip a regexp pattern for ":vimgrep[add] pat file..." */
4289 p = skip_grep_pat(eap);
4290 #else
4291 p = eap->arg;
4292 #endif
4295 * Decide to expand wildcards *before* replacing '%', '#', etc. If
4296 * the file name contains a wildcard it should not cause expanding.
4297 * (it will be expanded anyway if there is a wildcard before replacing).
4299 has_wildcards = mch_has_wildcard(p);
4300 while (*p != NUL)
4302 #ifdef FEAT_EVAL
4303 /* Skip over `=expr`, wildcards in it are not expanded. */
4304 if (p[0] == '`' && p[1] == '=')
4306 p += 2;
4307 (void)skip_expr(&p);
4308 if (*p == '`')
4309 ++p;
4310 continue;
4312 #endif
4314 * Quick check if this cannot be the start of a special string.
4315 * Also removes backslash before '%', '#' and '<'.
4317 if (vim_strchr((char_u *)"%#<", *p) == NULL)
4319 ++p;
4320 continue;
4324 * Try to find a match at this position.
4326 repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
4327 errormsgp, &escaped);
4328 if (*errormsgp != NULL) /* error detected */
4329 return FAIL;
4330 if (repl == NULL) /* no match found */
4332 p += srclen;
4333 continue;
4336 /* Wildcards won't be expanded below, the replacement is taken
4337 * literally. But do expand "~/file", "~user/file" and "$HOME/file". */
4338 if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
4340 char_u *l = repl;
4342 repl = expand_env_save(repl);
4343 vim_free(l);
4346 /* Need to escape white space et al. with a backslash.
4347 * Don't do this for:
4348 * - replacement that already has been escaped: "##"
4349 * - shell commands (may have to use quotes instead).
4350 * - non-unix systems when there is a single argument (spaces don't
4351 * separate arguments then).
4353 if (!eap->usefilter
4354 && !escaped
4355 && eap->cmdidx != CMD_bang
4356 && eap->cmdidx != CMD_make
4357 && eap->cmdidx != CMD_lmake
4358 && eap->cmdidx != CMD_grep
4359 && eap->cmdidx != CMD_lgrep
4360 && eap->cmdidx != CMD_grepadd
4361 && eap->cmdidx != CMD_lgrepadd
4362 #ifndef UNIX
4363 && !(eap->argt & NOSPC)
4364 #endif
4367 char_u *l;
4368 #ifdef BACKSLASH_IN_FILENAME
4369 /* Don't escape a backslash here, because rem_backslash() doesn't
4370 * remove it later. */
4371 static char_u *nobslash = (char_u *)" \t\"|";
4372 # define ESCAPE_CHARS nobslash
4373 #else
4374 # define ESCAPE_CHARS escape_chars
4375 #endif
4377 for (l = repl; *l; ++l)
4378 if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
4380 l = vim_strsave_escaped(repl, ESCAPE_CHARS);
4381 if (l != NULL)
4383 vim_free(repl);
4384 repl = l;
4386 break;
4390 /* For a shell command a '!' must be escaped. */
4391 if ((eap->usefilter || eap->cmdidx == CMD_bang)
4392 && vim_strpbrk(repl, (char_u *)"!&;()<>") != NULL)
4394 char_u *l;
4396 l = vim_strsave_escaped(repl, (char_u *)"!&;()<>");
4397 if (l != NULL)
4399 vim_free(repl);
4400 repl = l;
4401 /* For a sh-like shell escape "!" another time. */
4402 if (strstr((char *)p_sh, "sh") != NULL)
4404 l = vim_strsave_escaped(repl, (char_u *)"!");
4405 if (l != NULL)
4407 vim_free(repl);
4408 repl = l;
4414 p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4415 vim_free(repl);
4416 if (p == NULL)
4417 return FAIL;
4421 * One file argument: Expand wildcards.
4422 * Don't do this with ":r !command" or ":w !command".
4424 if ((eap->argt & NOSPC) && !eap->usefilter)
4427 * May do this twice:
4428 * 1. Replace environment variables.
4429 * 2. Replace any other wildcards, remove backslashes.
4431 for (n = 1; n <= 2; ++n)
4433 if (n == 2)
4435 #ifdef UNIX
4437 * Only for Unix we check for more than one file name.
4438 * For other systems spaces are considered to be part
4439 * of the file name.
4440 * Only check here if there is no wildcard, otherwise
4441 * ExpandOne() will check for errors. This allows
4442 * ":e `ls ve*.c`" on Unix.
4444 if (!has_wildcards)
4445 for (p = eap->arg; *p; ++p)
4447 /* skip escaped characters */
4448 if (p[1] && (*p == '\\' || *p == Ctrl_V))
4449 ++p;
4450 else if (vim_iswhite(*p))
4452 *errormsgp = (char_u *)_("E172: Only one file name allowed");
4453 return FAIL;
4456 #endif
4459 * Halve the number of backslashes (this is Vi compatible).
4460 * For Unix and OS/2, when wildcards are expanded, this is
4461 * done by ExpandOne() below.
4463 #if defined(UNIX) || defined(OS2)
4464 if (!has_wildcards)
4465 #endif
4466 backslash_halve(eap->arg);
4469 if (has_wildcards)
4471 if (n == 1)
4474 * First loop: May expand environment variables. This
4475 * can be done much faster with expand_env() than with
4476 * something else (e.g., calling a shell).
4477 * After expanding environment variables, check again
4478 * if there are still wildcards present.
4480 if (vim_strchr(eap->arg, '$') != NULL
4481 || vim_strchr(eap->arg, '~') != NULL)
4483 expand_env_esc(eap->arg, NameBuff, MAXPATHL,
4484 TRUE, TRUE, NULL);
4485 has_wildcards = mch_has_wildcard(NameBuff);
4486 p = NameBuff;
4488 else
4489 p = NULL;
4491 else /* n == 2 */
4493 expand_T xpc;
4495 ExpandInit(&xpc);
4496 xpc.xp_context = EXPAND_FILES;
4497 p = ExpandOne(&xpc, eap->arg, NULL,
4498 WILD_LIST_NOTFOUND|WILD_ADD_SLASH,
4499 WILD_EXPAND_FREE);
4500 if (p == NULL)
4501 return FAIL;
4503 if (p != NULL)
4505 (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
4506 p, cmdlinep);
4507 if (n == 2) /* p came from ExpandOne() */
4508 vim_free(p);
4513 return OK;
4517 * Replace part of the command line, keeping eap->cmd, eap->arg and
4518 * eap->nextcmd correct.
4519 * "src" points to the part that is to be replaced, of length "srclen".
4520 * "repl" is the replacement string.
4521 * Returns a pointer to the character after the replaced string.
4522 * Returns NULL for failure.
4524 static char_u *
4525 repl_cmdline(eap, src, srclen, repl, cmdlinep)
4526 exarg_T *eap;
4527 char_u *src;
4528 int srclen;
4529 char_u *repl;
4530 char_u **cmdlinep;
4532 int len;
4533 int i;
4534 char_u *new_cmdline;
4537 * The new command line is build in new_cmdline[].
4538 * First allocate it.
4539 * Careful: a "+cmd" argument may have been NUL terminated.
4541 len = (int)STRLEN(repl);
4542 i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
4543 if (eap->nextcmd != NULL)
4544 i += (int)STRLEN(eap->nextcmd);/* add space for next command */
4545 if ((new_cmdline = alloc((unsigned)i)) == NULL)
4546 return NULL; /* out of memory! */
4549 * Copy the stuff before the expanded part.
4550 * Copy the expanded stuff.
4551 * Copy what came after the expanded part.
4552 * Copy the next commands, if there are any.
4554 i = (int)(src - *cmdlinep); /* length of part before match */
4555 mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
4557 mch_memmove(new_cmdline + i, repl, (size_t)len);
4558 i += len; /* remember the end of the string */
4559 STRCPY(new_cmdline + i, src + srclen);
4560 src = new_cmdline + i; /* remember where to continue */
4562 if (eap->nextcmd != NULL) /* append next command */
4564 i = (int)STRLEN(new_cmdline) + 1;
4565 STRCPY(new_cmdline + i, eap->nextcmd);
4566 eap->nextcmd = new_cmdline + i;
4568 eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4569 eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4570 if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
4571 eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4572 vim_free(*cmdlinep);
4573 *cmdlinep = new_cmdline;
4575 return src;
4579 * Check for '|' to separate commands and '"' to start comments.
4581 void
4582 separate_nextcmd(eap)
4583 exarg_T *eap;
4585 char_u *p;
4587 #ifdef FEAT_QUICKFIX
4588 p = skip_grep_pat(eap);
4589 #else
4590 p = eap->arg;
4591 #endif
4593 for ( ; *p; mb_ptr_adv(p))
4595 if (*p == Ctrl_V)
4597 if (eap->argt & (USECTRLV | XFILE))
4598 ++p; /* skip CTRL-V and next char */
4599 else
4600 /* remove CTRL-V and skip next char */
4601 STRMOVE(p, p + 1);
4602 if (*p == NUL) /* stop at NUL after CTRL-V */
4603 break;
4606 #ifdef FEAT_EVAL
4607 /* Skip over `=expr` when wildcards are expanded. */
4608 else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE))
4610 p += 2;
4611 (void)skip_expr(&p);
4613 #endif
4615 /* Check for '"': start of comment or '|': next command */
4616 /* :@" and :*" do not start a comment!
4617 * :redir @" doesn't either. */
4618 else if ((*p == '"' && !(eap->argt & NOTRLCOM)
4619 && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
4620 || p != eap->arg)
4621 && (eap->cmdidx != CMD_redir
4622 || p != eap->arg + 1 || p[-1] != '@'))
4623 || *p == '|' || *p == '\n')
4626 * We remove the '\' before the '|', unless USECTRLV is used
4627 * AND 'b' is present in 'cpoptions'.
4629 if ((vim_strchr(p_cpo, CPO_BAR) == NULL
4630 || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
4632 STRMOVE(p - 1, p); /* remove the '\' */
4633 --p;
4635 else
4637 eap->nextcmd = check_nextcmd(p);
4638 *p = NUL;
4639 break;
4644 if (!(eap->argt & NOTRLCOM)) /* remove trailing spaces */
4645 del_trailing_spaces(eap->arg);
4649 * get + command from ex argument
4651 static char_u *
4652 getargcmd(argp)
4653 char_u **argp;
4655 char_u *arg = *argp;
4656 char_u *command = NULL;
4658 if (*arg == '+') /* +[command] */
4660 ++arg;
4661 if (vim_isspace(*arg))
4662 command = dollar_command;
4663 else
4665 command = arg;
4666 arg = skip_cmd_arg(command, TRUE);
4667 if (*arg != NUL)
4668 *arg++ = NUL; /* terminate command with NUL */
4671 arg = skipwhite(arg); /* skip over spaces */
4672 *argp = arg;
4674 return command;
4678 * Find end of "+command" argument. Skip over "\ " and "\\".
4680 static char_u *
4681 skip_cmd_arg(p, rembs)
4682 char_u *p;
4683 int rembs; /* TRUE to halve the number of backslashes */
4685 while (*p && !vim_isspace(*p))
4687 if (*p == '\\' && p[1] != NUL)
4689 if (rembs)
4690 STRMOVE(p, p + 1);
4691 else
4692 ++p;
4694 mb_ptr_adv(p);
4696 return p;
4700 * Get "++opt=arg" argument.
4701 * Return FAIL or OK.
4703 static int
4704 getargopt(eap)
4705 exarg_T *eap;
4707 char_u *arg = eap->arg + 2;
4708 int *pp = NULL;
4709 #ifdef FEAT_MBYTE
4710 int bad_char_idx;
4711 char_u *p;
4712 #endif
4714 /* ":edit ++[no]bin[ary] file" */
4715 if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4717 if (*arg == 'n')
4719 arg += 2;
4720 eap->force_bin = FORCE_NOBIN;
4722 else
4723 eap->force_bin = FORCE_BIN;
4724 if (!checkforcmd(&arg, "binary", 3))
4725 return FAIL;
4726 eap->arg = skipwhite(arg);
4727 return OK;
4730 /* ":read ++edit file" */
4731 if (STRNCMP(arg, "edit", 4) == 0)
4733 eap->read_edit = TRUE;
4734 eap->arg = skipwhite(arg + 4);
4735 return OK;
4738 if (STRNCMP(arg, "ff", 2) == 0)
4740 arg += 2;
4741 pp = &eap->force_ff;
4743 else if (STRNCMP(arg, "fileformat", 10) == 0)
4745 arg += 10;
4746 pp = &eap->force_ff;
4748 #ifdef FEAT_MBYTE
4749 else if (STRNCMP(arg, "enc", 3) == 0)
4751 arg += 3;
4752 pp = &eap->force_enc;
4754 else if (STRNCMP(arg, "encoding", 8) == 0)
4756 arg += 8;
4757 pp = &eap->force_enc;
4759 else if (STRNCMP(arg, "bad", 3) == 0)
4761 arg += 3;
4762 pp = &bad_char_idx;
4764 #endif
4766 if (pp == NULL || *arg != '=')
4767 return FAIL;
4769 ++arg;
4770 *pp = (int)(arg - eap->cmd);
4771 arg = skip_cmd_arg(arg, FALSE);
4772 eap->arg = skipwhite(arg);
4773 *arg = NUL;
4775 #ifdef FEAT_MBYTE
4776 if (pp == &eap->force_ff)
4778 #endif
4779 if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4780 return FAIL;
4781 #ifdef FEAT_MBYTE
4783 else if (pp == &eap->force_enc)
4785 /* Make 'fileencoding' lower case. */
4786 for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4787 *p = TOLOWER_ASC(*p);
4789 else
4791 /* Check ++bad= argument. Must be a single-byte character, "keep" or
4792 * "drop". */
4793 p = eap->cmd + bad_char_idx;
4794 if (STRICMP(p, "keep") == 0)
4795 eap->bad_char = BAD_KEEP;
4796 else if (STRICMP(p, "drop") == 0)
4797 eap->bad_char = BAD_DROP;
4798 else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
4799 eap->bad_char = *p;
4800 else
4801 return FAIL;
4803 #endif
4805 return OK;
4809 * ":abbreviate" and friends.
4811 static void
4812 ex_abbreviate(eap)
4813 exarg_T *eap;
4815 do_exmap(eap, TRUE); /* almost the same as mapping */
4819 * ":map" and friends.
4821 static void
4822 ex_map(eap)
4823 exarg_T *eap;
4826 * If we are sourcing .exrc or .vimrc in current directory we
4827 * print the mappings for security reasons.
4829 if (secure)
4831 secure = 2;
4832 msg_outtrans(eap->cmd);
4833 msg_putchar('\n');
4835 do_exmap(eap, FALSE);
4839 * ":unmap" and friends.
4841 static void
4842 ex_unmap(eap)
4843 exarg_T *eap;
4845 do_exmap(eap, FALSE);
4849 * ":mapclear" and friends.
4851 static void
4852 ex_mapclear(eap)
4853 exarg_T *eap;
4855 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4859 * ":abclear" and friends.
4861 static void
4862 ex_abclear(eap)
4863 exarg_T *eap;
4865 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4868 #ifdef FEAT_AUTOCMD
4869 static void
4870 ex_autocmd(eap)
4871 exarg_T *eap;
4874 * Disallow auto commands from .exrc and .vimrc in current
4875 * directory for security reasons.
4877 if (secure)
4879 secure = 2;
4880 eap->errmsg = e_curdir;
4882 else if (eap->cmdidx == CMD_autocmd)
4883 do_autocmd(eap->arg, eap->forceit);
4884 else
4885 do_augroup(eap->arg, eap->forceit);
4889 * ":doautocmd": Apply the automatic commands to the current buffer.
4891 static void
4892 ex_doautocmd(eap)
4893 exarg_T *eap;
4895 (void)do_doautocmd(eap->arg, TRUE);
4896 do_modelines(0);
4898 #endif
4900 #ifdef FEAT_LISTCMDS
4902 * :[N]bunload[!] [N] [bufname] unload buffer
4903 * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4904 * :[N]bwipeout[!] [N] [bufname] delete buffer really
4906 static void
4907 ex_bunload(eap)
4908 exarg_T *eap;
4910 eap->errmsg = do_bufdel(
4911 eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4912 : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4913 : DOBUF_UNLOAD, eap->arg,
4914 eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4918 * :[N]buffer [N] to buffer N
4919 * :[N]sbuffer [N] to buffer N
4921 static void
4922 ex_buffer(eap)
4923 exarg_T *eap;
4925 if (*eap->arg)
4926 eap->errmsg = e_trailing;
4927 else
4929 if (eap->addr_count == 0) /* default is current buffer */
4930 goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4931 else
4932 goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4937 * :[N]bmodified [N] to next mod. buffer
4938 * :[N]sbmodified [N] to next mod. buffer
4940 static void
4941 ex_bmodified(eap)
4942 exarg_T *eap;
4944 goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4948 * :[N]bnext [N] to next buffer
4949 * :[N]sbnext [N] split and to next buffer
4951 static void
4952 ex_bnext(eap)
4953 exarg_T *eap;
4955 goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4959 * :[N]bNext [N] to previous buffer
4960 * :[N]bprevious [N] to previous buffer
4961 * :[N]sbNext [N] split and to previous buffer
4962 * :[N]sbprevious [N] split and to previous buffer
4964 static void
4965 ex_bprevious(eap)
4966 exarg_T *eap;
4968 goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4972 * :brewind to first buffer
4973 * :bfirst to first buffer
4974 * :sbrewind split and to first buffer
4975 * :sbfirst split and to first buffer
4977 static void
4978 ex_brewind(eap)
4979 exarg_T *eap;
4981 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4985 * :blast to last buffer
4986 * :sblast split and to last buffer
4988 static void
4989 ex_blast(eap)
4990 exarg_T *eap;
4992 goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4994 #endif
4997 ends_excmd(c)
4998 int c;
5000 return (c == NUL || c == '|' || c == '"' || c == '\n');
5003 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
5004 || defined(PROTO)
5006 * Return the next command, after the first '|' or '\n'.
5007 * Return NULL if not found.
5009 char_u *
5010 find_nextcmd(p)
5011 char_u *p;
5013 while (*p != '|' && *p != '\n')
5015 if (*p == NUL)
5016 return NULL;
5017 ++p;
5019 return (p + 1);
5021 #endif
5024 * Check if *p is a separator between Ex commands.
5025 * Return NULL if it isn't, (p + 1) if it is.
5027 char_u *
5028 check_nextcmd(p)
5029 char_u *p;
5031 p = skipwhite(p);
5032 if (*p == '|' || *p == '\n')
5033 return (p + 1);
5034 else
5035 return NULL;
5039 * - if there are more files to edit
5040 * - and this is the last window
5041 * - and forceit not used
5042 * - and not repeated twice on a row
5043 * return FAIL and give error message if 'message' TRUE
5044 * return OK otherwise
5046 static int
5047 check_more(message, forceit)
5048 int message; /* when FALSE check only, no messages */
5049 int forceit;
5051 int n = ARGCOUNT - curwin->w_arg_idx - 1;
5053 if (!forceit && only_one_window()
5054 && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5056 if (message)
5058 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5059 if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5061 char_u buff[IOSIZE];
5063 if (n == 1)
5064 STRCPY(buff, _("1 more file to edit. Quit anyway?"));
5065 else
5066 vim_snprintf((char *)buff, IOSIZE,
5067 _("%d more files to edit. Quit anyway?"), n);
5068 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5069 return OK;
5070 return FAIL;
5072 #endif
5073 if (n == 1)
5074 EMSG(_("E173: 1 more file to edit"));
5075 else
5076 EMSGN(_("E173: %ld more files to edit"), n);
5077 quitmore = 2; /* next try to quit is allowed */
5079 return FAIL;
5081 return OK;
5084 #ifdef FEAT_CMDL_COMPL
5086 * Function given to ExpandGeneric() to obtain the list of command names.
5088 char_u *
5089 get_command_name(xp, idx)
5090 expand_T *xp UNUSED;
5091 int idx;
5093 if (idx >= (int)CMD_SIZE)
5094 # ifdef FEAT_USR_CMDS
5095 return get_user_command_name(idx);
5096 # else
5097 return NULL;
5098 # endif
5099 return cmdnames[idx].cmd_name;
5101 #endif
5103 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5104 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));
5105 static void uc_list __ARGS((char_u *name, size_t name_len));
5106 static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
5107 static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp));
5108 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));
5110 static int
5111 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
5112 char_u *name;
5113 size_t name_len;
5114 char_u *rep;
5115 long argt;
5116 long def;
5117 int flags;
5118 int compl;
5119 char_u *compl_arg;
5120 int force;
5122 ucmd_T *cmd = NULL;
5123 char_u *p;
5124 int i;
5125 int cmp = 1;
5126 char_u *rep_buf = NULL;
5127 garray_T *gap;
5129 replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5130 if (rep_buf == NULL)
5132 /* Can't replace termcodes - try using the string as is */
5133 rep_buf = vim_strsave(rep);
5135 /* Give up if out of memory */
5136 if (rep_buf == NULL)
5137 return FAIL;
5140 /* get address of growarray: global or in curbuf */
5141 if (flags & UC_BUFFER)
5143 gap = &curbuf->b_ucmds;
5144 if (gap->ga_itemsize == 0)
5145 ga_init2(gap, (int)sizeof(ucmd_T), 4);
5147 else
5148 gap = &ucmds;
5150 /* Search for the command in the already defined commands. */
5151 for (i = 0; i < gap->ga_len; ++i)
5153 size_t len;
5155 cmd = USER_CMD_GA(gap, i);
5156 len = STRLEN(cmd->uc_name);
5157 cmp = STRNCMP(name, cmd->uc_name, name_len);
5158 if (cmp == 0)
5160 if (name_len < len)
5161 cmp = -1;
5162 else if (name_len > len)
5163 cmp = 1;
5166 if (cmp == 0)
5168 if (!force)
5170 EMSG(_("E174: Command already exists: add ! to replace it"));
5171 goto fail;
5174 vim_free(cmd->uc_rep);
5175 cmd->uc_rep = NULL;
5176 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5177 vim_free(cmd->uc_compl_arg);
5178 cmd->uc_compl_arg = NULL;
5179 #endif
5180 break;
5183 /* Stop as soon as we pass the name to add */
5184 if (cmp < 0)
5185 break;
5188 /* Extend the array unless we're replacing an existing command */
5189 if (cmp != 0)
5191 if (ga_grow(gap, 1) != OK)
5192 goto fail;
5193 if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5194 goto fail;
5196 cmd = USER_CMD_GA(gap, i);
5197 mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5199 ++gap->ga_len;
5201 cmd->uc_name = p;
5204 cmd->uc_rep = rep_buf;
5205 cmd->uc_argt = argt;
5206 cmd->uc_def = def;
5207 cmd->uc_compl = compl;
5208 #ifdef FEAT_EVAL
5209 cmd->uc_scriptID = current_SID;
5210 # ifdef FEAT_CMDL_COMPL
5211 cmd->uc_compl_arg = compl_arg;
5212 # endif
5213 #endif
5215 return OK;
5217 fail:
5218 vim_free(rep_buf);
5219 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5220 vim_free(compl_arg);
5221 #endif
5222 return FAIL;
5226 * List of names for completion for ":command" with the EXPAND_ flag.
5227 * Must be alphabetical for completion.
5229 static struct
5231 int expand;
5232 char *name;
5233 } command_complete[] =
5235 {EXPAND_AUGROUP, "augroup"},
5236 {EXPAND_BUFFERS, "buffer"},
5237 {EXPAND_COMMANDS, "command"},
5238 #if defined(FEAT_CSCOPE)
5239 {EXPAND_CSCOPE, "cscope"},
5240 #endif
5241 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5242 {EXPAND_USER_DEFINED, "custom"},
5243 {EXPAND_USER_LIST, "customlist"},
5244 #endif
5245 {EXPAND_DIRECTORIES, "dir"},
5246 {EXPAND_ENV_VARS, "environment"},
5247 {EXPAND_EVENTS, "event"},
5248 {EXPAND_EXPRESSION, "expression"},
5249 {EXPAND_FILES, "file"},
5250 {EXPAND_FUNCTIONS, "function"},
5251 {EXPAND_HELP, "help"},
5252 {EXPAND_HIGHLIGHT, "highlight"},
5253 {EXPAND_MAPPINGS, "mapping"},
5254 {EXPAND_MENUS, "menu"},
5255 {EXPAND_SETTINGS, "option"},
5256 {EXPAND_SHELLCMD, "shellcmd"},
5257 #if defined(FEAT_SIGNS)
5258 {EXPAND_SIGN, "sign"},
5259 #endif
5260 {EXPAND_TAGS, "tag"},
5261 {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5262 {EXPAND_USER_VARS, "var"},
5263 {0, NULL}
5266 static void
5267 uc_list(name, name_len)
5268 char_u *name;
5269 size_t name_len;
5271 int i, j;
5272 int found = FALSE;
5273 ucmd_T *cmd;
5274 int len;
5275 long a;
5276 garray_T *gap;
5278 gap = &curbuf->b_ucmds;
5279 for (;;)
5281 for (i = 0; i < gap->ga_len; ++i)
5283 cmd = USER_CMD_GA(gap, i);
5284 a = (long)cmd->uc_argt;
5286 /* Skip commands which don't match the requested prefix */
5287 if (STRNCMP(name, cmd->uc_name, name_len) != 0)
5288 continue;
5290 /* Put out the title first time */
5291 if (!found)
5292 MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition"));
5293 found = TRUE;
5294 msg_putchar('\n');
5295 if (got_int)
5296 break;
5298 /* Special cases */
5299 msg_putchar(a & BANG ? '!' : ' ');
5300 msg_putchar(a & REGSTR ? '"' : ' ');
5301 msg_putchar(gap != &ucmds ? 'b' : ' ');
5302 msg_putchar(' ');
5304 msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
5305 len = (int)STRLEN(cmd->uc_name) + 4;
5307 do {
5308 msg_putchar(' ');
5309 ++len;
5310 } while (len < 16);
5312 len = 0;
5314 /* Arguments */
5315 switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
5317 case 0: IObuff[len++] = '0'; break;
5318 case (EXTRA): IObuff[len++] = '*'; break;
5319 case (EXTRA|NOSPC): IObuff[len++] = '?'; break;
5320 case (EXTRA|NEEDARG): IObuff[len++] = '+'; break;
5321 case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
5324 do {
5325 IObuff[len++] = ' ';
5326 } while (len < 5);
5328 /* Range */
5329 if (a & (RANGE|COUNT))
5331 if (a & COUNT)
5333 /* -count=N */
5334 sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
5335 len += (int)STRLEN(IObuff + len);
5337 else if (a & DFLALL)
5338 IObuff[len++] = '%';
5339 else if (cmd->uc_def >= 0)
5341 /* -range=N */
5342 sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
5343 len += (int)STRLEN(IObuff + len);
5345 else
5346 IObuff[len++] = '.';
5349 do {
5350 IObuff[len++] = ' ';
5351 } while (len < 11);
5353 /* Completion */
5354 for (j = 0; command_complete[j].expand != 0; ++j)
5355 if (command_complete[j].expand == cmd->uc_compl)
5357 STRCPY(IObuff + len, command_complete[j].name);
5358 len += (int)STRLEN(IObuff + len);
5359 break;
5362 do {
5363 IObuff[len++] = ' ';
5364 } while (len < 21);
5366 IObuff[len] = '\0';
5367 msg_outtrans(IObuff);
5369 msg_outtrans_special(cmd->uc_rep, FALSE);
5370 #ifdef FEAT_EVAL
5371 if (p_verbose > 0)
5372 last_set_msg(cmd->uc_scriptID);
5373 #endif
5374 out_flush();
5375 ui_breakcheck();
5376 if (got_int)
5377 break;
5379 if (gap == &ucmds || i < gap->ga_len)
5380 break;
5381 gap = &ucmds;
5384 if (!found)
5385 MSG(_("No user-defined commands found"));
5388 static char_u *
5389 uc_fun_cmd()
5391 static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
5392 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
5393 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
5394 0xb9, 0x7f, 0};
5395 int i;
5397 for (i = 0; fcmd[i]; ++i)
5398 IObuff[i] = fcmd[i] - 0x40;
5399 IObuff[i] = 0;
5400 return IObuff;
5403 static int
5404 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
5405 char_u *attr;
5406 size_t len;
5407 long *argt;
5408 long *def;
5409 int *flags;
5410 int *compl;
5411 char_u **compl_arg;
5413 char_u *p;
5415 if (len == 0)
5417 EMSG(_("E175: No attribute specified"));
5418 return FAIL;
5421 /* First, try the simple attributes (no arguments) */
5422 if (STRNICMP(attr, "bang", len) == 0)
5423 *argt |= BANG;
5424 else if (STRNICMP(attr, "buffer", len) == 0)
5425 *flags |= UC_BUFFER;
5426 else if (STRNICMP(attr, "register", len) == 0)
5427 *argt |= REGSTR;
5428 else if (STRNICMP(attr, "bar", len) == 0)
5429 *argt |= TRLBAR;
5430 else
5432 int i;
5433 char_u *val = NULL;
5434 size_t vallen = 0;
5435 size_t attrlen = len;
5437 /* Look for the attribute name - which is the part before any '=' */
5438 for (i = 0; i < (int)len; ++i)
5440 if (attr[i] == '=')
5442 val = &attr[i + 1];
5443 vallen = len - i - 1;
5444 attrlen = i;
5445 break;
5449 if (STRNICMP(attr, "nargs", attrlen) == 0)
5451 if (vallen == 1)
5453 if (*val == '0')
5454 /* Do nothing - this is the default */;
5455 else if (*val == '1')
5456 *argt |= (EXTRA | NOSPC | NEEDARG);
5457 else if (*val == '*')
5458 *argt |= EXTRA;
5459 else if (*val == '?')
5460 *argt |= (EXTRA | NOSPC);
5461 else if (*val == '+')
5462 *argt |= (EXTRA | NEEDARG);
5463 else
5464 goto wrong_nargs;
5466 else
5468 wrong_nargs:
5469 EMSG(_("E176: Invalid number of arguments"));
5470 return FAIL;
5473 else if (STRNICMP(attr, "range", attrlen) == 0)
5475 *argt |= RANGE;
5476 if (vallen == 1 && *val == '%')
5477 *argt |= DFLALL;
5478 else if (val != NULL)
5480 p = val;
5481 if (*def >= 0)
5483 two_count:
5484 EMSG(_("E177: Count cannot be specified twice"));
5485 return FAIL;
5488 *def = getdigits(&p);
5489 *argt |= (ZEROR | NOTADR);
5491 if (p != val + vallen || vallen == 0)
5493 invalid_count:
5494 EMSG(_("E178: Invalid default value for count"));
5495 return FAIL;
5499 else if (STRNICMP(attr, "count", attrlen) == 0)
5501 *argt |= (COUNT | ZEROR | RANGE | NOTADR);
5503 if (val != NULL)
5505 p = val;
5506 if (*def >= 0)
5507 goto two_count;
5509 *def = getdigits(&p);
5511 if (p != val + vallen)
5512 goto invalid_count;
5515 if (*def < 0)
5516 *def = 0;
5518 else if (STRNICMP(attr, "complete", attrlen) == 0)
5520 if (val == NULL)
5522 EMSG(_("E179: argument required for -complete"));
5523 return FAIL;
5526 if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
5527 == FAIL)
5528 return FAIL;
5530 else
5532 char_u ch = attr[len];
5533 attr[len] = '\0';
5534 EMSG2(_("E181: Invalid attribute: %s"), attr);
5535 attr[len] = ch;
5536 return FAIL;
5540 return OK;
5544 * ":command ..."
5546 static void
5547 ex_command(eap)
5548 exarg_T *eap;
5550 char_u *name;
5551 char_u *end;
5552 char_u *p;
5553 long argt = 0;
5554 long def = -1;
5555 int flags = 0;
5556 int compl = EXPAND_NOTHING;
5557 char_u *compl_arg = NULL;
5558 int has_attr = (eap->arg[0] == '-');
5560 p = eap->arg;
5562 /* Check for attributes */
5563 while (*p == '-')
5565 ++p;
5566 end = skiptowhite(p);
5567 if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5568 == FAIL)
5569 return;
5570 p = skipwhite(end);
5573 /* Get the name (if any) and skip to the following argument */
5574 name = p;
5575 if (ASCII_ISALPHA(*p))
5576 while (ASCII_ISALNUM(*p))
5577 ++p;
5578 if (!ends_excmd(*p) && !vim_iswhite(*p))
5580 EMSG(_("E182: Invalid command name"));
5581 return;
5583 end = p;
5585 /* If there is nothing after the name, and no attributes were specified,
5586 * we are listing commands
5588 p = skipwhite(end);
5589 if (!has_attr && ends_excmd(*p))
5591 uc_list(name, end - name);
5593 else if (!ASCII_ISUPPER(*name))
5595 EMSG(_("E183: User defined commands must start with an uppercase letter"));
5596 return;
5598 else
5599 uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5600 eap->forceit);
5604 * ":comclear"
5605 * Clear all user commands, global and for current buffer.
5607 void
5608 ex_comclear(eap)
5609 exarg_T *eap UNUSED;
5611 uc_clear(&ucmds);
5612 uc_clear(&curbuf->b_ucmds);
5616 * Clear all user commands for "gap".
5618 void
5619 uc_clear(gap)
5620 garray_T *gap;
5622 int i;
5623 ucmd_T *cmd;
5625 for (i = 0; i < gap->ga_len; ++i)
5627 cmd = USER_CMD_GA(gap, i);
5628 vim_free(cmd->uc_name);
5629 vim_free(cmd->uc_rep);
5630 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5631 vim_free(cmd->uc_compl_arg);
5632 # endif
5634 ga_clear(gap);
5637 static void
5638 ex_delcommand(eap)
5639 exarg_T *eap;
5641 int i = 0;
5642 ucmd_T *cmd = NULL;
5643 int cmp = -1;
5644 garray_T *gap;
5646 gap = &curbuf->b_ucmds;
5647 for (;;)
5649 for (i = 0; i < gap->ga_len; ++i)
5651 cmd = USER_CMD_GA(gap, i);
5652 cmp = STRCMP(eap->arg, cmd->uc_name);
5653 if (cmp <= 0)
5654 break;
5656 if (gap == &ucmds || cmp == 0)
5657 break;
5658 gap = &ucmds;
5661 if (cmp != 0)
5663 EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5664 return;
5667 vim_free(cmd->uc_name);
5668 vim_free(cmd->uc_rep);
5669 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5670 vim_free(cmd->uc_compl_arg);
5671 # endif
5673 --gap->ga_len;
5675 if (i < gap->ga_len)
5676 mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5680 * split and quote args for <f-args>
5682 static char_u *
5683 uc_split_args(arg, lenp)
5684 char_u *arg;
5685 size_t *lenp;
5687 char_u *buf;
5688 char_u *p;
5689 char_u *q;
5690 int len;
5692 /* Precalculate length */
5693 p = arg;
5694 len = 2; /* Initial and final quotes */
5696 while (*p)
5698 if (p[0] == '\\' && p[1] == '\\')
5700 len += 2;
5701 p += 2;
5703 else if (p[0] == '\\' && vim_iswhite(p[1]))
5705 len += 1;
5706 p += 2;
5708 else if (*p == '\\' || *p == '"')
5710 len += 2;
5711 p += 1;
5713 else if (vim_iswhite(*p))
5715 p = skipwhite(p);
5716 if (*p == NUL)
5717 break;
5718 len += 3; /* "," */
5720 else
5722 ++len;
5723 ++p;
5727 buf = alloc(len + 1);
5728 if (buf == NULL)
5730 *lenp = 0;
5731 return buf;
5734 p = arg;
5735 q = buf;
5736 *q++ = '"';
5737 while (*p)
5739 if (p[0] == '\\' && p[1] == '\\')
5741 *q++ = '\\';
5742 *q++ = '\\';
5743 p += 2;
5745 else if (p[0] == '\\' && vim_iswhite(p[1]))
5747 *q++ = p[1];
5748 p += 2;
5750 else if (*p == '\\' || *p == '"')
5752 *q++ = '\\';
5753 *q++ = *p++;
5755 else if (vim_iswhite(*p))
5757 p = skipwhite(p);
5758 if (*p == NUL)
5759 break;
5760 *q++ = '"';
5761 *q++ = ',';
5762 *q++ = '"';
5764 else
5766 *q++ = *p++;
5769 *q++ = '"';
5770 *q = 0;
5772 *lenp = len;
5773 return buf;
5777 * Check for a <> code in a user command.
5778 * "code" points to the '<'. "len" the length of the <> (inclusive).
5779 * "buf" is where the result is to be added.
5780 * "split_buf" points to a buffer used for splitting, caller should free it.
5781 * "split_len" is the length of what "split_buf" contains.
5782 * Returns the length of the replacement, which has been added to "buf".
5783 * Returns -1 if there was no match, and only the "<" has been copied.
5785 static size_t
5786 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5787 char_u *code;
5788 size_t len;
5789 char_u *buf;
5790 ucmd_T *cmd; /* the user command we're expanding */
5791 exarg_T *eap; /* ex arguments */
5792 char_u **split_buf;
5793 size_t *split_len;
5795 size_t result = 0;
5796 char_u *p = code + 1;
5797 size_t l = len - 2;
5798 int quote = 0;
5799 enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5800 ct_LT, ct_NONE } type = ct_NONE;
5802 if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5804 quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5805 p += 2;
5806 l -= 2;
5809 ++l;
5810 if (l <= 1)
5811 type = ct_NONE;
5812 else if (STRNICMP(p, "args>", l) == 0)
5813 type = ct_ARGS;
5814 else if (STRNICMP(p, "bang>", l) == 0)
5815 type = ct_BANG;
5816 else if (STRNICMP(p, "count>", l) == 0)
5817 type = ct_COUNT;
5818 else if (STRNICMP(p, "line1>", l) == 0)
5819 type = ct_LINE1;
5820 else if (STRNICMP(p, "line2>", l) == 0)
5821 type = ct_LINE2;
5822 else if (STRNICMP(p, "lt>", l) == 0)
5823 type = ct_LT;
5824 else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
5825 type = ct_REGISTER;
5827 switch (type)
5829 case ct_ARGS:
5830 /* Simple case first */
5831 if (*eap->arg == NUL)
5833 if (quote == 1)
5835 result = 2;
5836 if (buf != NULL)
5837 STRCPY(buf, "''");
5839 else
5840 result = 0;
5841 break;
5844 /* When specified there is a single argument don't split it.
5845 * Works for ":Cmd %" when % is "a b c". */
5846 if ((eap->argt & NOSPC) && quote == 2)
5847 quote = 1;
5849 switch (quote)
5851 case 0: /* No quoting, no splitting */
5852 result = STRLEN(eap->arg);
5853 if (buf != NULL)
5854 STRCPY(buf, eap->arg);
5855 break;
5856 case 1: /* Quote, but don't split */
5857 result = STRLEN(eap->arg) + 2;
5858 for (p = eap->arg; *p; ++p)
5860 if (*p == '\\' || *p == '"')
5861 ++result;
5864 if (buf != NULL)
5866 *buf++ = '"';
5867 for (p = eap->arg; *p; ++p)
5869 if (*p == '\\' || *p == '"')
5870 *buf++ = '\\';
5871 *buf++ = *p;
5873 *buf = '"';
5876 break;
5877 case 2: /* Quote and split (<f-args>) */
5878 /* This is hard, so only do it once, and cache the result */
5879 if (*split_buf == NULL)
5880 *split_buf = uc_split_args(eap->arg, split_len);
5882 result = *split_len;
5883 if (buf != NULL && result != 0)
5884 STRCPY(buf, *split_buf);
5886 break;
5888 break;
5890 case ct_BANG:
5891 result = eap->forceit ? 1 : 0;
5892 if (quote)
5893 result += 2;
5894 if (buf != NULL)
5896 if (quote)
5897 *buf++ = '"';
5898 if (eap->forceit)
5899 *buf++ = '!';
5900 if (quote)
5901 *buf = '"';
5903 break;
5905 case ct_LINE1:
5906 case ct_LINE2:
5907 case ct_COUNT:
5909 char num_buf[20];
5910 long num = (type == ct_LINE1) ? eap->line1 :
5911 (type == ct_LINE2) ? eap->line2 :
5912 (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5913 size_t num_len;
5915 sprintf(num_buf, "%ld", num);
5916 num_len = STRLEN(num_buf);
5917 result = num_len;
5919 if (quote)
5920 result += 2;
5922 if (buf != NULL)
5924 if (quote)
5925 *buf++ = '"';
5926 STRCPY(buf, num_buf);
5927 buf += num_len;
5928 if (quote)
5929 *buf = '"';
5932 break;
5935 case ct_REGISTER:
5936 result = eap->regname ? 1 : 0;
5937 if (quote)
5938 result += 2;
5939 if (buf != NULL)
5941 if (quote)
5942 *buf++ = '\'';
5943 if (eap->regname)
5944 *buf++ = eap->regname;
5945 if (quote)
5946 *buf = '\'';
5948 break;
5950 case ct_LT:
5951 result = 1;
5952 if (buf != NULL)
5953 *buf = '<';
5954 break;
5956 default:
5957 /* Not recognized: just copy the '<' and return -1. */
5958 result = (size_t)-1;
5959 if (buf != NULL)
5960 *buf = '<';
5961 break;
5964 return result;
5967 static void
5968 do_ucmd(eap)
5969 exarg_T *eap;
5971 char_u *buf;
5972 char_u *p;
5973 char_u *q;
5975 char_u *start;
5976 char_u *end = NULL;
5977 char_u *ksp;
5978 size_t len, totlen;
5980 size_t split_len = 0;
5981 char_u *split_buf = NULL;
5982 ucmd_T *cmd;
5983 #ifdef FEAT_EVAL
5984 scid_T save_current_SID = current_SID;
5985 #endif
5987 if (eap->cmdidx == CMD_USER)
5988 cmd = USER_CMD(eap->useridx);
5989 else
5990 cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5993 * Replace <> in the command by the arguments.
5994 * First round: "buf" is NULL, compute length, allocate "buf".
5995 * Second round: copy result into "buf".
5997 buf = NULL;
5998 for (;;)
6000 p = cmd->uc_rep; /* source */
6001 q = buf; /* destination */
6002 totlen = 0;
6004 for (;;)
6006 start = vim_strchr(p, '<');
6007 if (start != NULL)
6008 end = vim_strchr(start + 1, '>');
6009 if (buf != NULL)
6011 ksp = vim_strchr(p, K_SPECIAL);
6012 if (ksp != NULL && (start == NULL || ksp < start || end == NULL)
6013 && ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)
6014 # ifdef FEAT_GUI
6015 || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI)
6016 # endif
6019 /* K_SPECIAL han been put in the buffer as K_SPECIAL
6020 * KS_SPECIAL KE_FILLER, like for mappings, but
6021 * do_cmdline() doesn't handle that, so convert it back.
6022 * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */
6023 len = ksp - p;
6024 if (len > 0)
6026 mch_memmove(q, p, len);
6027 q += len;
6029 *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI;
6030 p = ksp + 3;
6031 continue;
6035 /* break if there no <item> is found */
6036 if (start == NULL || end == NULL)
6037 break;
6039 /* Include the '>' */
6040 ++end;
6042 /* Take everything up to the '<' */
6043 len = start - p;
6044 if (buf == NULL)
6045 totlen += len;
6046 else
6048 mch_memmove(q, p, len);
6049 q += len;
6052 len = uc_check_code(start, end - start, q, cmd, eap,
6053 &split_buf, &split_len);
6054 if (len == (size_t)-1)
6056 /* no match, continue after '<' */
6057 p = start + 1;
6058 len = 1;
6060 else
6061 p = end;
6062 if (buf == NULL)
6063 totlen += len;
6064 else
6065 q += len;
6067 if (buf != NULL) /* second time here, finished */
6069 STRCPY(q, p);
6070 break;
6073 totlen += STRLEN(p); /* Add on the trailing characters */
6074 buf = alloc((unsigned)(totlen + 1));
6075 if (buf == NULL)
6077 vim_free(split_buf);
6078 return;
6082 #ifdef FEAT_EVAL
6083 current_SID = cmd->uc_scriptID;
6084 #endif
6085 (void)do_cmdline(buf, eap->getline, eap->cookie,
6086 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6087 #ifdef FEAT_EVAL
6088 current_SID = save_current_SID;
6089 #endif
6090 vim_free(buf);
6091 vim_free(split_buf);
6094 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6095 static char_u *
6096 get_user_command_name(idx)
6097 int idx;
6099 return get_user_commands(NULL, idx - (int)CMD_SIZE);
6103 * Function given to ExpandGeneric() to obtain the list of user command names.
6105 char_u *
6106 get_user_commands(xp, idx)
6107 expand_T *xp UNUSED;
6108 int idx;
6110 if (idx < curbuf->b_ucmds.ga_len)
6111 return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
6112 idx -= curbuf->b_ucmds.ga_len;
6113 if (idx < ucmds.ga_len)
6114 return USER_CMD(idx)->uc_name;
6115 return NULL;
6119 * Function given to ExpandGeneric() to obtain the list of user command
6120 * attributes.
6122 char_u *
6123 get_user_cmd_flags(xp, idx)
6124 expand_T *xp UNUSED;
6125 int idx;
6127 static char *user_cmd_flags[] =
6128 {"bang", "bar", "buffer", "complete", "count",
6129 "nargs", "range", "register"};
6131 if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0])))
6132 return NULL;
6133 return (char_u *)user_cmd_flags[idx];
6137 * Function given to ExpandGeneric() to obtain the list of values for -nargs.
6139 char_u *
6140 get_user_cmd_nargs(xp, idx)
6141 expand_T *xp UNUSED;
6142 int idx;
6144 static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
6146 if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0])))
6147 return NULL;
6148 return (char_u *)user_cmd_nargs[idx];
6152 * Function given to ExpandGeneric() to obtain the list of values for -complete.
6154 char_u *
6155 get_user_cmd_complete(xp, idx)
6156 expand_T *xp UNUSED;
6157 int idx;
6159 return (char_u *)command_complete[idx].name;
6161 # endif /* FEAT_CMDL_COMPL */
6163 #endif /* FEAT_USR_CMDS */
6165 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
6167 * Parse a completion argument "value[vallen]".
6168 * The detected completion goes in "*complp", argument type in "*argt".
6169 * When there is an argument, for function and user defined completion, it's
6170 * copied to allocated memory and stored in "*compl_arg".
6171 * Returns FAIL if something is wrong.
6174 parse_compl_arg(value, vallen, complp, argt, compl_arg)
6175 char_u *value;
6176 int vallen;
6177 int *complp;
6178 long *argt;
6179 char_u **compl_arg;
6181 char_u *arg = NULL;
6182 size_t arglen = 0;
6183 int i;
6184 int valend = vallen;
6186 /* Look for any argument part - which is the part after any ',' */
6187 for (i = 0; i < vallen; ++i)
6189 if (value[i] == ',')
6191 arg = &value[i + 1];
6192 arglen = vallen - i - 1;
6193 valend = i;
6194 break;
6198 for (i = 0; command_complete[i].expand != 0; ++i)
6200 if ((int)STRLEN(command_complete[i].name) == valend
6201 && STRNCMP(value, command_complete[i].name, valend) == 0)
6203 *complp = command_complete[i].expand;
6204 if (command_complete[i].expand == EXPAND_BUFFERS)
6205 *argt |= BUFNAME;
6206 else if (command_complete[i].expand == EXPAND_DIRECTORIES
6207 || command_complete[i].expand == EXPAND_FILES)
6208 *argt |= XFILE;
6209 break;
6213 if (command_complete[i].expand == 0)
6215 EMSG2(_("E180: Invalid complete value: %s"), value);
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)
6222 # else
6223 if (arg != NULL)
6224 # endif
6226 EMSG(_("E468: Completion argument only allowed for custom completion"));
6227 return FAIL;
6230 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6231 if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
6232 && arg == NULL)
6234 EMSG(_("E467: Custom completion requires a function argument"));
6235 return FAIL;
6238 if (arg != NULL)
6239 *compl_arg = vim_strnsave(arg, (int)arglen);
6240 # endif
6241 return OK;
6243 #endif
6245 static void
6246 ex_colorscheme(eap)
6247 exarg_T *eap;
6249 if (*eap->arg == NUL)
6251 #ifdef FEAT_EVAL
6252 char_u *expr = vim_strsave((char_u *)"g:colors_name");
6253 char_u *p = NULL;
6255 if (expr != NULL)
6257 ++emsg_off;
6258 p = eval_to_string(expr, NULL, FALSE);
6259 --emsg_off;
6260 vim_free(expr);
6262 if (p != NULL)
6264 MSG(p);
6265 vim_free(p);
6267 else
6268 MSG("default");
6269 #else
6270 MSG(_("unknown"));
6271 #endif
6273 else if (load_colors(eap->arg) == FAIL)
6274 EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
6277 static void
6278 ex_highlight(eap)
6279 exarg_T *eap;
6281 if (*eap->arg == NUL && eap->cmd[2] == '!')
6282 MSG(_("Greetings, Vim user!"));
6283 do_highlight(eap->arg, eap->forceit, FALSE);
6288 * Call this function if we thought we were going to exit, but we won't
6289 * (because of an error). May need to restore the terminal mode.
6291 void
6292 not_exiting()
6294 exiting = FALSE;
6295 settmode(TMODE_RAW);
6299 * ":quit": quit current window, quit Vim if closed the last window.
6301 static void
6302 ex_quit(eap)
6303 exarg_T *eap;
6305 #ifdef FEAT_CMDWIN
6306 if (cmdwin_type != 0)
6308 cmdwin_result = Ctrl_C;
6309 return;
6311 #endif
6312 /* Don't quit while editing the command line. */
6313 if (text_locked())
6315 text_locked_msg();
6316 return;
6318 #ifdef FEAT_AUTOCMD
6319 if (curbuf_locked())
6320 return;
6321 #endif
6323 #ifdef FEAT_NETBEANS_INTG
6324 netbeansForcedQuit = eap->forceit;
6325 #endif
6328 * If there are more files or windows we won't exit.
6330 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6331 exiting = TRUE;
6332 if ((!P_HID(curbuf)
6333 && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
6334 || check_more(TRUE, eap->forceit) == FAIL
6335 || (only_one_window() && check_changed_any(eap->forceit)))
6337 not_exiting();
6339 else
6341 #ifdef FEAT_WINDOWS
6342 if (only_one_window()) /* quit last window */
6343 #endif
6344 getout(0);
6345 #ifdef FEAT_WINDOWS
6346 # ifdef FEAT_GUI
6347 need_mouse_correct = TRUE;
6348 # endif
6349 /* close window; may free buffer */
6350 win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
6351 #endif
6356 * ":cquit".
6358 static void
6359 ex_cquit(eap)
6360 exarg_T *eap UNUSED;
6362 getout(1); /* this does not always pass on the exit code to the Manx
6363 compiler. why? */
6367 * ":qall": try to quit all windows
6369 static void
6370 ex_quit_all(eap)
6371 exarg_T *eap;
6373 # ifdef FEAT_CMDWIN
6374 if (cmdwin_type != 0)
6376 if (eap->forceit)
6377 cmdwin_result = K_XF1; /* ex_window() takes care of this */
6378 else
6379 cmdwin_result = K_XF2;
6380 return;
6382 # endif
6384 /* Don't quit while editing the command line. */
6385 if (text_locked())
6387 text_locked_msg();
6388 return;
6390 #ifdef FEAT_AUTOCMD
6391 if (curbuf_locked())
6392 return;
6393 #endif
6395 exiting = TRUE;
6396 if (eap->forceit || !check_changed_any(FALSE))
6397 getout(0);
6398 not_exiting();
6401 #if defined(FEAT_WINDOWS) || defined(PROTO)
6403 * ":close": close current window, unless it is the last one
6405 static void
6406 ex_close(eap)
6407 exarg_T *eap;
6409 # ifdef FEAT_CMDWIN
6410 if (cmdwin_type != 0)
6411 cmdwin_result = K_IGNORE;
6412 else
6413 # endif
6414 if (!text_locked()
6415 #ifdef FEAT_AUTOCMD
6416 && !curbuf_locked()
6417 #endif
6419 ex_win_close(eap->forceit, curwin, NULL);
6422 # ifdef FEAT_QUICKFIX
6424 * ":pclose": Close any preview window.
6426 static void
6427 ex_pclose(eap)
6428 exarg_T *eap;
6430 win_T *win;
6432 for (win = firstwin; win != NULL; win = win->w_next)
6433 if (win->w_p_pvw)
6435 ex_win_close(eap->forceit, win, NULL);
6436 break;
6439 # endif
6442 * Close window "win" and take care of handling closing the last window for a
6443 * modified buffer.
6445 static void
6446 ex_win_close(forceit, win, tp)
6447 int forceit;
6448 win_T *win;
6449 tabpage_T *tp; /* NULL or the tab page "win" is in */
6451 int need_hide;
6452 buf_T *buf = win->w_buffer;
6454 need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
6455 if (need_hide && !P_HID(buf) && !forceit)
6457 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6458 if ((p_confirm || cmdmod.confirm) && p_write)
6460 dialog_changed(buf, FALSE);
6461 if (buf_valid(buf) && bufIsChanged(buf))
6462 return;
6463 need_hide = FALSE;
6465 else
6466 # endif
6468 EMSG(_(e_nowrtmsg));
6469 return;
6473 # ifdef FEAT_GUI
6474 need_mouse_correct = TRUE;
6475 # endif
6477 /* free buffer when not hiding it or when it's a scratch buffer */
6478 if (tp == NULL)
6479 win_close(win, !need_hide && !P_HID(buf));
6480 else
6481 win_close_othertab(win, !need_hide && !P_HID(buf), tp);
6485 * ":tabclose": close current tab page, unless it is the last one.
6486 * ":tabclose N": close tab page N.
6488 static void
6489 ex_tabclose(eap)
6490 exarg_T *eap;
6492 tabpage_T *tp;
6494 # ifdef FEAT_CMDWIN
6495 if (cmdwin_type != 0)
6496 cmdwin_result = K_IGNORE;
6497 else
6498 # endif
6499 if (first_tabpage->tp_next == NULL)
6500 EMSG(_("E784: Cannot close last tab page"));
6501 else
6503 if (eap->addr_count > 0)
6505 tp = find_tabpage((int)eap->line2);
6506 if (tp == NULL)
6508 beep_flush();
6509 return;
6511 if (tp != curtab)
6513 tabpage_close_other(tp, eap->forceit);
6514 return;
6517 if (!text_locked()
6518 #ifdef FEAT_AUTOCMD
6519 && !curbuf_locked()
6520 #endif
6522 tabpage_close(eap->forceit);
6527 * ":tabonly": close all tab pages except the current one
6529 static void
6530 ex_tabonly(eap)
6531 exarg_T *eap;
6533 tabpage_T *tp;
6534 int done;
6536 # ifdef FEAT_CMDWIN
6537 if (cmdwin_type != 0)
6538 cmdwin_result = K_IGNORE;
6539 else
6540 # endif
6541 if (first_tabpage->tp_next == NULL)
6542 MSG(_("Already only one tab page"));
6543 else
6545 /* Repeat this up to a 1000 times, because autocommands may mess
6546 * up the lists. */
6547 for (done = 0; done < 1000; ++done)
6549 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6550 if (tp->tp_topframe != topframe)
6552 tabpage_close_other(tp, eap->forceit);
6553 /* if we failed to close it quit */
6554 if (valid_tabpage(tp))
6555 done = 1000;
6556 /* start over, "tp" is now invalid */
6557 break;
6559 if (first_tabpage->tp_next == NULL)
6560 break;
6566 * Close the current tab page.
6568 void
6569 tabpage_close(forceit)
6570 int forceit;
6572 /* First close all the windows but the current one. If that worked then
6573 * close the last window in this tab, that will close it. */
6574 if (lastwin != firstwin)
6575 close_others(TRUE, forceit);
6576 if (lastwin == firstwin)
6577 ex_win_close(forceit, curwin, NULL);
6578 # ifdef FEAT_GUI
6579 need_mouse_correct = TRUE;
6580 # endif
6584 * Close tab page "tp", which is not the current tab page.
6585 * Note that autocommands may make "tp" invalid.
6586 * Also takes care of the tab pages line disappearing when closing the
6587 * last-but-one tab page.
6589 void
6590 tabpage_close_other(tp, forceit)
6591 tabpage_T *tp;
6592 int forceit;
6594 int done = 0;
6595 win_T *wp;
6596 int h = tabline_height();
6598 /* Limit to 1000 windows, autocommands may add a window while we close
6599 * one. OK, so I'm paranoid... */
6600 while (++done < 1000)
6602 wp = tp->tp_firstwin;
6603 ex_win_close(forceit, wp, tp);
6605 /* Autocommands may delete the tab page under our fingers and we may
6606 * fail to close a window with a modified buffer. */
6607 if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
6608 break;
6611 redraw_tabline = TRUE;
6612 if (h != tabline_height())
6613 shell_new_rows();
6617 * ":only".
6619 static void
6620 ex_only(eap)
6621 exarg_T *eap;
6623 # ifdef FEAT_GUI
6624 need_mouse_correct = TRUE;
6625 # endif
6626 close_others(TRUE, eap->forceit);
6630 * ":all" and ":sall".
6631 * Also used for ":tab drop file ..." after setting the argument list.
6633 void
6634 ex_all(eap)
6635 exarg_T *eap;
6637 if (eap->addr_count == 0)
6638 eap->line2 = 9999;
6639 do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
6641 #endif /* FEAT_WINDOWS */
6643 static void
6644 ex_hide(eap)
6645 exarg_T *eap;
6647 if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
6648 eap->errmsg = e_invarg;
6649 else
6651 /* ":hide" or ":hide | cmd": hide current window */
6652 eap->nextcmd = check_nextcmd(eap->arg);
6653 #ifdef FEAT_WINDOWS
6654 if (!eap->skip)
6656 # ifdef FEAT_GUI
6657 need_mouse_correct = TRUE;
6658 # endif
6659 win_close(curwin, FALSE); /* don't free buffer */
6661 #endif
6666 * ":stop" and ":suspend": Suspend Vim.
6668 static void
6669 ex_stop(eap)
6670 exarg_T *eap;
6673 * Disallow suspending for "rvim".
6675 if (!check_restricted()
6676 #ifdef WIN3264
6678 * Check if external commands are allowed now.
6680 && can_end_termcap_mode(TRUE)
6681 #endif
6684 if (!eap->forceit)
6685 autowrite_all();
6686 windgoto((int)Rows - 1, 0);
6687 out_char('\n');
6688 out_flush();
6689 stoptermcap();
6690 out_flush(); /* needed for SUN to restore xterm buffer */
6691 #ifdef FEAT_TITLE
6692 mch_restore_title(3); /* restore window titles */
6693 #endif
6694 ui_suspend(); /* call machine specific function */
6695 #ifdef FEAT_TITLE
6696 maketitle();
6697 resettitle(); /* force updating the title */
6698 #endif
6699 starttermcap();
6700 scroll_start(); /* scroll screen before redrawing */
6701 redraw_later_clear();
6702 shell_resized(); /* may have resized window */
6707 * ":exit", ":xit" and ":wq": Write file and exit Vim.
6709 static void
6710 ex_exit(eap)
6711 exarg_T *eap;
6713 #ifdef FEAT_CMDWIN
6714 if (cmdwin_type != 0)
6716 cmdwin_result = Ctrl_C;
6717 return;
6719 #endif
6720 /* Don't quit while editing the command line. */
6721 if (text_locked())
6723 text_locked_msg();
6724 return;
6726 #ifdef FEAT_AUTOCMD
6727 if (curbuf_locked())
6728 return;
6729 #endif
6732 * if more files or windows we won't exit
6734 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6735 exiting = TRUE;
6736 if ( ((eap->cmdidx == CMD_wq
6737 || curbufIsChanged())
6738 && do_write(eap) == FAIL)
6739 || check_more(TRUE, eap->forceit) == FAIL
6740 || (only_one_window() && check_changed_any(eap->forceit)))
6742 not_exiting();
6744 else
6746 #ifdef FEAT_WINDOWS
6747 if (only_one_window()) /* quit last window, exit Vim */
6748 #endif
6749 getout(0);
6750 #ifdef FEAT_WINDOWS
6751 # ifdef FEAT_GUI
6752 need_mouse_correct = TRUE;
6753 # endif
6754 /* quit current window, may free buffer */
6755 win_close(curwin, !P_HID(curwin->w_buffer));
6756 #endif
6761 * ":print", ":list", ":number".
6763 static void
6764 ex_print(eap)
6765 exarg_T *eap;
6767 if (curbuf->b_ml.ml_flags & ML_EMPTY)
6768 EMSG(_(e_emptybuf));
6769 else
6771 for ( ;!got_int; ui_breakcheck())
6773 print_line(eap->line1,
6774 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
6775 || (eap->flags & EXFLAG_NR)),
6776 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
6777 if (++eap->line1 > eap->line2)
6778 break;
6779 out_flush(); /* show one line at a time */
6781 setpcmark();
6782 /* put cursor at last line */
6783 curwin->w_cursor.lnum = eap->line2;
6784 beginline(BL_SOL | BL_FIX);
6787 ex_no_reprint = TRUE;
6790 #ifdef FEAT_BYTEOFF
6791 static void
6792 ex_goto(eap)
6793 exarg_T *eap;
6795 goto_byte(eap->line2);
6797 #endif
6800 * ":shell".
6802 static void
6803 ex_shell(eap)
6804 exarg_T *eap UNUSED;
6806 do_shell(NULL, 0);
6809 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6810 || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6811 || defined(FEAT_GUI_MSWIN) \
6812 || defined(FEAT_GUI_MAC) \
6813 || defined(PROTO)
6816 * Handle a file drop. The code is here because a drop is *nearly* like an
6817 * :args command, but not quite (we have a list of exact filenames, so we
6818 * don't want to (a) parse a command line, or (b) expand wildcards. So the
6819 * code is very similar to :args and hence needs access to a lot of the static
6820 * functions in this file.
6822 * The list should be allocated using alloc(), as should each item in the
6823 * list. This function takes over responsibility for freeing the list.
6825 * XXX The list is made into the argument list. This is freed using
6826 * FreeWild(), which does a series of vim_free() calls, unless the two defines
6827 * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6828 * routine _fnexplodefree() is used. This may cause problems, but as the drop
6829 * file functionality is (currently) not in EMX this is not presently a
6830 * problem.
6832 void
6833 handle_drop(filec, filev, split)
6834 int filec; /* the number of files dropped */
6835 char_u **filev; /* the list of files dropped */
6836 int split; /* force splitting the window */
6838 exarg_T ea;
6839 int save_msg_scroll = msg_scroll;
6841 /* Postpone this while editing the command line. */
6842 if (text_locked())
6843 return;
6844 #ifdef FEAT_AUTOCMD
6845 if (curbuf_locked())
6846 return;
6847 #endif
6848 /* When the screen is being updated we should not change buffers and
6849 * windows structures, it may cause freed memory to be used. */
6850 if (updating_screen)
6851 return;
6853 /* Check whether the current buffer is changed. If so, we will need
6854 * to split the current window or data could be lost.
6855 * We don't need to check if the 'hidden' option is set, as in this
6856 * case the buffer won't be lost.
6858 if (!P_HID(curbuf) && !split)
6860 ++emsg_off;
6861 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6862 --emsg_off;
6864 if (split)
6866 # ifdef FEAT_WINDOWS
6867 if (win_split(0, 0) == FAIL)
6868 return;
6869 # ifdef FEAT_SCROLLBIND
6870 curwin->w_p_scb = FALSE;
6871 # endif
6873 /* When splitting the window, create a new alist. Otherwise the
6874 * existing one is overwritten. */
6875 alist_unlink(curwin->w_alist);
6876 alist_new();
6877 # else
6878 return; /* can't split, always fail */
6879 # endif
6883 * Set up the new argument list.
6885 alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
6888 * Move to the first file.
6890 /* Fake up a minimal "next" command for do_argfile() */
6891 vim_memset(&ea, 0, sizeof(ea));
6892 ea.cmd = (char_u *)"next";
6893 do_argfile(&ea, 0);
6895 /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6896 * mode that is not needed here. */
6897 need_start_insertmode = FALSE;
6899 /* Restore msg_scroll, otherwise a following command may cause scrolling
6900 * unexpectedly. The screen will be redrawn by the caller, thus
6901 * msg_scroll being set by displaying a message is irrelevant. */
6902 msg_scroll = save_msg_scroll;
6904 #endif
6907 * Clear an argument list: free all file names and reset it to zero entries.
6909 void
6910 alist_clear(al)
6911 alist_T *al;
6913 while (--al->al_ga.ga_len >= 0)
6914 vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6915 ga_clear(&al->al_ga);
6919 * Init an argument list.
6921 void
6922 alist_init(al)
6923 alist_T *al;
6925 ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6928 #if defined(FEAT_WINDOWS) || defined(PROTO)
6931 * Remove a reference from an argument list.
6932 * Ignored when the argument list is the global one.
6933 * If the argument list is no longer used by any window, free it.
6935 void
6936 alist_unlink(al)
6937 alist_T *al;
6939 if (al != &global_alist && --al->al_refcount <= 0)
6941 alist_clear(al);
6942 vim_free(al);
6946 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6948 * Create a new argument list and use it for the current window.
6950 void
6951 alist_new()
6953 curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6954 if (curwin->w_alist == NULL)
6956 curwin->w_alist = &global_alist;
6957 ++global_alist.al_refcount;
6959 else
6961 curwin->w_alist->al_refcount = 1;
6962 alist_init(curwin->w_alist);
6965 # endif
6966 #endif
6968 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6970 * Expand the file names in the global argument list.
6971 * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
6972 * numbers to be re-used.
6974 void
6975 alist_expand(fnum_list, fnum_len)
6976 int *fnum_list;
6977 int fnum_len;
6979 char_u **old_arg_files;
6980 int old_arg_count;
6981 char_u **new_arg_files;
6982 int new_arg_file_count;
6983 char_u *save_p_su = p_su;
6984 int i;
6986 /* Don't use 'suffixes' here. This should work like the shell did the
6987 * expansion. Also, the vimrc file isn't read yet, thus the user
6988 * can't set the options. */
6989 p_su = empty_option;
6990 old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6991 if (old_arg_files != NULL)
6993 for (i = 0; i < GARGCOUNT; ++i)
6994 old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
6995 old_arg_count = GARGCOUNT;
6996 if (expand_wildcards(old_arg_count, old_arg_files,
6997 &new_arg_file_count, &new_arg_files,
6998 EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6999 && new_arg_file_count > 0)
7001 alist_set(&global_alist, new_arg_file_count, new_arg_files,
7002 TRUE, fnum_list, fnum_len);
7003 FreeWild(old_arg_count, old_arg_files);
7006 p_su = save_p_su;
7008 #endif
7011 * Set the argument list for the current window.
7012 * Takes over the allocated files[] and the allocated fnames in it.
7014 void
7015 alist_set(al, count, files, use_curbuf, fnum_list, fnum_len)
7016 alist_T *al;
7017 int count;
7018 char_u **files;
7019 int use_curbuf;
7020 int *fnum_list;
7021 int fnum_len;
7023 int i;
7025 alist_clear(al);
7026 if (ga_grow(&al->al_ga, count) == OK)
7028 for (i = 0; i < count; ++i)
7030 if (got_int)
7032 /* When adding many buffers this can take a long time. Allow
7033 * interrupting here. */
7034 while (i < count)
7035 vim_free(files[i++]);
7036 break;
7039 /* May set buffer name of a buffer previously used for the
7040 * argument list, so that it's re-used by alist_add. */
7041 if (fnum_list != NULL && i < fnum_len)
7042 buf_set_name(fnum_list[i], files[i]);
7044 alist_add(al, files[i], use_curbuf ? 2 : 1);
7045 ui_breakcheck();
7047 vim_free(files);
7049 else
7050 FreeWild(count, files);
7051 #ifdef FEAT_WINDOWS
7052 if (al == &global_alist)
7053 #endif
7054 arg_had_last = FALSE;
7058 * Add file "fname" to argument list "al".
7059 * "fname" must have been allocated and "al" must have been checked for room.
7061 void
7062 alist_add(al, fname, set_fnum)
7063 alist_T *al;
7064 char_u *fname;
7065 int set_fnum; /* 1: set buffer number; 2: re-use curbuf */
7067 if (fname == NULL) /* don't add NULL file names */
7068 return;
7069 #ifdef BACKSLASH_IN_FILENAME
7070 slash_adjust(fname);
7071 #endif
7072 AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
7073 if (set_fnum > 0)
7074 AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
7075 buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
7076 ++al->al_ga.ga_len;
7079 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7081 * Adjust slashes in file names. Called after 'shellslash' was set.
7083 void
7084 alist_slash_adjust()
7086 int i;
7087 # ifdef FEAT_WINDOWS
7088 win_T *wp;
7089 tabpage_T *tp;
7090 # endif
7092 for (i = 0; i < GARGCOUNT; ++i)
7093 if (GARGLIST[i].ae_fname != NULL)
7094 slash_adjust(GARGLIST[i].ae_fname);
7095 # ifdef FEAT_WINDOWS
7096 FOR_ALL_TAB_WINDOWS(tp, wp)
7097 if (wp->w_alist != &global_alist)
7098 for (i = 0; i < WARGCOUNT(wp); ++i)
7099 if (WARGLIST(wp)[i].ae_fname != NULL)
7100 slash_adjust(WARGLIST(wp)[i].ae_fname);
7101 # endif
7103 #endif
7106 * ":preserve".
7108 static void
7109 ex_preserve(eap)
7110 exarg_T *eap UNUSED;
7112 curbuf->b_flags |= BF_PRESERVED;
7113 ml_preserve(curbuf, TRUE);
7117 * ":recover".
7119 static void
7120 ex_recover(eap)
7121 exarg_T *eap;
7123 /* Set recoverymode right away to avoid the ATTENTION prompt. */
7124 recoverymode = TRUE;
7125 if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
7126 && (*eap->arg == NUL
7127 || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
7128 ml_recover();
7129 recoverymode = FALSE;
7133 * Command modifier used in a wrong way.
7135 static void
7136 ex_wrongmodifier(eap)
7137 exarg_T *eap;
7139 eap->errmsg = e_invcmd;
7142 #ifdef FEAT_WINDOWS
7144 * :sview [+command] file split window with new file, read-only
7145 * :split [[+command] file] split window with current or new file
7146 * :vsplit [[+command] file] split window vertically with current or new file
7147 * :new [[+command] file] split window with no or new file
7148 * :vnew [[+command] file] split vertically window with no or new file
7149 * :sfind [+command] file split window with file in 'path'
7151 * :tabedit open new Tab page with empty window
7152 * :tabedit [+command] file open new Tab page and edit "file"
7153 * :tabnew [[+command] file] just like :tabedit
7154 * :tabfind [+command] file open new Tab page and find "file"
7156 void
7157 ex_splitview(eap)
7158 exarg_T *eap;
7160 win_T *old_curwin = curwin;
7161 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7162 char_u *fname = NULL;
7163 # endif
7164 # ifdef FEAT_BROWSE
7165 int browse_flag = cmdmod.browse;
7166 # endif
7168 # ifndef FEAT_VERTSPLIT
7169 if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
7171 ex_ni(eap);
7172 return;
7174 # endif
7176 # ifdef FEAT_GUI
7177 need_mouse_correct = TRUE;
7178 # endif
7180 # ifdef FEAT_QUICKFIX
7181 /* A ":split" in the quickfix window works like ":new". Don't want two
7182 * quickfix windows. But it's OK when doing ":tab split". */
7183 if (bt_quickfix(curbuf) && cmdmod.tab == 0)
7185 if (eap->cmdidx == CMD_split)
7186 eap->cmdidx = CMD_new;
7187 # ifdef FEAT_VERTSPLIT
7188 if (eap->cmdidx == CMD_vsplit)
7189 eap->cmdidx = CMD_vnew;
7190 # endif
7192 # endif
7194 # ifdef FEAT_SEARCHPATH
7195 if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
7197 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
7198 FNAME_MESS, TRUE, curbuf->b_ffname);
7199 if (fname == NULL)
7200 goto theend;
7201 eap->arg = fname;
7203 # ifdef FEAT_BROWSE
7204 else
7205 # endif
7206 # endif
7207 # ifdef FEAT_BROWSE
7208 if (cmdmod.browse
7209 # ifdef FEAT_VERTSPLIT
7210 && eap->cmdidx != CMD_vnew
7211 # endif
7212 && eap->cmdidx != CMD_new)
7214 # ifdef FEAT_AUTOCMD
7215 if (
7216 # ifdef FEAT_GUI
7217 !gui.in_use &&
7218 # endif
7219 au_has_group((char_u *)"FileExplorer"))
7221 /* No browsing supported but we do have the file explorer:
7222 * Edit the directory. */
7223 if (*eap->arg == NUL || !mch_isdir(eap->arg))
7224 eap->arg = (char_u *)".";
7226 else
7227 # endif
7229 fname = do_browse(0, (char_u *)_("Edit File in new window"),
7230 eap->arg, NULL, NULL, NULL, curbuf);
7231 if (fname == NULL)
7232 goto theend;
7233 eap->arg = fname;
7236 cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */
7237 # endif
7240 * Either open new tab page or split the window.
7242 if (eap->cmdidx == CMD_tabedit
7243 || eap->cmdidx == CMD_tabfind
7244 || eap->cmdidx == CMD_tabnew)
7246 if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
7247 : eap->addr_count == 0 ? 0
7248 : (int)eap->line2 + 1) != FAIL)
7250 do_exedit(eap, old_curwin);
7252 /* set the alternate buffer for the window we came from */
7253 if (curwin != old_curwin
7254 && win_valid(old_curwin)
7255 && old_curwin->w_buffer != curbuf
7256 && !cmdmod.keepalt)
7257 old_curwin->w_alt_fnum = curbuf->b_fnum;
7260 else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
7261 *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
7263 # ifdef FEAT_SCROLLBIND
7264 /* Reset 'scrollbind' when editing another file, but keep it when
7265 * doing ":split" without arguments. */
7266 if (*eap->arg != NUL
7267 # ifdef FEAT_BROWSE
7268 || cmdmod.browse
7269 # endif
7271 curwin->w_p_scb = FALSE;
7272 else
7273 do_check_scrollbind(FALSE);
7274 # endif
7275 do_exedit(eap, old_curwin);
7278 # ifdef FEAT_BROWSE
7279 cmdmod.browse = browse_flag;
7280 # endif
7282 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7283 theend:
7284 vim_free(fname);
7285 # endif
7289 * Open a new tab page.
7291 void
7292 tabpage_new()
7294 exarg_T ea;
7296 vim_memset(&ea, 0, sizeof(ea));
7297 ea.cmdidx = CMD_tabnew;
7298 ea.cmd = (char_u *)"tabn";
7299 ea.arg = (char_u *)"";
7300 ex_splitview(&ea);
7304 * :tabnext command
7306 static void
7307 ex_tabnext(eap)
7308 exarg_T *eap;
7310 switch (eap->cmdidx)
7312 case CMD_tabfirst:
7313 case CMD_tabrewind:
7314 goto_tabpage(1);
7315 break;
7316 case CMD_tablast:
7317 goto_tabpage(9999);
7318 break;
7319 case CMD_tabprevious:
7320 case CMD_tabNext:
7321 goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2);
7322 break;
7323 default: /* CMD_tabnext */
7324 goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2);
7325 break;
7330 * :tabmove command
7332 static void
7333 ex_tabmove(eap)
7334 exarg_T *eap;
7336 tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2);
7340 * :tabs command: List tabs and their contents.
7342 static void
7343 ex_tabs(eap)
7344 exarg_T *eap UNUSED;
7346 tabpage_T *tp;
7347 win_T *wp;
7348 int tabcount = 1;
7349 char_u *bname;
7351 msg_start();
7352 msg_scroll = TRUE;
7353 for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
7355 msg_putchar('\n');
7356 vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
7357 msg_outtrans_attr(IObuff, hl_attr(HLF_T));
7358 out_flush(); /* output one line at a time */
7359 ui_breakcheck();
7361 if (tp == curtab)
7362 wp = firstwin;
7363 else
7364 wp = tp->tp_firstwin;
7365 for ( ; wp != NULL && !got_int; wp = wp->w_next)
7367 msg_putchar('\n');
7368 msg_putchar(wp == curwin ? '>' : ' ');
7369 msg_putchar(' ');
7370 msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
7371 msg_putchar(' ');
7372 if ((bname = (char_u *)buf_spname(wp->w_buffer)) != NULL)
7374 vim_strncpy(IObuff, bname, IOSIZE - 1);
7375 vim_free(bname);
7377 else
7378 home_replace(wp->w_buffer, wp->w_buffer->b_fname,
7379 IObuff, IOSIZE, TRUE);
7380 msg_outtrans(IObuff);
7381 out_flush(); /* output one line at a time */
7382 ui_breakcheck();
7387 #endif /* FEAT_WINDOWS */
7390 * ":mode": Set screen mode.
7391 * If no argument given, just get the screen size and redraw.
7393 static void
7394 ex_mode(eap)
7395 exarg_T *eap;
7397 if (*eap->arg == NUL)
7398 shell_resized();
7399 else
7400 mch_screenmode(eap->arg);
7403 #ifdef FEAT_WINDOWS
7405 * ":resize".
7406 * set, increment or decrement current window height
7408 static void
7409 ex_resize(eap)
7410 exarg_T *eap;
7412 int n;
7413 win_T *wp = curwin;
7415 if (eap->addr_count > 0)
7417 n = eap->line2;
7418 for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
7422 #ifdef FEAT_GUI
7423 need_mouse_correct = TRUE;
7424 #endif
7425 n = atol((char *)eap->arg);
7426 #ifdef FEAT_VERTSPLIT
7427 if (cmdmod.split & WSP_VERT)
7429 if (*eap->arg == '-' || *eap->arg == '+')
7430 n += W_WIDTH(curwin);
7431 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7432 n = 9999;
7433 win_setwidth_win((int)n, wp);
7435 else
7436 #endif
7438 if (*eap->arg == '-' || *eap->arg == '+')
7439 n += curwin->w_height;
7440 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7441 n = 9999;
7442 win_setheight_win((int)n, wp);
7445 #endif
7448 * ":find [+command] <file>" command.
7450 static void
7451 ex_find(eap)
7452 exarg_T *eap;
7454 #ifdef FEAT_SEARCHPATH
7455 char_u *fname;
7456 int count;
7458 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
7459 TRUE, curbuf->b_ffname);
7460 if (eap->addr_count > 0)
7462 /* Repeat finding the file "count" times. This matters when it
7463 * appears several times in the path. */
7464 count = eap->line2;
7465 while (fname != NULL && --count > 0)
7467 vim_free(fname);
7468 fname = find_file_in_path(NULL, 0, FNAME_MESS,
7469 FALSE, curbuf->b_ffname);
7473 if (fname != NULL)
7475 eap->arg = fname;
7476 #endif
7477 do_exedit(eap, NULL);
7478 #ifdef FEAT_SEARCHPATH
7479 vim_free(fname);
7481 #endif
7485 * ":open" simulation: for now just work like ":visual".
7487 static void
7488 ex_open(eap)
7489 exarg_T *eap;
7491 regmatch_T regmatch;
7492 char_u *p;
7494 curwin->w_cursor.lnum = eap->line2;
7495 beginline(BL_SOL | BL_FIX);
7496 if (*eap->arg == '/')
7498 /* ":open /pattern/": put cursor in column found with pattern */
7499 ++eap->arg;
7500 p = skip_regexp(eap->arg, '/', p_magic, NULL);
7501 *p = NUL;
7502 regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
7503 if (regmatch.regprog != NULL)
7505 regmatch.rm_ic = p_ic;
7506 p = ml_get_curline();
7507 if (vim_regexec(&regmatch, p, (colnr_T)0))
7508 curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
7509 else
7510 EMSG(_(e_nomatch));
7511 vim_free(regmatch.regprog);
7513 /* Move to the NUL, ignore any other arguments. */
7514 eap->arg += STRLEN(eap->arg);
7516 check_cursor();
7518 eap->cmdidx = CMD_visual;
7519 do_exedit(eap, NULL);
7523 * ":edit", ":badd", ":visual".
7525 static void
7526 ex_edit(eap)
7527 exarg_T *eap;
7529 do_exedit(eap, NULL);
7533 * ":edit <file>" command and alikes.
7535 void
7536 do_exedit(eap, old_curwin)
7537 exarg_T *eap;
7538 win_T *old_curwin; /* curwin before doing a split or NULL */
7540 int n;
7541 #ifdef FEAT_WINDOWS
7542 int need_hide;
7543 #endif
7544 int exmode_was = exmode_active;
7547 * ":vi" command ends Ex mode.
7549 if (exmode_active && (eap->cmdidx == CMD_visual
7550 || eap->cmdidx == CMD_view))
7552 exmode_active = FALSE;
7553 if (*eap->arg == NUL)
7555 /* Special case: ":global/pat/visual\NLvi-commands" */
7556 if (global_busy)
7558 int rd = RedrawingDisabled;
7559 int nwr = no_wait_return;
7560 int ms = msg_scroll;
7561 #ifdef FEAT_GUI
7562 int he = hold_gui_events;
7563 #endif
7565 if (eap->nextcmd != NULL)
7567 stuffReadbuff(eap->nextcmd);
7568 eap->nextcmd = NULL;
7571 if (exmode_was != EXMODE_VIM)
7572 settmode(TMODE_RAW);
7573 RedrawingDisabled = 0;
7574 no_wait_return = 0;
7575 need_wait_return = FALSE;
7576 msg_scroll = 0;
7577 #ifdef FEAT_GUI
7578 hold_gui_events = 0;
7579 #endif
7580 must_redraw = CLEAR;
7582 main_loop(FALSE, TRUE);
7584 RedrawingDisabled = rd;
7585 no_wait_return = nwr;
7586 msg_scroll = ms;
7587 #ifdef FEAT_GUI
7588 hold_gui_events = he;
7589 #endif
7591 return;
7595 if ((eap->cmdidx == CMD_new
7596 || eap->cmdidx == CMD_tabnew
7597 || eap->cmdidx == CMD_tabedit
7598 #ifdef FEAT_VERTSPLIT
7599 || eap->cmdidx == CMD_vnew
7600 #endif
7601 ) && *eap->arg == NUL)
7603 /* ":new" or ":tabnew" without argument: edit an new empty buffer */
7604 setpcmark();
7605 (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
7606 ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
7607 old_curwin == NULL ? curwin : NULL);
7609 else if ((eap->cmdidx != CMD_split
7610 #ifdef FEAT_VERTSPLIT
7611 && eap->cmdidx != CMD_vsplit
7612 #endif
7614 || *eap->arg != NUL
7615 #ifdef FEAT_BROWSE
7616 || cmdmod.browse
7617 #endif
7620 #ifdef FEAT_AUTOCMD
7621 /* Can't edit another file when "curbuf_lock" is set. Only ":edit"
7622 * can bring us here, others are stopped earlier. */
7623 if (*eap->arg != NUL && curbuf_locked())
7624 return;
7625 #endif
7626 n = readonlymode;
7627 if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
7628 readonlymode = TRUE;
7629 else if (eap->cmdidx == CMD_enew)
7630 readonlymode = FALSE; /* 'readonly' doesn't make sense in an
7631 empty buffer */
7632 setpcmark();
7633 if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
7634 NULL, eap,
7635 /* ":edit" goes to first line if Vi compatible */
7636 (*eap->arg == NUL && eap->do_ecmd_lnum == 0
7637 && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
7638 ? ECMD_ONE : eap->do_ecmd_lnum,
7639 (P_HID(curbuf) ? ECMD_HIDE : 0)
7640 + (eap->forceit ? ECMD_FORCEIT : 0)
7641 #ifdef FEAT_LISTCMDS
7642 + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
7643 #endif
7644 , old_curwin == NULL ? curwin : NULL) == FAIL)
7646 /* Editing the file failed. If the window was split, close it. */
7647 #ifdef FEAT_WINDOWS
7648 if (old_curwin != NULL)
7650 need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
7651 if (!need_hide || P_HID(curbuf))
7653 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7654 cleanup_T cs;
7656 /* Reset the error/interrupt/exception state here so that
7657 * aborting() returns FALSE when closing a window. */
7658 enter_cleanup(&cs);
7659 # endif
7660 # ifdef FEAT_GUI
7661 need_mouse_correct = TRUE;
7662 # endif
7663 win_close(curwin, !need_hide && !P_HID(curbuf));
7665 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7666 /* Restore the error/interrupt/exception state if not
7667 * discarded by a new aborting error, interrupt, or
7668 * uncaught exception. */
7669 leave_cleanup(&cs);
7670 # endif
7673 #endif
7675 else if (readonlymode && curbuf->b_nwindows == 1)
7677 /* When editing an already visited buffer, 'readonly' won't be set
7678 * but the previous value is kept. With ":view" and ":sview" we
7679 * want the file to be readonly, except when another window is
7680 * editing the same buffer. */
7681 curbuf->b_p_ro = TRUE;
7683 readonlymode = n;
7685 else
7687 if (eap->do_ecmd_cmd != NULL)
7688 do_cmdline_cmd(eap->do_ecmd_cmd);
7689 #ifdef FEAT_TITLE
7690 n = curwin->w_arg_idx_invalid;
7691 #endif
7692 check_arg_idx(curwin);
7693 #ifdef FEAT_TITLE
7694 if (n != curwin->w_arg_idx_invalid)
7695 maketitle();
7696 #endif
7699 #ifdef FEAT_WINDOWS
7701 * if ":split file" worked, set alternate file name in old window to new
7702 * file
7704 if (old_curwin != NULL
7705 && *eap->arg != NUL
7706 && curwin != old_curwin
7707 && win_valid(old_curwin)
7708 && old_curwin->w_buffer != curbuf
7709 && !cmdmod.keepalt)
7710 old_curwin->w_alt_fnum = curbuf->b_fnum;
7711 #endif
7713 ex_no_reprint = TRUE;
7716 #ifndef FEAT_GUI
7718 * ":gui" and ":gvim" when there is no GUI.
7720 static void
7721 ex_nogui(eap)
7722 exarg_T *eap;
7724 eap->errmsg = e_nogvim;
7726 #endif
7728 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
7729 static void
7730 ex_tearoff(eap)
7731 exarg_T *eap;
7733 gui_make_tearoff(eap->arg);
7735 #endif
7737 #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU)
7738 static void
7739 ex_popup(eap)
7740 exarg_T *eap;
7742 gui_make_popup(eap->arg, eap->forceit);
7744 #endif
7746 static void
7747 ex_swapname(eap)
7748 exarg_T *eap UNUSED;
7750 if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
7751 MSG(_("No swap file"));
7752 else
7753 msg(curbuf->b_ml.ml_mfp->mf_fname);
7757 * ":syncbind" forces all 'scrollbind' windows to have the same relative
7758 * offset.
7759 * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
7761 static void
7762 ex_syncbind(eap)
7763 exarg_T *eap UNUSED;
7765 #ifdef FEAT_SCROLLBIND
7766 win_T *wp;
7767 long topline;
7768 long y;
7769 linenr_T old_linenr = curwin->w_cursor.lnum;
7771 setpcmark();
7774 * determine max topline
7776 if (curwin->w_p_scb)
7778 topline = curwin->w_topline;
7779 for (wp = firstwin; wp; wp = wp->w_next)
7781 if (wp->w_p_scb && wp->w_buffer)
7783 y = wp->w_buffer->b_ml.ml_line_count - p_so;
7784 if (topline > y)
7785 topline = y;
7788 if (topline < 1)
7789 topline = 1;
7791 else
7793 topline = 1;
7798 * set all scrollbind windows to the same topline
7800 wp = curwin;
7801 for (curwin = firstwin; curwin; curwin = curwin->w_next)
7803 if (curwin->w_p_scb)
7805 y = topline - curwin->w_topline;
7806 if (y > 0)
7807 scrollup(y, TRUE);
7808 else
7809 scrolldown(-y, TRUE);
7810 curwin->w_scbind_pos = topline;
7811 redraw_later(VALID);
7812 cursor_correct();
7813 #ifdef FEAT_WINDOWS
7814 curwin->w_redr_status = TRUE;
7815 #endif
7818 curwin = wp;
7819 if (curwin->w_p_scb)
7821 did_syncbind = TRUE;
7822 checkpcmark();
7823 if (old_linenr != curwin->w_cursor.lnum)
7825 char_u ctrl_o[2];
7827 ctrl_o[0] = Ctrl_O;
7828 ctrl_o[1] = 0;
7829 ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
7832 #endif
7836 static void
7837 ex_read(eap)
7838 exarg_T *eap;
7840 int i;
7841 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7842 linenr_T lnum;
7844 if (eap->usefilter) /* :r!cmd */
7845 do_bang(1, eap, FALSE, FALSE, TRUE);
7846 else
7848 if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
7849 return;
7851 #ifdef FEAT_BROWSE
7852 if (cmdmod.browse)
7854 char_u *browseFile;
7856 browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
7857 NULL, NULL, NULL, curbuf);
7858 if (browseFile != NULL)
7860 i = readfile(browseFile, NULL,
7861 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7862 vim_free(browseFile);
7864 else
7865 i = OK;
7867 else
7868 #endif
7869 if (*eap->arg == NUL)
7871 if (check_fname() == FAIL) /* check for no file name */
7872 return;
7873 i = readfile(curbuf->b_ffname, curbuf->b_fname,
7874 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7876 else
7878 if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
7879 (void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
7880 i = readfile(eap->arg, NULL,
7881 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7884 if (i == FAIL)
7886 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7887 if (!aborting())
7888 #endif
7889 EMSG2(_(e_notopen), eap->arg);
7891 else
7893 if (empty && exmode_active)
7895 /* Delete the empty line that remains. Historically ex does
7896 * this but vi doesn't. */
7897 if (eap->line2 == 0)
7898 lnum = curbuf->b_ml.ml_line_count;
7899 else
7900 lnum = 1;
7901 if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
7903 ml_delete(lnum, FALSE);
7904 if (curwin->w_cursor.lnum > 1
7905 && curwin->w_cursor.lnum >= lnum)
7906 --curwin->w_cursor.lnum;
7907 deleted_lines_mark(lnum, 1L);
7910 redraw_curbuf_later(VALID);
7915 static char_u *prev_dir = NULL;
7917 #if defined(EXITFREE) || defined(PROTO)
7918 void
7919 free_cd_dir()
7921 vim_free(prev_dir);
7922 prev_dir = NULL;
7924 vim_free(globaldir);
7925 globaldir = NULL;
7927 #endif
7931 * ":cd", ":lcd", ":chdir" and ":lchdir".
7933 void
7934 ex_cd(eap)
7935 exarg_T *eap;
7937 char_u *new_dir;
7938 char_u *tofree;
7940 new_dir = eap->arg;
7941 #if !defined(UNIX) && !defined(VMS)
7942 /* for non-UNIX ":cd" means: print current directory */
7943 if (*new_dir == NUL)
7944 ex_pwd(NULL);
7945 else
7946 #endif
7948 #ifdef FEAT_AUTOCMD
7949 if (allbuf_locked())
7950 return;
7951 #endif
7952 if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
7953 && !eap->forceit)
7955 EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
7956 return;
7959 /* ":cd -": Change to previous directory */
7960 if (STRCMP(new_dir, "-") == 0)
7962 if (prev_dir == NULL)
7964 EMSG(_("E186: No previous directory"));
7965 return;
7967 new_dir = prev_dir;
7970 /* Save current directory for next ":cd -" */
7971 tofree = prev_dir;
7972 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7973 prev_dir = vim_strsave(NameBuff);
7974 else
7975 prev_dir = NULL;
7977 #if defined(UNIX) || defined(VMS)
7978 /* for UNIX ":cd" means: go to home directory */
7979 if (*new_dir == NUL)
7981 /* use NameBuff for home directory name */
7982 # ifdef VMS
7983 char_u *p;
7985 p = mch_getenv((char_u *)"SYS$LOGIN");
7986 if (p == NULL || *p == NUL) /* empty is the same as not set */
7987 NameBuff[0] = NUL;
7988 else
7989 vim_strncpy(NameBuff, p, MAXPATHL - 1);
7990 # else
7991 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
7992 # endif
7993 new_dir = NameBuff;
7995 #endif
7996 if (new_dir == NULL || vim_chdir(new_dir))
7997 EMSG(_(e_failed));
7998 else
8000 vim_free(curwin->w_localdir);
8001 if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
8003 /* If still in global directory, need to remember current
8004 * directory as global directory. */
8005 if (globaldir == NULL && prev_dir != NULL)
8006 globaldir = vim_strsave(prev_dir);
8007 /* Remember this local directory for the window. */
8008 if (mch_dirname(NameBuff, MAXPATHL) == OK)
8009 curwin->w_localdir = vim_strsave(NameBuff);
8011 else
8013 /* We are now in the global directory, no need to remember its
8014 * name. */
8015 vim_free(globaldir);
8016 globaldir = NULL;
8017 curwin->w_localdir = NULL;
8020 shorten_fnames(TRUE);
8022 /* Echo the new current directory if the command was typed. */
8023 if (KeyTyped || p_verbose >= 5)
8024 ex_pwd(eap);
8026 vim_free(tofree);
8031 * ":pwd".
8033 static void
8034 ex_pwd(eap)
8035 exarg_T *eap UNUSED;
8037 if (mch_dirname(NameBuff, MAXPATHL) == OK)
8039 #ifdef BACKSLASH_IN_FILENAME
8040 slash_adjust(NameBuff);
8041 #endif
8042 msg(NameBuff);
8044 else
8045 EMSG(_("E187: Unknown"));
8049 * ":=".
8051 static void
8052 ex_equal(eap)
8053 exarg_T *eap;
8055 smsg((char_u *)"%ld", (long)eap->line2);
8056 ex_may_print(eap);
8059 static void
8060 ex_sleep(eap)
8061 exarg_T *eap;
8063 int n;
8064 long len;
8066 if (cursor_valid())
8068 n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
8069 if (n >= 0)
8070 windgoto((int)n, curwin->w_wcol);
8073 len = eap->line2;
8074 switch (*eap->arg)
8076 case 'm': break;
8077 case NUL: len *= 1000L; break;
8078 default: EMSG2(_(e_invarg2), eap->arg); return;
8080 do_sleep(len);
8084 * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
8086 void
8087 do_sleep(msec)
8088 long msec;
8090 long done;
8092 cursor_on();
8093 out_flush();
8094 for (done = 0; !got_int && done < msec; done += 1000L)
8096 ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
8097 ui_breakcheck();
8101 static void
8102 do_exmap(eap, isabbrev)
8103 exarg_T *eap;
8104 int isabbrev;
8106 int mode;
8107 char_u *cmdp;
8109 cmdp = eap->cmd;
8110 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
8112 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
8113 eap->arg, mode, isabbrev))
8115 case 1: EMSG(_(e_invarg));
8116 break;
8117 case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
8118 break;
8123 * ":winsize" command (obsolete).
8125 static void
8126 ex_winsize(eap)
8127 exarg_T *eap;
8129 int w, h;
8130 char_u *arg = eap->arg;
8131 char_u *p;
8133 w = getdigits(&arg);
8134 arg = skipwhite(arg);
8135 p = arg;
8136 h = getdigits(&arg);
8137 if (*p != NUL && *arg == NUL)
8138 set_shellsize(w, h, TRUE);
8139 else
8140 EMSG(_("E465: :winsize requires two number arguments"));
8143 #ifdef FEAT_WINDOWS
8144 static void
8145 ex_wincmd(eap)
8146 exarg_T *eap;
8148 int xchar = NUL;
8149 char_u *p;
8151 if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
8153 /* CTRL-W g and CTRL-W CTRL-G have an extra command character */
8154 if (eap->arg[1] == NUL)
8156 EMSG(_(e_invarg));
8157 return;
8159 xchar = eap->arg[1];
8160 p = eap->arg + 2;
8162 else
8163 p = eap->arg + 1;
8165 eap->nextcmd = check_nextcmd(p);
8166 p = skipwhite(p);
8167 if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
8168 EMSG(_(e_invarg));
8169 else
8171 /* Pass flags on for ":vertical wincmd ]". */
8172 postponed_split_flags = cmdmod.split;
8173 postponed_split_tab = cmdmod.tab;
8174 do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
8175 postponed_split_flags = 0;
8176 postponed_split_tab = 0;
8179 #endif
8181 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
8183 * ":winpos".
8185 static void
8186 ex_winpos(eap)
8187 exarg_T *eap;
8189 int x, y;
8190 char_u *arg = eap->arg;
8191 char_u *p;
8193 if (*arg == NUL)
8195 # if defined(FEAT_GUI) || defined(MSWIN)
8196 # ifdef FEAT_GUI
8197 if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
8198 # else
8199 if (mch_get_winpos(&x, &y) != FAIL)
8200 # endif
8202 sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
8203 msg(IObuff);
8205 else
8206 # endif
8207 EMSG(_("E188: Obtaining window position not implemented for this platform"));
8209 else
8211 x = getdigits(&arg);
8212 arg = skipwhite(arg);
8213 p = arg;
8214 y = getdigits(&arg);
8215 if (*p == NUL || *arg != NUL)
8217 EMSG(_("E466: :winpos requires two number arguments"));
8218 return;
8220 # ifdef FEAT_GUI
8221 if (gui.in_use)
8222 gui_mch_set_winpos(x, y);
8223 else if (gui.starting)
8225 /* Remember the coordinates for when the window is opened. */
8226 gui_win_x = x;
8227 gui_win_y = y;
8229 # ifdef HAVE_TGETENT
8230 else
8231 # endif
8232 # else
8233 # ifdef MSWIN
8234 mch_set_winpos(x, y);
8235 # endif
8236 # endif
8237 # ifdef HAVE_TGETENT
8238 if (*T_CWP)
8239 term_set_winpos(x, y);
8240 # endif
8243 #endif
8246 * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
8248 static void
8249 ex_operators(eap)
8250 exarg_T *eap;
8252 oparg_T oa;
8254 clear_oparg(&oa);
8255 oa.regname = eap->regname;
8256 oa.start.lnum = eap->line1;
8257 oa.end.lnum = eap->line2;
8258 oa.line_count = eap->line2 - eap->line1 + 1;
8259 oa.motion_type = MLINE;
8260 #ifdef FEAT_VIRTUALEDIT
8261 virtual_op = FALSE;
8262 #endif
8263 if (eap->cmdidx != CMD_yank) /* position cursor for undo */
8265 setpcmark();
8266 curwin->w_cursor.lnum = eap->line1;
8267 beginline(BL_SOL | BL_FIX);
8270 switch (eap->cmdidx)
8272 case CMD_delete:
8273 oa.op_type = OP_DELETE;
8274 op_delete(&oa);
8275 break;
8277 case CMD_yank:
8278 oa.op_type = OP_YANK;
8279 (void)op_yank(&oa, FALSE, TRUE);
8280 break;
8282 default: /* CMD_rshift or CMD_lshift */
8283 if ((eap->cmdidx == CMD_rshift)
8284 #ifdef FEAT_RIGHTLEFT
8285 ^ curwin->w_p_rl
8286 #endif
8288 oa.op_type = OP_RSHIFT;
8289 else
8290 oa.op_type = OP_LSHIFT;
8291 op_shift(&oa, FALSE, eap->amount);
8292 break;
8294 #ifdef FEAT_VIRTUALEDIT
8295 virtual_op = MAYBE;
8296 #endif
8297 ex_may_print(eap);
8301 * ":put".
8303 static void
8304 ex_put(eap)
8305 exarg_T *eap;
8307 /* ":0put" works like ":1put!". */
8308 if (eap->line2 == 0)
8310 eap->line2 = 1;
8311 eap->forceit = TRUE;
8313 curwin->w_cursor.lnum = eap->line2;
8314 do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
8315 PUT_LINE|PUT_CURSLINE);
8319 * Handle ":copy" and ":move".
8321 static void
8322 ex_copymove(eap)
8323 exarg_T *eap;
8325 long n;
8327 n = get_address(&eap->arg, FALSE, FALSE);
8328 if (eap->arg == NULL) /* error detected */
8330 eap->nextcmd = NULL;
8331 return;
8333 get_flags(eap);
8336 * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
8338 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
8340 EMSG(_(e_invaddr));
8341 return;
8344 if (eap->cmdidx == CMD_move)
8346 if (do_move(eap->line1, eap->line2, n) == FAIL)
8347 return;
8349 else
8350 ex_copy(eap->line1, eap->line2, n);
8351 u_clearline();
8352 beginline(BL_SOL | BL_FIX);
8353 ex_may_print(eap);
8357 * Print the current line if flags were given to the Ex command.
8359 static void
8360 ex_may_print(eap)
8361 exarg_T *eap;
8363 if (eap->flags != 0)
8365 print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
8366 (eap->flags & EXFLAG_LIST));
8367 ex_no_reprint = TRUE;
8372 * ":smagic" and ":snomagic".
8374 static void
8375 ex_submagic(eap)
8376 exarg_T *eap;
8378 int magic_save = p_magic;
8380 p_magic = (eap->cmdidx == CMD_smagic);
8381 do_sub(eap);
8382 p_magic = magic_save;
8386 * ":join".
8388 static void
8389 ex_join(eap)
8390 exarg_T *eap;
8392 curwin->w_cursor.lnum = eap->line1;
8393 if (eap->line1 == eap->line2)
8395 if (eap->addr_count >= 2) /* :2,2join does nothing */
8396 return;
8397 if (eap->line2 == curbuf->b_ml.ml_line_count)
8399 beep_flush();
8400 return;
8402 ++eap->line2;
8404 (void)do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
8405 beginline(BL_WHITE | BL_FIX);
8406 ex_may_print(eap);
8410 * ":[addr]@r" or ":[addr]*r": execute register
8412 static void
8413 ex_at(eap)
8414 exarg_T *eap;
8416 int c;
8417 int prev_len = typebuf.tb_len;
8419 curwin->w_cursor.lnum = eap->line2;
8421 #ifdef USE_ON_FLY_SCROLL
8422 dont_scroll = TRUE; /* disallow scrolling here */
8423 #endif
8425 /* get the register name. No name means to use the previous one */
8426 c = *eap->arg;
8427 if (c == NUL || (c == '*' && *eap->cmd == '*'))
8428 c = '@';
8429 /* Put the register in the typeahead buffer with the "silent" flag. */
8430 if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
8431 == FAIL)
8433 beep_flush();
8435 else
8437 int save_efr = exec_from_reg;
8439 exec_from_reg = TRUE;
8442 * Execute from the typeahead buffer.
8443 * Continue until the stuff buffer is empty and all added characters
8444 * have been consumed.
8446 while (!stuff_empty() || typebuf.tb_len > prev_len)
8447 (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
8449 exec_from_reg = save_efr;
8454 * ":!".
8456 static void
8457 ex_bang(eap)
8458 exarg_T *eap;
8460 do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
8464 * ":undo".
8466 static void
8467 ex_undo(eap)
8468 exarg_T *eap UNUSED;
8470 if (eap->addr_count == 1) /* :undo 123 */
8471 undo_time(eap->line2, FALSE, TRUE);
8472 else
8473 u_undo(1);
8476 #ifdef FEAT_PERSISTENT_UNDO
8477 void
8478 ex_wundo(eap)
8479 exarg_T *eap;
8481 char_u *name = eap->arg;
8482 u_wundo(name, curbuf);
8485 void
8486 ex_rundo(eap)
8487 exarg_T *eap;
8489 char_u *name = eap->arg;
8490 u_rundo(name, 0);
8492 #endif
8495 * ":redo".
8497 static void
8498 ex_redo(eap)
8499 exarg_T *eap UNUSED;
8501 u_redo(1);
8505 * ":earlier" and ":later".
8507 static void
8508 ex_later(eap)
8509 exarg_T *eap;
8511 long count = 0;
8512 int sec = FALSE;
8513 char_u *p = eap->arg;
8515 if (*p == NUL)
8516 count = 1;
8517 else if (isdigit(*p))
8519 count = getdigits(&p);
8520 switch (*p)
8522 case 's': ++p; sec = TRUE; break;
8523 case 'm': ++p; sec = TRUE; count *= 60; break;
8524 case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
8528 if (*p != NUL)
8529 EMSG2(_(e_invarg2), eap->arg);
8530 else
8531 undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, FALSE);
8535 * ":redir": start/stop redirection.
8537 static void
8538 ex_redir(eap)
8539 exarg_T *eap;
8541 char *mode;
8542 char_u *fname;
8543 char_u *arg = eap->arg;
8545 if (STRICMP(eap->arg, "END") == 0)
8546 close_redir();
8547 else
8549 if (*arg == '>')
8551 ++arg;
8552 if (*arg == '>')
8554 ++arg;
8555 mode = "a";
8557 else
8558 mode = "w";
8559 arg = skipwhite(arg);
8561 close_redir();
8563 /* Expand environment variables and "~/". */
8564 fname = expand_env_save(arg);
8565 if (fname == NULL)
8566 return;
8567 #ifdef FEAT_BROWSE
8568 if (cmdmod.browse)
8570 char_u *browseFile;
8572 browseFile = do_browse(BROWSE_SAVE,
8573 (char_u *)_("Save Redirection"),
8574 fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
8575 if (browseFile == NULL)
8576 return; /* operation cancelled */
8577 vim_free(fname);
8578 fname = browseFile;
8579 eap->forceit = TRUE; /* since dialog already asked */
8581 #endif
8583 redir_fd = open_exfile(fname, eap->forceit, mode);
8584 vim_free(fname);
8586 #ifdef FEAT_EVAL
8587 else if (*arg == '@')
8589 /* redirect to a register a-z (resp. A-Z for appending) */
8590 close_redir();
8591 ++arg;
8592 if (ASCII_ISALPHA(*arg)
8593 # ifdef FEAT_CLIPBOARD
8594 || *arg == '*'
8595 || *arg == '+'
8596 # endif
8597 || *arg == '"')
8599 redir_reg = *arg++;
8600 if (*arg == '>' && arg[1] == '>') /* append */
8601 arg += 2;
8602 else
8604 /* Can use both "@a" and "@a>". */
8605 if (*arg == '>')
8606 arg++;
8607 /* Make register empty when not using @A-@Z and the
8608 * command is valid. */
8609 if (*arg == NUL && !isupper(redir_reg))
8610 write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
8613 if (*arg != NUL)
8615 redir_reg = 0;
8616 EMSG2(_(e_invarg2), eap->arg);
8619 else if (*arg == '=' && arg[1] == '>')
8621 int append;
8623 /* redirect to a variable */
8624 close_redir();
8625 arg += 2;
8627 if (*arg == '>')
8629 ++arg;
8630 append = TRUE;
8632 else
8633 append = FALSE;
8635 if (var_redir_start(skipwhite(arg), append) == OK)
8636 redir_vname = 1;
8638 #endif
8640 /* TODO: redirect to a buffer */
8642 else
8643 EMSG2(_(e_invarg2), eap->arg);
8646 /* Make sure redirection is not off. Can happen for cmdline completion
8647 * that indirectly invokes a command to catch its output. */
8648 if (redir_fd != NULL
8649 #ifdef FEAT_EVAL
8650 || redir_reg || redir_vname
8651 #endif
8653 redir_off = FALSE;
8657 * ":redraw": force redraw
8659 static void
8660 ex_redraw(eap)
8661 exarg_T *eap;
8663 int r = RedrawingDisabled;
8664 int p = p_lz;
8666 RedrawingDisabled = 0;
8667 p_lz = FALSE;
8668 update_topline();
8669 update_screen(eap->forceit ? CLEAR :
8670 #ifdef FEAT_VISUAL
8671 VIsual_active ? INVERTED :
8672 #endif
8674 #ifdef FEAT_TITLE
8675 if (need_maketitle)
8676 maketitle();
8677 #endif
8678 RedrawingDisabled = r;
8679 p_lz = p;
8681 /* Reset msg_didout, so that a message that's there is overwritten. */
8682 msg_didout = FALSE;
8683 msg_col = 0;
8685 out_flush();
8689 * ":redrawstatus": force redraw of status line(s)
8691 static void
8692 ex_redrawstatus(eap)
8693 exarg_T *eap UNUSED;
8695 #if defined(FEAT_WINDOWS)
8696 int r = RedrawingDisabled;
8697 int p = p_lz;
8699 RedrawingDisabled = 0;
8700 p_lz = FALSE;
8701 if (eap->forceit)
8702 status_redraw_all();
8703 else
8704 status_redraw_curbuf();
8705 update_screen(
8706 # ifdef FEAT_VISUAL
8707 VIsual_active ? INVERTED :
8708 # endif
8710 RedrawingDisabled = r;
8711 p_lz = p;
8712 out_flush();
8713 #endif
8716 static void
8717 close_redir()
8719 if (redir_fd != NULL)
8721 fclose(redir_fd);
8722 redir_fd = NULL;
8724 #ifdef FEAT_EVAL
8725 redir_reg = 0;
8726 if (redir_vname)
8728 var_redir_stop();
8729 redir_vname = 0;
8731 #endif
8734 #if defined(FEAT_SESSION) && defined(USE_CRNL)
8735 # define MKSESSION_NL
8736 static int mksession_nl = FALSE; /* use NL only in put_eol() */
8737 #endif
8740 * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
8742 static void
8743 ex_mkrc(eap)
8744 exarg_T *eap;
8746 FILE *fd;
8747 int failed = FALSE;
8748 char_u *fname;
8749 #ifdef FEAT_BROWSE
8750 char_u *browseFile = NULL;
8751 #endif
8752 #ifdef FEAT_SESSION
8753 int view_session = FALSE;
8754 int using_vdir = FALSE; /* using 'viewdir'? */
8755 char_u *viewFile = NULL;
8756 unsigned *flagp;
8757 #endif
8759 if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
8761 #ifdef FEAT_SESSION
8762 view_session = TRUE;
8763 #else
8764 ex_ni(eap);
8765 return;
8766 #endif
8769 #ifdef FEAT_SESSION
8770 /* Use the short file name until ":lcd" is used. We also don't use the
8771 * short file name when 'acd' is set, that is checked later. */
8772 did_lcd = FALSE;
8774 /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
8775 if (eap->cmdidx == CMD_mkview
8776 && (*eap->arg == NUL
8777 || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
8779 eap->forceit = TRUE;
8780 fname = get_view_file(*eap->arg);
8781 if (fname == NULL)
8782 return;
8783 viewFile = fname;
8784 using_vdir = TRUE;
8786 else
8787 #endif
8788 if (*eap->arg != NUL)
8789 fname = eap->arg;
8790 else if (eap->cmdidx == CMD_mkvimrc)
8791 fname = (char_u *)VIMRC_FILE;
8792 #ifdef FEAT_SESSION
8793 else if (eap->cmdidx == CMD_mksession)
8794 fname = (char_u *)SESSION_FILE;
8795 #endif
8796 else
8797 fname = (char_u *)EXRC_FILE;
8799 #ifdef FEAT_BROWSE
8800 if (cmdmod.browse)
8802 browseFile = do_browse(BROWSE_SAVE,
8803 # ifdef FEAT_SESSION
8804 eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
8805 eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
8806 # endif
8807 (char_u *)_("Save Setup"),
8808 fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
8809 if (browseFile == NULL)
8810 goto theend;
8811 fname = browseFile;
8812 eap->forceit = TRUE; /* since dialog already asked */
8814 #endif
8816 #if defined(FEAT_SESSION) && defined(vim_mkdir)
8817 /* When using 'viewdir' may have to create the directory. */
8818 if (using_vdir && !mch_isdir(p_vdir))
8819 vim_mkdir_emsg(p_vdir, 0755);
8820 #endif
8822 fd = open_exfile(fname, eap->forceit, WRITEBIN);
8823 if (fd != NULL)
8825 #ifdef FEAT_SESSION
8826 if (eap->cmdidx == CMD_mkview)
8827 flagp = &vop_flags;
8828 else
8829 flagp = &ssop_flags;
8830 #endif
8832 #ifdef MKSESSION_NL
8833 /* "unix" in 'sessionoptions': use NL line separator */
8834 if (view_session && (*flagp & SSOP_UNIX))
8835 mksession_nl = TRUE;
8836 #endif
8838 /* Write the version command for :mkvimrc */
8839 if (eap->cmdidx == CMD_mkvimrc)
8840 (void)put_line(fd, "version 6.0");
8842 #ifdef FEAT_SESSION
8843 if (eap->cmdidx == CMD_mksession)
8845 if (put_line(fd, "let SessionLoad = 1") == FAIL)
8846 failed = TRUE;
8849 if (eap->cmdidx != CMD_mkview)
8850 #endif
8852 /* Write setting 'compatible' first, because it has side effects.
8853 * For that same reason only do it when needed. */
8854 if (p_cp)
8855 (void)put_line(fd, "if !&cp | set cp | endif");
8856 else
8857 (void)put_line(fd, "if &cp | set nocp | endif");
8860 #ifdef FEAT_SESSION
8861 if (!view_session
8862 || (eap->cmdidx == CMD_mksession
8863 && (*flagp & SSOP_OPTIONS)))
8864 #endif
8865 failed |= (makemap(fd, NULL) == FAIL
8866 || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
8868 #ifdef FEAT_SESSION
8869 if (!failed && view_session)
8871 if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
8872 failed = TRUE;
8873 if (eap->cmdidx == CMD_mksession)
8875 char_u dirnow[MAXPATHL]; /* current directory */
8878 * Change to session file's dir.
8880 if (mch_dirname(dirnow, MAXPATHL) == FAIL
8881 || mch_chdir((char *)dirnow) != 0)
8882 *dirnow = NUL;
8883 if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
8885 if (vim_chdirfile(fname) == OK)
8886 shorten_fnames(TRUE);
8888 else if (*dirnow != NUL
8889 && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
8891 if (mch_chdir((char *)globaldir) == 0)
8892 shorten_fnames(TRUE);
8895 failed |= (makeopens(fd, dirnow) == FAIL);
8897 /* restore original dir */
8898 if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
8899 || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
8901 if (mch_chdir((char *)dirnow) != 0)
8902 EMSG(_(e_prev_dir));
8903 shorten_fnames(TRUE);
8906 else
8908 failed |= (put_view(fd, curwin, !using_vdir, flagp,
8909 -1) == FAIL);
8911 if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
8912 == FAIL)
8913 failed = TRUE;
8914 if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
8915 failed = TRUE;
8916 if (eap->cmdidx == CMD_mksession)
8918 if (put_line(fd, "unlet SessionLoad") == FAIL)
8919 failed = TRUE;
8922 #endif
8923 if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
8924 failed = TRUE;
8926 failed |= fclose(fd);
8928 if (failed)
8929 EMSG(_(e_write));
8930 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
8931 else if (eap->cmdidx == CMD_mksession)
8933 /* successful session write - set this_session var */
8934 char_u tbuf[MAXPATHL];
8936 if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
8937 set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
8939 #endif
8940 #ifdef MKSESSION_NL
8941 mksession_nl = FALSE;
8942 #endif
8945 #ifdef FEAT_BROWSE
8946 theend:
8947 vim_free(browseFile);
8948 #endif
8949 #ifdef FEAT_SESSION
8950 vim_free(viewFile);
8951 #endif
8954 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
8955 || defined(PROTO)
8957 vim_mkdir_emsg(name, prot)
8958 char_u *name;
8959 int prot UNUSED;
8961 if (vim_mkdir(name, prot) != 0)
8963 EMSG2(_("E739: Cannot create directory: %s"), name);
8964 return FAIL;
8966 return OK;
8968 #endif
8971 * Open a file for writing for an Ex command, with some checks.
8972 * Return file descriptor, or NULL on failure.
8974 FILE *
8975 open_exfile(fname, forceit, mode)
8976 char_u *fname;
8977 int forceit;
8978 char *mode; /* "w" for create new file or "a" for append */
8980 FILE *fd;
8982 #ifdef UNIX
8983 /* with Unix it is possible to open a directory */
8984 if (mch_isdir(fname))
8986 EMSG2(_(e_isadir2), fname);
8987 return NULL;
8989 #endif
8990 if (!forceit && *mode != 'a' && vim_fexists(fname))
8992 EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
8993 return NULL;
8996 if ((fd = mch_fopen((char *)fname, mode)) == NULL)
8997 EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
8999 return fd;
9003 * ":mark" and ":k".
9005 static void
9006 ex_mark(eap)
9007 exarg_T *eap;
9009 pos_T pos;
9011 if (*eap->arg == NUL) /* No argument? */
9012 EMSG(_(e_argreq));
9013 else if (eap->arg[1] != NUL) /* more than one character? */
9014 EMSG(_(e_trailing));
9015 else
9017 pos = curwin->w_cursor; /* save curwin->w_cursor */
9018 curwin->w_cursor.lnum = eap->line2;
9019 beginline(BL_WHITE | BL_FIX);
9020 if (setmark(*eap->arg) == FAIL) /* set mark */
9021 EMSG(_("E191: Argument must be a letter or forward/backward quote"));
9022 curwin->w_cursor = pos; /* restore curwin->w_cursor */
9027 * Update w_topline, w_leftcol and the cursor position.
9029 void
9030 update_topline_cursor()
9032 check_cursor(); /* put cursor on valid line */
9033 update_topline();
9034 if (!curwin->w_p_wrap)
9035 validate_cursor();
9036 update_curswant();
9039 #ifdef FEAT_EX_EXTRA
9041 * ":normal[!] {commands}": Execute normal mode commands.
9043 static void
9044 ex_normal(eap)
9045 exarg_T *eap;
9047 int save_msg_scroll = msg_scroll;
9048 int save_restart_edit = restart_edit;
9049 int save_msg_didout = msg_didout;
9050 int save_State = State;
9051 tasave_T tabuf;
9052 int save_insertmode = p_im;
9053 int save_finish_op = finish_op;
9054 int save_opcount = opcount;
9055 #ifdef FEAT_MBYTE
9056 char_u *arg = NULL;
9057 int l;
9058 char_u *p;
9059 #endif
9061 if (ex_normal_lock > 0)
9063 EMSG(_(e_secure));
9064 return;
9066 if (ex_normal_busy >= p_mmd)
9068 EMSG(_("E192: Recursive use of :normal too deep"));
9069 return;
9071 ++ex_normal_busy;
9073 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
9074 restart_edit = 0; /* don't go to Insert mode */
9075 p_im = FALSE; /* don't use 'insertmode' */
9077 #ifdef FEAT_MBYTE
9079 * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
9080 * this for the K_SPECIAL leading byte, otherwise special keys will not
9081 * work.
9083 if (has_mbyte)
9085 int len = 0;
9087 /* Count the number of characters to be escaped. */
9088 for (p = eap->arg; *p != NUL; ++p)
9090 # ifdef FEAT_GUI
9091 if (*p == CSI) /* leadbyte CSI */
9092 len += 2;
9093 # endif
9094 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9095 if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */
9096 # ifdef FEAT_GUI
9097 || *p == CSI
9098 # endif
9100 len += 2;
9102 if (len > 0)
9104 arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
9105 if (arg != NULL)
9107 len = 0;
9108 for (p = eap->arg; *p != NUL; ++p)
9110 arg[len++] = *p;
9111 # ifdef FEAT_GUI
9112 if (*p == CSI)
9114 arg[len++] = KS_EXTRA;
9115 arg[len++] = (int)KE_CSI;
9117 # endif
9118 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9120 arg[len++] = *++p;
9121 if (*p == K_SPECIAL)
9123 arg[len++] = KS_SPECIAL;
9124 arg[len++] = KE_FILLER;
9126 # ifdef FEAT_GUI
9127 else if (*p == CSI)
9129 arg[len++] = KS_EXTRA;
9130 arg[len++] = (int)KE_CSI;
9132 # endif
9134 arg[len] = NUL;
9139 #endif
9142 * Save the current typeahead. This is required to allow using ":normal"
9143 * from an event handler and makes sure we don't hang when the argument
9144 * ends with half a command.
9146 save_typeahead(&tabuf);
9147 if (tabuf.typebuf_valid)
9150 * Repeat the :normal command for each line in the range. When no
9151 * range given, execute it just once, without positioning the cursor
9152 * first.
9156 if (eap->addr_count != 0)
9158 curwin->w_cursor.lnum = eap->line1++;
9159 curwin->w_cursor.col = 0;
9162 exec_normal_cmd(
9163 #ifdef FEAT_MBYTE
9164 arg != NULL ? arg :
9165 #endif
9166 eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
9168 while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
9171 /* Might not return to the main loop when in an event handler. */
9172 update_topline_cursor();
9174 /* Restore the previous typeahead. */
9175 restore_typeahead(&tabuf);
9177 --ex_normal_busy;
9178 msg_scroll = save_msg_scroll;
9179 restart_edit = save_restart_edit;
9180 p_im = save_insertmode;
9181 finish_op = save_finish_op;
9182 opcount = save_opcount;
9183 msg_didout |= save_msg_didout; /* don't reset msg_didout now */
9185 /* Restore the state (needed when called from a function executed for
9186 * 'indentexpr'). */
9187 State = save_State;
9188 #ifdef FEAT_MBYTE
9189 vim_free(arg);
9190 #endif
9194 * ":startinsert", ":startreplace" and ":startgreplace"
9196 static void
9197 ex_startinsert(eap)
9198 exarg_T *eap;
9200 if (eap->forceit)
9202 coladvance((colnr_T)MAXCOL);
9203 curwin->w_curswant = MAXCOL;
9204 curwin->w_set_curswant = FALSE;
9207 /* Ignore the command when already in Insert mode. Inserting an
9208 * expression register that invokes a function can do this. */
9209 if (State & INSERT)
9210 return;
9212 if (eap->cmdidx == CMD_startinsert)
9213 restart_edit = 'a';
9214 else if (eap->cmdidx == CMD_startreplace)
9215 restart_edit = 'R';
9216 else
9217 restart_edit = 'V';
9219 if (!eap->forceit)
9221 if (eap->cmdidx == CMD_startinsert)
9222 restart_edit = 'i';
9223 curwin->w_curswant = 0; /* avoid MAXCOL */
9228 * ":stopinsert"
9230 static void
9231 ex_stopinsert(eap)
9232 exarg_T *eap UNUSED;
9234 restart_edit = 0;
9235 stop_insert_mode = TRUE;
9237 #endif
9239 #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO)
9241 * Execute normal mode command "cmd".
9242 * "remap" can be REMAP_NONE or REMAP_YES.
9244 void
9245 exec_normal_cmd(cmd, remap, silent)
9246 char_u *cmd;
9247 int remap;
9248 int silent;
9250 oparg_T oa;
9253 * Stuff the argument into the typeahead buffer.
9254 * Execute normal_cmd() until there is no typeahead left.
9256 clear_oparg(&oa);
9257 finish_op = FALSE;
9258 ins_typebuf(cmd, remap, 0, TRUE, silent);
9259 while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
9260 && !got_int)
9262 update_topline_cursor();
9263 normal_cmd(&oa, FALSE); /* execute a Normal mode cmd */
9266 #endif
9268 #ifdef FEAT_FIND_ID
9269 static void
9270 ex_checkpath(eap)
9271 exarg_T *eap;
9273 find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
9274 eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
9275 (linenr_T)1, (linenr_T)MAXLNUM);
9278 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
9280 * ":psearch"
9282 static void
9283 ex_psearch(eap)
9284 exarg_T *eap;
9286 g_do_tagpreview = p_pvh;
9287 ex_findpat(eap);
9288 g_do_tagpreview = 0;
9290 #endif
9292 static void
9293 ex_findpat(eap)
9294 exarg_T *eap;
9296 int whole = TRUE;
9297 long n;
9298 char_u *p;
9299 int action;
9301 switch (cmdnames[eap->cmdidx].cmd_name[2])
9303 case 'e': /* ":psearch", ":isearch" and ":dsearch" */
9304 if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
9305 action = ACTION_GOTO;
9306 else
9307 action = ACTION_SHOW;
9308 break;
9309 case 'i': /* ":ilist" and ":dlist" */
9310 action = ACTION_SHOW_ALL;
9311 break;
9312 case 'u': /* ":ijump" and ":djump" */
9313 action = ACTION_GOTO;
9314 break;
9315 default: /* ":isplit" and ":dsplit" */
9316 action = ACTION_SPLIT;
9317 break;
9320 n = 1;
9321 if (vim_isdigit(*eap->arg)) /* get count */
9323 n = getdigits(&eap->arg);
9324 eap->arg = skipwhite(eap->arg);
9326 if (*eap->arg == '/') /* Match regexp, not just whole words */
9328 whole = FALSE;
9329 ++eap->arg;
9330 p = skip_regexp(eap->arg, '/', p_magic, NULL);
9331 if (*p)
9333 *p++ = NUL;
9334 p = skipwhite(p);
9336 /* Check for trailing illegal characters */
9337 if (!ends_excmd(*p))
9338 eap->errmsg = e_trailing;
9339 else
9340 eap->nextcmd = check_nextcmd(p);
9343 if (!eap->skip)
9344 find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
9345 whole, !eap->forceit,
9346 *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY,
9347 n, action, eap->line1, eap->line2);
9349 #endif
9351 #ifdef FEAT_WINDOWS
9353 # ifdef FEAT_QUICKFIX
9355 * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
9357 static void
9358 ex_ptag(eap)
9359 exarg_T *eap;
9361 g_do_tagpreview = p_pvh;
9362 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9366 * ":pedit"
9368 static void
9369 ex_pedit(eap)
9370 exarg_T *eap;
9372 win_T *curwin_save = curwin;
9374 g_do_tagpreview = p_pvh;
9375 prepare_tagpreview(TRUE);
9376 keep_help_flag = curwin_save->w_buffer->b_help;
9377 do_exedit(eap, NULL);
9378 keep_help_flag = FALSE;
9379 if (curwin != curwin_save && win_valid(curwin_save))
9381 /* Return cursor to where we were */
9382 validate_cursor();
9383 redraw_later(VALID);
9384 win_enter(curwin_save, TRUE);
9386 g_do_tagpreview = 0;
9388 # endif
9391 * ":stag", ":stselect" and ":stjump".
9393 static void
9394 ex_stag(eap)
9395 exarg_T *eap;
9397 postponed_split = -1;
9398 postponed_split_flags = cmdmod.split;
9399 postponed_split_tab = cmdmod.tab;
9400 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9401 postponed_split_flags = 0;
9402 postponed_split_tab = 0;
9404 #endif
9407 * ":tag", ":tselect", ":tjump", ":tnext", etc.
9409 static void
9410 ex_tag(eap)
9411 exarg_T *eap;
9413 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
9416 static void
9417 ex_tag_cmd(eap, name)
9418 exarg_T *eap;
9419 char_u *name;
9421 int cmd;
9423 switch (name[1])
9425 case 'j': cmd = DT_JUMP; /* ":tjump" */
9426 break;
9427 case 's': cmd = DT_SELECT; /* ":tselect" */
9428 break;
9429 case 'p': cmd = DT_PREV; /* ":tprevious" */
9430 break;
9431 case 'N': cmd = DT_PREV; /* ":tNext" */
9432 break;
9433 case 'n': cmd = DT_NEXT; /* ":tnext" */
9434 break;
9435 case 'o': cmd = DT_POP; /* ":pop" */
9436 break;
9437 case 'f': /* ":tfirst" */
9438 case 'r': cmd = DT_FIRST; /* ":trewind" */
9439 break;
9440 case 'l': cmd = DT_LAST; /* ":tlast" */
9441 break;
9442 default: /* ":tag" */
9443 #ifdef FEAT_CSCOPE
9444 if (p_cst && *eap->arg != NUL)
9446 do_cstag(eap);
9447 return;
9449 #endif
9450 cmd = DT_TAG;
9451 break;
9454 if (name[0] == 'l')
9456 #ifndef FEAT_QUICKFIX
9457 ex_ni(eap);
9458 return;
9459 #else
9460 cmd = DT_LTAG;
9461 #endif
9464 do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
9465 eap->forceit, TRUE);
9469 * Check "str" for starting with a special cmdline variable.
9470 * If found return one of the SPEC_ values and set "*usedlen" to the length of
9471 * the variable. Otherwise return -1 and "*usedlen" is unchanged.
9474 find_cmdline_var(src, usedlen)
9475 char_u *src;
9476 int *usedlen;
9478 int len;
9479 int i;
9480 static char *(spec_str[]) = {
9481 "%",
9482 #define SPEC_PERC 0
9483 "#",
9484 #define SPEC_HASH 1
9485 "<cword>", /* cursor word */
9486 #define SPEC_CWORD 2
9487 "<cWORD>", /* cursor WORD */
9488 #define SPEC_CCWORD 3
9489 "<cfile>", /* cursor path name */
9490 #define SPEC_CFILE 4
9491 "<sfile>", /* ":so" file name */
9492 #define SPEC_SFILE 5
9493 #ifdef FEAT_AUTOCMD
9494 "<afile>", /* autocommand file name */
9495 # define SPEC_AFILE 6
9496 "<abuf>", /* autocommand buffer number */
9497 # define SPEC_ABUF 7
9498 "<amatch>", /* autocommand match name */
9499 # define SPEC_AMATCH 8
9500 #endif
9501 #ifdef FEAT_CLIENTSERVER
9502 "<client>"
9503 # define SPEC_CLIENT 9
9504 #endif
9507 for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i)
9509 len = (int)STRLEN(spec_str[i]);
9510 if (STRNCMP(src, spec_str[i], len) == 0)
9512 *usedlen = len;
9513 return i;
9516 return -1;
9520 * Evaluate cmdline variables.
9522 * change '%' to curbuf->b_ffname
9523 * '#' to curwin->w_altfile
9524 * '<cword>' to word under the cursor
9525 * '<cWORD>' to WORD under the cursor
9526 * '<cfile>' to path name under the cursor
9527 * '<sfile>' to sourced file name
9528 * '<afile>' to file name for autocommand
9529 * '<abuf>' to buffer number for autocommand
9530 * '<amatch>' to matching name for autocommand
9532 * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
9533 * "" for error without a message) and NULL is returned.
9534 * Returns an allocated string if a valid match was found.
9535 * Returns NULL if no match was found. "usedlen" then still contains the
9536 * number of characters to skip.
9538 char_u *
9539 eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped)
9540 char_u *src; /* pointer into commandline */
9541 char_u *srcstart; /* beginning of valid memory for src */
9542 int *usedlen; /* characters after src that are used */
9543 linenr_T *lnump; /* line number for :e command, or NULL */
9544 char_u **errormsg; /* pointer to error message */
9545 int *escaped; /* return value has escaped white space (can
9546 * be NULL) */
9548 int i;
9549 char_u *s;
9550 char_u *result;
9551 char_u *resultbuf = NULL;
9552 int resultlen;
9553 buf_T *buf;
9554 int valid = VALID_HEAD + VALID_PATH; /* assume valid result */
9555 int spec_idx;
9556 #ifdef FEAT_MODIFY_FNAME
9557 int skip_mod = FALSE;
9558 #endif
9560 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
9561 char_u strbuf[30];
9562 #endif
9564 *errormsg = NULL;
9565 if (escaped != NULL)
9566 *escaped = FALSE;
9569 * Check if there is something to do.
9571 spec_idx = find_cmdline_var(src, usedlen);
9572 if (spec_idx < 0) /* no match */
9574 *usedlen = 1;
9575 return NULL;
9579 * Skip when preceded with a backslash "\%" and "\#".
9580 * Note: In "\\%" the % is also not recognized!
9582 if (src > srcstart && src[-1] == '\\')
9584 *usedlen = 0;
9585 STRMOVE(src - 1, src); /* remove backslash */
9586 return NULL;
9590 * word or WORD under cursor
9592 if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
9594 resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
9595 (FIND_IDENT|FIND_STRING) : FIND_STRING);
9596 if (resultlen == 0)
9598 *errormsg = (char_u *)"";
9599 return NULL;
9604 * '#': Alternate file name
9605 * '%': Current file name
9606 * File name under the cursor
9607 * File name for autocommand
9608 * and following modifiers
9610 else
9612 switch (spec_idx)
9614 case SPEC_PERC: /* '%': current file */
9615 if (curbuf->b_fname == NULL)
9617 result = (char_u *)"";
9618 valid = 0; /* Must have ":p:h" to be valid */
9620 else
9621 #ifdef RISCOS
9622 /* Always use the full path for RISC OS if possible. */
9623 result = curbuf->b_ffname;
9624 if (result == NULL)
9625 result = curbuf->b_fname;
9626 #else
9627 result = curbuf->b_fname;
9628 #endif
9629 break;
9631 case SPEC_HASH: /* '#' or "#99": alternate file */
9632 if (src[1] == '#') /* "##": the argument list */
9634 result = arg_all();
9635 resultbuf = result;
9636 *usedlen = 2;
9637 if (escaped != NULL)
9638 *escaped = TRUE;
9639 #ifdef FEAT_MODIFY_FNAME
9640 skip_mod = TRUE;
9641 #endif
9642 break;
9644 s = src + 1;
9645 if (*s == '<') /* "#<99" uses v:oldfiles */
9646 ++s;
9647 i = (int)getdigits(&s);
9648 *usedlen = (int)(s - src); /* length of what we expand */
9650 if (src[1] == '<')
9652 if (*usedlen < 2)
9654 /* Should we give an error message for #<text? */
9655 *usedlen = 1;
9656 return NULL;
9658 #ifdef FEAT_EVAL
9659 result = list_find_str(get_vim_var_list(VV_OLDFILES),
9660 (long)i);
9661 if (result == NULL)
9663 *errormsg = (char_u *)"";
9664 return NULL;
9666 #else
9667 *errormsg = (char_u *)_("E809: #< is not available without the +eval feature");
9668 return NULL;
9669 #endif
9671 else
9673 buf = buflist_findnr(i);
9674 if (buf == NULL)
9676 *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
9677 return NULL;
9679 if (lnump != NULL)
9680 *lnump = ECMD_LAST;
9681 if (buf->b_fname == NULL)
9683 result = (char_u *)"";
9684 valid = 0; /* Must have ":p:h" to be valid */
9686 else
9687 result = buf->b_fname;
9689 break;
9691 #ifdef FEAT_SEARCHPATH
9692 case SPEC_CFILE: /* file name under cursor */
9693 result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
9694 if (result == NULL)
9696 *errormsg = (char_u *)"";
9697 return NULL;
9699 resultbuf = result; /* remember allocated string */
9700 break;
9701 #endif
9703 #ifdef FEAT_AUTOCMD
9704 case SPEC_AFILE: /* file name for autocommand */
9705 result = autocmd_fname;
9706 if (result != NULL && !autocmd_fname_full)
9708 /* Still need to turn the fname into a full path. It is
9709 * postponed to avoid a delay when <afile> is not used. */
9710 autocmd_fname_full = TRUE;
9711 result = FullName_save(autocmd_fname, FALSE);
9712 vim_free(autocmd_fname);
9713 autocmd_fname = result;
9715 if (result == NULL)
9717 *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
9718 return NULL;
9720 result = shorten_fname1(result);
9721 break;
9723 case SPEC_ABUF: /* buffer number for autocommand */
9724 if (autocmd_bufnr <= 0)
9726 *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
9727 return NULL;
9729 sprintf((char *)strbuf, "%d", autocmd_bufnr);
9730 result = strbuf;
9731 break;
9733 case SPEC_AMATCH: /* match name for autocommand */
9734 result = autocmd_match;
9735 if (result == NULL)
9737 *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
9738 return NULL;
9740 break;
9742 #endif
9743 case SPEC_SFILE: /* file name for ":so" command */
9744 result = sourcing_name;
9745 if (result == NULL)
9747 *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
9748 return NULL;
9750 break;
9751 #if defined(FEAT_CLIENTSERVER)
9752 case SPEC_CLIENT: /* Source of last submitted input */
9753 sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
9754 (long_u)clientWindow);
9755 result = strbuf;
9756 break;
9757 #endif
9760 resultlen = (int)STRLEN(result); /* length of new string */
9761 if (src[*usedlen] == '<') /* remove the file name extension */
9763 ++*usedlen;
9764 #ifdef RISCOS
9765 if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
9766 #else
9767 if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
9768 #endif
9769 resultlen = (int)(s - result);
9771 #ifdef FEAT_MODIFY_FNAME
9772 else if (!skip_mod)
9774 valid |= modify_fname(src, usedlen, &result, &resultbuf,
9775 &resultlen);
9776 if (result == NULL)
9778 *errormsg = (char_u *)"";
9779 return NULL;
9782 #endif
9785 if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
9787 if (valid != VALID_HEAD + VALID_PATH)
9788 /* xgettext:no-c-format */
9789 *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
9790 else
9791 *errormsg = (char_u *)_("E500: Evaluates to an empty string");
9792 result = NULL;
9794 else
9795 result = vim_strnsave(result, resultlen);
9796 vim_free(resultbuf);
9797 return result;
9801 * Concatenate all files in the argument list, separated by spaces, and return
9802 * it in one allocated string.
9803 * Spaces and backslashes in the file names are escaped with a backslash.
9804 * Returns NULL when out of memory.
9806 static char_u *
9807 arg_all()
9809 int len;
9810 int idx;
9811 char_u *retval = NULL;
9812 char_u *p;
9815 * Do this loop two times:
9816 * first time: compute the total length
9817 * second time: concatenate the names
9819 for (;;)
9821 len = 0;
9822 for (idx = 0; idx < ARGCOUNT; ++idx)
9824 p = alist_name(&ARGLIST[idx]);
9825 if (p != NULL)
9827 if (len > 0)
9829 /* insert a space in between names */
9830 if (retval != NULL)
9831 retval[len] = ' ';
9832 ++len;
9834 for ( ; *p != NUL; ++p)
9836 if (*p == ' ' || *p == '\\')
9838 /* insert a backslash */
9839 if (retval != NULL)
9840 retval[len] = '\\';
9841 ++len;
9843 if (retval != NULL)
9844 retval[len] = *p;
9845 ++len;
9850 /* second time: break here */
9851 if (retval != NULL)
9853 retval[len] = NUL;
9854 break;
9857 /* allocate memory */
9858 retval = alloc((unsigned)len + 1);
9859 if (retval == NULL)
9860 break;
9863 return retval;
9866 #if defined(FEAT_AUTOCMD) || defined(PROTO)
9868 * Expand the <sfile> string in "arg".
9870 * Returns an allocated string, or NULL for any error.
9872 char_u *
9873 expand_sfile(arg)
9874 char_u *arg;
9876 char_u *errormsg;
9877 int len;
9878 char_u *result;
9879 char_u *newres;
9880 char_u *repl;
9881 int srclen;
9882 char_u *p;
9884 result = vim_strsave(arg);
9885 if (result == NULL)
9886 return NULL;
9888 for (p = result; *p; )
9890 if (STRNCMP(p, "<sfile>", 7) != 0)
9891 ++p;
9892 else
9894 /* replace "<sfile>" with the sourced file name, and do ":" stuff */
9895 repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
9896 if (errormsg != NULL)
9898 if (*errormsg)
9899 emsg(errormsg);
9900 vim_free(result);
9901 return NULL;
9903 if (repl == NULL) /* no match (cannot happen) */
9905 p += srclen;
9906 continue;
9908 len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
9909 newres = alloc(len);
9910 if (newres == NULL)
9912 vim_free(repl);
9913 vim_free(result);
9914 return NULL;
9916 mch_memmove(newres, result, (size_t)(p - result));
9917 STRCPY(newres + (p - result), repl);
9918 len = (int)STRLEN(newres);
9919 STRCAT(newres, p + srclen);
9920 vim_free(repl);
9921 vim_free(result);
9922 result = newres;
9923 p = newres + len; /* continue after the match */
9927 return result;
9929 #endif
9931 #ifdef FEAT_SESSION
9932 static int ses_winsizes __ARGS((FILE *fd, int restore_size,
9933 win_T *tab_firstwin));
9934 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
9935 static frame_T *ses_skipframe __ARGS((frame_T *fr));
9936 static int ses_do_frame __ARGS((frame_T *fr));
9937 static int ses_do_win __ARGS((win_T *wp));
9938 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
9939 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
9940 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
9943 * Write openfile commands for the current buffers to an .exrc file.
9944 * Return FAIL on error, OK otherwise.
9946 static int
9947 makeopens(fd, dirnow)
9948 FILE *fd;
9949 char_u *dirnow; /* Current directory name */
9951 buf_T *buf;
9952 int only_save_windows = TRUE;
9953 int nr;
9954 int cnr = 1;
9955 int restore_size = TRUE;
9956 win_T *wp;
9957 char_u *sname;
9958 win_T *edited_win = NULL;
9959 int tabnr;
9960 win_T *tab_firstwin;
9961 frame_T *tab_topframe;
9962 int cur_arg_idx = 0;
9963 int next_arg_idx = 0;
9965 if (ssop_flags & SSOP_BUFFERS)
9966 only_save_windows = FALSE; /* Save ALL buffers */
9969 * Begin by setting the this_session variable, and then other
9970 * sessionable variables.
9972 #ifdef FEAT_EVAL
9973 if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
9974 return FAIL;
9975 if (ssop_flags & SSOP_GLOBALS)
9976 if (store_session_globals(fd) == FAIL)
9977 return FAIL;
9978 #endif
9981 * Close all windows but one.
9983 if (put_line(fd, "silent only") == FAIL)
9984 return FAIL;
9987 * Now a :cd command to the session directory or the current directory
9989 if (ssop_flags & SSOP_SESDIR)
9991 if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
9992 == FAIL)
9993 return FAIL;
9995 else if (ssop_flags & SSOP_CURDIR)
9997 sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
9998 if (sname == NULL
9999 || fputs("cd ", fd) < 0
10000 || ses_put_fname(fd, sname, &ssop_flags) == FAIL
10001 || put_eol(fd) == FAIL)
10003 vim_free(sname);
10004 return FAIL;
10006 vim_free(sname);
10010 * If there is an empty, unnamed buffer we will wipe it out later.
10011 * Remember the buffer number.
10013 if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
10014 return FAIL;
10015 if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL)
10016 return FAIL;
10017 if (put_line(fd, "endif") == FAIL)
10018 return FAIL;
10021 * Now save the current files, current buffer first.
10023 if (put_line(fd, "set shortmess=aoO") == FAIL)
10024 return FAIL;
10026 /* Now put the other buffers into the buffer list */
10027 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
10029 if (!(only_save_windows && buf->b_nwindows == 0)
10030 && !(buf->b_help && !(ssop_flags & SSOP_HELP))
10031 && buf->b_fname != NULL
10032 && buf->b_p_bl)
10034 if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
10035 : buf->b_wininfo->wi_fpos.lnum) < 0
10036 || ses_fname(fd, buf, &ssop_flags) == FAIL)
10037 return FAIL;
10041 /* the global argument list */
10042 if (ses_arglist(fd, "args", &global_alist.al_ga,
10043 !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
10044 return FAIL;
10046 if (ssop_flags & SSOP_RESIZE)
10048 /* Note: after the restore we still check it worked!*/
10049 if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
10050 || put_eol(fd) == FAIL)
10051 return FAIL;
10054 #ifdef FEAT_GUI
10055 if (gui.in_use && (ssop_flags & SSOP_WINPOS))
10057 int x, y;
10059 if (gui_mch_get_winpos(&x, &y) == OK)
10061 /* Note: after the restore we still check it worked!*/
10062 if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
10063 return FAIL;
10066 #endif
10069 * May repeat putting Windows for each tab, when "tabpages" is in
10070 * 'sessionoptions'.
10071 * Don't use goto_tabpage(), it may change directory and trigger
10072 * autocommands.
10074 tab_firstwin = firstwin; /* first window in tab page "tabnr" */
10075 tab_topframe = topframe;
10076 for (tabnr = 1; ; ++tabnr)
10078 int need_tabnew = FALSE;
10080 if ((ssop_flags & SSOP_TABPAGES))
10082 tabpage_T *tp = find_tabpage(tabnr);
10084 if (tp == NULL)
10085 break; /* done all tab pages */
10086 if (tp == curtab)
10088 tab_firstwin = firstwin;
10089 tab_topframe = topframe;
10091 else
10093 tab_firstwin = tp->tp_firstwin;
10094 tab_topframe = tp->tp_topframe;
10096 if (tabnr > 1)
10097 need_tabnew = TRUE;
10101 * Before creating the window layout, try loading one file. If this
10102 * is aborted we don't end up with a number of useless windows.
10103 * This may have side effects! (e.g., compressed or network file).
10105 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10107 if (ses_do_win(wp)
10108 && wp->w_buffer->b_ffname != NULL
10109 && !wp->w_buffer->b_help
10110 #ifdef FEAT_QUICKFIX
10111 && !bt_nofile(wp->w_buffer)
10112 #endif
10115 if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
10116 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
10117 return FAIL;
10118 need_tabnew = FALSE;
10119 if (!wp->w_arg_idx_invalid)
10120 edited_win = wp;
10121 break;
10125 /* If no file got edited create an empty tab page. */
10126 if (need_tabnew && put_line(fd, "tabnew") == FAIL)
10127 return FAIL;
10130 * Save current window layout.
10132 if (put_line(fd, "set splitbelow splitright") == FAIL)
10133 return FAIL;
10134 if (ses_win_rec(fd, tab_topframe) == FAIL)
10135 return FAIL;
10136 if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
10137 return FAIL;
10138 if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
10139 return FAIL;
10142 * Check if window sizes can be restored (no windows omitted).
10143 * Remember the window number of the current window after restoring.
10145 nr = 0;
10146 for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
10148 if (ses_do_win(wp))
10149 ++nr;
10150 else
10151 restore_size = FALSE;
10152 if (curwin == wp)
10153 cnr = nr;
10156 /* Go to the first window. */
10157 if (put_line(fd, "wincmd t") == FAIL)
10158 return FAIL;
10161 * If more than one window, see if sizes can be restored.
10162 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
10163 * resized when moving between windows.
10164 * Do this before restoring the view, so that the topline and the
10165 * cursor can be set. This is done again below.
10167 if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
10168 return FAIL;
10169 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10170 return FAIL;
10173 * Restore the view of the window (options, file, cursor, etc.).
10175 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10177 if (!ses_do_win(wp))
10178 continue;
10179 if (put_view(fd, wp, wp != edited_win, &ssop_flags,
10180 cur_arg_idx) == FAIL)
10181 return FAIL;
10182 if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
10183 return FAIL;
10184 next_arg_idx = wp->w_arg_idx;
10187 /* The argument index in the first tab page is zero, need to set it in
10188 * each window. For further tab pages it's the window where we do
10189 * "tabedit". */
10190 cur_arg_idx = next_arg_idx;
10193 * Restore cursor to the current window if it's not the first one.
10195 if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
10196 || put_eol(fd) == FAIL))
10197 return FAIL;
10200 * Restore window sizes again after jumping around in windows, because
10201 * the current window has a minimum size while others may not.
10203 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10204 return FAIL;
10206 /* Don't continue in another tab page when doing only the current one
10207 * or when at the last tab page. */
10208 if (!(ssop_flags & SSOP_TABPAGES))
10209 break;
10212 if (ssop_flags & SSOP_TABPAGES)
10214 if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
10215 || put_eol(fd) == FAIL)
10216 return FAIL;
10220 * Wipe out an empty unnamed buffer we started in.
10222 if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
10223 return FAIL;
10224 if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL)
10225 return FAIL;
10226 if (put_line(fd, "endif") == FAIL)
10227 return FAIL;
10228 if (put_line(fd, "unlet! s:wipebuf") == FAIL)
10229 return FAIL;
10231 /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
10232 if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
10233 p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
10234 return FAIL;
10237 * Lastly, execute the x.vim file if it exists.
10239 if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
10240 || put_line(fd, "if file_readable(s:sx)") == FAIL
10241 || put_line(fd, " exe \"source \" . fnameescape(s:sx)") == FAIL
10242 || put_line(fd, "endif") == FAIL)
10243 return FAIL;
10245 return OK;
10248 static int
10249 ses_winsizes(fd, restore_size, tab_firstwin)
10250 FILE *fd;
10251 int restore_size;
10252 win_T *tab_firstwin;
10254 int n = 0;
10255 win_T *wp;
10257 if (restore_size && (ssop_flags & SSOP_WINSIZE))
10259 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10261 if (!ses_do_win(wp))
10262 continue;
10263 ++n;
10265 /* restore height when not full height */
10266 if (wp->w_height + wp->w_status_height < topframe->fr_height
10267 && (fprintf(fd,
10268 "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
10269 n, (long)wp->w_height, Rows / 2, Rows) < 0
10270 || put_eol(fd) == FAIL))
10271 return FAIL;
10273 /* restore width when not full width */
10274 if (wp->w_width < Columns && (fprintf(fd,
10275 "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
10276 n, (long)wp->w_width, Columns / 2, Columns) < 0
10277 || put_eol(fd) == FAIL))
10278 return FAIL;
10281 else
10283 /* Just equalise window sizes */
10284 if (put_line(fd, "wincmd =") == FAIL)
10285 return FAIL;
10287 return OK;
10291 * Write commands to "fd" to recursively create windows for frame "fr",
10292 * horizontally and vertically split.
10293 * After the commands the last window in the frame is the current window.
10294 * Returns FAIL when writing the commands to "fd" fails.
10296 static int
10297 ses_win_rec(fd, fr)
10298 FILE *fd;
10299 frame_T *fr;
10301 frame_T *frc;
10302 int count = 0;
10304 if (fr->fr_layout != FR_LEAF)
10306 /* Find first frame that's not skipped and then create a window for
10307 * each following one (first frame is already there). */
10308 frc = ses_skipframe(fr->fr_child);
10309 if (frc != NULL)
10310 while ((frc = ses_skipframe(frc->fr_next)) != NULL)
10312 /* Make window as big as possible so that we have lots of room
10313 * to split. */
10314 if (put_line(fd, "wincmd _ | wincmd |") == FAIL
10315 || put_line(fd, fr->fr_layout == FR_COL
10316 ? "split" : "vsplit") == FAIL)
10317 return FAIL;
10318 ++count;
10321 /* Go back to the first window. */
10322 if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
10323 ? "%dwincmd k" : "%dwincmd h", count) < 0
10324 || put_eol(fd) == FAIL))
10325 return FAIL;
10327 /* Recursively create frames/windows in each window of this column or
10328 * row. */
10329 frc = ses_skipframe(fr->fr_child);
10330 while (frc != NULL)
10332 ses_win_rec(fd, frc);
10333 frc = ses_skipframe(frc->fr_next);
10334 /* Go to next window. */
10335 if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
10336 return FAIL;
10339 return OK;
10343 * Skip frames that don't contain windows we want to save in the Session.
10344 * Returns NULL when there none.
10346 static frame_T *
10347 ses_skipframe(fr)
10348 frame_T *fr;
10350 frame_T *frc;
10352 for (frc = fr; frc != NULL; frc = frc->fr_next)
10353 if (ses_do_frame(frc))
10354 break;
10355 return frc;
10359 * Return TRUE if frame "fr" has a window somewhere that we want to save in
10360 * the Session.
10362 static int
10363 ses_do_frame(fr)
10364 frame_T *fr;
10366 frame_T *frc;
10368 if (fr->fr_layout == FR_LEAF)
10369 return ses_do_win(fr->fr_win);
10370 for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
10371 if (ses_do_frame(frc))
10372 return TRUE;
10373 return FALSE;
10377 * Return non-zero if window "wp" is to be stored in the Session.
10379 static int
10380 ses_do_win(wp)
10381 win_T *wp;
10383 if (wp->w_buffer->b_fname == NULL
10384 #ifdef FEAT_QUICKFIX
10385 /* When 'buftype' is "nofile" can't restore the window contents. */
10386 || bt_nofile(wp->w_buffer)
10387 #endif
10389 return (ssop_flags & SSOP_BLANK);
10390 if (wp->w_buffer->b_help)
10391 return (ssop_flags & SSOP_HELP);
10392 return TRUE;
10396 * Write commands to "fd" to restore the view of a window.
10397 * Caller must make sure 'scrolloff' is zero.
10399 static int
10400 put_view(fd, wp, add_edit, flagp, current_arg_idx)
10401 FILE *fd;
10402 win_T *wp;
10403 int add_edit; /* add ":edit" command to view */
10404 unsigned *flagp; /* vop_flags or ssop_flags */
10405 int current_arg_idx; /* current argument index of the window, use
10406 * -1 if unknown */
10408 win_T *save_curwin;
10409 int f;
10410 int do_cursor;
10411 int did_next = FALSE;
10413 /* Always restore cursor position for ":mksession". For ":mkview" only
10414 * when 'viewoptions' contains "cursor". */
10415 do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
10418 * Local argument list.
10420 if (wp->w_alist == &global_alist)
10422 if (put_line(fd, "argglobal") == FAIL)
10423 return FAIL;
10425 else
10427 if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
10428 flagp == &vop_flags
10429 || !(*flagp & SSOP_CURDIR)
10430 || wp->w_localdir != NULL, flagp) == FAIL)
10431 return FAIL;
10434 /* Only when part of a session: restore the argument index. Some
10435 * arguments may have been deleted, check if the index is valid. */
10436 if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx <= WARGCOUNT(wp)
10437 && flagp == &ssop_flags)
10439 if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
10440 || put_eol(fd) == FAIL)
10441 return FAIL;
10442 did_next = TRUE;
10445 /* Edit the file. Skip this when ":next" already did it. */
10446 if (add_edit && (!did_next || wp->w_arg_idx_invalid))
10449 * Load the file.
10451 if (wp->w_buffer->b_ffname != NULL
10452 #ifdef FEAT_QUICKFIX
10453 && !bt_nofile(wp->w_buffer)
10454 #endif
10458 * Editing a file in this buffer: use ":edit file".
10459 * This may have side effects! (e.g., compressed or network file).
10461 if (fputs("edit ", fd) < 0
10462 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10463 return FAIL;
10465 else
10467 /* No file in this buffer, just make it empty. */
10468 if (put_line(fd, "enew") == FAIL)
10469 return FAIL;
10470 #ifdef FEAT_QUICKFIX
10471 if (wp->w_buffer->b_ffname != NULL)
10473 /* The buffer does have a name, but it's not a file name. */
10474 if (fputs("file ", fd) < 0
10475 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10476 return FAIL;
10478 #endif
10479 do_cursor = FALSE;
10484 * Local mappings and abbreviations.
10486 if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10487 && makemap(fd, wp->w_buffer) == FAIL)
10488 return FAIL;
10491 * Local options. Need to go to the window temporarily.
10492 * Store only local values when using ":mkview" and when ":mksession" is
10493 * used and 'sessionoptions' doesn't include "options".
10494 * Some folding options are always stored when "folds" is included,
10495 * otherwise the folds would not be restored correctly.
10497 save_curwin = curwin;
10498 curwin = wp;
10499 curbuf = curwin->w_buffer;
10500 if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10501 f = makeset(fd, OPT_LOCAL,
10502 flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
10503 #ifdef FEAT_FOLDING
10504 else if (*flagp & SSOP_FOLDS)
10505 f = makefoldset(fd);
10506 #endif
10507 else
10508 f = OK;
10509 curwin = save_curwin;
10510 curbuf = curwin->w_buffer;
10511 if (f == FAIL)
10512 return FAIL;
10514 #ifdef FEAT_FOLDING
10516 * Save Folds when 'buftype' is empty and for help files.
10518 if ((*flagp & SSOP_FOLDS)
10519 && wp->w_buffer->b_ffname != NULL
10520 # ifdef FEAT_QUICKFIX
10521 && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help)
10522 # endif
10525 if (put_folds(fd, wp) == FAIL)
10526 return FAIL;
10528 #endif
10531 * Set the cursor after creating folds, since that moves the cursor.
10533 if (do_cursor)
10536 /* Restore the cursor line in the file and relatively in the
10537 * window. Don't use "G", it changes the jumplist. */
10538 if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
10539 (long)wp->w_cursor.lnum,
10540 (long)(wp->w_cursor.lnum - wp->w_topline),
10541 (long)wp->w_height / 2, (long)wp->w_height) < 0
10542 || put_eol(fd) == FAIL
10543 || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
10544 || put_line(fd, "exe s:l") == FAIL
10545 || put_line(fd, "normal! zt") == FAIL
10546 || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
10547 || put_eol(fd) == FAIL)
10548 return FAIL;
10549 /* Restore the cursor column and left offset when not wrapping. */
10550 if (wp->w_cursor.col == 0)
10552 if (put_line(fd, "normal! 0") == FAIL)
10553 return FAIL;
10555 else
10557 if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
10559 if (fprintf(fd,
10560 "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
10561 (long)wp->w_cursor.col,
10562 (long)(wp->w_cursor.col - wp->w_leftcol),
10563 (long)wp->w_width / 2, (long)wp->w_width) < 0
10564 || put_eol(fd) == FAIL
10565 || put_line(fd, "if s:c > 0") == FAIL
10566 || fprintf(fd,
10567 " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
10568 (long)wp->w_cursor.col) < 0
10569 || put_eol(fd) == FAIL
10570 || put_line(fd, "else") == FAIL
10571 || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0
10572 || put_eol(fd) == FAIL
10573 || put_line(fd, "endif") == FAIL)
10574 return FAIL;
10576 else
10578 if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
10579 || put_eol(fd) == FAIL)
10580 return FAIL;
10586 * Local directory.
10588 if (wp->w_localdir != NULL)
10590 if (fputs("lcd ", fd) < 0
10591 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
10592 || put_eol(fd) == FAIL)
10593 return FAIL;
10594 did_lcd = TRUE;
10597 return OK;
10601 * Write an argument list to the session file.
10602 * Returns FAIL if writing fails.
10604 static int
10605 ses_arglist(fd, cmd, gap, fullname, flagp)
10606 FILE *fd;
10607 char *cmd;
10608 garray_T *gap;
10609 int fullname; /* TRUE: use full path name */
10610 unsigned *flagp;
10612 int i;
10613 char_u buf[MAXPATHL];
10614 char_u *s;
10616 if (gap->ga_len == 0)
10617 return put_line(fd, "silent! argdel *");
10618 if (fputs(cmd, fd) < 0)
10619 return FAIL;
10620 for (i = 0; i < gap->ga_len; ++i)
10622 /* NULL file names are skipped (only happens when out of memory). */
10623 s = alist_name(&((aentry_T *)gap->ga_data)[i]);
10624 if (s != NULL)
10626 if (fullname)
10628 (void)vim_FullName(s, buf, MAXPATHL, FALSE);
10629 s = buf;
10631 if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
10632 return FAIL;
10635 return put_eol(fd);
10639 * Write a buffer name to the session file.
10640 * Also ends the line.
10641 * Returns FAIL if writing fails.
10643 static int
10644 ses_fname(fd, buf, flagp)
10645 FILE *fd;
10646 buf_T *buf;
10647 unsigned *flagp;
10649 char_u *name;
10651 /* Use the short file name if the current directory is known at the time
10652 * the session file will be sourced.
10653 * Don't do this for ":mkview", we don't know the current directory.
10654 * Don't do this after ":lcd", we don't keep track of what the current
10655 * directory is. */
10656 if (buf->b_sfname != NULL
10657 && flagp == &ssop_flags
10658 && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
10659 #ifdef FEAT_AUTOCHDIR
10660 && !p_acd
10661 #endif
10662 && !did_lcd)
10663 name = buf->b_sfname;
10664 else
10665 name = buf->b_ffname;
10666 if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
10667 return FAIL;
10668 return OK;
10672 * Write a file name to the session file.
10673 * Takes care of the "slash" option in 'sessionoptions' and escapes special
10674 * characters.
10675 * Returns FAIL if writing fails.
10677 static int
10678 ses_put_fname(fd, name, flagp)
10679 FILE *fd;
10680 char_u *name;
10681 unsigned *flagp;
10683 char_u *sname;
10684 int retval = OK;
10685 int c;
10687 sname = home_replace_save(NULL, name);
10688 if (sname != NULL)
10689 name = sname;
10690 while (*name != NUL)
10692 #ifdef FEAT_MBYTE
10694 int l;
10696 if (has_mbyte && (l = (*mb_ptr2len)(name)) > 1)
10698 /* copy a multibyte char */
10699 while (--l >= 0)
10701 if (putc(*name, fd) != *name)
10702 retval = FAIL;
10703 ++name;
10705 continue;
10708 #endif
10709 c = *name++;
10710 if (c == '\\' && (*flagp & SSOP_SLASH))
10711 /* change a backslash to a forward slash */
10712 c = '/';
10713 else if ((vim_strchr(escape_chars, c) != NULL
10714 #ifdef BACKSLASH_IN_FILENAME
10715 && c != '\\'
10716 #endif
10717 ) || c == '#' || c == '%')
10719 /* escape a special character with a backslash */
10720 if (putc('\\', fd) != '\\')
10721 retval = FAIL;
10723 if (putc(c, fd) != c)
10724 retval = FAIL;
10726 vim_free(sname);
10727 return retval;
10731 * ":loadview [nr]"
10733 static void
10734 ex_loadview(eap)
10735 exarg_T *eap;
10737 char_u *fname;
10739 fname = get_view_file(*eap->arg);
10740 if (fname != NULL)
10742 do_source(fname, FALSE, DOSO_NONE);
10743 vim_free(fname);
10748 * Get the name of the view file for the current buffer.
10750 static char_u *
10751 get_view_file(c)
10752 int c;
10754 int len = 0;
10755 char_u *p, *s;
10756 char_u *retval;
10757 char_u *sname;
10759 if (curbuf->b_ffname == NULL)
10761 EMSG(_(e_noname));
10762 return NULL;
10764 sname = home_replace_save(NULL, curbuf->b_ffname);
10765 if (sname == NULL)
10766 return NULL;
10769 * We want a file name without separators, because we're not going to make
10770 * a directory.
10771 * "normal" path separator -> "=+"
10772 * "=" -> "=="
10773 * ":" path separator -> "=-"
10775 for (p = sname; *p; ++p)
10776 if (*p == '=' || vim_ispathsep(*p))
10777 ++len;
10778 retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
10779 if (retval != NULL)
10781 STRCPY(retval, p_vdir);
10782 add_pathsep(retval);
10783 s = retval + STRLEN(retval);
10784 for (p = sname; *p; ++p)
10786 if (*p == '=')
10788 *s++ = '=';
10789 *s++ = '=';
10791 else if (vim_ispathsep(*p))
10793 *s++ = '=';
10794 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
10795 || defined(VMS)
10796 if (*p == ':')
10797 *s++ = '-';
10798 else
10799 #endif
10800 *s++ = '+';
10802 else
10803 *s++ = *p;
10805 *s++ = '=';
10806 *s++ = c;
10807 STRCPY(s, ".vim");
10810 vim_free(sname);
10811 return retval;
10814 #endif /* FEAT_SESSION */
10817 * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
10818 * Return FAIL for a write error.
10821 put_eol(fd)
10822 FILE *fd;
10824 if (
10825 #ifdef USE_CRNL
10827 # ifdef MKSESSION_NL
10828 !mksession_nl &&
10829 # endif
10830 (putc('\r', fd) < 0)) ||
10831 #endif
10832 (putc('\n', fd) < 0))
10833 return FAIL;
10834 return OK;
10838 * Write a line to "fd".
10839 * Return FAIL for a write error.
10842 put_line(fd, s)
10843 FILE *fd;
10844 char *s;
10846 if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
10847 return FAIL;
10848 return OK;
10851 #ifdef FEAT_VIMINFO
10853 * ":rviminfo" and ":wviminfo".
10855 static void
10856 ex_viminfo(eap)
10857 exarg_T *eap;
10859 char_u *save_viminfo;
10861 save_viminfo = p_viminfo;
10862 if (*p_viminfo == NUL)
10863 p_viminfo = (char_u *)"'100";
10864 if (eap->cmdidx == CMD_rviminfo)
10866 if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS
10867 | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL)
10868 EMSG(_("E195: Cannot open viminfo file for reading"));
10870 else
10871 write_viminfo(eap->arg, eap->forceit);
10872 p_viminfo = save_viminfo;
10874 #endif
10876 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
10878 * Make a dialog message in "buff[IOSIZE]".
10879 * "format" must contain "%s".
10881 void
10882 dialog_msg(buff, format, fname)
10883 char_u *buff;
10884 char *format;
10885 char_u *fname;
10887 if (fname == NULL)
10888 fname = (char_u *)_("Untitled");
10889 vim_snprintf((char *)buff, IOSIZE, format, fname);
10891 #endif
10894 * ":behave {mswin,xterm}"
10896 static void
10897 ex_behave(eap)
10898 exarg_T *eap;
10900 if (STRCMP(eap->arg, "mswin") == 0)
10902 set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
10903 set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
10904 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
10905 set_option_value((char_u *)"keymodel", 0L,
10906 (char_u *)"startsel,stopsel", 0);
10908 else if (STRCMP(eap->arg, "xterm") == 0)
10910 set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
10911 set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
10912 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
10913 set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
10915 else
10916 EMSG2(_(e_invarg2), eap->arg);
10919 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10921 * Function given to ExpandGeneric() to obtain the possible arguments of the
10922 * ":behave {mswin,xterm}" command.
10924 char_u *
10925 get_behave_arg(xp, idx)
10926 expand_T *xp UNUSED;
10927 int idx;
10929 if (idx == 0)
10930 return (char_u *)"mswin";
10931 if (idx == 1)
10932 return (char_u *)"xterm";
10933 return NULL;
10935 #endif
10937 #ifdef FEAT_AUTOCMD
10938 static int filetype_detect = FALSE;
10939 static int filetype_plugin = FALSE;
10940 static int filetype_indent = FALSE;
10943 * ":filetype [plugin] [indent] {on,off,detect}"
10944 * on: Load the filetype.vim file to install autocommands for file types.
10945 * off: Load the ftoff.vim file to remove all autocommands for file types.
10946 * plugin on: load filetype.vim and ftplugin.vim
10947 * plugin off: load ftplugof.vim
10948 * indent on: load filetype.vim and indent.vim
10949 * indent off: load indoff.vim
10951 static void
10952 ex_filetype(eap)
10953 exarg_T *eap;
10955 char_u *arg = eap->arg;
10956 int plugin = FALSE;
10957 int indent = FALSE;
10959 if (*eap->arg == NUL)
10961 /* Print current status. */
10962 smsg((char_u *)"filetype detection:%s plugin:%s indent:%s",
10963 filetype_detect ? "ON" : "OFF",
10964 filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
10965 filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
10966 return;
10969 /* Accept "plugin" and "indent" in any order. */
10970 for (;;)
10972 if (STRNCMP(arg, "plugin", 6) == 0)
10974 plugin = TRUE;
10975 arg = skipwhite(arg + 6);
10976 continue;
10978 if (STRNCMP(arg, "indent", 6) == 0)
10980 indent = TRUE;
10981 arg = skipwhite(arg + 6);
10982 continue;
10984 break;
10986 if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
10988 if (*arg == 'o' || !filetype_detect)
10990 source_runtime((char_u *)FILETYPE_FILE, TRUE);
10991 filetype_detect = TRUE;
10992 if (plugin)
10994 source_runtime((char_u *)FTPLUGIN_FILE, TRUE);
10995 filetype_plugin = TRUE;
10997 if (indent)
10999 source_runtime((char_u *)INDENT_FILE, TRUE);
11000 filetype_indent = TRUE;
11003 if (*arg == 'd')
11005 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
11006 do_modelines(0);
11009 else if (STRCMP(arg, "off") == 0)
11011 if (plugin || indent)
11013 if (plugin)
11015 source_runtime((char_u *)FTPLUGOF_FILE, TRUE);
11016 filetype_plugin = FALSE;
11018 if (indent)
11020 source_runtime((char_u *)INDOFF_FILE, TRUE);
11021 filetype_indent = FALSE;
11024 else
11026 source_runtime((char_u *)FTOFF_FILE, TRUE);
11027 filetype_detect = FALSE;
11030 else
11031 EMSG2(_(e_invarg2), arg);
11035 * ":setfiletype {name}"
11037 static void
11038 ex_setfiletype(eap)
11039 exarg_T *eap;
11041 if (!did_filetype)
11042 set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
11044 #endif
11046 static void
11047 ex_digraphs(eap)
11048 exarg_T *eap UNUSED;
11050 #ifdef FEAT_DIGRAPHS
11051 if (*eap->arg != NUL)
11052 putdigraph(eap->arg);
11053 else
11054 listdigraphs();
11055 #else
11056 EMSG(_("E196: No digraphs in this version"));
11057 #endif
11060 static void
11061 ex_set(eap)
11062 exarg_T *eap;
11064 int flags = 0;
11066 if (eap->cmdidx == CMD_setlocal)
11067 flags = OPT_LOCAL;
11068 else if (eap->cmdidx == CMD_setglobal)
11069 flags = OPT_GLOBAL;
11070 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
11071 if (cmdmod.browse && flags == 0)
11072 ex_options(eap);
11073 else
11074 #endif
11075 (void)do_set(eap->arg, flags);
11078 #ifdef FEAT_SEARCH_EXTRA
11080 * ":nohlsearch"
11082 static void
11083 ex_nohlsearch(eap)
11084 exarg_T *eap UNUSED;
11086 no_hlsearch = TRUE;
11087 redraw_all_later(SOME_VALID);
11091 * ":[N]match {group} {pattern}"
11092 * Sets nextcmd to the start of the next command, if any. Also called when
11093 * skipping commands to find the next command.
11095 static void
11096 ex_match(eap)
11097 exarg_T *eap;
11099 char_u *p;
11100 char_u *g = NULL;
11101 char_u *end;
11102 int c;
11103 int id;
11105 if (eap->line2 <= 3)
11106 id = eap->line2;
11107 else
11109 EMSG(e_invcmd);
11110 return;
11113 /* First clear any old pattern. */
11114 if (!eap->skip)
11115 match_delete(curwin, id, FALSE);
11117 if (ends_excmd(*eap->arg))
11118 end = eap->arg;
11119 else if ((STRNICMP(eap->arg, "none", 4) == 0
11120 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
11121 end = eap->arg + 4;
11122 else
11124 p = skiptowhite(eap->arg);
11125 if (!eap->skip)
11126 g = vim_strnsave(eap->arg, (int)(p - eap->arg));
11127 p = skipwhite(p);
11128 if (*p == NUL)
11130 /* There must be two arguments. */
11131 EMSG2(_(e_invarg2), eap->arg);
11132 return;
11134 end = skip_regexp(p + 1, *p, TRUE, NULL);
11135 if (!eap->skip)
11137 if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
11139 eap->errmsg = e_trailing;
11140 return;
11142 if (*end != *p)
11144 EMSG2(_(e_invarg2), p);
11145 return;
11148 c = *end;
11149 *end = NUL;
11150 match_add(curwin, g, p + 1, 10, id);
11151 vim_free(g);
11152 *end = c;
11155 eap->nextcmd = find_nextcmd(end);
11157 #endif
11159 #ifdef FEAT_CRYPT
11161 * ":X": Get crypt key
11163 static void
11164 ex_X(eap)
11165 exarg_T *eap UNUSED;
11167 (void)get_crypt_key(TRUE, TRUE);
11169 #endif
11171 #ifdef FEAT_FOLDING
11172 static void
11173 ex_fold(eap)
11174 exarg_T *eap;
11176 if (foldManualAllowed(TRUE))
11177 foldCreate(eap->line1, eap->line2);
11180 static void
11181 ex_foldopen(eap)
11182 exarg_T *eap;
11184 opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
11185 eap->forceit, FALSE);
11188 static void
11189 ex_folddo(eap)
11190 exarg_T *eap;
11192 linenr_T lnum;
11194 /* First set the marks for all lines closed/open. */
11195 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
11196 if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
11197 ml_setmarked(lnum);
11199 /* Execute the command on the marked lines. */
11200 global_exe(eap->arg);
11201 ml_clearmarked(); /* clear rest of the marks */
11203 #endif